linux/drivers/scsi/megaraid/megaraid_sas_base.c
<<
>>
Prefs
   1/*
   2 *  Linux MegaRAID driver for SAS based RAID controllers
   3 *
   4 *  Copyright (c) 2003-2012  LSI Corporation.
   5 *
   6 *  This program is free software; you can redistribute it and/or
   7 *  modify it under the terms of the GNU General Public License
   8 *  as published by the Free Software Foundation; either version 2
   9 *  of the License, or (at your option) any later version.
  10 *
  11 *  This program is distributed in the hope that it will be useful,
  12 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
  13 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14 *  GNU General Public License for more details.
  15 *
  16 *  You should have received a copy of the GNU General Public License
  17 *  along with this program; if not, write to the Free Software
  18 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19 *
  20 *  FILE: megaraid_sas_base.c
  21 *  Version : 06.803.01.00-rc1
  22 *
  23 *  Authors: LSI Corporation
  24 *           Sreenivas Bagalkote
  25 *           Sumant Patro
  26 *           Bo Yang
  27 *           Adam Radford <linuxraid@lsi.com>
  28 *
  29 *  Send feedback to: <megaraidlinux@lsi.com>
  30 *
  31 *  Mail to: LSI Corporation, 1621 Barber Lane, Milpitas, CA 95035
  32 *     ATTN: Linuxraid
  33 */
  34
  35#include <linux/kernel.h>
  36#include <linux/types.h>
  37#include <linux/pci.h>
  38#include <linux/list.h>
  39#include <linux/moduleparam.h>
  40#include <linux/module.h>
  41#include <linux/spinlock.h>
  42#include <linux/interrupt.h>
  43#include <linux/delay.h>
  44#include <linux/uio.h>
  45#include <linux/slab.h>
  46#include <asm/uaccess.h>
  47#include <linux/fs.h>
  48#include <linux/compat.h>
  49#include <linux/blkdev.h>
  50#include <linux/mutex.h>
  51#include <linux/poll.h>
  52
  53#include <scsi/scsi.h>
  54#include <scsi/scsi_cmnd.h>
  55#include <scsi/scsi_device.h>
  56#include <scsi/scsi_host.h>
  57#include <scsi/scsi_tcq.h>
  58#include "megaraid_sas_fusion.h"
  59#include "megaraid_sas.h"
  60
  61/*
  62 * Number of sectors per IO command
  63 * Will be set in megasas_init_mfi if user does not provide
  64 */
  65static unsigned int max_sectors;
  66module_param_named(max_sectors, max_sectors, int, 0);
  67MODULE_PARM_DESC(max_sectors,
  68        "Maximum number of sectors per IO command");
  69
  70static int msix_disable;
  71module_param(msix_disable, int, S_IRUGO);
  72MODULE_PARM_DESC(msix_disable, "Disable MSI-X interrupt handling. Default: 0");
  73
  74static unsigned int msix_vectors;
  75module_param(msix_vectors, int, S_IRUGO);
  76MODULE_PARM_DESC(msix_vectors, "MSI-X max vector count. Default: Set by FW");
  77
  78static int allow_vf_ioctls;
  79module_param(allow_vf_ioctls, int, S_IRUGO);
  80MODULE_PARM_DESC(allow_vf_ioctls, "Allow ioctls in SR-IOV VF mode. Default: 0");
  81
  82static int throttlequeuedepth = MEGASAS_THROTTLE_QUEUE_DEPTH;
  83module_param(throttlequeuedepth, int, S_IRUGO);
  84MODULE_PARM_DESC(throttlequeuedepth,
  85        "Adapter queue depth when throttled due to I/O timeout. Default: 16");
  86
  87int resetwaittime = MEGASAS_RESET_WAIT_TIME;
  88module_param(resetwaittime, int, S_IRUGO);
  89MODULE_PARM_DESC(resetwaittime, "Wait time in seconds after I/O timeout "
  90                 "before resetting adapter. Default: 180");
  91
  92MODULE_LICENSE("GPL");
  93MODULE_VERSION(MEGASAS_VERSION);
  94MODULE_AUTHOR("megaraidlinux@lsi.com");
  95MODULE_DESCRIPTION("LSI MegaRAID SAS Driver");
  96
  97int megasas_transition_to_ready(struct megasas_instance *instance, int ocr);
  98static int megasas_get_pd_list(struct megasas_instance *instance);
  99static int megasas_ld_list_query(struct megasas_instance *instance,
 100                                 u8 query_type);
 101static int megasas_issue_init_mfi(struct megasas_instance *instance);
 102static int megasas_register_aen(struct megasas_instance *instance,
 103                                u32 seq_num, u32 class_locale_word);
 104/*
 105 * PCI ID table for all supported controllers
 106 */
 107static struct pci_device_id megasas_pci_table[] = {
 108
 109        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1064R)},
 110        /* xscale IOP */
 111        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078R)},
 112        /* ppc IOP */
 113        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078DE)},
 114        /* ppc IOP */
 115        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS1078GEN2)},
 116        /* gen2*/
 117        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0079GEN2)},
 118        /* gen2*/
 119        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0073SKINNY)},
 120        /* skinny*/
 121        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_SAS0071SKINNY)},
 122        /* skinny*/
 123        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_VERDE_ZCR)},
 124        /* xscale IOP, vega */
 125        {PCI_DEVICE(PCI_VENDOR_ID_DELL, PCI_DEVICE_ID_DELL_PERC5)},
 126        /* xscale IOP */
 127        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FUSION)},
 128        /* Fusion */
 129        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_PLASMA)},
 130        /* Plasma */
 131        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_INVADER)},
 132        /* Invader */
 133        {PCI_DEVICE(PCI_VENDOR_ID_LSI_LOGIC, PCI_DEVICE_ID_LSI_FURY)},
 134        /* Fury */
 135        {}
 136};
 137
 138MODULE_DEVICE_TABLE(pci, megasas_pci_table);
 139
 140static int megasas_mgmt_majorno;
 141struct megasas_mgmt_info megasas_mgmt_info;
 142static struct fasync_struct *megasas_async_queue;
 143static DEFINE_MUTEX(megasas_async_queue_mutex);
 144
 145static int megasas_poll_wait_aen;
 146static DECLARE_WAIT_QUEUE_HEAD(megasas_poll_wait);
 147static u32 support_poll_for_event;
 148u32 megasas_dbg_lvl;
 149static u32 support_device_change;
 150
 151/* define lock for aen poll */
 152spinlock_t poll_aen_lock;
 153
 154void
 155megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
 156                     u8 alt_status);
 157static u32
 158megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs);
 159static int
 160megasas_adp_reset_gen2(struct megasas_instance *instance,
 161                       struct megasas_register_set __iomem *reg_set);
 162static irqreturn_t megasas_isr(int irq, void *devp);
 163static u32
 164megasas_init_adapter_mfi(struct megasas_instance *instance);
 165u32
 166megasas_build_and_issue_cmd(struct megasas_instance *instance,
 167                            struct scsi_cmnd *scmd);
 168static void megasas_complete_cmd_dpc(unsigned long instance_addr);
 169void
 170megasas_release_fusion(struct megasas_instance *instance);
 171int
 172megasas_ioc_init_fusion(struct megasas_instance *instance);
 173void
 174megasas_free_cmds_fusion(struct megasas_instance *instance);
 175u8
 176megasas_get_map_info(struct megasas_instance *instance);
 177int
 178megasas_sync_map_info(struct megasas_instance *instance);
 179int
 180wait_and_poll(struct megasas_instance *instance, struct megasas_cmd *cmd,
 181        int seconds);
 182void megasas_reset_reply_desc(struct megasas_instance *instance);
 183int megasas_reset_fusion(struct Scsi_Host *shost, int iotimeout);
 184void megasas_fusion_ocr_wq(struct work_struct *work);
 185static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
 186                                         int initial);
 187int megasas_check_mpio_paths(struct megasas_instance *instance,
 188                             struct scsi_cmnd *scmd);
 189
 190void
 191megasas_issue_dcmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
 192{
 193        instance->instancet->fire_cmd(instance,
 194                cmd->frame_phys_addr, 0, instance->reg_set);
 195}
 196
 197/**
 198 * megasas_get_cmd -    Get a command from the free pool
 199 * @instance:           Adapter soft state
 200 *
 201 * Returns a free command from the pool
 202 */
 203struct megasas_cmd *megasas_get_cmd(struct megasas_instance
 204                                                  *instance)
 205{
 206        unsigned long flags;
 207        struct megasas_cmd *cmd = NULL;
 208
 209        spin_lock_irqsave(&instance->cmd_pool_lock, flags);
 210
 211        if (!list_empty(&instance->cmd_pool)) {
 212                cmd = list_entry((&instance->cmd_pool)->next,
 213                                 struct megasas_cmd, list);
 214                list_del_init(&cmd->list);
 215        } else {
 216                printk(KERN_ERR "megasas: Command pool empty!\n");
 217        }
 218
 219        spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
 220        return cmd;
 221}
 222
 223/**
 224 * megasas_return_cmd - Return a cmd to free command pool
 225 * @instance:           Adapter soft state
 226 * @cmd:                Command packet to be returned to free command pool
 227 */
 228inline void
 229megasas_return_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd)
 230{
 231        unsigned long flags;
 232
 233        spin_lock_irqsave(&instance->cmd_pool_lock, flags);
 234
 235        cmd->scmd = NULL;
 236        cmd->frame_count = 0;
 237        if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
 238            (instance->pdev->device != PCI_DEVICE_ID_LSI_PLASMA) &&
 239            (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
 240            (instance->pdev->device != PCI_DEVICE_ID_LSI_FURY) &&
 241            (reset_devices))
 242                cmd->frame->hdr.cmd = MFI_CMD_INVALID;
 243        list_add_tail(&cmd->list, &instance->cmd_pool);
 244
 245        spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
 246}
 247
 248
 249/**
 250*       The following functions are defined for xscale
 251*       (deviceid : 1064R, PERC5) controllers
 252*/
 253
 254/**
 255 * megasas_enable_intr_xscale - Enables interrupts
 256 * @regs:                       MFI register set
 257 */
 258static inline void
 259megasas_enable_intr_xscale(struct megasas_instance *instance)
 260{
 261        struct megasas_register_set __iomem *regs;
 262        regs = instance->reg_set;
 263        writel(0, &(regs)->outbound_intr_mask);
 264
 265        /* Dummy readl to force pci flush */
 266        readl(&regs->outbound_intr_mask);
 267}
 268
 269/**
 270 * megasas_disable_intr_xscale -Disables interrupt
 271 * @regs:                       MFI register set
 272 */
 273static inline void
 274megasas_disable_intr_xscale(struct megasas_instance *instance)
 275{
 276        struct megasas_register_set __iomem *regs;
 277        u32 mask = 0x1f;
 278        regs = instance->reg_set;
 279        writel(mask, &regs->outbound_intr_mask);
 280        /* Dummy readl to force pci flush */
 281        readl(&regs->outbound_intr_mask);
 282}
 283
 284/**
 285 * megasas_read_fw_status_reg_xscale - returns the current FW status value
 286 * @regs:                       MFI register set
 287 */
 288static u32
 289megasas_read_fw_status_reg_xscale(struct megasas_register_set __iomem * regs)
 290{
 291        return readl(&(regs)->outbound_msg_0);
 292}
 293/**
 294 * megasas_clear_interrupt_xscale -     Check & clear interrupt
 295 * @regs:                               MFI register set
 296 */
 297static int
 298megasas_clear_intr_xscale(struct megasas_register_set __iomem * regs)
 299{
 300        u32 status;
 301        u32 mfiStatus = 0;
 302        /*
 303         * Check if it is our interrupt
 304         */
 305        status = readl(&regs->outbound_intr_status);
 306
 307        if (status & MFI_OB_INTR_STATUS_MASK)
 308                mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 309        if (status & MFI_XSCALE_OMR0_CHANGE_INTERRUPT)
 310                mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 311
 312        /*
 313         * Clear the interrupt by writing back the same value
 314         */
 315        if (mfiStatus)
 316                writel(status, &regs->outbound_intr_status);
 317
 318        /* Dummy readl to force pci flush */
 319        readl(&regs->outbound_intr_status);
 320
 321        return mfiStatus;
 322}
 323
 324/**
 325 * megasas_fire_cmd_xscale -    Sends command to the FW
 326 * @frame_phys_addr :           Physical address of cmd
 327 * @frame_count :               Number of frames for the command
 328 * @regs :                      MFI register set
 329 */
 330static inline void
 331megasas_fire_cmd_xscale(struct megasas_instance *instance,
 332                dma_addr_t frame_phys_addr,
 333                u32 frame_count,
 334                struct megasas_register_set __iomem *regs)
 335{
 336        unsigned long flags;
 337        spin_lock_irqsave(&instance->hba_lock, flags);
 338        writel((frame_phys_addr >> 3)|(frame_count),
 339               &(regs)->inbound_queue_port);
 340        spin_unlock_irqrestore(&instance->hba_lock, flags);
 341}
 342
 343/**
 344 * megasas_adp_reset_xscale -  For controller reset
 345 * @regs:                              MFI register set
 346 */
 347static int
 348megasas_adp_reset_xscale(struct megasas_instance *instance,
 349        struct megasas_register_set __iomem *regs)
 350{
 351        u32 i;
 352        u32 pcidata;
 353        writel(MFI_ADP_RESET, &regs->inbound_doorbell);
 354
 355        for (i = 0; i < 3; i++)
 356                msleep(1000); /* sleep for 3 secs */
 357        pcidata  = 0;
 358        pci_read_config_dword(instance->pdev, MFI_1068_PCSR_OFFSET, &pcidata);
 359        printk(KERN_NOTICE "pcidata = %x\n", pcidata);
 360        if (pcidata & 0x2) {
 361                printk(KERN_NOTICE "mfi 1068 offset read=%x\n", pcidata);
 362                pcidata &= ~0x2;
 363                pci_write_config_dword(instance->pdev,
 364                                MFI_1068_PCSR_OFFSET, pcidata);
 365
 366                for (i = 0; i < 2; i++)
 367                        msleep(1000); /* need to wait 2 secs again */
 368
 369                pcidata  = 0;
 370                pci_read_config_dword(instance->pdev,
 371                                MFI_1068_FW_HANDSHAKE_OFFSET, &pcidata);
 372                printk(KERN_NOTICE "1068 offset handshake read=%x\n", pcidata);
 373                if ((pcidata & 0xffff0000) == MFI_1068_FW_READY) {
 374                        printk(KERN_NOTICE "1068 offset pcidt=%x\n", pcidata);
 375                        pcidata = 0;
 376                        pci_write_config_dword(instance->pdev,
 377                                MFI_1068_FW_HANDSHAKE_OFFSET, pcidata);
 378                }
 379        }
 380        return 0;
 381}
 382
 383/**
 384 * megasas_check_reset_xscale - For controller reset check
 385 * @regs:                               MFI register set
 386 */
 387static int
 388megasas_check_reset_xscale(struct megasas_instance *instance,
 389                struct megasas_register_set __iomem *regs)
 390{
 391
 392        if ((instance->adprecovery != MEGASAS_HBA_OPERATIONAL) &&
 393            (le32_to_cpu(*instance->consumer) ==
 394                MEGASAS_ADPRESET_INPROG_SIGN))
 395                return 1;
 396        return 0;
 397}
 398
 399static struct megasas_instance_template megasas_instance_template_xscale = {
 400
 401        .fire_cmd = megasas_fire_cmd_xscale,
 402        .enable_intr = megasas_enable_intr_xscale,
 403        .disable_intr = megasas_disable_intr_xscale,
 404        .clear_intr = megasas_clear_intr_xscale,
 405        .read_fw_status_reg = megasas_read_fw_status_reg_xscale,
 406        .adp_reset = megasas_adp_reset_xscale,
 407        .check_reset = megasas_check_reset_xscale,
 408        .service_isr = megasas_isr,
 409        .tasklet = megasas_complete_cmd_dpc,
 410        .init_adapter = megasas_init_adapter_mfi,
 411        .build_and_issue_cmd = megasas_build_and_issue_cmd,
 412        .issue_dcmd = megasas_issue_dcmd,
 413};
 414
 415/**
 416*       This is the end of set of functions & definitions specific
 417*       to xscale (deviceid : 1064R, PERC5) controllers
 418*/
 419
 420/**
 421*       The following functions are defined for ppc (deviceid : 0x60)
 422*       controllers
 423*/
 424
 425/**
 426 * megasas_enable_intr_ppc -    Enables interrupts
 427 * @regs:                       MFI register set
 428 */
 429static inline void
 430megasas_enable_intr_ppc(struct megasas_instance *instance)
 431{
 432        struct megasas_register_set __iomem *regs;
 433        regs = instance->reg_set;
 434        writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
 435
 436        writel(~0x80000000, &(regs)->outbound_intr_mask);
 437
 438        /* Dummy readl to force pci flush */
 439        readl(&regs->outbound_intr_mask);
 440}
 441
 442/**
 443 * megasas_disable_intr_ppc -   Disable interrupt
 444 * @regs:                       MFI register set
 445 */
 446static inline void
 447megasas_disable_intr_ppc(struct megasas_instance *instance)
 448{
 449        struct megasas_register_set __iomem *regs;
 450        u32 mask = 0xFFFFFFFF;
 451        regs = instance->reg_set;
 452        writel(mask, &regs->outbound_intr_mask);
 453        /* Dummy readl to force pci flush */
 454        readl(&regs->outbound_intr_mask);
 455}
 456
 457/**
 458 * megasas_read_fw_status_reg_ppc - returns the current FW status value
 459 * @regs:                       MFI register set
 460 */
 461static u32
 462megasas_read_fw_status_reg_ppc(struct megasas_register_set __iomem * regs)
 463{
 464        return readl(&(regs)->outbound_scratch_pad);
 465}
 466
 467/**
 468 * megasas_clear_interrupt_ppc -        Check & clear interrupt
 469 * @regs:                               MFI register set
 470 */
 471static int
 472megasas_clear_intr_ppc(struct megasas_register_set __iomem * regs)
 473{
 474        u32 status, mfiStatus = 0;
 475
 476        /*
 477         * Check if it is our interrupt
 478         */
 479        status = readl(&regs->outbound_intr_status);
 480
 481        if (status & MFI_REPLY_1078_MESSAGE_INTERRUPT)
 482                mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 483
 484        if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT)
 485                mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 486
 487        /*
 488         * Clear the interrupt by writing back the same value
 489         */
 490        writel(status, &regs->outbound_doorbell_clear);
 491
 492        /* Dummy readl to force pci flush */
 493        readl(&regs->outbound_doorbell_clear);
 494
 495        return mfiStatus;
 496}
 497
 498/**
 499 * megasas_fire_cmd_ppc -       Sends command to the FW
 500 * @frame_phys_addr :           Physical address of cmd
 501 * @frame_count :               Number of frames for the command
 502 * @regs :                      MFI register set
 503 */
 504static inline void
 505megasas_fire_cmd_ppc(struct megasas_instance *instance,
 506                dma_addr_t frame_phys_addr,
 507                u32 frame_count,
 508                struct megasas_register_set __iomem *regs)
 509{
 510        unsigned long flags;
 511        spin_lock_irqsave(&instance->hba_lock, flags);
 512        writel((frame_phys_addr | (frame_count<<1))|1,
 513                        &(regs)->inbound_queue_port);
 514        spin_unlock_irqrestore(&instance->hba_lock, flags);
 515}
 516
 517/**
 518 * megasas_check_reset_ppc -    For controller reset check
 519 * @regs:                               MFI register set
 520 */
 521static int
 522megasas_check_reset_ppc(struct megasas_instance *instance,
 523                        struct megasas_register_set __iomem *regs)
 524{
 525        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
 526                return 1;
 527
 528        return 0;
 529}
 530
 531static struct megasas_instance_template megasas_instance_template_ppc = {
 532
 533        .fire_cmd = megasas_fire_cmd_ppc,
 534        .enable_intr = megasas_enable_intr_ppc,
 535        .disable_intr = megasas_disable_intr_ppc,
 536        .clear_intr = megasas_clear_intr_ppc,
 537        .read_fw_status_reg = megasas_read_fw_status_reg_ppc,
 538        .adp_reset = megasas_adp_reset_xscale,
 539        .check_reset = megasas_check_reset_ppc,
 540        .service_isr = megasas_isr,
 541        .tasklet = megasas_complete_cmd_dpc,
 542        .init_adapter = megasas_init_adapter_mfi,
 543        .build_and_issue_cmd = megasas_build_and_issue_cmd,
 544        .issue_dcmd = megasas_issue_dcmd,
 545};
 546
 547/**
 548 * megasas_enable_intr_skinny - Enables interrupts
 549 * @regs:                       MFI register set
 550 */
 551static inline void
 552megasas_enable_intr_skinny(struct megasas_instance *instance)
 553{
 554        struct megasas_register_set __iomem *regs;
 555        regs = instance->reg_set;
 556        writel(0xFFFFFFFF, &(regs)->outbound_intr_mask);
 557
 558        writel(~MFI_SKINNY_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
 559
 560        /* Dummy readl to force pci flush */
 561        readl(&regs->outbound_intr_mask);
 562}
 563
 564/**
 565 * megasas_disable_intr_skinny -        Disables interrupt
 566 * @regs:                       MFI register set
 567 */
 568static inline void
 569megasas_disable_intr_skinny(struct megasas_instance *instance)
 570{
 571        struct megasas_register_set __iomem *regs;
 572        u32 mask = 0xFFFFFFFF;
 573        regs = instance->reg_set;
 574        writel(mask, &regs->outbound_intr_mask);
 575        /* Dummy readl to force pci flush */
 576        readl(&regs->outbound_intr_mask);
 577}
 578
 579/**
 580 * megasas_read_fw_status_reg_skinny - returns the current FW status value
 581 * @regs:                       MFI register set
 582 */
 583static u32
 584megasas_read_fw_status_reg_skinny(struct megasas_register_set __iomem *regs)
 585{
 586        return readl(&(regs)->outbound_scratch_pad);
 587}
 588
 589/**
 590 * megasas_clear_interrupt_skinny -     Check & clear interrupt
 591 * @regs:                               MFI register set
 592 */
 593static int
 594megasas_clear_intr_skinny(struct megasas_register_set __iomem *regs)
 595{
 596        u32 status;
 597        u32 mfiStatus = 0;
 598
 599        /*
 600         * Check if it is our interrupt
 601         */
 602        status = readl(&regs->outbound_intr_status);
 603
 604        if (!(status & MFI_SKINNY_ENABLE_INTERRUPT_MASK)) {
 605                return 0;
 606        }
 607
 608        /*
 609         * Check if it is our interrupt
 610         */
 611        if ((megasas_read_fw_status_reg_skinny(regs) & MFI_STATE_MASK) ==
 612            MFI_STATE_FAULT) {
 613                mfiStatus = MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 614        } else
 615                mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 616
 617        /*
 618         * Clear the interrupt by writing back the same value
 619         */
 620        writel(status, &regs->outbound_intr_status);
 621
 622        /*
 623        * dummy read to flush PCI
 624        */
 625        readl(&regs->outbound_intr_status);
 626
 627        return mfiStatus;
 628}
 629
 630/**
 631 * megasas_fire_cmd_skinny -    Sends command to the FW
 632 * @frame_phys_addr :           Physical address of cmd
 633 * @frame_count :               Number of frames for the command
 634 * @regs :                      MFI register set
 635 */
 636static inline void
 637megasas_fire_cmd_skinny(struct megasas_instance *instance,
 638                        dma_addr_t frame_phys_addr,
 639                        u32 frame_count,
 640                        struct megasas_register_set __iomem *regs)
 641{
 642        unsigned long flags;
 643        spin_lock_irqsave(&instance->hba_lock, flags);
 644        writel(upper_32_bits(frame_phys_addr),
 645               &(regs)->inbound_high_queue_port);
 646        writel((lower_32_bits(frame_phys_addr) | (frame_count<<1))|1,
 647               &(regs)->inbound_low_queue_port);
 648        spin_unlock_irqrestore(&instance->hba_lock, flags);
 649}
 650
 651/**
 652 * megasas_check_reset_skinny - For controller reset check
 653 * @regs:                               MFI register set
 654 */
 655static int
 656megasas_check_reset_skinny(struct megasas_instance *instance,
 657                                struct megasas_register_set __iomem *regs)
 658{
 659        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL)
 660                return 1;
 661
 662        return 0;
 663}
 664
 665static struct megasas_instance_template megasas_instance_template_skinny = {
 666
 667        .fire_cmd = megasas_fire_cmd_skinny,
 668        .enable_intr = megasas_enable_intr_skinny,
 669        .disable_intr = megasas_disable_intr_skinny,
 670        .clear_intr = megasas_clear_intr_skinny,
 671        .read_fw_status_reg = megasas_read_fw_status_reg_skinny,
 672        .adp_reset = megasas_adp_reset_gen2,
 673        .check_reset = megasas_check_reset_skinny,
 674        .service_isr = megasas_isr,
 675        .tasklet = megasas_complete_cmd_dpc,
 676        .init_adapter = megasas_init_adapter_mfi,
 677        .build_and_issue_cmd = megasas_build_and_issue_cmd,
 678        .issue_dcmd = megasas_issue_dcmd,
 679};
 680
 681
 682/**
 683*       The following functions are defined for gen2 (deviceid : 0x78 0x79)
 684*       controllers
 685*/
 686
 687/**
 688 * megasas_enable_intr_gen2 -  Enables interrupts
 689 * @regs:                      MFI register set
 690 */
 691static inline void
 692megasas_enable_intr_gen2(struct megasas_instance *instance)
 693{
 694        struct megasas_register_set __iomem *regs;
 695        regs = instance->reg_set;
 696        writel(0xFFFFFFFF, &(regs)->outbound_doorbell_clear);
 697
 698        /* write ~0x00000005 (4 & 1) to the intr mask*/
 699        writel(~MFI_GEN2_ENABLE_INTERRUPT_MASK, &(regs)->outbound_intr_mask);
 700
 701        /* Dummy readl to force pci flush */
 702        readl(&regs->outbound_intr_mask);
 703}
 704
 705/**
 706 * megasas_disable_intr_gen2 - Disables interrupt
 707 * @regs:                      MFI register set
 708 */
 709static inline void
 710megasas_disable_intr_gen2(struct megasas_instance *instance)
 711{
 712        struct megasas_register_set __iomem *regs;
 713        u32 mask = 0xFFFFFFFF;
 714        regs = instance->reg_set;
 715        writel(mask, &regs->outbound_intr_mask);
 716        /* Dummy readl to force pci flush */
 717        readl(&regs->outbound_intr_mask);
 718}
 719
 720/**
 721 * megasas_read_fw_status_reg_gen2 - returns the current FW status value
 722 * @regs:                      MFI register set
 723 */
 724static u32
 725megasas_read_fw_status_reg_gen2(struct megasas_register_set __iomem *regs)
 726{
 727        return readl(&(regs)->outbound_scratch_pad);
 728}
 729
 730/**
 731 * megasas_clear_interrupt_gen2 -      Check & clear interrupt
 732 * @regs:                              MFI register set
 733 */
 734static int
 735megasas_clear_intr_gen2(struct megasas_register_set __iomem *regs)
 736{
 737        u32 status;
 738        u32 mfiStatus = 0;
 739        /*
 740         * Check if it is our interrupt
 741         */
 742        status = readl(&regs->outbound_intr_status);
 743
 744        if (status & MFI_INTR_FLAG_REPLY_MESSAGE) {
 745                mfiStatus = MFI_INTR_FLAG_REPLY_MESSAGE;
 746        }
 747        if (status & MFI_G2_OUTBOUND_DOORBELL_CHANGE_INTERRUPT) {
 748                mfiStatus |= MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE;
 749        }
 750
 751        /*
 752         * Clear the interrupt by writing back the same value
 753         */
 754        if (mfiStatus)
 755                writel(status, &regs->outbound_doorbell_clear);
 756
 757        /* Dummy readl to force pci flush */
 758        readl(&regs->outbound_intr_status);
 759
 760        return mfiStatus;
 761}
 762/**
 763 * megasas_fire_cmd_gen2 -     Sends command to the FW
 764 * @frame_phys_addr :          Physical address of cmd
 765 * @frame_count :              Number of frames for the command
 766 * @regs :                     MFI register set
 767 */
 768static inline void
 769megasas_fire_cmd_gen2(struct megasas_instance *instance,
 770                        dma_addr_t frame_phys_addr,
 771                        u32 frame_count,
 772                        struct megasas_register_set __iomem *regs)
 773{
 774        unsigned long flags;
 775        spin_lock_irqsave(&instance->hba_lock, flags);
 776        writel((frame_phys_addr | (frame_count<<1))|1,
 777                        &(regs)->inbound_queue_port);
 778        spin_unlock_irqrestore(&instance->hba_lock, flags);
 779}
 780
 781/**
 782 * megasas_adp_reset_gen2 -     For controller reset
 783 * @regs:                               MFI register set
 784 */
 785static int
 786megasas_adp_reset_gen2(struct megasas_instance *instance,
 787                        struct megasas_register_set __iomem *reg_set)
 788{
 789        u32                     retry = 0 ;
 790        u32                     HostDiag;
 791        u32                     *seq_offset = &reg_set->seq_offset;
 792        u32                     *hostdiag_offset = &reg_set->host_diag;
 793
 794        if (instance->instancet == &megasas_instance_template_skinny) {
 795                seq_offset = &reg_set->fusion_seq_offset;
 796                hostdiag_offset = &reg_set->fusion_host_diag;
 797        }
 798
 799        writel(0, seq_offset);
 800        writel(4, seq_offset);
 801        writel(0xb, seq_offset);
 802        writel(2, seq_offset);
 803        writel(7, seq_offset);
 804        writel(0xd, seq_offset);
 805
 806        msleep(1000);
 807
 808        HostDiag = (u32)readl(hostdiag_offset);
 809
 810        while ( !( HostDiag & DIAG_WRITE_ENABLE) ) {
 811                msleep(100);
 812                HostDiag = (u32)readl(hostdiag_offset);
 813                printk(KERN_NOTICE "RESETGEN2: retry=%x, hostdiag=%x\n",
 814                                        retry, HostDiag);
 815
 816                if (retry++ >= 100)
 817                        return 1;
 818
 819        }
 820
 821        printk(KERN_NOTICE "ADP_RESET_GEN2: HostDiag=%x\n", HostDiag);
 822
 823        writel((HostDiag | DIAG_RESET_ADAPTER), hostdiag_offset);
 824
 825        ssleep(10);
 826
 827        HostDiag = (u32)readl(hostdiag_offset);
 828        while ( ( HostDiag & DIAG_RESET_ADAPTER) ) {
 829                msleep(100);
 830                HostDiag = (u32)readl(hostdiag_offset);
 831                printk(KERN_NOTICE "RESET_GEN2: retry=%x, hostdiag=%x\n",
 832                                retry, HostDiag);
 833
 834                if (retry++ >= 1000)
 835                        return 1;
 836
 837        }
 838        return 0;
 839}
 840
 841/**
 842 * megasas_check_reset_gen2 -   For controller reset check
 843 * @regs:                               MFI register set
 844 */
 845static int
 846megasas_check_reset_gen2(struct megasas_instance *instance,
 847                struct megasas_register_set __iomem *regs)
 848{
 849        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
 850                return 1;
 851        }
 852
 853        return 0;
 854}
 855
 856static struct megasas_instance_template megasas_instance_template_gen2 = {
 857
 858        .fire_cmd = megasas_fire_cmd_gen2,
 859        .enable_intr = megasas_enable_intr_gen2,
 860        .disable_intr = megasas_disable_intr_gen2,
 861        .clear_intr = megasas_clear_intr_gen2,
 862        .read_fw_status_reg = megasas_read_fw_status_reg_gen2,
 863        .adp_reset = megasas_adp_reset_gen2,
 864        .check_reset = megasas_check_reset_gen2,
 865        .service_isr = megasas_isr,
 866        .tasklet = megasas_complete_cmd_dpc,
 867        .init_adapter = megasas_init_adapter_mfi,
 868        .build_and_issue_cmd = megasas_build_and_issue_cmd,
 869        .issue_dcmd = megasas_issue_dcmd,
 870};
 871
 872/**
 873*       This is the end of set of functions & definitions
 874*       specific to gen2 (deviceid : 0x78, 0x79) controllers
 875*/
 876
 877/*
 878 * Template added for TB (Fusion)
 879 */
 880extern struct megasas_instance_template megasas_instance_template_fusion;
 881
 882/**
 883 * megasas_issue_polled -       Issues a polling command
 884 * @instance:                   Adapter soft state
 885 * @cmd:                        Command packet to be issued
 886 *
 887 * For polling, MFI requires the cmd_status to be set to 0xFF before posting.
 888 */
 889int
 890megasas_issue_polled(struct megasas_instance *instance, struct megasas_cmd *cmd)
 891{
 892        int seconds;
 893
 894        struct megasas_header *frame_hdr = &cmd->frame->hdr;
 895
 896        frame_hdr->cmd_status = MFI_CMD_STATUS_POLL_MODE;
 897        frame_hdr->flags |= cpu_to_le16(MFI_FRAME_DONT_POST_IN_REPLY_QUEUE);
 898
 899        /*
 900         * Issue the frame using inbound queue port
 901         */
 902        instance->instancet->issue_dcmd(instance, cmd);
 903
 904        /*
 905         * Wait for cmd_status to change
 906         */
 907        if (instance->requestorId)
 908                seconds = MEGASAS_ROUTINE_WAIT_TIME_VF;
 909        else
 910                seconds = MFI_POLL_TIMEOUT_SECS;
 911        return wait_and_poll(instance, cmd, seconds);
 912}
 913
 914/**
 915 * megasas_issue_blocked_cmd -  Synchronous wrapper around regular FW cmds
 916 * @instance:                   Adapter soft state
 917 * @cmd:                        Command to be issued
 918 * @timeout:                    Timeout in seconds
 919 *
 920 * This function waits on an event for the command to be returned from ISR.
 921 * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
 922 * Used to issue ioctl commands.
 923 */
 924static int
 925megasas_issue_blocked_cmd(struct megasas_instance *instance,
 926                          struct megasas_cmd *cmd, int timeout)
 927{
 928        int ret = 0;
 929        cmd->cmd_status = ENODATA;
 930
 931        instance->instancet->issue_dcmd(instance, cmd);
 932        if (timeout) {
 933                ret = wait_event_timeout(instance->int_cmd_wait_q,
 934                                cmd->cmd_status != ENODATA, timeout * HZ);
 935                if (!ret)
 936                        return 1;
 937        } else
 938                wait_event(instance->int_cmd_wait_q,
 939                                cmd->cmd_status != ENODATA);
 940
 941        return 0;
 942}
 943
 944/**
 945 * megasas_issue_blocked_abort_cmd -    Aborts previously issued cmd
 946 * @instance:                           Adapter soft state
 947 * @cmd_to_abort:                       Previously issued cmd to be aborted
 948 * @timeout:                            Timeout in seconds
 949 *
 950 * MFI firmware can abort previously issued AEN comamnd (automatic event
 951 * notification). The megasas_issue_blocked_abort_cmd() issues such abort
 952 * cmd and waits for return status.
 953 * Max wait time is MEGASAS_INTERNAL_CMD_WAIT_TIME secs
 954 */
 955static int
 956megasas_issue_blocked_abort_cmd(struct megasas_instance *instance,
 957                                struct megasas_cmd *cmd_to_abort, int timeout)
 958{
 959        struct megasas_cmd *cmd;
 960        struct megasas_abort_frame *abort_fr;
 961        int ret = 0;
 962
 963        cmd = megasas_get_cmd(instance);
 964
 965        if (!cmd)
 966                return -1;
 967
 968        abort_fr = &cmd->frame->abort;
 969
 970        /*
 971         * Prepare and issue the abort frame
 972         */
 973        abort_fr->cmd = MFI_CMD_ABORT;
 974        abort_fr->cmd_status = 0xFF;
 975        abort_fr->flags = cpu_to_le16(0);
 976        abort_fr->abort_context = cpu_to_le32(cmd_to_abort->index);
 977        abort_fr->abort_mfi_phys_addr_lo =
 978                cpu_to_le32(lower_32_bits(cmd_to_abort->frame_phys_addr));
 979        abort_fr->abort_mfi_phys_addr_hi =
 980                cpu_to_le32(upper_32_bits(cmd_to_abort->frame_phys_addr));
 981
 982        cmd->sync_cmd = 1;
 983        cmd->cmd_status = 0xFF;
 984
 985        instance->instancet->issue_dcmd(instance, cmd);
 986
 987        if (timeout) {
 988                ret = wait_event_timeout(instance->abort_cmd_wait_q,
 989                                cmd->cmd_status != ENODATA, timeout * HZ);
 990                if (!ret) {
 991                        dev_err(&instance->pdev->dev, "Command timedout"
 992                                "from %s\n", __func__);
 993                        return 1;
 994                }
 995        } else
 996                wait_event(instance->abort_cmd_wait_q,
 997                                cmd->cmd_status != ENODATA);
 998
 999        cmd->sync_cmd = 0;
1000
1001        megasas_return_cmd(instance, cmd);
1002        return 0;
1003}
1004
1005/**
1006 * megasas_make_sgl32 - Prepares 32-bit SGL
1007 * @instance:           Adapter soft state
1008 * @scp:                SCSI command from the mid-layer
1009 * @mfi_sgl:            SGL to be filled in
1010 *
1011 * If successful, this function returns the number of SG elements. Otherwise,
1012 * it returnes -1.
1013 */
1014static int
1015megasas_make_sgl32(struct megasas_instance *instance, struct scsi_cmnd *scp,
1016                   union megasas_sgl *mfi_sgl)
1017{
1018        int i;
1019        int sge_count;
1020        struct scatterlist *os_sgl;
1021
1022        sge_count = scsi_dma_map(scp);
1023        BUG_ON(sge_count < 0);
1024
1025        if (sge_count) {
1026                scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1027                        mfi_sgl->sge32[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1028                        mfi_sgl->sge32[i].phys_addr = cpu_to_le32(sg_dma_address(os_sgl));
1029                }
1030        }
1031        return sge_count;
1032}
1033
1034/**
1035 * megasas_make_sgl64 - Prepares 64-bit SGL
1036 * @instance:           Adapter soft state
1037 * @scp:                SCSI command from the mid-layer
1038 * @mfi_sgl:            SGL to be filled in
1039 *
1040 * If successful, this function returns the number of SG elements. Otherwise,
1041 * it returnes -1.
1042 */
1043static int
1044megasas_make_sgl64(struct megasas_instance *instance, struct scsi_cmnd *scp,
1045                   union megasas_sgl *mfi_sgl)
1046{
1047        int i;
1048        int sge_count;
1049        struct scatterlist *os_sgl;
1050
1051        sge_count = scsi_dma_map(scp);
1052        BUG_ON(sge_count < 0);
1053
1054        if (sge_count) {
1055                scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1056                        mfi_sgl->sge64[i].length = cpu_to_le32(sg_dma_len(os_sgl));
1057                        mfi_sgl->sge64[i].phys_addr = cpu_to_le64(sg_dma_address(os_sgl));
1058                }
1059        }
1060        return sge_count;
1061}
1062
1063/**
1064 * megasas_make_sgl_skinny - Prepares IEEE SGL
1065 * @instance:           Adapter soft state
1066 * @scp:                SCSI command from the mid-layer
1067 * @mfi_sgl:            SGL to be filled in
1068 *
1069 * If successful, this function returns the number of SG elements. Otherwise,
1070 * it returnes -1.
1071 */
1072static int
1073megasas_make_sgl_skinny(struct megasas_instance *instance,
1074                struct scsi_cmnd *scp, union megasas_sgl *mfi_sgl)
1075{
1076        int i;
1077        int sge_count;
1078        struct scatterlist *os_sgl;
1079
1080        sge_count = scsi_dma_map(scp);
1081
1082        if (sge_count) {
1083                scsi_for_each_sg(scp, os_sgl, sge_count, i) {
1084                        mfi_sgl->sge_skinny[i].length =
1085                                cpu_to_le32(sg_dma_len(os_sgl));
1086                        mfi_sgl->sge_skinny[i].phys_addr =
1087                                cpu_to_le64(sg_dma_address(os_sgl));
1088                        mfi_sgl->sge_skinny[i].flag = cpu_to_le32(0);
1089                }
1090        }
1091        return sge_count;
1092}
1093
1094 /**
1095 * megasas_get_frame_count - Computes the number of frames
1096 * @frame_type          : type of frame- io or pthru frame
1097 * @sge_count           : number of sg elements
1098 *
1099 * Returns the number of frames required for numnber of sge's (sge_count)
1100 */
1101
1102static u32 megasas_get_frame_count(struct megasas_instance *instance,
1103                        u8 sge_count, u8 frame_type)
1104{
1105        int num_cnt;
1106        int sge_bytes;
1107        u32 sge_sz;
1108        u32 frame_count=0;
1109
1110        sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
1111            sizeof(struct megasas_sge32);
1112
1113        if (instance->flag_ieee) {
1114                sge_sz = sizeof(struct megasas_sge_skinny);
1115        }
1116
1117        /*
1118         * Main frame can contain 2 SGEs for 64-bit SGLs and
1119         * 3 SGEs for 32-bit SGLs for ldio &
1120         * 1 SGEs for 64-bit SGLs and
1121         * 2 SGEs for 32-bit SGLs for pthru frame
1122         */
1123        if (unlikely(frame_type == PTHRU_FRAME)) {
1124                if (instance->flag_ieee == 1) {
1125                        num_cnt = sge_count - 1;
1126                } else if (IS_DMA64)
1127                        num_cnt = sge_count - 1;
1128                else
1129                        num_cnt = sge_count - 2;
1130        } else {
1131                if (instance->flag_ieee == 1) {
1132                        num_cnt = sge_count - 1;
1133                } else if (IS_DMA64)
1134                        num_cnt = sge_count - 2;
1135                else
1136                        num_cnt = sge_count - 3;
1137        }
1138
1139        if(num_cnt>0){
1140                sge_bytes = sge_sz * num_cnt;
1141
1142                frame_count = (sge_bytes / MEGAMFI_FRAME_SIZE) +
1143                    ((sge_bytes % MEGAMFI_FRAME_SIZE) ? 1 : 0) ;
1144        }
1145        /* Main frame */
1146        frame_count +=1;
1147
1148        if (frame_count > 7)
1149                frame_count = 8;
1150        return frame_count;
1151}
1152
1153/**
1154 * megasas_build_dcdb - Prepares a direct cdb (DCDB) command
1155 * @instance:           Adapter soft state
1156 * @scp:                SCSI command
1157 * @cmd:                Command to be prepared in
1158 *
1159 * This function prepares CDB commands. These are typcially pass-through
1160 * commands to the devices.
1161 */
1162static int
1163megasas_build_dcdb(struct megasas_instance *instance, struct scsi_cmnd *scp,
1164                   struct megasas_cmd *cmd)
1165{
1166        u32 is_logical;
1167        u32 device_id;
1168        u16 flags = 0;
1169        struct megasas_pthru_frame *pthru;
1170
1171        is_logical = MEGASAS_IS_LOGICAL(scp);
1172        device_id = MEGASAS_DEV_INDEX(instance, scp);
1173        pthru = (struct megasas_pthru_frame *)cmd->frame;
1174
1175        if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1176                flags = MFI_FRAME_DIR_WRITE;
1177        else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1178                flags = MFI_FRAME_DIR_READ;
1179        else if (scp->sc_data_direction == PCI_DMA_NONE)
1180                flags = MFI_FRAME_DIR_NONE;
1181
1182        if (instance->flag_ieee == 1) {
1183                flags |= MFI_FRAME_IEEE;
1184        }
1185
1186        /*
1187         * Prepare the DCDB frame
1188         */
1189        pthru->cmd = (is_logical) ? MFI_CMD_LD_SCSI_IO : MFI_CMD_PD_SCSI_IO;
1190        pthru->cmd_status = 0x0;
1191        pthru->scsi_status = 0x0;
1192        pthru->target_id = device_id;
1193        pthru->lun = scp->device->lun;
1194        pthru->cdb_len = scp->cmd_len;
1195        pthru->timeout = 0;
1196        pthru->pad_0 = 0;
1197        pthru->flags = cpu_to_le16(flags);
1198        pthru->data_xfer_len = cpu_to_le32(scsi_bufflen(scp));
1199
1200        memcpy(pthru->cdb, scp->cmnd, scp->cmd_len);
1201
1202        /*
1203        * If the command is for the tape device, set the
1204        * pthru timeout to the os layer timeout value.
1205        */
1206        if (scp->device->type == TYPE_TAPE) {
1207                if ((scp->request->timeout / HZ) > 0xFFFF)
1208                        pthru->timeout = 0xFFFF;
1209                else
1210                        pthru->timeout = cpu_to_le16(scp->request->timeout / HZ);
1211        }
1212
1213        /*
1214         * Construct SGL
1215         */
1216        if (instance->flag_ieee == 1) {
1217                pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1218                pthru->sge_count = megasas_make_sgl_skinny(instance, scp,
1219                                                      &pthru->sgl);
1220        } else if (IS_DMA64) {
1221                pthru->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1222                pthru->sge_count = megasas_make_sgl64(instance, scp,
1223                                                      &pthru->sgl);
1224        } else
1225                pthru->sge_count = megasas_make_sgl32(instance, scp,
1226                                                      &pthru->sgl);
1227
1228        if (pthru->sge_count > instance->max_num_sge) {
1229                printk(KERN_ERR "megasas: DCDB two many SGE NUM=%x\n",
1230                        pthru->sge_count);
1231                return 0;
1232        }
1233
1234        /*
1235         * Sense info specific
1236         */
1237        pthru->sense_len = SCSI_SENSE_BUFFERSIZE;
1238        pthru->sense_buf_phys_addr_hi =
1239                cpu_to_le32(upper_32_bits(cmd->sense_phys_addr));
1240        pthru->sense_buf_phys_addr_lo =
1241                cpu_to_le32(lower_32_bits(cmd->sense_phys_addr));
1242
1243        /*
1244         * Compute the total number of frames this command consumes. FW uses
1245         * this number to pull sufficient number of frames from host memory.
1246         */
1247        cmd->frame_count = megasas_get_frame_count(instance, pthru->sge_count,
1248                                                        PTHRU_FRAME);
1249
1250        return cmd->frame_count;
1251}
1252
1253/**
1254 * megasas_build_ldio - Prepares IOs to logical devices
1255 * @instance:           Adapter soft state
1256 * @scp:                SCSI command
1257 * @cmd:                Command to be prepared
1258 *
1259 * Frames (and accompanying SGLs) for regular SCSI IOs use this function.
1260 */
1261static int
1262megasas_build_ldio(struct megasas_instance *instance, struct scsi_cmnd *scp,
1263                   struct megasas_cmd *cmd)
1264{
1265        u32 device_id;
1266        u8 sc = scp->cmnd[0];
1267        u16 flags = 0;
1268        struct megasas_io_frame *ldio;
1269
1270        device_id = MEGASAS_DEV_INDEX(instance, scp);
1271        ldio = (struct megasas_io_frame *)cmd->frame;
1272
1273        if (scp->sc_data_direction == PCI_DMA_TODEVICE)
1274                flags = MFI_FRAME_DIR_WRITE;
1275        else if (scp->sc_data_direction == PCI_DMA_FROMDEVICE)
1276                flags = MFI_FRAME_DIR_READ;
1277
1278        if (instance->flag_ieee == 1) {
1279                flags |= MFI_FRAME_IEEE;
1280        }
1281
1282        /*
1283         * Prepare the Logical IO frame: 2nd bit is zero for all read cmds
1284         */
1285        ldio->cmd = (sc & 0x02) ? MFI_CMD_LD_WRITE : MFI_CMD_LD_READ;
1286        ldio->cmd_status = 0x0;
1287        ldio->scsi_status = 0x0;
1288        ldio->target_id = device_id;
1289        ldio->timeout = 0;
1290        ldio->reserved_0 = 0;
1291        ldio->pad_0 = 0;
1292        ldio->flags = cpu_to_le16(flags);
1293        ldio->start_lba_hi = 0;
1294        ldio->access_byte = (scp->cmd_len != 6) ? scp->cmnd[1] : 0;
1295
1296        /*
1297         * 6-byte READ(0x08) or WRITE(0x0A) cdb
1298         */
1299        if (scp->cmd_len == 6) {
1300                ldio->lba_count = cpu_to_le32((u32) scp->cmnd[4]);
1301                ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[1] << 16) |
1302                                                 ((u32) scp->cmnd[2] << 8) |
1303                                                 (u32) scp->cmnd[3]);
1304
1305                ldio->start_lba_lo &= cpu_to_le32(0x1FFFFF);
1306        }
1307
1308        /*
1309         * 10-byte READ(0x28) or WRITE(0x2A) cdb
1310         */
1311        else if (scp->cmd_len == 10) {
1312                ldio->lba_count = cpu_to_le32((u32) scp->cmnd[8] |
1313                                              ((u32) scp->cmnd[7] << 8));
1314                ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1315                                                 ((u32) scp->cmnd[3] << 16) |
1316                                                 ((u32) scp->cmnd[4] << 8) |
1317                                                 (u32) scp->cmnd[5]);
1318        }
1319
1320        /*
1321         * 12-byte READ(0xA8) or WRITE(0xAA) cdb
1322         */
1323        else if (scp->cmd_len == 12) {
1324                ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1325                                              ((u32) scp->cmnd[7] << 16) |
1326                                              ((u32) scp->cmnd[8] << 8) |
1327                                              (u32) scp->cmnd[9]);
1328
1329                ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1330                                                 ((u32) scp->cmnd[3] << 16) |
1331                                                 ((u32) scp->cmnd[4] << 8) |
1332                                                 (u32) scp->cmnd[5]);
1333        }
1334
1335        /*
1336         * 16-byte READ(0x88) or WRITE(0x8A) cdb
1337         */
1338        else if (scp->cmd_len == 16) {
1339                ldio->lba_count = cpu_to_le32(((u32) scp->cmnd[10] << 24) |
1340                                              ((u32) scp->cmnd[11] << 16) |
1341                                              ((u32) scp->cmnd[12] << 8) |
1342                                              (u32) scp->cmnd[13]);
1343
1344                ldio->start_lba_lo = cpu_to_le32(((u32) scp->cmnd[6] << 24) |
1345                                                 ((u32) scp->cmnd[7] << 16) |
1346                                                 ((u32) scp->cmnd[8] << 8) |
1347                                                 (u32) scp->cmnd[9]);
1348
1349                ldio->start_lba_hi = cpu_to_le32(((u32) scp->cmnd[2] << 24) |
1350                                                 ((u32) scp->cmnd[3] << 16) |
1351                                                 ((u32) scp->cmnd[4] << 8) |
1352                                                 (u32) scp->cmnd[5]);
1353
1354        }
1355
1356        /*
1357         * Construct SGL
1358         */
1359        if (instance->flag_ieee) {
1360                ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1361                ldio->sge_count = megasas_make_sgl_skinny(instance, scp,
1362                                              &ldio->sgl);
1363        } else if (IS_DMA64) {
1364                ldio->flags |= cpu_to_le16(MFI_FRAME_SGL64);
1365                ldio->sge_count = megasas_make_sgl64(instance, scp, &ldio->sgl);
1366        } else
1367                ldio->sge_count = megasas_make_sgl32(instance, scp, &ldio->sgl);
1368
1369        if (ldio->sge_count > instance->max_num_sge) {
1370                printk(KERN_ERR "megasas: build_ld_io: sge_count = %x\n",
1371                        ldio->sge_count);
1372                return 0;
1373        }
1374
1375        /*
1376         * Sense info specific
1377         */
1378        ldio->sense_len = SCSI_SENSE_BUFFERSIZE;
1379        ldio->sense_buf_phys_addr_hi = 0;
1380        ldio->sense_buf_phys_addr_lo = cpu_to_le32(cmd->sense_phys_addr);
1381
1382        /*
1383         * Compute the total number of frames this command consumes. FW uses
1384         * this number to pull sufficient number of frames from host memory.
1385         */
1386        cmd->frame_count = megasas_get_frame_count(instance,
1387                        ldio->sge_count, IO_FRAME);
1388
1389        return cmd->frame_count;
1390}
1391
1392/**
1393 * megasas_is_ldio -            Checks if the cmd is for logical drive
1394 * @scmd:                       SCSI command
1395 *
1396 * Called by megasas_queue_command to find out if the command to be queued
1397 * is a logical drive command
1398 */
1399inline int megasas_is_ldio(struct scsi_cmnd *cmd)
1400{
1401        if (!MEGASAS_IS_LOGICAL(cmd))
1402                return 0;
1403        switch (cmd->cmnd[0]) {
1404        case READ_10:
1405        case WRITE_10:
1406        case READ_12:
1407        case WRITE_12:
1408        case READ_6:
1409        case WRITE_6:
1410        case READ_16:
1411        case WRITE_16:
1412                return 1;
1413        default:
1414                return 0;
1415        }
1416}
1417
1418 /**
1419 * megasas_dump_pending_frames -        Dumps the frame address of all pending cmds
1420 *                                      in FW
1421 * @instance:                           Adapter soft state
1422 */
1423static inline void
1424megasas_dump_pending_frames(struct megasas_instance *instance)
1425{
1426        struct megasas_cmd *cmd;
1427        int i,n;
1428        union megasas_sgl *mfi_sgl;
1429        struct megasas_io_frame *ldio;
1430        struct megasas_pthru_frame *pthru;
1431        u32 sgcount;
1432        u32 max_cmd = instance->max_fw_cmds;
1433
1434        printk(KERN_ERR "\nmegasas[%d]: Dumping Frame Phys Address of all pending cmds in FW\n",instance->host->host_no);
1435        printk(KERN_ERR "megasas[%d]: Total OS Pending cmds : %d\n",instance->host->host_no,atomic_read(&instance->fw_outstanding));
1436        if (IS_DMA64)
1437                printk(KERN_ERR "\nmegasas[%d]: 64 bit SGLs were sent to FW\n",instance->host->host_no);
1438        else
1439                printk(KERN_ERR "\nmegasas[%d]: 32 bit SGLs were sent to FW\n",instance->host->host_no);
1440
1441        printk(KERN_ERR "megasas[%d]: Pending OS cmds in FW : \n",instance->host->host_no);
1442        for (i = 0; i < max_cmd; i++) {
1443                cmd = instance->cmd_list[i];
1444                if(!cmd->scmd)
1445                        continue;
1446                printk(KERN_ERR "megasas[%d]: Frame addr :0x%08lx : ",instance->host->host_no,(unsigned long)cmd->frame_phys_addr);
1447                if (megasas_is_ldio(cmd->scmd)){
1448                        ldio = (struct megasas_io_frame *)cmd->frame;
1449                        mfi_sgl = &ldio->sgl;
1450                        sgcount = ldio->sge_count;
1451                        printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x,"
1452                        " lba lo : 0x%x, lba_hi : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1453                        instance->host->host_no, cmd->frame_count, ldio->cmd, ldio->target_id,
1454                        le32_to_cpu(ldio->start_lba_lo), le32_to_cpu(ldio->start_lba_hi),
1455                        le32_to_cpu(ldio->sense_buf_phys_addr_lo), sgcount);
1456                }
1457                else {
1458                        pthru = (struct megasas_pthru_frame *) cmd->frame;
1459                        mfi_sgl = &pthru->sgl;
1460                        sgcount = pthru->sge_count;
1461                        printk(KERN_ERR "megasas[%d]: frame count : 0x%x, Cmd : 0x%x, Tgt id : 0x%x, "
1462                        "lun : 0x%x, cdb_len : 0x%x, data xfer len : 0x%x, sense_buf addr : 0x%x,sge count : 0x%x\n",
1463                        instance->host->host_no, cmd->frame_count, pthru->cmd, pthru->target_id,
1464                        pthru->lun, pthru->cdb_len, le32_to_cpu(pthru->data_xfer_len),
1465                        le32_to_cpu(pthru->sense_buf_phys_addr_lo), sgcount);
1466                }
1467        if(megasas_dbg_lvl & MEGASAS_DBG_LVL){
1468                for (n = 0; n < sgcount; n++){
1469                        if (IS_DMA64)
1470                                printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%llx ",
1471                                        le32_to_cpu(mfi_sgl->sge64[n].length),
1472                                        le64_to_cpu(mfi_sgl->sge64[n].phys_addr));
1473                        else
1474                                printk(KERN_ERR "megasas: sgl len : 0x%x, sgl addr : 0x%x ",
1475                                        le32_to_cpu(mfi_sgl->sge32[n].length),
1476                                        le32_to_cpu(mfi_sgl->sge32[n].phys_addr));
1477                        }
1478                }
1479                printk(KERN_ERR "\n");
1480        } /*for max_cmd*/
1481        printk(KERN_ERR "\nmegasas[%d]: Pending Internal cmds in FW : \n",instance->host->host_no);
1482        for (i = 0; i < max_cmd; i++) {
1483
1484                cmd = instance->cmd_list[i];
1485
1486                if(cmd->sync_cmd == 1){
1487                        printk(KERN_ERR "0x%08lx : ", (unsigned long)cmd->frame_phys_addr);
1488                }
1489        }
1490        printk(KERN_ERR "megasas[%d]: Dumping Done.\n\n",instance->host->host_no);
1491}
1492
1493u32
1494megasas_build_and_issue_cmd(struct megasas_instance *instance,
1495                            struct scsi_cmnd *scmd)
1496{
1497        struct megasas_cmd *cmd;
1498        u32 frame_count;
1499
1500        cmd = megasas_get_cmd(instance);
1501        if (!cmd)
1502                return SCSI_MLQUEUE_HOST_BUSY;
1503
1504        /*
1505         * Logical drive command
1506         */
1507        if (megasas_is_ldio(scmd))
1508                frame_count = megasas_build_ldio(instance, scmd, cmd);
1509        else
1510                frame_count = megasas_build_dcdb(instance, scmd, cmd);
1511
1512        if (!frame_count)
1513                goto out_return_cmd;
1514
1515        cmd->scmd = scmd;
1516        scmd->SCp.ptr = (char *)cmd;
1517
1518        /*
1519         * Issue the command to the FW
1520         */
1521        atomic_inc(&instance->fw_outstanding);
1522
1523        instance->instancet->fire_cmd(instance, cmd->frame_phys_addr,
1524                                cmd->frame_count-1, instance->reg_set);
1525
1526        return 0;
1527out_return_cmd:
1528        megasas_return_cmd(instance, cmd);
1529        return 1;
1530}
1531
1532
1533/**
1534 * megasas_queue_command -      Queue entry point
1535 * @scmd:                       SCSI command to be queued
1536 * @done:                       Callback entry point
1537 */
1538static int
1539megasas_queue_command_lck(struct scsi_cmnd *scmd, void (*done) (struct scsi_cmnd *))
1540{
1541        struct megasas_instance *instance;
1542        unsigned long flags;
1543
1544        instance = (struct megasas_instance *)
1545            scmd->device->host->hostdata;
1546
1547        if (instance->issuepend_done == 0)
1548                return SCSI_MLQUEUE_HOST_BUSY;
1549
1550        spin_lock_irqsave(&instance->hba_lock, flags);
1551
1552        /* Check for an mpio path and adjust behavior */
1553        if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
1554                if (megasas_check_mpio_paths(instance, scmd) ==
1555                    (DID_RESET << 16)) {
1556                        spin_unlock_irqrestore(&instance->hba_lock, flags);
1557                        return SCSI_MLQUEUE_HOST_BUSY;
1558                } else {
1559                        spin_unlock_irqrestore(&instance->hba_lock, flags);
1560                        scmd->result = DID_NO_CONNECT << 16;
1561                        done(scmd);
1562                        return 0;
1563                }
1564        }
1565
1566        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
1567                spin_unlock_irqrestore(&instance->hba_lock, flags);
1568                scmd->result = DID_NO_CONNECT << 16;
1569                done(scmd);
1570                return 0;
1571        }
1572
1573        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
1574                spin_unlock_irqrestore(&instance->hba_lock, flags);
1575                return SCSI_MLQUEUE_HOST_BUSY;
1576        }
1577
1578        spin_unlock_irqrestore(&instance->hba_lock, flags);
1579
1580        scmd->scsi_done = done;
1581        scmd->result = 0;
1582
1583        if (MEGASAS_IS_LOGICAL(scmd) &&
1584            (scmd->device->id >= MEGASAS_MAX_LD || scmd->device->lun)) {
1585                scmd->result = DID_BAD_TARGET << 16;
1586                goto out_done;
1587        }
1588
1589        switch (scmd->cmnd[0]) {
1590        case SYNCHRONIZE_CACHE:
1591                /*
1592                 * FW takes care of flush cache on its own
1593                 * No need to send it down
1594                 */
1595                scmd->result = DID_OK << 16;
1596                goto out_done;
1597        default:
1598                break;
1599        }
1600
1601        if (instance->instancet->build_and_issue_cmd(instance, scmd)) {
1602                printk(KERN_ERR "megasas: Err returned from build_and_issue_cmd\n");
1603                return SCSI_MLQUEUE_HOST_BUSY;
1604        }
1605
1606        return 0;
1607
1608 out_done:
1609        done(scmd);
1610        return 0;
1611}
1612
1613static DEF_SCSI_QCMD(megasas_queue_command)
1614
1615static struct megasas_instance *megasas_lookup_instance(u16 host_no)
1616{
1617        int i;
1618
1619        for (i = 0; i < megasas_mgmt_info.max_index; i++) {
1620
1621                if ((megasas_mgmt_info.instance[i]) &&
1622                    (megasas_mgmt_info.instance[i]->host->host_no == host_no))
1623                        return megasas_mgmt_info.instance[i];
1624        }
1625
1626        return NULL;
1627}
1628
1629static int megasas_slave_configure(struct scsi_device *sdev)
1630{
1631        u16             pd_index = 0;
1632        struct  megasas_instance *instance ;
1633
1634        instance = megasas_lookup_instance(sdev->host->host_no);
1635
1636        /*
1637        * Don't export physical disk devices to the disk driver.
1638        *
1639        * FIXME: Currently we don't export them to the midlayer at all.
1640        *        That will be fixed once LSI engineers have audited the
1641        *        firmware for possible issues.
1642        */
1643        if (sdev->channel < MEGASAS_MAX_PD_CHANNELS &&
1644                                sdev->type == TYPE_DISK) {
1645                pd_index = (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1646                                                                sdev->id;
1647                if (instance->pd_list[pd_index].driveState ==
1648                                                MR_PD_STATE_SYSTEM) {
1649                        blk_queue_rq_timeout(sdev->request_queue,
1650                                MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1651                        return 0;
1652                }
1653                return -ENXIO;
1654        }
1655
1656        /*
1657        * The RAID firmware may require extended timeouts.
1658        */
1659        blk_queue_rq_timeout(sdev->request_queue,
1660                MEGASAS_DEFAULT_CMD_TIMEOUT * HZ);
1661        return 0;
1662}
1663
1664static int megasas_slave_alloc(struct scsi_device *sdev)
1665{
1666        u16             pd_index = 0;
1667        struct megasas_instance *instance ;
1668        instance = megasas_lookup_instance(sdev->host->host_no);
1669        if ((sdev->channel < MEGASAS_MAX_PD_CHANNELS) &&
1670                                (sdev->type == TYPE_DISK)) {
1671                /*
1672                 * Open the OS scan to the SYSTEM PD
1673                 */
1674                pd_index =
1675                        (sdev->channel * MEGASAS_MAX_DEV_PER_CHANNEL) +
1676                        sdev->id;
1677                if ((instance->pd_list[pd_index].driveState ==
1678                                        MR_PD_STATE_SYSTEM) &&
1679                        (instance->pd_list[pd_index].driveType ==
1680                                                TYPE_DISK)) {
1681                        return 0;
1682                }
1683                return -ENXIO;
1684        }
1685        return 0;
1686}
1687
1688void megaraid_sas_kill_hba(struct megasas_instance *instance)
1689{
1690        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
1691            (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
1692            (instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
1693            (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
1694            (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
1695            (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
1696                writel(MFI_STOP_ADP, &instance->reg_set->doorbell);
1697                /* Flush */
1698                readl(&instance->reg_set->doorbell);
1699                if (instance->mpio && instance->requestorId)
1700                        memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
1701        } else {
1702                writel(MFI_STOP_ADP, &instance->reg_set->inbound_doorbell);
1703        }
1704}
1705
1706 /**
1707  * megasas_check_and_restore_queue_depth - Check if queue depth needs to be
1708  *                                     restored to max value
1709  * @instance:                  Adapter soft state
1710  *
1711  */
1712void
1713megasas_check_and_restore_queue_depth(struct megasas_instance *instance)
1714{
1715        unsigned long flags;
1716        if (instance->flag & MEGASAS_FW_BUSY
1717            && time_after(jiffies, instance->last_time + 5 * HZ)
1718            && atomic_read(&instance->fw_outstanding) <
1719            instance->throttlequeuedepth + 1) {
1720
1721                spin_lock_irqsave(instance->host->host_lock, flags);
1722                instance->flag &= ~MEGASAS_FW_BUSY;
1723                if (instance->is_imr) {
1724                        instance->host->can_queue =
1725                                instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
1726                } else
1727                        instance->host->can_queue =
1728                                instance->max_fw_cmds - MEGASAS_INT_CMDS;
1729
1730                spin_unlock_irqrestore(instance->host->host_lock, flags);
1731        }
1732}
1733
1734/**
1735 * megasas_complete_cmd_dpc      -      Returns FW's controller structure
1736 * @instance_addr:                      Address of adapter soft state
1737 *
1738 * Tasklet to complete cmds
1739 */
1740static void megasas_complete_cmd_dpc(unsigned long instance_addr)
1741{
1742        u32 producer;
1743        u32 consumer;
1744        u32 context;
1745        struct megasas_cmd *cmd;
1746        struct megasas_instance *instance =
1747                                (struct megasas_instance *)instance_addr;
1748        unsigned long flags;
1749
1750        /* If we have already declared adapter dead, donot complete cmds */
1751        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR )
1752                return;
1753
1754        spin_lock_irqsave(&instance->completion_lock, flags);
1755
1756        producer = le32_to_cpu(*instance->producer);
1757        consumer = le32_to_cpu(*instance->consumer);
1758
1759        while (consumer != producer) {
1760                context = le32_to_cpu(instance->reply_queue[consumer]);
1761                if (context >= instance->max_fw_cmds) {
1762                        printk(KERN_ERR "Unexpected context value %x\n",
1763                                context);
1764                        BUG();
1765                }
1766
1767                cmd = instance->cmd_list[context];
1768
1769                megasas_complete_cmd(instance, cmd, DID_OK);
1770
1771                consumer++;
1772                if (consumer == (instance->max_fw_cmds + 1)) {
1773                        consumer = 0;
1774                }
1775        }
1776
1777        *instance->consumer = cpu_to_le32(producer);
1778
1779        spin_unlock_irqrestore(&instance->completion_lock, flags);
1780
1781        /*
1782         * Check if we can restore can_queue
1783         */
1784        megasas_check_and_restore_queue_depth(instance);
1785}
1786
1787/**
1788 * megasas_start_timer - Initializes a timer object
1789 * @instance:           Adapter soft state
1790 * @timer:              timer object to be initialized
1791 * @fn:                 timer function
1792 * @interval:           time interval between timer function call
1793 *
1794 */
1795void megasas_start_timer(struct megasas_instance *instance,
1796                        struct timer_list *timer,
1797                        void *fn, unsigned long interval)
1798{
1799        init_timer(timer);
1800        timer->expires = jiffies + interval;
1801        timer->data = (unsigned long)instance;
1802        timer->function = fn;
1803        add_timer(timer);
1804}
1805
1806static void
1807megasas_internal_reset_defer_cmds(struct megasas_instance *instance);
1808
1809static void
1810process_fw_state_change_wq(struct work_struct *work);
1811
1812void megasas_do_ocr(struct megasas_instance *instance)
1813{
1814        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
1815        (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
1816        (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
1817                *instance->consumer = cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
1818        }
1819        instance->instancet->disable_intr(instance);
1820        instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
1821        instance->issuepend_done = 0;
1822
1823        atomic_set(&instance->fw_outstanding, 0);
1824        megasas_internal_reset_defer_cmds(instance);
1825        process_fw_state_change_wq(&instance->work_init);
1826}
1827
1828/* This function will get the current SR-IOV LD/VF affiliation */
1829static int megasas_get_ld_vf_affiliation(struct megasas_instance *instance,
1830        int initial)
1831{
1832        struct megasas_cmd *cmd;
1833        struct megasas_dcmd_frame *dcmd;
1834        struct MR_LD_VF_AFFILIATION *new_affiliation = NULL;
1835        struct MR_LD_VF_AFFILIATION_111 *new_affiliation_111 = NULL;
1836        struct MR_LD_VF_MAP *newmap = NULL, *savedmap = NULL;
1837        dma_addr_t new_affiliation_h;
1838        dma_addr_t new_affiliation_111_h;
1839        int ld, retval = 0;
1840        u8 thisVf;
1841
1842        cmd = megasas_get_cmd(instance);
1843
1844        if (!cmd) {
1845                printk(KERN_DEBUG "megasas: megasas_get_ld_vf_"
1846                       "affiliation: Failed to get cmd for scsi%d.\n",
1847                        instance->host->host_no);
1848                return -ENOMEM;
1849        }
1850
1851        dcmd = &cmd->frame->dcmd;
1852
1853        if (!instance->vf_affiliation && !instance->vf_affiliation_111) {
1854                printk(KERN_WARNING "megasas: SR-IOV: Couldn't get LD/VF "
1855                       "affiliation for scsi%d.\n", instance->host->host_no);
1856                megasas_return_cmd(instance, cmd);
1857                return -ENOMEM;
1858        }
1859
1860        if (initial)
1861                if (instance->PlasmaFW111)
1862                        memset(instance->vf_affiliation_111, 0,
1863                               sizeof(struct MR_LD_VF_AFFILIATION_111));
1864                else
1865                        memset(instance->vf_affiliation, 0,
1866                               (MAX_LOGICAL_DRIVES + 1) *
1867                               sizeof(struct MR_LD_VF_AFFILIATION));
1868        else {
1869                if (instance->PlasmaFW111)
1870                        new_affiliation_111 =
1871                                pci_alloc_consistent(instance->pdev,
1872                                                     sizeof(struct MR_LD_VF_AFFILIATION_111),
1873                                                     &new_affiliation_111_h);
1874                else
1875                        new_affiliation =
1876                                pci_alloc_consistent(instance->pdev,
1877                                                     (MAX_LOGICAL_DRIVES + 1) *
1878                                                     sizeof(struct MR_LD_VF_AFFILIATION),
1879                                                     &new_affiliation_h);
1880                if (!new_affiliation && !new_affiliation_111) {
1881                        printk(KERN_DEBUG "megasas: SR-IOV: Couldn't allocate "
1882                               "memory for new affiliation for scsi%d.\n",
1883                                instance->host->host_no);
1884                        megasas_return_cmd(instance, cmd);
1885                        return -ENOMEM;
1886                }
1887                if (instance->PlasmaFW111)
1888                        memset(new_affiliation_111, 0,
1889                               sizeof(struct MR_LD_VF_AFFILIATION_111));
1890                else
1891                        memset(new_affiliation, 0, (MAX_LOGICAL_DRIVES + 1) *
1892                               sizeof(struct MR_LD_VF_AFFILIATION));
1893        }
1894
1895        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
1896
1897        dcmd->cmd = MFI_CMD_DCMD;
1898        dcmd->cmd_status = 0xFF;
1899        dcmd->sge_count = 1;
1900        dcmd->flags = MFI_FRAME_DIR_BOTH;
1901        dcmd->timeout = 0;
1902        dcmd->pad_0 = 0;
1903        if (instance->PlasmaFW111) {
1904                dcmd->data_xfer_len = sizeof(struct MR_LD_VF_AFFILIATION_111);
1905                dcmd->opcode = MR_DCMD_LD_VF_MAP_GET_ALL_LDS_111;
1906        } else {
1907                dcmd->data_xfer_len = (MAX_LOGICAL_DRIVES + 1) *
1908                        sizeof(struct MR_LD_VF_AFFILIATION);
1909                dcmd->opcode = MR_DCMD_LD_VF_MAP_GET_ALL_LDS;
1910        }
1911
1912        if (initial) {
1913                if (instance->PlasmaFW111)
1914                        dcmd->sgl.sge32[0].phys_addr =
1915                          instance->vf_affiliation_111_h;
1916                else
1917                        dcmd->sgl.sge32[0].phys_addr =
1918                          instance->vf_affiliation_h;
1919        } else {
1920                if (instance->PlasmaFW111)
1921                        dcmd->sgl.sge32[0].phys_addr = new_affiliation_111_h;
1922                else
1923                        dcmd->sgl.sge32[0].phys_addr = new_affiliation_h;
1924        }
1925        if (instance->PlasmaFW111)
1926                dcmd->sgl.sge32[0].length =
1927                  sizeof(struct MR_LD_VF_AFFILIATION_111);
1928        else
1929                dcmd->sgl.sge32[0].length = (MAX_LOGICAL_DRIVES + 1) *
1930                        sizeof(struct MR_LD_VF_AFFILIATION);
1931
1932        printk(KERN_WARNING "megasas: SR-IOV: Getting LD/VF affiliation for "
1933               "scsi%d\n", instance->host->host_no);
1934
1935        megasas_issue_blocked_cmd(instance, cmd, 0);
1936
1937        if (dcmd->cmd_status) {
1938                printk(KERN_WARNING "megasas: SR-IOV: LD/VF affiliation DCMD"
1939                       " failed with status 0x%x for scsi%d.\n",
1940                       dcmd->cmd_status, instance->host->host_no);
1941                retval = 1; /* Do a scan if we couldn't get affiliation */
1942                goto out;
1943        }
1944
1945        if (!initial) {
1946                if (instance->PlasmaFW111) {
1947                        if (!new_affiliation_111->vdCount) {
1948                                printk(KERN_WARNING "megasas: SR-IOV: Got new "
1949                                       "LD/VF affiliation for passive path "
1950                                       "for scsi%d.\n",
1951                                        instance->host->host_no);
1952                                retval = 1;
1953                                goto out;
1954                        }
1955                        thisVf = new_affiliation_111->thisVf;
1956                        for (ld = 0 ; ld < new_affiliation_111->vdCount; ld++)
1957                                if (instance->vf_affiliation_111->map[ld].policy[thisVf] != new_affiliation_111->map[ld].policy[thisVf]) {
1958                                        printk(KERN_WARNING "megasas: SR-IOV: "
1959                                               "Got new LD/VF affiliation "
1960                                               "for scsi%d.\n",
1961                                                instance->host->host_no);
1962                                        memcpy(instance->vf_affiliation_111,
1963                                               new_affiliation_111,
1964                                               sizeof(struct MR_LD_VF_AFFILIATION_111));
1965                                        retval = 1;
1966                                        goto out;
1967                                }
1968                } else {
1969                        if (!new_affiliation->ldCount) {
1970                                printk(KERN_WARNING "megasas: SR-IOV: Got new "
1971                                       "LD/VF affiliation for passive "
1972                                       "path for scsi%d.\n",
1973                                       instance->host->host_no);
1974                                retval = 1;
1975                                goto out;
1976                        }
1977                        newmap = new_affiliation->map;
1978                        savedmap = instance->vf_affiliation->map;
1979                        thisVf = new_affiliation->thisVf;
1980                        for (ld = 0 ; ld < new_affiliation->ldCount; ld++) {
1981                                if (savedmap->policy[thisVf] !=
1982                                    newmap->policy[thisVf]) {
1983                                        printk(KERN_WARNING "megasas: SR-IOV: "
1984                                               "Got new LD/VF affiliation "
1985                                               "for scsi%d.\n",
1986                                                instance->host->host_no);
1987                                        memcpy(instance->vf_affiliation,
1988                                               new_affiliation,
1989                                               new_affiliation->size);
1990                                        retval = 1;
1991                                        goto out;
1992                                }
1993                                savedmap = (struct MR_LD_VF_MAP *)
1994                                        ((unsigned char *)savedmap +
1995                                         savedmap->size);
1996                                newmap = (struct MR_LD_VF_MAP *)
1997                                        ((unsigned char *)newmap +
1998                                         newmap->size);
1999                        }
2000                }
2001        }
2002out:
2003        if (new_affiliation) {
2004                if (instance->PlasmaFW111)
2005                        pci_free_consistent(instance->pdev,
2006                                            sizeof(struct MR_LD_VF_AFFILIATION_111),
2007                                            new_affiliation_111,
2008                                            new_affiliation_111_h);
2009                else
2010                        pci_free_consistent(instance->pdev,
2011                                            (MAX_LOGICAL_DRIVES + 1) *
2012                                            sizeof(struct MR_LD_VF_AFFILIATION),
2013                                            new_affiliation, new_affiliation_h);
2014        }
2015        megasas_return_cmd(instance, cmd);
2016
2017        return retval;
2018}
2019
2020/* This function will tell FW to start the SR-IOV heartbeat */
2021int megasas_sriov_start_heartbeat(struct megasas_instance *instance,
2022                                         int initial)
2023{
2024        struct megasas_cmd *cmd;
2025        struct megasas_dcmd_frame *dcmd;
2026        int retval = 0;
2027
2028        cmd = megasas_get_cmd(instance);
2029
2030        if (!cmd) {
2031                printk(KERN_DEBUG "megasas: megasas_sriov_start_heartbeat: "
2032                       "Failed to get cmd for scsi%d.\n",
2033                       instance->host->host_no);
2034                return -ENOMEM;
2035        }
2036
2037        dcmd = &cmd->frame->dcmd;
2038
2039        if (initial) {
2040                instance->hb_host_mem =
2041                        pci_alloc_consistent(instance->pdev,
2042                                             sizeof(struct MR_CTRL_HB_HOST_MEM),
2043                                             &instance->hb_host_mem_h);
2044                if (!instance->hb_host_mem) {
2045                        printk(KERN_DEBUG "megasas: SR-IOV: Couldn't allocate"
2046                               " memory for heartbeat host memory for "
2047                               "scsi%d.\n", instance->host->host_no);
2048                        retval = -ENOMEM;
2049                        goto out;
2050                }
2051                memset(instance->hb_host_mem, 0,
2052                       sizeof(struct MR_CTRL_HB_HOST_MEM));
2053        }
2054
2055        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
2056
2057        dcmd->mbox.s[0] = sizeof(struct MR_CTRL_HB_HOST_MEM);
2058        dcmd->cmd = MFI_CMD_DCMD;
2059        dcmd->cmd_status = 0xFF;
2060        dcmd->sge_count = 1;
2061        dcmd->flags = MFI_FRAME_DIR_BOTH;
2062        dcmd->timeout = 0;
2063        dcmd->pad_0 = 0;
2064        dcmd->data_xfer_len = sizeof(struct MR_CTRL_HB_HOST_MEM);
2065        dcmd->opcode = MR_DCMD_CTRL_SHARED_HOST_MEM_ALLOC;
2066        dcmd->sgl.sge32[0].phys_addr = instance->hb_host_mem_h;
2067        dcmd->sgl.sge32[0].length = sizeof(struct MR_CTRL_HB_HOST_MEM);
2068
2069        printk(KERN_WARNING "megasas: SR-IOV: Starting heartbeat for scsi%d\n",
2070               instance->host->host_no);
2071
2072        if (!megasas_issue_polled(instance, cmd)) {
2073                retval = 0;
2074        } else {
2075                printk(KERN_WARNING "megasas: SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2076                       "_MEM_ALLOC DCMD timed out for scsi%d\n",
2077                       instance->host->host_no);
2078                retval = 1;
2079                goto out;
2080        }
2081
2082
2083        if (dcmd->cmd_status) {
2084                printk(KERN_WARNING "megasas: SR-IOV: MR_DCMD_CTRL_SHARED_HOST"
2085                       "_MEM_ALLOC DCMD failed with status 0x%x for scsi%d\n",
2086                       dcmd->cmd_status,
2087                       instance->host->host_no);
2088                retval = 1;
2089                goto out;
2090        }
2091
2092out:
2093        megasas_return_cmd(instance, cmd);
2094
2095        return retval;
2096}
2097
2098/* Handler for SR-IOV heartbeat */
2099void megasas_sriov_heartbeat_handler(unsigned long instance_addr)
2100{
2101        struct megasas_instance *instance =
2102                (struct megasas_instance *)instance_addr;
2103
2104        if (instance->hb_host_mem->HB.fwCounter !=
2105            instance->hb_host_mem->HB.driverCounter) {
2106                instance->hb_host_mem->HB.driverCounter =
2107                        instance->hb_host_mem->HB.fwCounter;
2108                mod_timer(&instance->sriov_heartbeat_timer,
2109                          jiffies + MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
2110        } else {
2111                printk(KERN_WARNING "megasas: SR-IOV: Heartbeat never "
2112                       "completed for scsi%d\n", instance->host->host_no);
2113                schedule_work(&instance->work_init);
2114        }
2115}
2116
2117/**
2118 * megasas_wait_for_outstanding -       Wait for all outstanding cmds
2119 * @instance:                           Adapter soft state
2120 *
2121 * This function waits for up to MEGASAS_RESET_WAIT_TIME seconds for FW to
2122 * complete all its outstanding commands. Returns error if one or more IOs
2123 * are pending after this time period. It also marks the controller dead.
2124 */
2125static int megasas_wait_for_outstanding(struct megasas_instance *instance)
2126{
2127        int i;
2128        u32 reset_index;
2129        u32 wait_time = MEGASAS_RESET_WAIT_TIME;
2130        u8 adprecovery;
2131        unsigned long flags;
2132        struct list_head clist_local;
2133        struct megasas_cmd *reset_cmd;
2134        u32 fw_state;
2135        u8 kill_adapter_flag;
2136
2137        spin_lock_irqsave(&instance->hba_lock, flags);
2138        adprecovery = instance->adprecovery;
2139        spin_unlock_irqrestore(&instance->hba_lock, flags);
2140
2141        if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
2142
2143                INIT_LIST_HEAD(&clist_local);
2144                spin_lock_irqsave(&instance->hba_lock, flags);
2145                list_splice_init(&instance->internal_reset_pending_q,
2146                                &clist_local);
2147                spin_unlock_irqrestore(&instance->hba_lock, flags);
2148
2149                printk(KERN_NOTICE "megasas: HBA reset wait ...\n");
2150                for (i = 0; i < wait_time; i++) {
2151                        msleep(1000);
2152                        spin_lock_irqsave(&instance->hba_lock, flags);
2153                        adprecovery = instance->adprecovery;
2154                        spin_unlock_irqrestore(&instance->hba_lock, flags);
2155                        if (adprecovery == MEGASAS_HBA_OPERATIONAL)
2156                                break;
2157                }
2158
2159                if (adprecovery != MEGASAS_HBA_OPERATIONAL) {
2160                        printk(KERN_NOTICE "megasas: reset: Stopping HBA.\n");
2161                        spin_lock_irqsave(&instance->hba_lock, flags);
2162                        instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2163                        spin_unlock_irqrestore(&instance->hba_lock, flags);
2164                        return FAILED;
2165                }
2166
2167                reset_index     = 0;
2168                while (!list_empty(&clist_local)) {
2169                        reset_cmd       = list_entry((&clist_local)->next,
2170                                                struct megasas_cmd, list);
2171                        list_del_init(&reset_cmd->list);
2172                        if (reset_cmd->scmd) {
2173                                reset_cmd->scmd->result = DID_RESET << 16;
2174                                printk(KERN_NOTICE "%d:%p reset [%02x]\n",
2175                                        reset_index, reset_cmd,
2176                                        reset_cmd->scmd->cmnd[0]);
2177
2178                                reset_cmd->scmd->scsi_done(reset_cmd->scmd);
2179                                megasas_return_cmd(instance, reset_cmd);
2180                        } else if (reset_cmd->sync_cmd) {
2181                                printk(KERN_NOTICE "megasas:%p synch cmds"
2182                                                "reset queue\n",
2183                                                reset_cmd);
2184
2185                                reset_cmd->cmd_status = ENODATA;
2186                                instance->instancet->fire_cmd(instance,
2187                                                reset_cmd->frame_phys_addr,
2188                                                0, instance->reg_set);
2189                        } else {
2190                                printk(KERN_NOTICE "megasas: %p unexpected"
2191                                        "cmds lst\n",
2192                                        reset_cmd);
2193                        }
2194                        reset_index++;
2195                }
2196
2197                return SUCCESS;
2198        }
2199
2200        for (i = 0; i < resetwaittime; i++) {
2201
2202                int outstanding = atomic_read(&instance->fw_outstanding);
2203
2204                if (!outstanding)
2205                        break;
2206
2207                if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
2208                        printk(KERN_NOTICE "megasas: [%2d]waiting for %d "
2209                               "commands to complete\n",i,outstanding);
2210                        /*
2211                         * Call cmd completion routine. Cmd to be
2212                         * be completed directly without depending on isr.
2213                         */
2214                        megasas_complete_cmd_dpc((unsigned long)instance);
2215                }
2216
2217                msleep(1000);
2218        }
2219
2220        i = 0;
2221        kill_adapter_flag = 0;
2222        do {
2223                fw_state = instance->instancet->read_fw_status_reg(
2224                                        instance->reg_set) & MFI_STATE_MASK;
2225                if ((fw_state == MFI_STATE_FAULT) &&
2226                        (instance->disableOnlineCtrlReset == 0)) {
2227                        if (i == 3) {
2228                                kill_adapter_flag = 2;
2229                                break;
2230                        }
2231                        megasas_do_ocr(instance);
2232                        kill_adapter_flag = 1;
2233
2234                        /* wait for 1 secs to let FW finish the pending cmds */
2235                        msleep(1000);
2236                }
2237                i++;
2238        } while (i <= 3);
2239
2240        if (atomic_read(&instance->fw_outstanding) &&
2241                                        !kill_adapter_flag) {
2242                if (instance->disableOnlineCtrlReset == 0) {
2243
2244                        megasas_do_ocr(instance);
2245
2246                        /* wait for 5 secs to let FW finish the pending cmds */
2247                        for (i = 0; i < wait_time; i++) {
2248                                int outstanding =
2249                                        atomic_read(&instance->fw_outstanding);
2250                                if (!outstanding)
2251                                        return SUCCESS;
2252                                msleep(1000);
2253                        }
2254                }
2255        }
2256
2257        if (atomic_read(&instance->fw_outstanding) ||
2258                                        (kill_adapter_flag == 2)) {
2259                printk(KERN_NOTICE "megaraid_sas: pending cmds after reset\n");
2260                /*
2261                * Send signal to FW to stop processing any pending cmds.
2262                * The controller will be taken offline by the OS now.
2263                */
2264                if ((instance->pdev->device ==
2265                        PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
2266                        (instance->pdev->device ==
2267                        PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
2268                        writel(MFI_STOP_ADP,
2269                                &instance->reg_set->doorbell);
2270                } else {
2271                        writel(MFI_STOP_ADP,
2272                                &instance->reg_set->inbound_doorbell);
2273                }
2274                megasas_dump_pending_frames(instance);
2275                spin_lock_irqsave(&instance->hba_lock, flags);
2276                instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2277                spin_unlock_irqrestore(&instance->hba_lock, flags);
2278                return FAILED;
2279        }
2280
2281        printk(KERN_NOTICE "megaraid_sas: no pending cmds after reset\n");
2282
2283        return SUCCESS;
2284}
2285
2286/**
2287 * megasas_generic_reset -      Generic reset routine
2288 * @scmd:                       Mid-layer SCSI command
2289 *
2290 * This routine implements a generic reset handler for device, bus and host
2291 * reset requests. Device, bus and host specific reset handlers can use this
2292 * function after they do their specific tasks.
2293 */
2294static int megasas_generic_reset(struct scsi_cmnd *scmd)
2295{
2296        int ret_val;
2297        struct megasas_instance *instance;
2298
2299        instance = (struct megasas_instance *)scmd->device->host->hostdata;
2300
2301        scmd_printk(KERN_NOTICE, scmd, "megasas: RESET cmd=%x retries=%x\n",
2302                 scmd->cmnd[0], scmd->retries);
2303
2304        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
2305                printk(KERN_ERR "megasas: cannot recover from previous reset "
2306                       "failures\n");
2307                return FAILED;
2308        }
2309
2310        ret_val = megasas_wait_for_outstanding(instance);
2311        if (ret_val == SUCCESS)
2312                printk(KERN_NOTICE "megasas: reset successful \n");
2313        else
2314                printk(KERN_ERR "megasas: failed to do reset\n");
2315
2316        return ret_val;
2317}
2318
2319/**
2320 * megasas_reset_timer - quiesce the adapter if required
2321 * @scmd:               scsi cmnd
2322 *
2323 * Sets the FW busy flag and reduces the host->can_queue if the
2324 * cmd has not been completed within the timeout period.
2325 */
2326static enum
2327blk_eh_timer_return megasas_reset_timer(struct scsi_cmnd *scmd)
2328{
2329        struct megasas_instance *instance;
2330        unsigned long flags;
2331
2332        if (time_after(jiffies, scmd->jiffies_at_alloc +
2333                                (MEGASAS_DEFAULT_CMD_TIMEOUT * 2) * HZ)) {
2334                return BLK_EH_NOT_HANDLED;
2335        }
2336
2337        instance = (struct megasas_instance *)scmd->device->host->hostdata;
2338        if (!(instance->flag & MEGASAS_FW_BUSY)) {
2339                /* FW is busy, throttle IO */
2340                spin_lock_irqsave(instance->host->host_lock, flags);
2341
2342                instance->host->can_queue = instance->throttlequeuedepth;
2343                instance->last_time = jiffies;
2344                instance->flag |= MEGASAS_FW_BUSY;
2345
2346                spin_unlock_irqrestore(instance->host->host_lock, flags);
2347        }
2348        return BLK_EH_RESET_TIMER;
2349}
2350
2351/**
2352 * megasas_reset_device -       Device reset handler entry point
2353 */
2354static int megasas_reset_device(struct scsi_cmnd *scmd)
2355{
2356        int ret;
2357
2358        /*
2359         * First wait for all commands to complete
2360         */
2361        ret = megasas_generic_reset(scmd);
2362
2363        return ret;
2364}
2365
2366/**
2367 * megasas_reset_bus_host -     Bus & host reset handler entry point
2368 */
2369static int megasas_reset_bus_host(struct scsi_cmnd *scmd)
2370{
2371        int ret;
2372        struct megasas_instance *instance;
2373        instance = (struct megasas_instance *)scmd->device->host->hostdata;
2374
2375        /*
2376         * First wait for all commands to complete
2377         */
2378        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
2379            (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
2380            (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
2381            (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY))
2382                ret = megasas_reset_fusion(scmd->device->host, 1);
2383        else
2384                ret = megasas_generic_reset(scmd);
2385
2386        return ret;
2387}
2388
2389/**
2390 * megasas_bios_param - Returns disk geometry for a disk
2391 * @sdev:               device handle
2392 * @bdev:               block device
2393 * @capacity:           drive capacity
2394 * @geom:               geometry parameters
2395 */
2396static int
2397megasas_bios_param(struct scsi_device *sdev, struct block_device *bdev,
2398                 sector_t capacity, int geom[])
2399{
2400        int heads;
2401        int sectors;
2402        sector_t cylinders;
2403        unsigned long tmp;
2404        /* Default heads (64) & sectors (32) */
2405        heads = 64;
2406        sectors = 32;
2407
2408        tmp = heads * sectors;
2409        cylinders = capacity;
2410
2411        sector_div(cylinders, tmp);
2412
2413        /*
2414         * Handle extended translation size for logical drives > 1Gb
2415         */
2416
2417        if (capacity >= 0x200000) {
2418                heads = 255;
2419                sectors = 63;
2420                tmp = heads*sectors;
2421                cylinders = capacity;
2422                sector_div(cylinders, tmp);
2423        }
2424
2425        geom[0] = heads;
2426        geom[1] = sectors;
2427        geom[2] = cylinders;
2428
2429        return 0;
2430}
2431
2432static void megasas_aen_polling(struct work_struct *work);
2433
2434/**
2435 * megasas_service_aen -        Processes an event notification
2436 * @instance:                   Adapter soft state
2437 * @cmd:                        AEN command completed by the ISR
2438 *
2439 * For AEN, driver sends a command down to FW that is held by the FW till an
2440 * event occurs. When an event of interest occurs, FW completes the command
2441 * that it was previously holding.
2442 *
2443 * This routines sends SIGIO signal to processes that have registered with the
2444 * driver for AEN.
2445 */
2446static void
2447megasas_service_aen(struct megasas_instance *instance, struct megasas_cmd *cmd)
2448{
2449        unsigned long flags;
2450        /*
2451         * Don't signal app if it is just an aborted previously registered aen
2452         */
2453        if ((!cmd->abort_aen) && (instance->unload == 0)) {
2454                spin_lock_irqsave(&poll_aen_lock, flags);
2455                megasas_poll_wait_aen = 1;
2456                spin_unlock_irqrestore(&poll_aen_lock, flags);
2457                wake_up(&megasas_poll_wait);
2458                kill_fasync(&megasas_async_queue, SIGIO, POLL_IN);
2459        }
2460        else
2461                cmd->abort_aen = 0;
2462
2463        instance->aen_cmd = NULL;
2464        megasas_return_cmd(instance, cmd);
2465
2466        if ((instance->unload == 0) &&
2467                ((instance->issuepend_done == 1))) {
2468                struct megasas_aen_event *ev;
2469                ev = kzalloc(sizeof(*ev), GFP_ATOMIC);
2470                if (!ev) {
2471                        printk(KERN_ERR "megasas_service_aen: out of memory\n");
2472                } else {
2473                        ev->instance = instance;
2474                        instance->ev = ev;
2475                        INIT_DELAYED_WORK(&ev->hotplug_work,
2476                                          megasas_aen_polling);
2477                        schedule_delayed_work(&ev->hotplug_work, 0);
2478                }
2479        }
2480}
2481
2482static int megasas_change_queue_depth(struct scsi_device *sdev,
2483                                      int queue_depth, int reason)
2484{
2485        if (reason != SCSI_QDEPTH_DEFAULT)
2486                return -EOPNOTSUPP;
2487
2488        if (queue_depth > sdev->host->can_queue)
2489                queue_depth = sdev->host->can_queue;
2490        scsi_adjust_queue_depth(sdev, scsi_get_tag_type(sdev),
2491                                queue_depth);
2492
2493        return queue_depth;
2494}
2495
2496/*
2497 * Scsi host template for megaraid_sas driver
2498 */
2499static struct scsi_host_template megasas_template = {
2500
2501        .module = THIS_MODULE,
2502        .name = "LSI SAS based MegaRAID driver",
2503        .proc_name = "megaraid_sas",
2504        .slave_configure = megasas_slave_configure,
2505        .slave_alloc = megasas_slave_alloc,
2506        .queuecommand = megasas_queue_command,
2507        .eh_device_reset_handler = megasas_reset_device,
2508        .eh_bus_reset_handler = megasas_reset_bus_host,
2509        .eh_host_reset_handler = megasas_reset_bus_host,
2510        .eh_timed_out = megasas_reset_timer,
2511        .bios_param = megasas_bios_param,
2512        .use_clustering = ENABLE_CLUSTERING,
2513        .change_queue_depth = megasas_change_queue_depth,
2514        .no_write_same = 1,
2515};
2516
2517/**
2518 * megasas_complete_int_cmd -   Completes an internal command
2519 * @instance:                   Adapter soft state
2520 * @cmd:                        Command to be completed
2521 *
2522 * The megasas_issue_blocked_cmd() function waits for a command to complete
2523 * after it issues a command. This function wakes up that waiting routine by
2524 * calling wake_up() on the wait queue.
2525 */
2526static void
2527megasas_complete_int_cmd(struct megasas_instance *instance,
2528                         struct megasas_cmd *cmd)
2529{
2530        cmd->cmd_status = cmd->frame->io.cmd_status;
2531
2532        if (cmd->cmd_status == ENODATA) {
2533                cmd->cmd_status = 0;
2534        }
2535        wake_up(&instance->int_cmd_wait_q);
2536}
2537
2538/**
2539 * megasas_complete_abort -     Completes aborting a command
2540 * @instance:                   Adapter soft state
2541 * @cmd:                        Cmd that was issued to abort another cmd
2542 *
2543 * The megasas_issue_blocked_abort_cmd() function waits on abort_cmd_wait_q
2544 * after it issues an abort on a previously issued command. This function
2545 * wakes up all functions waiting on the same wait queue.
2546 */
2547static void
2548megasas_complete_abort(struct megasas_instance *instance,
2549                       struct megasas_cmd *cmd)
2550{
2551        if (cmd->sync_cmd) {
2552                cmd->sync_cmd = 0;
2553                cmd->cmd_status = 0;
2554                wake_up(&instance->abort_cmd_wait_q);
2555        }
2556
2557        return;
2558}
2559
2560/**
2561 * megasas_complete_cmd -       Completes a command
2562 * @instance:                   Adapter soft state
2563 * @cmd:                        Command to be completed
2564 * @alt_status:                 If non-zero, use this value as status to
2565 *                              SCSI mid-layer instead of the value returned
2566 *                              by the FW. This should be used if caller wants
2567 *                              an alternate status (as in the case of aborted
2568 *                              commands)
2569 */
2570void
2571megasas_complete_cmd(struct megasas_instance *instance, struct megasas_cmd *cmd,
2572                     u8 alt_status)
2573{
2574        int exception = 0;
2575        struct megasas_header *hdr = &cmd->frame->hdr;
2576        unsigned long flags;
2577        struct fusion_context *fusion = instance->ctrl_context;
2578        u32 opcode;
2579
2580        /* flag for the retry reset */
2581        cmd->retry_for_fw_reset = 0;
2582
2583        if (cmd->scmd)
2584                cmd->scmd->SCp.ptr = NULL;
2585
2586        switch (hdr->cmd) {
2587        case MFI_CMD_INVALID:
2588                /* Some older 1068 controller FW may keep a pended
2589                   MR_DCMD_CTRL_EVENT_GET_INFO left over from the main kernel
2590                   when booting the kdump kernel.  Ignore this command to
2591                   prevent a kernel panic on shutdown of the kdump kernel. */
2592                printk(KERN_WARNING "megaraid_sas: MFI_CMD_INVALID command "
2593                       "completed.\n");
2594                printk(KERN_WARNING "megaraid_sas: If you have a controller "
2595                       "other than PERC5, please upgrade your firmware.\n");
2596                break;
2597        case MFI_CMD_PD_SCSI_IO:
2598        case MFI_CMD_LD_SCSI_IO:
2599
2600                /*
2601                 * MFI_CMD_PD_SCSI_IO and MFI_CMD_LD_SCSI_IO could have been
2602                 * issued either through an IO path or an IOCTL path. If it
2603                 * was via IOCTL, we will send it to internal completion.
2604                 */
2605                if (cmd->sync_cmd) {
2606                        cmd->sync_cmd = 0;
2607                        megasas_complete_int_cmd(instance, cmd);
2608                        break;
2609                }
2610
2611        case MFI_CMD_LD_READ:
2612        case MFI_CMD_LD_WRITE:
2613
2614                if (alt_status) {
2615                        cmd->scmd->result = alt_status << 16;
2616                        exception = 1;
2617                }
2618
2619                if (exception) {
2620
2621                        atomic_dec(&instance->fw_outstanding);
2622
2623                        scsi_dma_unmap(cmd->scmd);
2624                        cmd->scmd->scsi_done(cmd->scmd);
2625                        megasas_return_cmd(instance, cmd);
2626
2627                        break;
2628                }
2629
2630                switch (hdr->cmd_status) {
2631
2632                case MFI_STAT_OK:
2633                        cmd->scmd->result = DID_OK << 16;
2634                        break;
2635
2636                case MFI_STAT_SCSI_IO_FAILED:
2637                case MFI_STAT_LD_INIT_IN_PROGRESS:
2638                        cmd->scmd->result =
2639                            (DID_ERROR << 16) | hdr->scsi_status;
2640                        break;
2641
2642                case MFI_STAT_SCSI_DONE_WITH_ERROR:
2643
2644                        cmd->scmd->result = (DID_OK << 16) | hdr->scsi_status;
2645
2646                        if (hdr->scsi_status == SAM_STAT_CHECK_CONDITION) {
2647                                memset(cmd->scmd->sense_buffer, 0,
2648                                       SCSI_SENSE_BUFFERSIZE);
2649                                memcpy(cmd->scmd->sense_buffer, cmd->sense,
2650                                       hdr->sense_len);
2651
2652                                cmd->scmd->result |= DRIVER_SENSE << 24;
2653                        }
2654
2655                        break;
2656
2657                case MFI_STAT_LD_OFFLINE:
2658                case MFI_STAT_DEVICE_NOT_FOUND:
2659                        cmd->scmd->result = DID_BAD_TARGET << 16;
2660                        break;
2661
2662                default:
2663                        printk(KERN_DEBUG "megasas: MFI FW status %#x\n",
2664                               hdr->cmd_status);
2665                        cmd->scmd->result = DID_ERROR << 16;
2666                        break;
2667                }
2668
2669                atomic_dec(&instance->fw_outstanding);
2670
2671                scsi_dma_unmap(cmd->scmd);
2672                cmd->scmd->scsi_done(cmd->scmd);
2673                megasas_return_cmd(instance, cmd);
2674
2675                break;
2676
2677        case MFI_CMD_SMP:
2678        case MFI_CMD_STP:
2679        case MFI_CMD_DCMD:
2680                opcode = le32_to_cpu(cmd->frame->dcmd.opcode);
2681                /* Check for LD map update */
2682                if ((opcode == MR_DCMD_LD_MAP_GET_INFO)
2683                        && (cmd->frame->dcmd.mbox.b[1] == 1)) {
2684                        fusion->fast_path_io = 0;
2685                        spin_lock_irqsave(instance->host->host_lock, flags);
2686                        if (cmd->frame->hdr.cmd_status != 0) {
2687                                if (cmd->frame->hdr.cmd_status !=
2688                                    MFI_STAT_NOT_FOUND)
2689                                        printk(KERN_WARNING "megasas: map sync"
2690                                               "failed, status = 0x%x.\n",
2691                                               cmd->frame->hdr.cmd_status);
2692                                else {
2693                                        megasas_return_cmd(instance, cmd);
2694                                        spin_unlock_irqrestore(
2695                                                instance->host->host_lock,
2696                                                flags);
2697                                        break;
2698                                }
2699                        } else
2700                                instance->map_id++;
2701                        megasas_return_cmd(instance, cmd);
2702
2703                        /*
2704                         * Set fast path IO to ZERO.
2705                         * Validate Map will set proper value.
2706                         * Meanwhile all IOs will go as LD IO.
2707                         */
2708                        if (MR_ValidateMapInfo(instance))
2709                                fusion->fast_path_io = 1;
2710                        else
2711                                fusion->fast_path_io = 0;
2712                        megasas_sync_map_info(instance);
2713                        spin_unlock_irqrestore(instance->host->host_lock,
2714                                               flags);
2715                        break;
2716                }
2717                if (opcode == MR_DCMD_CTRL_EVENT_GET_INFO ||
2718                    opcode == MR_DCMD_CTRL_EVENT_GET) {
2719                        spin_lock_irqsave(&poll_aen_lock, flags);
2720                        megasas_poll_wait_aen = 0;
2721                        spin_unlock_irqrestore(&poll_aen_lock, flags);
2722                }
2723
2724                /*
2725                 * See if got an event notification
2726                 */
2727                if (opcode == MR_DCMD_CTRL_EVENT_WAIT)
2728                        megasas_service_aen(instance, cmd);
2729                else
2730                        megasas_complete_int_cmd(instance, cmd);
2731
2732                break;
2733
2734        case MFI_CMD_ABORT:
2735                /*
2736                 * Cmd issued to abort another cmd returned
2737                 */
2738                megasas_complete_abort(instance, cmd);
2739                break;
2740
2741        default:
2742                printk("megasas: Unknown command completed! [0x%X]\n",
2743                       hdr->cmd);
2744                break;
2745        }
2746}
2747
2748/**
2749 * megasas_issue_pending_cmds_again -   issue all pending cmds
2750 *                                      in FW again because of the fw reset
2751 * @instance:                           Adapter soft state
2752 */
2753static inline void
2754megasas_issue_pending_cmds_again(struct megasas_instance *instance)
2755{
2756        struct megasas_cmd *cmd;
2757        struct list_head clist_local;
2758        union megasas_evt_class_locale class_locale;
2759        unsigned long flags;
2760        u32 seq_num;
2761
2762        INIT_LIST_HEAD(&clist_local);
2763        spin_lock_irqsave(&instance->hba_lock, flags);
2764        list_splice_init(&instance->internal_reset_pending_q, &clist_local);
2765        spin_unlock_irqrestore(&instance->hba_lock, flags);
2766
2767        while (!list_empty(&clist_local)) {
2768                cmd     = list_entry((&clist_local)->next,
2769                                        struct megasas_cmd, list);
2770                list_del_init(&cmd->list);
2771
2772                if (cmd->sync_cmd || cmd->scmd) {
2773                        printk(KERN_NOTICE "megaraid_sas: command %p, %p:%d"
2774                                "detected to be pending while HBA reset.\n",
2775                                        cmd, cmd->scmd, cmd->sync_cmd);
2776
2777                        cmd->retry_for_fw_reset++;
2778
2779                        if (cmd->retry_for_fw_reset == 3) {
2780                                printk(KERN_NOTICE "megaraid_sas: cmd %p, %p:%d"
2781                                        "was tried multiple times during reset."
2782                                        "Shutting down the HBA\n",
2783                                        cmd, cmd->scmd, cmd->sync_cmd);
2784                                megaraid_sas_kill_hba(instance);
2785
2786                                instance->adprecovery =
2787                                                MEGASAS_HW_CRITICAL_ERROR;
2788                                return;
2789                        }
2790                }
2791
2792                if (cmd->sync_cmd == 1) {
2793                        if (cmd->scmd) {
2794                                printk(KERN_NOTICE "megaraid_sas: unexpected"
2795                                        "cmd attached to internal command!\n");
2796                        }
2797                        printk(KERN_NOTICE "megasas: %p synchronous cmd"
2798                                                "on the internal reset queue,"
2799                                                "issue it again.\n", cmd);
2800                        cmd->cmd_status = ENODATA;
2801                        instance->instancet->fire_cmd(instance,
2802                                                        cmd->frame_phys_addr ,
2803                                                        0, instance->reg_set);
2804                } else if (cmd->scmd) {
2805                        printk(KERN_NOTICE "megasas: %p scsi cmd [%02x]"
2806                        "detected on the internal queue, issue again.\n",
2807                        cmd, cmd->scmd->cmnd[0]);
2808
2809                        atomic_inc(&instance->fw_outstanding);
2810                        instance->instancet->fire_cmd(instance,
2811                                        cmd->frame_phys_addr,
2812                                        cmd->frame_count-1, instance->reg_set);
2813                } else {
2814                        printk(KERN_NOTICE "megasas: %p unexpected cmd on the"
2815                                "internal reset defer list while re-issue!!\n",
2816                                cmd);
2817                }
2818        }
2819
2820        if (instance->aen_cmd) {
2821                printk(KERN_NOTICE "megaraid_sas: aen_cmd in def process\n");
2822                megasas_return_cmd(instance, instance->aen_cmd);
2823
2824                instance->aen_cmd       = NULL;
2825        }
2826
2827        /*
2828        * Initiate AEN (Asynchronous Event Notification)
2829        */
2830        seq_num = instance->last_seq_num;
2831        class_locale.members.reserved = 0;
2832        class_locale.members.locale = MR_EVT_LOCALE_ALL;
2833        class_locale.members.class = MR_EVT_CLASS_DEBUG;
2834
2835        megasas_register_aen(instance, seq_num, class_locale.word);
2836}
2837
2838/**
2839 * Move the internal reset pending commands to a deferred queue.
2840 *
2841 * We move the commands pending at internal reset time to a
2842 * pending queue. This queue would be flushed after successful
2843 * completion of the internal reset sequence. if the internal reset
2844 * did not complete in time, the kernel reset handler would flush
2845 * these commands.
2846 **/
2847static void
2848megasas_internal_reset_defer_cmds(struct megasas_instance *instance)
2849{
2850        struct megasas_cmd *cmd;
2851        int i;
2852        u32 max_cmd = instance->max_fw_cmds;
2853        u32 defer_index;
2854        unsigned long flags;
2855
2856        defer_index     = 0;
2857        spin_lock_irqsave(&instance->cmd_pool_lock, flags);
2858        for (i = 0; i < max_cmd; i++) {
2859                cmd = instance->cmd_list[i];
2860                if (cmd->sync_cmd == 1 || cmd->scmd) {
2861                        printk(KERN_NOTICE "megasas: moving cmd[%d]:%p:%d:%p"
2862                                        "on the defer queue as internal\n",
2863                                defer_index, cmd, cmd->sync_cmd, cmd->scmd);
2864
2865                        if (!list_empty(&cmd->list)) {
2866                                printk(KERN_NOTICE "megaraid_sas: ERROR while"
2867                                        " moving this cmd:%p, %d %p, it was"
2868                                        "discovered on some list?\n",
2869                                        cmd, cmd->sync_cmd, cmd->scmd);
2870
2871                                list_del_init(&cmd->list);
2872                        }
2873                        defer_index++;
2874                        list_add_tail(&cmd->list,
2875                                &instance->internal_reset_pending_q);
2876                }
2877        }
2878        spin_unlock_irqrestore(&instance->cmd_pool_lock, flags);
2879}
2880
2881
2882static void
2883process_fw_state_change_wq(struct work_struct *work)
2884{
2885        struct megasas_instance *instance =
2886                container_of(work, struct megasas_instance, work_init);
2887        u32 wait;
2888        unsigned long flags;
2889
2890        if (instance->adprecovery != MEGASAS_ADPRESET_SM_INFAULT) {
2891                printk(KERN_NOTICE "megaraid_sas: error, recovery st %x \n",
2892                                instance->adprecovery);
2893                return ;
2894        }
2895
2896        if (instance->adprecovery == MEGASAS_ADPRESET_SM_INFAULT) {
2897                printk(KERN_NOTICE "megaraid_sas: FW detected to be in fault"
2898                                        "state, restarting it...\n");
2899
2900                instance->instancet->disable_intr(instance);
2901                atomic_set(&instance->fw_outstanding, 0);
2902
2903                atomic_set(&instance->fw_reset_no_pci_access, 1);
2904                instance->instancet->adp_reset(instance, instance->reg_set);
2905                atomic_set(&instance->fw_reset_no_pci_access, 0 );
2906
2907                printk(KERN_NOTICE "megaraid_sas: FW restarted successfully,"
2908                                        "initiating next stage...\n");
2909
2910                printk(KERN_NOTICE "megaraid_sas: HBA recovery state machine,"
2911                                        "state 2 starting...\n");
2912
2913                /*waitting for about 20 second before start the second init*/
2914                for (wait = 0; wait < 30; wait++) {
2915                        msleep(1000);
2916                }
2917
2918                if (megasas_transition_to_ready(instance, 1)) {
2919                        printk(KERN_NOTICE "megaraid_sas:adapter not ready\n");
2920
2921                        megaraid_sas_kill_hba(instance);
2922                        instance->adprecovery   = MEGASAS_HW_CRITICAL_ERROR;
2923                        return ;
2924                }
2925
2926                if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS1064R) ||
2927                        (instance->pdev->device == PCI_DEVICE_ID_DELL_PERC5) ||
2928                        (instance->pdev->device == PCI_DEVICE_ID_LSI_VERDE_ZCR)
2929                        ) {
2930                        *instance->consumer = *instance->producer;
2931                } else {
2932                        *instance->consumer = 0;
2933                        *instance->producer = 0;
2934                }
2935
2936                megasas_issue_init_mfi(instance);
2937
2938                spin_lock_irqsave(&instance->hba_lock, flags);
2939                instance->adprecovery   = MEGASAS_HBA_OPERATIONAL;
2940                spin_unlock_irqrestore(&instance->hba_lock, flags);
2941                instance->instancet->enable_intr(instance);
2942
2943                megasas_issue_pending_cmds_again(instance);
2944                instance->issuepend_done = 1;
2945        }
2946        return ;
2947}
2948
2949/**
2950 * megasas_deplete_reply_queue -        Processes all completed commands
2951 * @instance:                           Adapter soft state
2952 * @alt_status:                         Alternate status to be returned to
2953 *                                      SCSI mid-layer instead of the status
2954 *                                      returned by the FW
2955 * Note: this must be called with hba lock held
2956 */
2957static int
2958megasas_deplete_reply_queue(struct megasas_instance *instance,
2959                                        u8 alt_status)
2960{
2961        u32 mfiStatus;
2962        u32 fw_state;
2963
2964        if ((mfiStatus = instance->instancet->check_reset(instance,
2965                                        instance->reg_set)) == 1) {
2966                return IRQ_HANDLED;
2967        }
2968
2969        if ((mfiStatus = instance->instancet->clear_intr(
2970                                                instance->reg_set)
2971                                                ) == 0) {
2972                /* Hardware may not set outbound_intr_status in MSI-X mode */
2973                if (!instance->msix_vectors)
2974                        return IRQ_NONE;
2975        }
2976
2977        instance->mfiStatus = mfiStatus;
2978
2979        if ((mfiStatus & MFI_INTR_FLAG_FIRMWARE_STATE_CHANGE)) {
2980                fw_state = instance->instancet->read_fw_status_reg(
2981                                instance->reg_set) & MFI_STATE_MASK;
2982
2983                if (fw_state != MFI_STATE_FAULT) {
2984                        printk(KERN_NOTICE "megaraid_sas: fw state:%x\n",
2985                                                fw_state);
2986                }
2987
2988                if ((fw_state == MFI_STATE_FAULT) &&
2989                                (instance->disableOnlineCtrlReset == 0)) {
2990                        printk(KERN_NOTICE "megaraid_sas: wait adp restart\n");
2991
2992                        if ((instance->pdev->device ==
2993                                        PCI_DEVICE_ID_LSI_SAS1064R) ||
2994                                (instance->pdev->device ==
2995                                        PCI_DEVICE_ID_DELL_PERC5) ||
2996                                (instance->pdev->device ==
2997                                        PCI_DEVICE_ID_LSI_VERDE_ZCR)) {
2998
2999                                *instance->consumer =
3000                                        cpu_to_le32(MEGASAS_ADPRESET_INPROG_SIGN);
3001                        }
3002
3003
3004                        instance->instancet->disable_intr(instance);
3005                        instance->adprecovery   = MEGASAS_ADPRESET_SM_INFAULT;
3006                        instance->issuepend_done = 0;
3007
3008                        atomic_set(&instance->fw_outstanding, 0);
3009                        megasas_internal_reset_defer_cmds(instance);
3010
3011                        printk(KERN_NOTICE "megasas: fwState=%x, stage:%d\n",
3012                                        fw_state, instance->adprecovery);
3013
3014                        schedule_work(&instance->work_init);
3015                        return IRQ_HANDLED;
3016
3017                } else {
3018                        printk(KERN_NOTICE "megasas: fwstate:%x, dis_OCR=%x\n",
3019                                fw_state, instance->disableOnlineCtrlReset);
3020                }
3021        }
3022
3023        tasklet_schedule(&instance->isr_tasklet);
3024        return IRQ_HANDLED;
3025}
3026/**
3027 * megasas_isr - isr entry point
3028 */
3029static irqreturn_t megasas_isr(int irq, void *devp)
3030{
3031        struct megasas_irq_context *irq_context = devp;
3032        struct megasas_instance *instance = irq_context->instance;
3033        unsigned long flags;
3034        irqreturn_t     rc;
3035
3036        if (atomic_read(&instance->fw_reset_no_pci_access))
3037                return IRQ_HANDLED;
3038
3039        spin_lock_irqsave(&instance->hba_lock, flags);
3040        rc =  megasas_deplete_reply_queue(instance, DID_OK);
3041        spin_unlock_irqrestore(&instance->hba_lock, flags);
3042
3043        return rc;
3044}
3045
3046/**
3047 * megasas_transition_to_ready -        Move the FW to READY state
3048 * @instance:                           Adapter soft state
3049 *
3050 * During the initialization, FW passes can potentially be in any one of
3051 * several possible states. If the FW in operational, waiting-for-handshake
3052 * states, driver must take steps to bring it to ready state. Otherwise, it
3053 * has to wait for the ready state.
3054 */
3055int
3056megasas_transition_to_ready(struct megasas_instance *instance, int ocr)
3057{
3058        int i;
3059        u8 max_wait;
3060        u32 fw_state;
3061        u32 cur_state;
3062        u32 abs_state, curr_abs_state;
3063
3064        fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) & MFI_STATE_MASK;
3065
3066        if (fw_state != MFI_STATE_READY)
3067                printk(KERN_INFO "megasas: Waiting for FW to come to ready"
3068                       " state\n");
3069
3070        while (fw_state != MFI_STATE_READY) {
3071
3072                abs_state =
3073                instance->instancet->read_fw_status_reg(instance->reg_set);
3074
3075                switch (fw_state) {
3076
3077                case MFI_STATE_FAULT:
3078                        printk(KERN_DEBUG "megasas: FW in FAULT state!!\n");
3079                        if (ocr) {
3080                                max_wait = MEGASAS_RESET_WAIT_TIME;
3081                                cur_state = MFI_STATE_FAULT;
3082                                break;
3083                        } else
3084                                return -ENODEV;
3085
3086                case MFI_STATE_WAIT_HANDSHAKE:
3087                        /*
3088                         * Set the CLR bit in inbound doorbell
3089                         */
3090                        if ((instance->pdev->device ==
3091                                PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3092                                (instance->pdev->device ==
3093                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3094                                (instance->pdev->device ==
3095                                PCI_DEVICE_ID_LSI_FUSION) ||
3096                                (instance->pdev->device ==
3097                                PCI_DEVICE_ID_LSI_PLASMA) ||
3098                                (instance->pdev->device ==
3099                                PCI_DEVICE_ID_LSI_INVADER) ||
3100                                (instance->pdev->device ==
3101                                PCI_DEVICE_ID_LSI_FURY)) {
3102                                writel(
3103                                  MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3104                                  &instance->reg_set->doorbell);
3105                        } else {
3106                                writel(
3107                                    MFI_INIT_CLEAR_HANDSHAKE|MFI_INIT_HOTPLUG,
3108                                        &instance->reg_set->inbound_doorbell);
3109                        }
3110
3111                        max_wait = MEGASAS_RESET_WAIT_TIME;
3112                        cur_state = MFI_STATE_WAIT_HANDSHAKE;
3113                        break;
3114
3115                case MFI_STATE_BOOT_MESSAGE_PENDING:
3116                        if ((instance->pdev->device ==
3117                             PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3118                                (instance->pdev->device ==
3119                                 PCI_DEVICE_ID_LSI_SAS0071SKINNY) ||
3120                            (instance->pdev->device ==
3121                             PCI_DEVICE_ID_LSI_FUSION) ||
3122                            (instance->pdev->device ==
3123                             PCI_DEVICE_ID_LSI_PLASMA) ||
3124                            (instance->pdev->device ==
3125                             PCI_DEVICE_ID_LSI_INVADER) ||
3126                            (instance->pdev->device ==
3127                             PCI_DEVICE_ID_LSI_FURY)) {
3128                                writel(MFI_INIT_HOTPLUG,
3129                                       &instance->reg_set->doorbell);
3130                        } else
3131                                writel(MFI_INIT_HOTPLUG,
3132                                        &instance->reg_set->inbound_doorbell);
3133
3134                        max_wait = MEGASAS_RESET_WAIT_TIME;
3135                        cur_state = MFI_STATE_BOOT_MESSAGE_PENDING;
3136                        break;
3137
3138                case MFI_STATE_OPERATIONAL:
3139                        /*
3140                         * Bring it to READY state; assuming max wait 10 secs
3141                         */
3142                        instance->instancet->disable_intr(instance);
3143                        if ((instance->pdev->device ==
3144                                PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
3145                                (instance->pdev->device ==
3146                                PCI_DEVICE_ID_LSI_SAS0071SKINNY)  ||
3147                                (instance->pdev->device
3148                                        == PCI_DEVICE_ID_LSI_FUSION) ||
3149                                (instance->pdev->device
3150                                        == PCI_DEVICE_ID_LSI_PLASMA) ||
3151                                (instance->pdev->device
3152                                        == PCI_DEVICE_ID_LSI_INVADER) ||
3153                                (instance->pdev->device
3154                                        == PCI_DEVICE_ID_LSI_FURY)) {
3155                                writel(MFI_RESET_FLAGS,
3156                                        &instance->reg_set->doorbell);
3157                                if ((instance->pdev->device ==
3158                                        PCI_DEVICE_ID_LSI_FUSION) ||
3159                                        (instance->pdev->device ==
3160                                        PCI_DEVICE_ID_LSI_PLASMA) ||
3161                                        (instance->pdev->device ==
3162                                        PCI_DEVICE_ID_LSI_INVADER) ||
3163                                        (instance->pdev->device ==
3164                                        PCI_DEVICE_ID_LSI_FURY)) {
3165                                        for (i = 0; i < (10 * 1000); i += 20) {
3166                                                if (readl(
3167                                                            &instance->
3168                                                            reg_set->
3169                                                            doorbell) & 1)
3170                                                        msleep(20);
3171                                                else
3172                                                        break;
3173                                        }
3174                                }
3175                        } else
3176                                writel(MFI_RESET_FLAGS,
3177                                        &instance->reg_set->inbound_doorbell);
3178
3179                        max_wait = MEGASAS_RESET_WAIT_TIME;
3180                        cur_state = MFI_STATE_OPERATIONAL;
3181                        break;
3182
3183                case MFI_STATE_UNDEFINED:
3184                        /*
3185                         * This state should not last for more than 2 seconds
3186                         */
3187                        max_wait = MEGASAS_RESET_WAIT_TIME;
3188                        cur_state = MFI_STATE_UNDEFINED;
3189                        break;
3190
3191                case MFI_STATE_BB_INIT:
3192                        max_wait = MEGASAS_RESET_WAIT_TIME;
3193                        cur_state = MFI_STATE_BB_INIT;
3194                        break;
3195
3196                case MFI_STATE_FW_INIT:
3197                        max_wait = MEGASAS_RESET_WAIT_TIME;
3198                        cur_state = MFI_STATE_FW_INIT;
3199                        break;
3200
3201                case MFI_STATE_FW_INIT_2:
3202                        max_wait = MEGASAS_RESET_WAIT_TIME;
3203                        cur_state = MFI_STATE_FW_INIT_2;
3204                        break;
3205
3206                case MFI_STATE_DEVICE_SCAN:
3207                        max_wait = MEGASAS_RESET_WAIT_TIME;
3208                        cur_state = MFI_STATE_DEVICE_SCAN;
3209                        break;
3210
3211                case MFI_STATE_FLUSH_CACHE:
3212                        max_wait = MEGASAS_RESET_WAIT_TIME;
3213                        cur_state = MFI_STATE_FLUSH_CACHE;
3214                        break;
3215
3216                default:
3217                        printk(KERN_DEBUG "megasas: Unknown state 0x%x\n",
3218                               fw_state);
3219                        return -ENODEV;
3220                }
3221
3222                /*
3223                 * The cur_state should not last for more than max_wait secs
3224                 */
3225                for (i = 0; i < (max_wait * 1000); i++) {
3226                        fw_state = instance->instancet->read_fw_status_reg(instance->reg_set) &
3227                                        MFI_STATE_MASK ;
3228                curr_abs_state =
3229                instance->instancet->read_fw_status_reg(instance->reg_set);
3230
3231                        if (abs_state == curr_abs_state) {
3232                                msleep(1);
3233                        } else
3234                                break;
3235                }
3236
3237                /*
3238                 * Return error if fw_state hasn't changed after max_wait
3239                 */
3240                if (curr_abs_state == abs_state) {
3241                        printk(KERN_DEBUG "FW state [%d] hasn't changed "
3242                               "in %d secs\n", fw_state, max_wait);
3243                        return -ENODEV;
3244                }
3245        }
3246        printk(KERN_INFO "megasas: FW now in Ready state\n");
3247
3248        return 0;
3249}
3250
3251/**
3252 * megasas_teardown_frame_pool -        Destroy the cmd frame DMA pool
3253 * @instance:                           Adapter soft state
3254 */
3255static void megasas_teardown_frame_pool(struct megasas_instance *instance)
3256{
3257        int i;
3258        u32 max_cmd = instance->max_mfi_cmds;
3259        struct megasas_cmd *cmd;
3260
3261        if (!instance->frame_dma_pool)
3262                return;
3263
3264        /*
3265         * Return all frames to pool
3266         */
3267        for (i = 0; i < max_cmd; i++) {
3268
3269                cmd = instance->cmd_list[i];
3270
3271                if (cmd->frame)
3272                        pci_pool_free(instance->frame_dma_pool, cmd->frame,
3273                                      cmd->frame_phys_addr);
3274
3275                if (cmd->sense)
3276                        pci_pool_free(instance->sense_dma_pool, cmd->sense,
3277                                      cmd->sense_phys_addr);
3278        }
3279
3280        /*
3281         * Now destroy the pool itself
3282         */
3283        pci_pool_destroy(instance->frame_dma_pool);
3284        pci_pool_destroy(instance->sense_dma_pool);
3285
3286        instance->frame_dma_pool = NULL;
3287        instance->sense_dma_pool = NULL;
3288}
3289
3290/**
3291 * megasas_create_frame_pool -  Creates DMA pool for cmd frames
3292 * @instance:                   Adapter soft state
3293 *
3294 * Each command packet has an embedded DMA memory buffer that is used for
3295 * filling MFI frame and the SG list that immediately follows the frame. This
3296 * function creates those DMA memory buffers for each command packet by using
3297 * PCI pool facility.
3298 */
3299static int megasas_create_frame_pool(struct megasas_instance *instance)
3300{
3301        int i;
3302        u32 max_cmd;
3303        u32 sge_sz;
3304        u32 sgl_sz;
3305        u32 total_sz;
3306        u32 frame_count;
3307        struct megasas_cmd *cmd;
3308
3309        max_cmd = instance->max_mfi_cmds;
3310
3311        /*
3312         * Size of our frame is 64 bytes for MFI frame, followed by max SG
3313         * elements and finally SCSI_SENSE_BUFFERSIZE bytes for sense buffer
3314         */
3315        sge_sz = (IS_DMA64) ? sizeof(struct megasas_sge64) :
3316            sizeof(struct megasas_sge32);
3317
3318        if (instance->flag_ieee) {
3319                sge_sz = sizeof(struct megasas_sge_skinny);
3320        }
3321
3322        /*
3323         * Calculated the number of 64byte frames required for SGL
3324         */
3325        sgl_sz = sge_sz * instance->max_num_sge;
3326        frame_count = (sgl_sz + MEGAMFI_FRAME_SIZE - 1) / MEGAMFI_FRAME_SIZE;
3327        frame_count = 15;
3328
3329        /*
3330         * We need one extra frame for the MFI command
3331         */
3332        frame_count++;
3333
3334        total_sz = MEGAMFI_FRAME_SIZE * frame_count;
3335        /*
3336         * Use DMA pool facility provided by PCI layer
3337         */
3338        instance->frame_dma_pool = pci_pool_create("megasas frame pool",
3339                                                   instance->pdev, total_sz, 64,
3340                                                   0);
3341
3342        if (!instance->frame_dma_pool) {
3343                printk(KERN_DEBUG "megasas: failed to setup frame pool\n");
3344                return -ENOMEM;
3345        }
3346
3347        instance->sense_dma_pool = pci_pool_create("megasas sense pool",
3348                                                   instance->pdev, 128, 4, 0);
3349
3350        if (!instance->sense_dma_pool) {
3351                printk(KERN_DEBUG "megasas: failed to setup sense pool\n");
3352
3353                pci_pool_destroy(instance->frame_dma_pool);
3354                instance->frame_dma_pool = NULL;
3355
3356                return -ENOMEM;
3357        }
3358
3359        /*
3360         * Allocate and attach a frame to each of the commands in cmd_list.
3361         * By making cmd->index as the context instead of the &cmd, we can
3362         * always use 32bit context regardless of the architecture
3363         */
3364        for (i = 0; i < max_cmd; i++) {
3365
3366                cmd = instance->cmd_list[i];
3367
3368                cmd->frame = pci_pool_alloc(instance->frame_dma_pool,
3369                                            GFP_KERNEL, &cmd->frame_phys_addr);
3370
3371                cmd->sense = pci_pool_alloc(instance->sense_dma_pool,
3372                                            GFP_KERNEL, &cmd->sense_phys_addr);
3373
3374                /*
3375                 * megasas_teardown_frame_pool() takes care of freeing
3376                 * whatever has been allocated
3377                 */
3378                if (!cmd->frame || !cmd->sense) {
3379                        printk(KERN_DEBUG "megasas: pci_pool_alloc failed \n");
3380                        megasas_teardown_frame_pool(instance);
3381                        return -ENOMEM;
3382                }
3383
3384                memset(cmd->frame, 0, total_sz);
3385                cmd->frame->io.context = cpu_to_le32(cmd->index);
3386                cmd->frame->io.pad_0 = 0;
3387                if ((instance->pdev->device != PCI_DEVICE_ID_LSI_FUSION) &&
3388                    (instance->pdev->device != PCI_DEVICE_ID_LSI_PLASMA) &&
3389                    (instance->pdev->device != PCI_DEVICE_ID_LSI_INVADER) &&
3390                        (instance->pdev->device != PCI_DEVICE_ID_LSI_FURY) &&
3391                    (reset_devices))
3392                        cmd->frame->hdr.cmd = MFI_CMD_INVALID;
3393        }
3394
3395        return 0;
3396}
3397
3398/**
3399 * megasas_free_cmds -  Free all the cmds in the free cmd pool
3400 * @instance:           Adapter soft state
3401 */
3402void megasas_free_cmds(struct megasas_instance *instance)
3403{
3404        int i;
3405        /* First free the MFI frame pool */
3406        megasas_teardown_frame_pool(instance);
3407
3408        /* Free all the commands in the cmd_list */
3409        for (i = 0; i < instance->max_mfi_cmds; i++)
3410
3411                kfree(instance->cmd_list[i]);
3412
3413        /* Free the cmd_list buffer itself */
3414        kfree(instance->cmd_list);
3415        instance->cmd_list = NULL;
3416
3417        INIT_LIST_HEAD(&instance->cmd_pool);
3418}
3419
3420/**
3421 * megasas_alloc_cmds - Allocates the command packets
3422 * @instance:           Adapter soft state
3423 *
3424 * Each command that is issued to the FW, whether IO commands from the OS or
3425 * internal commands like IOCTLs, are wrapped in local data structure called
3426 * megasas_cmd. The frame embedded in this megasas_cmd is actually issued to
3427 * the FW.
3428 *
3429 * Each frame has a 32-bit field called context (tag). This context is used
3430 * to get back the megasas_cmd from the frame when a frame gets completed in
3431 * the ISR. Typically the address of the megasas_cmd itself would be used as
3432 * the context. But we wanted to keep the differences between 32 and 64 bit
3433 * systems to the mininum. We always use 32 bit integers for the context. In
3434 * this driver, the 32 bit values are the indices into an array cmd_list.
3435 * This array is used only to look up the megasas_cmd given the context. The
3436 * free commands themselves are maintained in a linked list called cmd_pool.
3437 */
3438int megasas_alloc_cmds(struct megasas_instance *instance)
3439{
3440        int i;
3441        int j;
3442        u32 max_cmd;
3443        struct megasas_cmd *cmd;
3444
3445        max_cmd = instance->max_mfi_cmds;
3446
3447        /*
3448         * instance->cmd_list is an array of struct megasas_cmd pointers.
3449         * Allocate the dynamic array first and then allocate individual
3450         * commands.
3451         */
3452        instance->cmd_list = kcalloc(max_cmd, sizeof(struct megasas_cmd*), GFP_KERNEL);
3453
3454        if (!instance->cmd_list) {
3455                printk(KERN_DEBUG "megasas: out of memory\n");
3456                return -ENOMEM;
3457        }
3458
3459        memset(instance->cmd_list, 0, sizeof(struct megasas_cmd *) *max_cmd);
3460
3461        for (i = 0; i < max_cmd; i++) {
3462                instance->cmd_list[i] = kmalloc(sizeof(struct megasas_cmd),
3463                                                GFP_KERNEL);
3464
3465                if (!instance->cmd_list[i]) {
3466
3467                        for (j = 0; j < i; j++)
3468                                kfree(instance->cmd_list[j]);
3469
3470                        kfree(instance->cmd_list);
3471                        instance->cmd_list = NULL;
3472
3473                        return -ENOMEM;
3474                }
3475        }
3476
3477        /*
3478         * Add all the commands to command pool (instance->cmd_pool)
3479         */
3480        for (i = 0; i < max_cmd; i++) {
3481                cmd = instance->cmd_list[i];
3482                memset(cmd, 0, sizeof(struct megasas_cmd));
3483                cmd->index = i;
3484                cmd->scmd = NULL;
3485                cmd->instance = instance;
3486
3487                list_add_tail(&cmd->list, &instance->cmd_pool);
3488        }
3489
3490        /*
3491         * Create a frame pool and assign one frame to each cmd
3492         */
3493        if (megasas_create_frame_pool(instance)) {
3494                printk(KERN_DEBUG "megasas: Error creating frame DMA pool\n");
3495                megasas_free_cmds(instance);
3496        }
3497
3498        return 0;
3499}
3500
3501/*
3502 * megasas_get_pd_list_info -   Returns FW's pd_list structure
3503 * @instance:                           Adapter soft state
3504 * @pd_list:                            pd_list structure
3505 *
3506 * Issues an internal command (DCMD) to get the FW's controller PD
3507 * list structure.  This information is mainly used to find out SYSTEM
3508 * supported by the FW.
3509 */
3510static int
3511megasas_get_pd_list(struct megasas_instance *instance)
3512{
3513        int ret = 0, pd_index = 0;
3514        struct megasas_cmd *cmd;
3515        struct megasas_dcmd_frame *dcmd;
3516        struct MR_PD_LIST *ci;
3517        struct MR_PD_ADDRESS *pd_addr;
3518        dma_addr_t ci_h = 0;
3519
3520        cmd = megasas_get_cmd(instance);
3521
3522        if (!cmd) {
3523                printk(KERN_DEBUG "megasas (get_pd_list): Failed to get cmd\n");
3524                return -ENOMEM;
3525        }
3526
3527        dcmd = &cmd->frame->dcmd;
3528
3529        ci = pci_alloc_consistent(instance->pdev,
3530                  MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST), &ci_h);
3531
3532        if (!ci) {
3533                printk(KERN_DEBUG "Failed to alloc mem for pd_list\n");
3534                megasas_return_cmd(instance, cmd);
3535                return -ENOMEM;
3536        }
3537
3538        memset(ci, 0, sizeof(*ci));
3539        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3540
3541        dcmd->mbox.b[0] = MR_PD_QUERY_TYPE_EXPOSED_TO_HOST;
3542        dcmd->mbox.b[1] = 0;
3543        dcmd->cmd = MFI_CMD_DCMD;
3544        dcmd->cmd_status = 0xFF;
3545        dcmd->sge_count = 1;
3546        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3547        dcmd->timeout = 0;
3548        dcmd->pad_0 = 0;
3549        dcmd->data_xfer_len = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
3550        dcmd->opcode = cpu_to_le32(MR_DCMD_PD_LIST_QUERY);
3551        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3552        dcmd->sgl.sge32[0].length = cpu_to_le32(MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST));
3553
3554        if (!megasas_issue_polled(instance, cmd)) {
3555                ret = 0;
3556        } else {
3557                ret = -1;
3558        }
3559
3560        /*
3561        * the following function will get the instance PD LIST.
3562        */
3563
3564        pd_addr = ci->addr;
3565
3566        if ( ret == 0 &&
3567             (le32_to_cpu(ci->count) <
3568                  (MEGASAS_MAX_PD_CHANNELS * MEGASAS_MAX_DEV_PER_CHANNEL))) {
3569
3570                memset(instance->local_pd_list, 0,
3571                        MEGASAS_MAX_PD * sizeof(struct megasas_pd_list));
3572
3573                for (pd_index = 0; pd_index < le32_to_cpu(ci->count); pd_index++) {
3574
3575                        instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].tid     =
3576                                le16_to_cpu(pd_addr->deviceId);
3577                        instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveType       =
3578                                                        pd_addr->scsiDevType;
3579                        instance->local_pd_list[le16_to_cpu(pd_addr->deviceId)].driveState      =
3580                                                        MR_PD_STATE_SYSTEM;
3581                        pd_addr++;
3582                }
3583                memcpy(instance->pd_list, instance->local_pd_list,
3584                        sizeof(instance->pd_list));
3585        }
3586
3587        pci_free_consistent(instance->pdev,
3588                                MEGASAS_MAX_PD * sizeof(struct MR_PD_LIST),
3589                                ci, ci_h);
3590        megasas_return_cmd(instance, cmd);
3591
3592        return ret;
3593}
3594
3595/*
3596 * megasas_get_ld_list_info -   Returns FW's ld_list structure
3597 * @instance:                           Adapter soft state
3598 * @ld_list:                            ld_list structure
3599 *
3600 * Issues an internal command (DCMD) to get the FW's controller PD
3601 * list structure.  This information is mainly used to find out SYSTEM
3602 * supported by the FW.
3603 */
3604static int
3605megasas_get_ld_list(struct megasas_instance *instance)
3606{
3607        int ret = 0, ld_index = 0, ids = 0;
3608        struct megasas_cmd *cmd;
3609        struct megasas_dcmd_frame *dcmd;
3610        struct MR_LD_LIST *ci;
3611        dma_addr_t ci_h = 0;
3612        u32 ld_count;
3613
3614        cmd = megasas_get_cmd(instance);
3615
3616        if (!cmd) {
3617                printk(KERN_DEBUG "megasas_get_ld_list: Failed to get cmd\n");
3618                return -ENOMEM;
3619        }
3620
3621        dcmd = &cmd->frame->dcmd;
3622
3623        ci = pci_alloc_consistent(instance->pdev,
3624                                sizeof(struct MR_LD_LIST),
3625                                &ci_h);
3626
3627        if (!ci) {
3628                printk(KERN_DEBUG "Failed to alloc mem in get_ld_list\n");
3629                megasas_return_cmd(instance, cmd);
3630                return -ENOMEM;
3631        }
3632
3633        memset(ci, 0, sizeof(*ci));
3634        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3635
3636        dcmd->cmd = MFI_CMD_DCMD;
3637        dcmd->cmd_status = 0xFF;
3638        dcmd->sge_count = 1;
3639        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3640        dcmd->timeout = 0;
3641        dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_LIST));
3642        dcmd->opcode = cpu_to_le32(MR_DCMD_LD_GET_LIST);
3643        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3644        dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct MR_LD_LIST));
3645        dcmd->pad_0  = 0;
3646
3647        if (!megasas_issue_polled(instance, cmd)) {
3648                ret = 0;
3649        } else {
3650                ret = -1;
3651        }
3652
3653        ld_count = le32_to_cpu(ci->ldCount);
3654
3655        /* the following function will get the instance PD LIST */
3656
3657        if ((ret == 0) && (ld_count <= MAX_LOGICAL_DRIVES)) {
3658                memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
3659
3660                for (ld_index = 0; ld_index < ld_count; ld_index++) {
3661                        if (ci->ldList[ld_index].state != 0) {
3662                                ids = ci->ldList[ld_index].ref.targetId;
3663                                instance->ld_ids[ids] =
3664                                        ci->ldList[ld_index].ref.targetId;
3665                        }
3666                }
3667        }
3668
3669        pci_free_consistent(instance->pdev,
3670                                sizeof(struct MR_LD_LIST),
3671                                ci,
3672                                ci_h);
3673
3674        megasas_return_cmd(instance, cmd);
3675        return ret;
3676}
3677
3678/**
3679 * megasas_ld_list_query -      Returns FW's ld_list structure
3680 * @instance:                           Adapter soft state
3681 * @ld_list:                            ld_list structure
3682 *
3683 * Issues an internal command (DCMD) to get the FW's controller PD
3684 * list structure.  This information is mainly used to find out SYSTEM
3685 * supported by the FW.
3686 */
3687static int
3688megasas_ld_list_query(struct megasas_instance *instance, u8 query_type)
3689{
3690        int ret = 0, ld_index = 0, ids = 0;
3691        struct megasas_cmd *cmd;
3692        struct megasas_dcmd_frame *dcmd;
3693        struct MR_LD_TARGETID_LIST *ci;
3694        dma_addr_t ci_h = 0;
3695        u32 tgtid_count;
3696
3697        cmd = megasas_get_cmd(instance);
3698
3699        if (!cmd) {
3700                printk(KERN_WARNING
3701                       "megasas:(megasas_ld_list_query): Failed to get cmd\n");
3702                return -ENOMEM;
3703        }
3704
3705        dcmd = &cmd->frame->dcmd;
3706
3707        ci = pci_alloc_consistent(instance->pdev,
3708                                  sizeof(struct MR_LD_TARGETID_LIST), &ci_h);
3709
3710        if (!ci) {
3711                printk(KERN_WARNING
3712                       "megasas: Failed to alloc mem for ld_list_query\n");
3713                megasas_return_cmd(instance, cmd);
3714                return -ENOMEM;
3715        }
3716
3717        memset(ci, 0, sizeof(*ci));
3718        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3719
3720        dcmd->mbox.b[0] = query_type;
3721
3722        dcmd->cmd = MFI_CMD_DCMD;
3723        dcmd->cmd_status = 0xFF;
3724        dcmd->sge_count = 1;
3725        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3726        dcmd->timeout = 0;
3727        dcmd->data_xfer_len = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
3728        dcmd->opcode = cpu_to_le32(MR_DCMD_LD_LIST_QUERY);
3729        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3730        dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct MR_LD_TARGETID_LIST));
3731        dcmd->pad_0  = 0;
3732
3733        if (!megasas_issue_polled(instance, cmd) && !dcmd->cmd_status) {
3734                ret = 0;
3735        } else {
3736                /* On failure, call older LD list DCMD */
3737                ret = 1;
3738        }
3739
3740        tgtid_count = le32_to_cpu(ci->count);
3741
3742        if ((ret == 0) && (tgtid_count <= (MAX_LOGICAL_DRIVES))) {
3743                memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
3744                for (ld_index = 0; ld_index < tgtid_count; ld_index++) {
3745                        ids = ci->targetId[ld_index];
3746                        instance->ld_ids[ids] = ci->targetId[ld_index];
3747                }
3748
3749        }
3750
3751        pci_free_consistent(instance->pdev, sizeof(struct MR_LD_TARGETID_LIST),
3752                            ci, ci_h);
3753
3754        megasas_return_cmd(instance, cmd);
3755
3756        return ret;
3757}
3758
3759/**
3760 * megasas_get_controller_info -        Returns FW's controller structure
3761 * @instance:                           Adapter soft state
3762 * @ctrl_info:                          Controller information structure
3763 *
3764 * Issues an internal command (DCMD) to get the FW's controller structure.
3765 * This information is mainly used to find out the maximum IO transfer per
3766 * command supported by the FW.
3767 */
3768static int
3769megasas_get_ctrl_info(struct megasas_instance *instance,
3770                      struct megasas_ctrl_info *ctrl_info)
3771{
3772        int ret = 0;
3773        struct megasas_cmd *cmd;
3774        struct megasas_dcmd_frame *dcmd;
3775        struct megasas_ctrl_info *ci;
3776        dma_addr_t ci_h = 0;
3777
3778        cmd = megasas_get_cmd(instance);
3779
3780        if (!cmd) {
3781                printk(KERN_DEBUG "megasas: Failed to get a free cmd\n");
3782                return -ENOMEM;
3783        }
3784
3785        dcmd = &cmd->frame->dcmd;
3786
3787        ci = pci_alloc_consistent(instance->pdev,
3788                                  sizeof(struct megasas_ctrl_info), &ci_h);
3789
3790        if (!ci) {
3791                printk(KERN_DEBUG "Failed to alloc mem for ctrl info\n");
3792                megasas_return_cmd(instance, cmd);
3793                return -ENOMEM;
3794        }
3795
3796        memset(ci, 0, sizeof(*ci));
3797        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
3798
3799        dcmd->cmd = MFI_CMD_DCMD;
3800        dcmd->cmd_status = 0xFF;
3801        dcmd->sge_count = 1;
3802        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
3803        dcmd->timeout = 0;
3804        dcmd->pad_0 = 0;
3805        dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_ctrl_info));
3806        dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_GET_INFO);
3807        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(ci_h);
3808        dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_ctrl_info));
3809
3810        if (!megasas_issue_polled(instance, cmd)) {
3811                ret = 0;
3812                memcpy(ctrl_info, ci, sizeof(struct megasas_ctrl_info));
3813        } else {
3814                ret = -1;
3815        }
3816
3817        pci_free_consistent(instance->pdev, sizeof(struct megasas_ctrl_info),
3818                            ci, ci_h);
3819
3820        megasas_return_cmd(instance, cmd);
3821        return ret;
3822}
3823
3824/**
3825 * megasas_issue_init_mfi -     Initializes the FW
3826 * @instance:           Adapter soft state
3827 *
3828 * Issues the INIT MFI cmd
3829 */
3830static int
3831megasas_issue_init_mfi(struct megasas_instance *instance)
3832{
3833        u32 context;
3834
3835        struct megasas_cmd *cmd;
3836
3837        struct megasas_init_frame *init_frame;
3838        struct megasas_init_queue_info *initq_info;
3839        dma_addr_t init_frame_h;
3840        dma_addr_t initq_info_h;
3841
3842        /*
3843         * Prepare a init frame. Note the init frame points to queue info
3844         * structure. Each frame has SGL allocated after first 64 bytes. For
3845         * this frame - since we don't need any SGL - we use SGL's space as
3846         * queue info structure
3847         *
3848         * We will not get a NULL command below. We just created the pool.
3849         */
3850        cmd = megasas_get_cmd(instance);
3851
3852        init_frame = (struct megasas_init_frame *)cmd->frame;
3853        initq_info = (struct megasas_init_queue_info *)
3854                ((unsigned long)init_frame + 64);
3855
3856        init_frame_h = cmd->frame_phys_addr;
3857        initq_info_h = init_frame_h + 64;
3858
3859        context = init_frame->context;
3860        memset(init_frame, 0, MEGAMFI_FRAME_SIZE);
3861        memset(initq_info, 0, sizeof(struct megasas_init_queue_info));
3862        init_frame->context = context;
3863
3864        initq_info->reply_queue_entries = cpu_to_le32(instance->max_fw_cmds + 1);
3865        initq_info->reply_queue_start_phys_addr_lo = cpu_to_le32(instance->reply_queue_h);
3866
3867        initq_info->producer_index_phys_addr_lo = cpu_to_le32(instance->producer_h);
3868        initq_info->consumer_index_phys_addr_lo = cpu_to_le32(instance->consumer_h);
3869
3870        init_frame->cmd = MFI_CMD_INIT;
3871        init_frame->cmd_status = 0xFF;
3872        init_frame->queue_info_new_phys_addr_lo =
3873                cpu_to_le32(lower_32_bits(initq_info_h));
3874        init_frame->queue_info_new_phys_addr_hi =
3875                cpu_to_le32(upper_32_bits(initq_info_h));
3876
3877        init_frame->data_xfer_len = cpu_to_le32(sizeof(struct megasas_init_queue_info));
3878
3879        /*
3880         * disable the intr before firing the init frame to FW
3881         */
3882        instance->instancet->disable_intr(instance);
3883
3884        /*
3885         * Issue the init frame in polled mode
3886         */
3887
3888        if (megasas_issue_polled(instance, cmd)) {
3889                printk(KERN_ERR "megasas: Failed to init firmware\n");
3890                megasas_return_cmd(instance, cmd);
3891                goto fail_fw_init;
3892        }
3893
3894        megasas_return_cmd(instance, cmd);
3895
3896        return 0;
3897
3898fail_fw_init:
3899        return -EINVAL;
3900}
3901
3902static u32
3903megasas_init_adapter_mfi(struct megasas_instance *instance)
3904{
3905        struct megasas_register_set __iomem *reg_set;
3906        u32 context_sz;
3907        u32 reply_q_sz;
3908
3909        reg_set = instance->reg_set;
3910
3911        /*
3912         * Get various operational parameters from status register
3913         */
3914        instance->max_fw_cmds = instance->instancet->read_fw_status_reg(reg_set) & 0x00FFFF;
3915        /*
3916         * Reduce the max supported cmds by 1. This is to ensure that the
3917         * reply_q_sz (1 more than the max cmd that driver may send)
3918         * does not exceed max cmds that the FW can support
3919         */
3920        instance->max_fw_cmds = instance->max_fw_cmds-1;
3921        instance->max_mfi_cmds = instance->max_fw_cmds;
3922        instance->max_num_sge = (instance->instancet->read_fw_status_reg(reg_set) & 0xFF0000) >>
3923                                        0x10;
3924        /*
3925         * Create a pool of commands
3926         */
3927        if (megasas_alloc_cmds(instance))
3928                goto fail_alloc_cmds;
3929
3930        /*
3931         * Allocate memory for reply queue. Length of reply queue should
3932         * be _one_ more than the maximum commands handled by the firmware.
3933         *
3934         * Note: When FW completes commands, it places corresponding contex
3935         * values in this circular reply queue. This circular queue is a fairly
3936         * typical producer-consumer queue. FW is the producer (of completed
3937         * commands) and the driver is the consumer.
3938         */
3939        context_sz = sizeof(u32);
3940        reply_q_sz = context_sz * (instance->max_fw_cmds + 1);
3941
3942        instance->reply_queue = pci_alloc_consistent(instance->pdev,
3943                                                     reply_q_sz,
3944                                                     &instance->reply_queue_h);
3945
3946        if (!instance->reply_queue) {
3947                printk(KERN_DEBUG "megasas: Out of DMA mem for reply queue\n");
3948                goto fail_reply_queue;
3949        }
3950
3951        if (megasas_issue_init_mfi(instance))
3952                goto fail_fw_init;
3953
3954        instance->fw_support_ieee = 0;
3955        instance->fw_support_ieee =
3956                (instance->instancet->read_fw_status_reg(reg_set) &
3957                0x04000000);
3958
3959        printk(KERN_NOTICE "megasas_init_mfi: fw_support_ieee=%d",
3960                        instance->fw_support_ieee);
3961
3962        if (instance->fw_support_ieee)
3963                instance->flag_ieee = 1;
3964
3965        return 0;
3966
3967fail_fw_init:
3968
3969        pci_free_consistent(instance->pdev, reply_q_sz,
3970                            instance->reply_queue, instance->reply_queue_h);
3971fail_reply_queue:
3972        megasas_free_cmds(instance);
3973
3974fail_alloc_cmds:
3975        return 1;
3976}
3977
3978/**
3979 * megasas_init_fw -    Initializes the FW
3980 * @instance:           Adapter soft state
3981 *
3982 * This is the main function for initializing firmware
3983 */
3984
3985static int megasas_init_fw(struct megasas_instance *instance)
3986{
3987        u32 max_sectors_1;
3988        u32 max_sectors_2;
3989        u32 tmp_sectors, msix_enable, scratch_pad_2;
3990        resource_size_t base_addr;
3991        struct megasas_register_set __iomem *reg_set;
3992        struct megasas_ctrl_info *ctrl_info;
3993        unsigned long bar_list;
3994        int i, loop, fw_msix_count = 0;
3995        struct IOV_111 *iovPtr;
3996
3997        /* Find first memory bar */
3998        bar_list = pci_select_bars(instance->pdev, IORESOURCE_MEM);
3999        instance->bar = find_first_bit(&bar_list, sizeof(unsigned long));
4000        if (pci_request_selected_regions(instance->pdev, instance->bar,
4001                                         "megasas: LSI")) {
4002                printk(KERN_DEBUG "megasas: IO memory region busy!\n");
4003                return -EBUSY;
4004        }
4005
4006        base_addr = pci_resource_start(instance->pdev, instance->bar);
4007        instance->reg_set = ioremap_nocache(base_addr, 8192);
4008
4009        if (!instance->reg_set) {
4010                printk(KERN_DEBUG "megasas: Failed to map IO mem\n");
4011                goto fail_ioremap;
4012        }
4013
4014        reg_set = instance->reg_set;
4015
4016        switch (instance->pdev->device) {
4017        case PCI_DEVICE_ID_LSI_FUSION:
4018        case PCI_DEVICE_ID_LSI_PLASMA:
4019        case PCI_DEVICE_ID_LSI_INVADER:
4020        case PCI_DEVICE_ID_LSI_FURY:
4021                instance->instancet = &megasas_instance_template_fusion;
4022                break;
4023        case PCI_DEVICE_ID_LSI_SAS1078R:
4024        case PCI_DEVICE_ID_LSI_SAS1078DE:
4025                instance->instancet = &megasas_instance_template_ppc;
4026                break;
4027        case PCI_DEVICE_ID_LSI_SAS1078GEN2:
4028        case PCI_DEVICE_ID_LSI_SAS0079GEN2:
4029                instance->instancet = &megasas_instance_template_gen2;
4030                break;
4031        case PCI_DEVICE_ID_LSI_SAS0073SKINNY:
4032        case PCI_DEVICE_ID_LSI_SAS0071SKINNY:
4033                instance->instancet = &megasas_instance_template_skinny;
4034                break;
4035        case PCI_DEVICE_ID_LSI_SAS1064R:
4036        case PCI_DEVICE_ID_DELL_PERC5:
4037        default:
4038                instance->instancet = &megasas_instance_template_xscale;
4039                break;
4040        }
4041
4042        if (megasas_transition_to_ready(instance, 0)) {
4043                atomic_set(&instance->fw_reset_no_pci_access, 1);
4044                instance->instancet->adp_reset
4045                        (instance, instance->reg_set);
4046                atomic_set(&instance->fw_reset_no_pci_access, 0);
4047                dev_info(&instance->pdev->dev,
4048                        "megasas: FW restarted successfully from %s!\n",
4049                        __func__);
4050
4051                /*waitting for about 30 second before retry*/
4052                ssleep(30);
4053
4054                if (megasas_transition_to_ready(instance, 0))
4055                        goto fail_ready_state;
4056        }
4057
4058        /*
4059         * MSI-X host index 0 is common for all adapter.
4060         * It is used for all MPT based Adapters.
4061         */
4062        instance->reply_post_host_index_addr[0] =
4063                (u32 *)((u8 *)instance->reg_set +
4064                MPI2_REPLY_POST_HOST_INDEX_OFFSET);
4065
4066        /* Check if MSI-X is supported while in ready state */
4067        msix_enable = (instance->instancet->read_fw_status_reg(reg_set) &
4068                       0x4000000) >> 0x1a;
4069        if (msix_enable && !msix_disable) {
4070                scratch_pad_2 = readl
4071                        (&instance->reg_set->outbound_scratch_pad_2);
4072                /* Check max MSI-X vectors */
4073                if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4074                    (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA)) {
4075                        instance->msix_vectors = (scratch_pad_2
4076                                & MR_MAX_REPLY_QUEUES_OFFSET) + 1;
4077                        fw_msix_count = instance->msix_vectors;
4078                        if (msix_vectors)
4079                                instance->msix_vectors =
4080                                        min(msix_vectors,
4081                                            instance->msix_vectors);
4082                } else if ((instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER)
4083                        || (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
4084                        /* Invader/Fury supports more than 8 MSI-X */
4085                        instance->msix_vectors = ((scratch_pad_2
4086                                & MR_MAX_REPLY_QUEUES_EXT_OFFSET)
4087                                >> MR_MAX_REPLY_QUEUES_EXT_OFFSET_SHIFT) + 1;
4088                        fw_msix_count = instance->msix_vectors;
4089                        /* Save 1-15 reply post index address to local memory
4090                         * Index 0 is already saved from reg offset
4091                         * MPI2_REPLY_POST_HOST_INDEX_OFFSET
4092                         */
4093                        for (loop = 1; loop < MR_MAX_MSIX_REG_ARRAY; loop++) {
4094                                instance->reply_post_host_index_addr[loop] =
4095                                        (u32 *)((u8 *)instance->reg_set +
4096                                        MPI2_SUP_REPLY_POST_HOST_INDEX_OFFSET
4097                                        + (loop * 0x10));
4098                        }
4099                        if (msix_vectors)
4100                                instance->msix_vectors = min(msix_vectors,
4101                                        instance->msix_vectors);
4102                } else
4103                        instance->msix_vectors = 1;
4104                /* Don't bother allocating more MSI-X vectors than cpus */
4105                instance->msix_vectors = min(instance->msix_vectors,
4106                                             (unsigned int)num_online_cpus());
4107                for (i = 0; i < instance->msix_vectors; i++)
4108                        instance->msixentry[i].entry = i;
4109                i = pci_enable_msix(instance->pdev, instance->msixentry,
4110                                    instance->msix_vectors);
4111                if (i >= 0) {
4112                        if (i) {
4113                                if (!pci_enable_msix(instance->pdev,
4114                                                     instance->msixentry, i))
4115                                        instance->msix_vectors = i;
4116                                else
4117                                        instance->msix_vectors = 0;
4118                        }
4119                } else
4120                        instance->msix_vectors = 0;
4121
4122                dev_info(&instance->pdev->dev, "[scsi%d]: FW supports"
4123                        "<%d> MSIX vector,Online CPUs: <%d>,"
4124                        "Current MSIX <%d>\n", instance->host->host_no,
4125                        fw_msix_count, (unsigned int)num_online_cpus(),
4126                        instance->msix_vectors);
4127        }
4128
4129        /* Get operational params, sge flags, send init cmd to controller */
4130        if (instance->instancet->init_adapter(instance))
4131                goto fail_init_adapter;
4132
4133        printk(KERN_ERR "megasas: INIT adapter done\n");
4134
4135        /** for passthrough
4136        * the following function will get the PD LIST.
4137        */
4138
4139        memset(instance->pd_list, 0 ,
4140                (MEGASAS_MAX_PD * sizeof(struct megasas_pd_list)));
4141        if (megasas_get_pd_list(instance) < 0) {
4142                printk(KERN_ERR "megasas: failed to get PD list\n");
4143                goto fail_init_adapter;
4144        }
4145
4146        memset(instance->ld_ids, 0xff, MEGASAS_MAX_LD_IDS);
4147        if (megasas_ld_list_query(instance,
4148                                  MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
4149                megasas_get_ld_list(instance);
4150
4151        ctrl_info = kmalloc(sizeof(struct megasas_ctrl_info), GFP_KERNEL);
4152
4153        /*
4154         * Compute the max allowed sectors per IO: The controller info has two
4155         * limits on max sectors. Driver should use the minimum of these two.
4156         *
4157         * 1 << stripe_sz_ops.min = max sectors per strip
4158         *
4159         * Note that older firmwares ( < FW ver 30) didn't report information
4160         * to calculate max_sectors_1. So the number ended up as zero always.
4161         */
4162        tmp_sectors = 0;
4163        if (ctrl_info && !megasas_get_ctrl_info(instance, ctrl_info)) {
4164
4165                max_sectors_1 = (1 << ctrl_info->stripe_sz_ops.min) *
4166                        le16_to_cpu(ctrl_info->max_strips_per_io);
4167                max_sectors_2 = le32_to_cpu(ctrl_info->max_request_size);
4168
4169                tmp_sectors = min_t(u32, max_sectors_1 , max_sectors_2);
4170
4171                /*Check whether controller is iMR or MR */
4172                if (ctrl_info->memory_size) {
4173                        instance->is_imr = 0;
4174                        dev_info(&instance->pdev->dev, "Controller type: MR,"
4175                                "Memory size is: %dMB\n",
4176                                le16_to_cpu(ctrl_info->memory_size));
4177                } else {
4178                        instance->is_imr = 1;
4179                        dev_info(&instance->pdev->dev,
4180                                "Controller type: iMR\n");
4181                }
4182                /* OnOffProperties are converted into CPU arch*/
4183                le32_to_cpus((u32 *)&ctrl_info->properties.OnOffProperties);
4184                instance->disableOnlineCtrlReset =
4185                ctrl_info->properties.OnOffProperties.disableOnlineCtrlReset;
4186                /* adapterOperations2 are converted into CPU arch*/
4187                le32_to_cpus((u32 *)&ctrl_info->adapterOperations2);
4188                instance->mpio = ctrl_info->adapterOperations2.mpio;
4189                instance->UnevenSpanSupport =
4190                        ctrl_info->adapterOperations2.supportUnevenSpans;
4191                if (instance->UnevenSpanSupport) {
4192                        struct fusion_context *fusion = instance->ctrl_context;
4193                        dev_info(&instance->pdev->dev, "FW supports: "
4194                        "UnevenSpanSupport=%x\n", instance->UnevenSpanSupport);
4195                        if (MR_ValidateMapInfo(instance))
4196                                fusion->fast_path_io = 1;
4197                        else
4198                                fusion->fast_path_io = 0;
4199
4200                }
4201                if (ctrl_info->host_interface.SRIOV) {
4202                        if (!ctrl_info->adapterOperations2.activePassive)
4203                                instance->PlasmaFW111 = 1;
4204
4205                        if (!instance->PlasmaFW111)
4206                                instance->requestorId =
4207                                        ctrl_info->iov.requestorId;
4208                        else {
4209                                iovPtr = (struct IOV_111 *)((unsigned char *)ctrl_info + IOV_111_OFFSET);
4210                                instance->requestorId = iovPtr->requestorId;
4211                        }
4212                        printk(KERN_WARNING "megaraid_sas: I am VF "
4213                               "requestorId %d\n", instance->requestorId);
4214                }
4215        }
4216        instance->max_sectors_per_req = instance->max_num_sge *
4217                                                PAGE_SIZE / 512;
4218        if (tmp_sectors && (instance->max_sectors_per_req > tmp_sectors))
4219                instance->max_sectors_per_req = tmp_sectors;
4220
4221        kfree(ctrl_info);
4222
4223        /* Check for valid throttlequeuedepth module parameter */
4224        if (instance->is_imr) {
4225                if (throttlequeuedepth > (instance->max_fw_cmds -
4226                                          MEGASAS_SKINNY_INT_CMDS))
4227                        instance->throttlequeuedepth =
4228                                MEGASAS_THROTTLE_QUEUE_DEPTH;
4229                else
4230                        instance->throttlequeuedepth = throttlequeuedepth;
4231        } else {
4232                if (throttlequeuedepth > (instance->max_fw_cmds -
4233                                          MEGASAS_INT_CMDS))
4234                        instance->throttlequeuedepth =
4235                                MEGASAS_THROTTLE_QUEUE_DEPTH;
4236                else
4237                        instance->throttlequeuedepth = throttlequeuedepth;
4238        }
4239
4240        /*
4241        * Setup tasklet for cmd completion
4242        */
4243
4244        tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
4245                (unsigned long)instance);
4246
4247        /* Launch SR-IOV heartbeat timer */
4248        if (instance->requestorId) {
4249                if (!megasas_sriov_start_heartbeat(instance, 1))
4250                        megasas_start_timer(instance,
4251                                            &instance->sriov_heartbeat_timer,
4252                                            megasas_sriov_heartbeat_handler,
4253                                            MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
4254                else
4255                        instance->skip_heartbeat_timer_del = 1;
4256        }
4257
4258        return 0;
4259
4260fail_init_adapter:
4261fail_ready_state:
4262        iounmap(instance->reg_set);
4263
4264      fail_ioremap:
4265        pci_release_selected_regions(instance->pdev, instance->bar);
4266
4267        return -EINVAL;
4268}
4269
4270/**
4271 * megasas_release_mfi -        Reverses the FW initialization
4272 * @intance:                    Adapter soft state
4273 */
4274static void megasas_release_mfi(struct megasas_instance *instance)
4275{
4276        u32 reply_q_sz = sizeof(u32) *(instance->max_mfi_cmds + 1);
4277
4278        if (instance->reply_queue)
4279                pci_free_consistent(instance->pdev, reply_q_sz,
4280                            instance->reply_queue, instance->reply_queue_h);
4281
4282        megasas_free_cmds(instance);
4283
4284        iounmap(instance->reg_set);
4285
4286        pci_release_selected_regions(instance->pdev, instance->bar);
4287}
4288
4289/**
4290 * megasas_get_seq_num -        Gets latest event sequence numbers
4291 * @instance:                   Adapter soft state
4292 * @eli:                        FW event log sequence numbers information
4293 *
4294 * FW maintains a log of all events in a non-volatile area. Upper layers would
4295 * usually find out the latest sequence number of the events, the seq number at
4296 * the boot etc. They would "read" all the events below the latest seq number
4297 * by issuing a direct fw cmd (DCMD). For the future events (beyond latest seq
4298 * number), they would subsribe to AEN (asynchronous event notification) and
4299 * wait for the events to happen.
4300 */
4301static int
4302megasas_get_seq_num(struct megasas_instance *instance,
4303                    struct megasas_evt_log_info *eli)
4304{
4305        struct megasas_cmd *cmd;
4306        struct megasas_dcmd_frame *dcmd;
4307        struct megasas_evt_log_info *el_info;
4308        dma_addr_t el_info_h = 0;
4309
4310        cmd = megasas_get_cmd(instance);
4311
4312        if (!cmd) {
4313                return -ENOMEM;
4314        }
4315
4316        dcmd = &cmd->frame->dcmd;
4317        el_info = pci_alloc_consistent(instance->pdev,
4318                                       sizeof(struct megasas_evt_log_info),
4319                                       &el_info_h);
4320
4321        if (!el_info) {
4322                megasas_return_cmd(instance, cmd);
4323                return -ENOMEM;
4324        }
4325
4326        memset(el_info, 0, sizeof(*el_info));
4327        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4328
4329        dcmd->cmd = MFI_CMD_DCMD;
4330        dcmd->cmd_status = 0x0;
4331        dcmd->sge_count = 1;
4332        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
4333        dcmd->timeout = 0;
4334        dcmd->pad_0 = 0;
4335        dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_log_info));
4336        dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_GET_INFO);
4337        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(el_info_h);
4338        dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_evt_log_info));
4339
4340        if (megasas_issue_blocked_cmd(instance, cmd, 30))
4341                dev_err(&instance->pdev->dev, "Command timedout"
4342                        "from %s\n", __func__);
4343        else {
4344                /*
4345                 * Copy the data back into callers buffer
4346                 */
4347                eli->newest_seq_num = le32_to_cpu(el_info->newest_seq_num);
4348                eli->oldest_seq_num = le32_to_cpu(el_info->oldest_seq_num);
4349                eli->clear_seq_num = le32_to_cpu(el_info->clear_seq_num);
4350                eli->shutdown_seq_num = le32_to_cpu(el_info->shutdown_seq_num);
4351                eli->boot_seq_num = le32_to_cpu(el_info->boot_seq_num);
4352        }
4353
4354        pci_free_consistent(instance->pdev, sizeof(struct megasas_evt_log_info),
4355                            el_info, el_info_h);
4356
4357        megasas_return_cmd(instance, cmd);
4358
4359        return 0;
4360}
4361
4362/**
4363 * megasas_register_aen -       Registers for asynchronous event notification
4364 * @instance:                   Adapter soft state
4365 * @seq_num:                    The starting sequence number
4366 * @class_locale:               Class of the event
4367 *
4368 * This function subscribes for AEN for events beyond the @seq_num. It requests
4369 * to be notified if and only if the event is of type @class_locale
4370 */
4371static int
4372megasas_register_aen(struct megasas_instance *instance, u32 seq_num,
4373                     u32 class_locale_word)
4374{
4375        int ret_val;
4376        struct megasas_cmd *cmd;
4377        struct megasas_dcmd_frame *dcmd;
4378        union megasas_evt_class_locale curr_aen;
4379        union megasas_evt_class_locale prev_aen;
4380
4381        /*
4382         * If there an AEN pending already (aen_cmd), check if the
4383         * class_locale of that pending AEN is inclusive of the new
4384         * AEN request we currently have. If it is, then we don't have
4385         * to do anything. In other words, whichever events the current
4386         * AEN request is subscribing to, have already been subscribed
4387         * to.
4388         *
4389         * If the old_cmd is _not_ inclusive, then we have to abort
4390         * that command, form a class_locale that is superset of both
4391         * old and current and re-issue to the FW
4392         */
4393
4394        curr_aen.word = class_locale_word;
4395
4396        if (instance->aen_cmd) {
4397
4398                prev_aen.word = instance->aen_cmd->frame->dcmd.mbox.w[1];
4399                prev_aen.members.locale = le16_to_cpu(prev_aen.members.locale);
4400
4401                /*
4402                 * A class whose enum value is smaller is inclusive of all
4403                 * higher values. If a PROGRESS (= -1) was previously
4404                 * registered, then a new registration requests for higher
4405                 * classes need not be sent to FW. They are automatically
4406                 * included.
4407                 *
4408                 * Locale numbers don't have such hierarchy. They are bitmap
4409                 * values
4410                 */
4411                if ((prev_aen.members.class <= curr_aen.members.class) &&
4412                    !((prev_aen.members.locale & curr_aen.members.locale) ^
4413                      curr_aen.members.locale)) {
4414                        /*
4415                         * Previously issued event registration includes
4416                         * current request. Nothing to do.
4417                         */
4418                        return 0;
4419                } else {
4420                        curr_aen.members.locale |= prev_aen.members.locale;
4421
4422                        if (prev_aen.members.class < curr_aen.members.class)
4423                                curr_aen.members.class = prev_aen.members.class;
4424
4425                        instance->aen_cmd->abort_aen = 1;
4426                        ret_val = megasas_issue_blocked_abort_cmd(instance,
4427                                                                  instance->
4428                                                                  aen_cmd, 30);
4429
4430                        if (ret_val) {
4431                                printk(KERN_DEBUG "megasas: Failed to abort "
4432                                       "previous AEN command\n");
4433                                return ret_val;
4434                        }
4435                }
4436        }
4437
4438        cmd = megasas_get_cmd(instance);
4439
4440        if (!cmd)
4441                return -ENOMEM;
4442
4443        dcmd = &cmd->frame->dcmd;
4444
4445        memset(instance->evt_detail, 0, sizeof(struct megasas_evt_detail));
4446
4447        /*
4448         * Prepare DCMD for aen registration
4449         */
4450        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4451
4452        dcmd->cmd = MFI_CMD_DCMD;
4453        dcmd->cmd_status = 0x0;
4454        dcmd->sge_count = 1;
4455        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_READ);
4456        dcmd->timeout = 0;
4457        dcmd->pad_0 = 0;
4458        dcmd->data_xfer_len = cpu_to_le32(sizeof(struct megasas_evt_detail));
4459        dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_EVENT_WAIT);
4460        dcmd->mbox.w[0] = cpu_to_le32(seq_num);
4461        instance->last_seq_num = seq_num;
4462        dcmd->mbox.w[1] = cpu_to_le32(curr_aen.word);
4463        dcmd->sgl.sge32[0].phys_addr = cpu_to_le32(instance->evt_detail_h);
4464        dcmd->sgl.sge32[0].length = cpu_to_le32(sizeof(struct megasas_evt_detail));
4465
4466        if (instance->aen_cmd != NULL) {
4467                megasas_return_cmd(instance, cmd);
4468                return 0;
4469        }
4470
4471        /*
4472         * Store reference to the cmd used to register for AEN. When an
4473         * application wants us to register for AEN, we have to abort this
4474         * cmd and re-register with a new EVENT LOCALE supplied by that app
4475         */
4476        instance->aen_cmd = cmd;
4477
4478        /*
4479         * Issue the aen registration frame
4480         */
4481        instance->instancet->issue_dcmd(instance, cmd);
4482
4483        return 0;
4484}
4485
4486/**
4487 * megasas_start_aen -  Subscribes to AEN during driver load time
4488 * @instance:           Adapter soft state
4489 */
4490static int megasas_start_aen(struct megasas_instance *instance)
4491{
4492        struct megasas_evt_log_info eli;
4493        union megasas_evt_class_locale class_locale;
4494
4495        /*
4496         * Get the latest sequence number from FW
4497         */
4498        memset(&eli, 0, sizeof(eli));
4499
4500        if (megasas_get_seq_num(instance, &eli))
4501                return -1;
4502
4503        /*
4504         * Register AEN with FW for latest sequence number plus 1
4505         */
4506        class_locale.members.reserved = 0;
4507        class_locale.members.locale = MR_EVT_LOCALE_ALL;
4508        class_locale.members.class = MR_EVT_CLASS_DEBUG;
4509
4510        return megasas_register_aen(instance,
4511                        eli.newest_seq_num + 1,
4512                        class_locale.word);
4513}
4514
4515/**
4516 * megasas_io_attach -  Attaches this driver to SCSI mid-layer
4517 * @instance:           Adapter soft state
4518 */
4519static int megasas_io_attach(struct megasas_instance *instance)
4520{
4521        struct Scsi_Host *host = instance->host;
4522
4523        /*
4524         * Export parameters required by SCSI mid-layer
4525         */
4526        host->irq = instance->pdev->irq;
4527        host->unique_id = instance->unique_id;
4528        if (instance->is_imr) {
4529                host->can_queue =
4530                        instance->max_fw_cmds - MEGASAS_SKINNY_INT_CMDS;
4531        } else
4532                host->can_queue =
4533                        instance->max_fw_cmds - MEGASAS_INT_CMDS;
4534        host->this_id = instance->init_id;
4535        host->sg_tablesize = instance->max_num_sge;
4536
4537        if (instance->fw_support_ieee)
4538                instance->max_sectors_per_req = MEGASAS_MAX_SECTORS_IEEE;
4539
4540        /*
4541         * Check if the module parameter value for max_sectors can be used
4542         */
4543        if (max_sectors && max_sectors < instance->max_sectors_per_req)
4544                instance->max_sectors_per_req = max_sectors;
4545        else {
4546                if (max_sectors) {
4547                        if (((instance->pdev->device ==
4548                                PCI_DEVICE_ID_LSI_SAS1078GEN2) ||
4549                                (instance->pdev->device ==
4550                                PCI_DEVICE_ID_LSI_SAS0079GEN2)) &&
4551                                (max_sectors <= MEGASAS_MAX_SECTORS)) {
4552                                instance->max_sectors_per_req = max_sectors;
4553                        } else {
4554                        printk(KERN_INFO "megasas: max_sectors should be > 0"
4555                                "and <= %d (or < 1MB for GEN2 controller)\n",
4556                                instance->max_sectors_per_req);
4557                        }
4558                }
4559        }
4560
4561        host->max_sectors = instance->max_sectors_per_req;
4562        host->cmd_per_lun = MEGASAS_DEFAULT_CMD_PER_LUN;
4563        host->max_channel = MEGASAS_MAX_CHANNELS - 1;
4564        host->max_id = MEGASAS_MAX_DEV_PER_CHANNEL;
4565        host->max_lun = MEGASAS_MAX_LUN;
4566        host->max_cmd_len = 16;
4567
4568        /* Fusion only supports host reset */
4569        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4570            (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
4571            (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
4572            (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY)) {
4573                host->hostt->eh_device_reset_handler = NULL;
4574                host->hostt->eh_bus_reset_handler = NULL;
4575        }
4576
4577        /*
4578         * Notify the mid-layer about the new controller
4579         */
4580        if (scsi_add_host(host, &instance->pdev->dev)) {
4581                printk(KERN_DEBUG "megasas: scsi_add_host failed\n");
4582                return -ENODEV;
4583        }
4584
4585        /*
4586         * Trigger SCSI to scan our drives
4587         */
4588        scsi_scan_host(host);
4589        return 0;
4590}
4591
4592static int
4593megasas_set_dma_mask(struct pci_dev *pdev)
4594{
4595        /*
4596         * All our contollers are capable of performing 64-bit DMA
4597         */
4598        if (IS_DMA64) {
4599                if (pci_set_dma_mask(pdev, DMA_BIT_MASK(64)) != 0) {
4600
4601                        if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
4602                                goto fail_set_dma_mask;
4603                }
4604        } else {
4605                if (pci_set_dma_mask(pdev, DMA_BIT_MASK(32)) != 0)
4606                        goto fail_set_dma_mask;
4607        }
4608        /*
4609         * Ensure that all data structures are allocated in 32-bit
4610         * memory.
4611         */
4612        if (pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)) != 0) {
4613                /* Try 32bit DMA mask and 32 bit Consistent dma mask */
4614                if (!pci_set_dma_mask(pdev, DMA_BIT_MASK(32))
4615                        && !pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32)))
4616                        dev_info(&pdev->dev, "set 32bit DMA mask"
4617                                "and 32 bit consistent mask\n");
4618                else
4619                        goto fail_set_dma_mask;
4620        }
4621
4622        return 0;
4623
4624fail_set_dma_mask:
4625        return 1;
4626}
4627
4628/**
4629 * megasas_probe_one -  PCI hotplug entry point
4630 * @pdev:               PCI device structure
4631 * @id:                 PCI ids of supported hotplugged adapter
4632 */
4633static int megasas_probe_one(struct pci_dev *pdev,
4634                             const struct pci_device_id *id)
4635{
4636        int rval, pos, i, j, cpu;
4637        struct Scsi_Host *host;
4638        struct megasas_instance *instance;
4639        u16 control = 0;
4640
4641        /* Reset MSI-X in the kdump kernel */
4642        if (reset_devices) {
4643                pos = pci_find_capability(pdev, PCI_CAP_ID_MSIX);
4644                if (pos) {
4645                        pci_read_config_word(pdev, pos + PCI_MSIX_FLAGS,
4646                                             &control);
4647                        if (control & PCI_MSIX_FLAGS_ENABLE) {
4648                                dev_info(&pdev->dev, "resetting MSI-X\n");
4649                                pci_write_config_word(pdev,
4650                                                      pos + PCI_MSIX_FLAGS,
4651                                                      control &
4652                                                      ~PCI_MSIX_FLAGS_ENABLE);
4653                        }
4654                }
4655        }
4656
4657        /*
4658         * Announce PCI information
4659         */
4660        printk(KERN_INFO "megasas: %#4.04x:%#4.04x:%#4.04x:%#4.04x: ",
4661               pdev->vendor, pdev->device, pdev->subsystem_vendor,
4662               pdev->subsystem_device);
4663
4664        printk("bus %d:slot %d:func %d\n",
4665               pdev->bus->number, PCI_SLOT(pdev->devfn), PCI_FUNC(pdev->devfn));
4666
4667        /*
4668         * PCI prepping: enable device set bus mastering and dma mask
4669         */
4670        rval = pci_enable_device_mem(pdev);
4671
4672        if (rval) {
4673                return rval;
4674        }
4675
4676        pci_set_master(pdev);
4677
4678        if (megasas_set_dma_mask(pdev))
4679                goto fail_set_dma_mask;
4680
4681        host = scsi_host_alloc(&megasas_template,
4682                               sizeof(struct megasas_instance));
4683
4684        if (!host) {
4685                printk(KERN_DEBUG "megasas: scsi_host_alloc failed\n");
4686                goto fail_alloc_instance;
4687        }
4688
4689        instance = (struct megasas_instance *)host->hostdata;
4690        memset(instance, 0, sizeof(*instance));
4691        atomic_set( &instance->fw_reset_no_pci_access, 0 );
4692        instance->pdev = pdev;
4693
4694        switch (instance->pdev->device) {
4695        case PCI_DEVICE_ID_LSI_FUSION:
4696        case PCI_DEVICE_ID_LSI_PLASMA:
4697        case PCI_DEVICE_ID_LSI_INVADER:
4698        case PCI_DEVICE_ID_LSI_FURY:
4699        {
4700                struct fusion_context *fusion;
4701
4702                instance->ctrl_context =
4703                        kzalloc(sizeof(struct fusion_context), GFP_KERNEL);
4704                if (!instance->ctrl_context) {
4705                        printk(KERN_DEBUG "megasas: Failed to allocate "
4706                               "memory for Fusion context info\n");
4707                        goto fail_alloc_dma_buf;
4708                }
4709                fusion = instance->ctrl_context;
4710                INIT_LIST_HEAD(&fusion->cmd_pool);
4711                spin_lock_init(&fusion->cmd_pool_lock);
4712        }
4713        break;
4714        default: /* For all other supported controllers */
4715
4716                instance->producer =
4717                        pci_alloc_consistent(pdev, sizeof(u32),
4718                                             &instance->producer_h);
4719                instance->consumer =
4720                        pci_alloc_consistent(pdev, sizeof(u32),
4721                                             &instance->consumer_h);
4722
4723                if (!instance->producer || !instance->consumer) {
4724                        printk(KERN_DEBUG "megasas: Failed to allocate"
4725                               "memory for producer, consumer\n");
4726                        goto fail_alloc_dma_buf;
4727                }
4728
4729                *instance->producer = 0;
4730                *instance->consumer = 0;
4731                break;
4732        }
4733
4734        megasas_poll_wait_aen = 0;
4735        instance->flag_ieee = 0;
4736        instance->ev = NULL;
4737        instance->issuepend_done = 1;
4738        instance->adprecovery = MEGASAS_HBA_OPERATIONAL;
4739        instance->is_imr = 0;
4740        megasas_poll_wait_aen = 0;
4741
4742        instance->evt_detail = pci_alloc_consistent(pdev,
4743                                                    sizeof(struct
4744                                                           megasas_evt_detail),
4745                                                    &instance->evt_detail_h);
4746
4747        if (!instance->evt_detail) {
4748                printk(KERN_DEBUG "megasas: Failed to allocate memory for "
4749                       "event detail structure\n");
4750                goto fail_alloc_dma_buf;
4751        }
4752
4753        /*
4754         * Initialize locks and queues
4755         */
4756        INIT_LIST_HEAD(&instance->cmd_pool);
4757        INIT_LIST_HEAD(&instance->internal_reset_pending_q);
4758
4759        atomic_set(&instance->fw_outstanding,0);
4760
4761        init_waitqueue_head(&instance->int_cmd_wait_q);
4762        init_waitqueue_head(&instance->abort_cmd_wait_q);
4763
4764        spin_lock_init(&instance->cmd_pool_lock);
4765        spin_lock_init(&instance->hba_lock);
4766        spin_lock_init(&instance->completion_lock);
4767
4768        mutex_init(&instance->aen_mutex);
4769        mutex_init(&instance->reset_mutex);
4770
4771        /*
4772         * Initialize PCI related and misc parameters
4773         */
4774        instance->host = host;
4775        instance->unique_id = pdev->bus->number << 8 | pdev->devfn;
4776        instance->init_id = MEGASAS_DEFAULT_INIT_ID;
4777
4778        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0073SKINNY) ||
4779                (instance->pdev->device == PCI_DEVICE_ID_LSI_SAS0071SKINNY)) {
4780                instance->flag_ieee = 1;
4781                sema_init(&instance->ioctl_sem, MEGASAS_SKINNY_INT_CMDS);
4782        } else
4783                sema_init(&instance->ioctl_sem, MEGASAS_INT_CMDS);
4784
4785        megasas_dbg_lvl = 0;
4786        instance->flag = 0;
4787        instance->unload = 1;
4788        instance->last_time = 0;
4789        instance->disableOnlineCtrlReset = 1;
4790        instance->UnevenSpanSupport = 0;
4791
4792        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4793            (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
4794            (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
4795            (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY))
4796                INIT_WORK(&instance->work_init, megasas_fusion_ocr_wq);
4797        else
4798                INIT_WORK(&instance->work_init, process_fw_state_change_wq);
4799
4800        /*
4801         * Initialize MFI Firmware
4802         */
4803        if (megasas_init_fw(instance))
4804                goto fail_init_mfi;
4805
4806        if (instance->requestorId) {
4807                if (instance->PlasmaFW111) {
4808                        instance->vf_affiliation_111 =
4809                                pci_alloc_consistent(pdev, sizeof(struct MR_LD_VF_AFFILIATION_111),
4810                                                     &instance->vf_affiliation_111_h);
4811                        if (!instance->vf_affiliation_111)
4812                                printk(KERN_WARNING "megasas: Can't allocate "
4813                                       "memory for VF affiliation buffer\n");
4814                } else {
4815                        instance->vf_affiliation =
4816                                pci_alloc_consistent(pdev,
4817                                                     (MAX_LOGICAL_DRIVES + 1) *
4818                                                     sizeof(struct MR_LD_VF_AFFILIATION),
4819                                                     &instance->vf_affiliation_h);
4820                        if (!instance->vf_affiliation)
4821                                printk(KERN_WARNING "megasas: Can't allocate "
4822                                       "memory for VF affiliation buffer\n");
4823                }
4824        }
4825
4826retry_irq_register:
4827        /*
4828         * Register IRQ
4829         */
4830        if (instance->msix_vectors) {
4831                cpu = cpumask_first(cpu_online_mask);
4832                for (i = 0; i < instance->msix_vectors; i++) {
4833                        instance->irq_context[i].instance = instance;
4834                        instance->irq_context[i].MSIxIndex = i;
4835                        if (request_irq(instance->msixentry[i].vector,
4836                                        instance->instancet->service_isr, 0,
4837                                        "megasas",
4838                                        &instance->irq_context[i])) {
4839                                printk(KERN_DEBUG "megasas: Failed to "
4840                                       "register IRQ for vector %d.\n", i);
4841                                for (j = 0; j < i; j++) {
4842                                        irq_set_affinity_hint(
4843                                                instance->msixentry[j].vector, NULL);
4844                                        free_irq(
4845                                                instance->msixentry[j].vector,
4846                                                &instance->irq_context[j]);
4847                                }
4848                                /* Retry irq register for IO_APIC */
4849                                instance->msix_vectors = 0;
4850                                goto retry_irq_register;
4851                        }
4852                        if (irq_set_affinity_hint(instance->msixentry[i].vector,
4853                                get_cpu_mask(cpu)))
4854                                dev_err(&instance->pdev->dev, "Error setting"
4855                                        "affinity hint for cpu %d\n", cpu);
4856                        cpu = cpumask_next(cpu, cpu_online_mask);
4857                }
4858        } else {
4859                instance->irq_context[0].instance = instance;
4860                instance->irq_context[0].MSIxIndex = 0;
4861                if (request_irq(pdev->irq, instance->instancet->service_isr,
4862                                IRQF_SHARED, "megasas",
4863                                &instance->irq_context[0])) {
4864                        printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
4865                        goto fail_irq;
4866                }
4867        }
4868
4869        instance->instancet->enable_intr(instance);
4870
4871        /*
4872         * Store instance in PCI softstate
4873         */
4874        pci_set_drvdata(pdev, instance);
4875
4876        /*
4877         * Add this controller to megasas_mgmt_info structure so that it
4878         * can be exported to management applications
4879         */
4880        megasas_mgmt_info.count++;
4881        megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = instance;
4882        megasas_mgmt_info.max_index++;
4883
4884        /*
4885         * Register with SCSI mid-layer
4886         */
4887        if (megasas_io_attach(instance))
4888                goto fail_io_attach;
4889
4890        instance->unload = 0;
4891
4892        /*
4893         * Initiate AEN (Asynchronous Event Notification)
4894         */
4895        if (megasas_start_aen(instance)) {
4896                printk(KERN_DEBUG "megasas: start aen failed\n");
4897                goto fail_start_aen;
4898        }
4899
4900        return 0;
4901
4902      fail_start_aen:
4903      fail_io_attach:
4904        megasas_mgmt_info.count--;
4905        megasas_mgmt_info.instance[megasas_mgmt_info.max_index] = NULL;
4906        megasas_mgmt_info.max_index--;
4907
4908        instance->instancet->disable_intr(instance);
4909        if (instance->msix_vectors)
4910                for (i = 0; i < instance->msix_vectors; i++) {
4911                        irq_set_affinity_hint(
4912                                instance->msixentry[i].vector, NULL);
4913                        free_irq(instance->msixentry[i].vector,
4914                                 &instance->irq_context[i]);
4915                }
4916        else
4917                free_irq(instance->pdev->irq, &instance->irq_context[0]);
4918fail_irq:
4919        if ((instance->pdev->device == PCI_DEVICE_ID_LSI_FUSION) ||
4920            (instance->pdev->device == PCI_DEVICE_ID_LSI_PLASMA) ||
4921            (instance->pdev->device == PCI_DEVICE_ID_LSI_INVADER) ||
4922            (instance->pdev->device == PCI_DEVICE_ID_LSI_FURY))
4923                megasas_release_fusion(instance);
4924        else
4925                megasas_release_mfi(instance);
4926      fail_init_mfi:
4927        if (instance->msix_vectors)
4928                pci_disable_msix(instance->pdev);
4929      fail_alloc_dma_buf:
4930        if (instance->evt_detail)
4931                pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
4932                                    instance->evt_detail,
4933                                    instance->evt_detail_h);
4934
4935        if (instance->producer)
4936                pci_free_consistent(pdev, sizeof(u32), instance->producer,
4937                                    instance->producer_h);
4938        if (instance->consumer)
4939                pci_free_consistent(pdev, sizeof(u32), instance->consumer,
4940                                    instance->consumer_h);
4941        scsi_host_put(host);
4942
4943      fail_alloc_instance:
4944      fail_set_dma_mask:
4945        pci_disable_device(pdev);
4946
4947        return -ENODEV;
4948}
4949
4950/**
4951 * megasas_flush_cache -        Requests FW to flush all its caches
4952 * @instance:                   Adapter soft state
4953 */
4954static void megasas_flush_cache(struct megasas_instance *instance)
4955{
4956        struct megasas_cmd *cmd;
4957        struct megasas_dcmd_frame *dcmd;
4958
4959        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
4960                return;
4961
4962        cmd = megasas_get_cmd(instance);
4963
4964        if (!cmd)
4965                return;
4966
4967        dcmd = &cmd->frame->dcmd;
4968
4969        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
4970
4971        dcmd->cmd = MFI_CMD_DCMD;
4972        dcmd->cmd_status = 0x0;
4973        dcmd->sge_count = 0;
4974        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
4975        dcmd->timeout = 0;
4976        dcmd->pad_0 = 0;
4977        dcmd->data_xfer_len = 0;
4978        dcmd->opcode = cpu_to_le32(MR_DCMD_CTRL_CACHE_FLUSH);
4979        dcmd->mbox.b[0] = MR_FLUSH_CTRL_CACHE | MR_FLUSH_DISK_CACHE;
4980
4981        if (megasas_issue_blocked_cmd(instance, cmd, 30))
4982                dev_err(&instance->pdev->dev, "Command timedout"
4983                        " from %s\n", __func__);
4984
4985        megasas_return_cmd(instance, cmd);
4986
4987        return;
4988}
4989
4990/**
4991 * megasas_shutdown_controller -        Instructs FW to shutdown the controller
4992 * @instance:                           Adapter soft state
4993 * @opcode:                             Shutdown/Hibernate
4994 */
4995static void megasas_shutdown_controller(struct megasas_instance *instance,
4996                                        u32 opcode)
4997{
4998        struct megasas_cmd *cmd;
4999        struct megasas_dcmd_frame *dcmd;
5000
5001        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR)
5002                return;
5003
5004        cmd = megasas_get_cmd(instance);
5005
5006        if (!cmd)
5007                return;
5008
5009        if (instance->aen_cmd)
5010                megasas_issue_blocked_abort_cmd(instance,
5011                        instance->aen_cmd, 30);
5012        if (instance->map_update_cmd)
5013                megasas_issue_blocked_abort_cmd(instance,
5014                        instance->map_update_cmd, 30);
5015        dcmd = &cmd->frame->dcmd;
5016
5017        memset(dcmd->mbox.b, 0, MFI_MBOX_SIZE);
5018
5019        dcmd->cmd = MFI_CMD_DCMD;
5020        dcmd->cmd_status = 0x0;
5021        dcmd->sge_count = 0;
5022        dcmd->flags = cpu_to_le16(MFI_FRAME_DIR_NONE);
5023        dcmd->timeout = 0;
5024        dcmd->pad_0 = 0;
5025        dcmd->data_xfer_len = 0;
5026        dcmd->opcode = cpu_to_le32(opcode);
5027
5028        if (megasas_issue_blocked_cmd(instance, cmd, 30))
5029                dev_err(&instance->pdev->dev, "Command timedout"
5030                        "from %s\n", __func__);
5031
5032        megasas_return_cmd(instance, cmd);
5033
5034        return;
5035}
5036
5037#ifdef CONFIG_PM
5038/**
5039 * megasas_suspend -    driver suspend entry point
5040 * @pdev:               PCI device structure
5041 * @state:              PCI power state to suspend routine
5042 */
5043static int
5044megasas_suspend(struct pci_dev *pdev, pm_message_t state)
5045{
5046        struct Scsi_Host *host;
5047        struct megasas_instance *instance;
5048        int i;
5049
5050        instance = pci_get_drvdata(pdev);
5051        host = instance->host;
5052        instance->unload = 1;
5053
5054        /* Shutdown SR-IOV heartbeat timer */
5055        if (instance->requestorId && !instance->skip_heartbeat_timer_del)
5056                del_timer_sync(&instance->sriov_heartbeat_timer);
5057
5058        megasas_flush_cache(instance);
5059        megasas_shutdown_controller(instance, MR_DCMD_HIBERNATE_SHUTDOWN);
5060
5061        /* cancel the delayed work if this work still in queue */
5062        if (instance->ev != NULL) {
5063                struct megasas_aen_event *ev = instance->ev;
5064                cancel_delayed_work_sync(&ev->hotplug_work);
5065                instance->ev = NULL;
5066        }
5067
5068        tasklet_kill(&instance->isr_tasklet);
5069
5070        pci_set_drvdata(instance->pdev, instance);
5071        instance->instancet->disable_intr(instance);
5072
5073        if (instance->msix_vectors)
5074                for (i = 0; i < instance->msix_vectors; i++) {
5075                        irq_set_affinity_hint(
5076                                instance->msixentry[i].vector, NULL);
5077                        free_irq(instance->msixentry[i].vector,
5078                                 &instance->irq_context[i]);
5079                }
5080        else
5081                free_irq(instance->pdev->irq, &instance->irq_context[0]);
5082        if (instance->msix_vectors)
5083                pci_disable_msix(instance->pdev);
5084
5085        pci_save_state(pdev);
5086        pci_disable_device(pdev);
5087
5088        pci_set_power_state(pdev, pci_choose_state(pdev, state));
5089
5090        return 0;
5091}
5092
5093/**
5094 * megasas_resume-      driver resume entry point
5095 * @pdev:               PCI device structure
5096 */
5097static int
5098megasas_resume(struct pci_dev *pdev)
5099{
5100        int rval, i, j, cpu;
5101        struct Scsi_Host *host;
5102        struct megasas_instance *instance;
5103
5104        instance = pci_get_drvdata(pdev);
5105        host = instance->host;
5106        pci_set_power_state(pdev, PCI_D0);
5107        pci_enable_wake(pdev, PCI_D0, 0);
5108        pci_restore_state(pdev);
5109
5110        /*
5111         * PCI prepping: enable device set bus mastering and dma mask
5112         */
5113        rval = pci_enable_device_mem(pdev);
5114
5115        if (rval) {
5116                printk(KERN_ERR "megasas: Enable device failed\n");
5117                return rval;
5118        }
5119
5120        pci_set_master(pdev);
5121
5122        if (megasas_set_dma_mask(pdev))
5123                goto fail_set_dma_mask;
5124
5125        /*
5126         * Initialize MFI Firmware
5127         */
5128
5129        atomic_set(&instance->fw_outstanding, 0);
5130
5131        /*
5132         * We expect the FW state to be READY
5133         */
5134        if (megasas_transition_to_ready(instance, 0))
5135                goto fail_ready_state;
5136
5137        /* Now re-enable MSI-X */
5138        if (instance->msix_vectors)
5139                pci_enable_msix(instance->pdev, instance->msixentry,
5140                                instance->msix_vectors);
5141
5142        switch (instance->pdev->device) {
5143        case PCI_DEVICE_ID_LSI_FUSION:
5144        case PCI_DEVICE_ID_LSI_PLASMA:
5145        case PCI_DEVICE_ID_LSI_INVADER:
5146        case PCI_DEVICE_ID_LSI_FURY:
5147        {
5148                megasas_reset_reply_desc(instance);
5149                if (megasas_ioc_init_fusion(instance)) {
5150                        megasas_free_cmds(instance);
5151                        megasas_free_cmds_fusion(instance);
5152                        goto fail_init_mfi;
5153                }
5154                if (!megasas_get_map_info(instance))
5155                        megasas_sync_map_info(instance);
5156        }
5157        break;
5158        default:
5159                *instance->producer = 0;
5160                *instance->consumer = 0;
5161                if (megasas_issue_init_mfi(instance))
5162                        goto fail_init_mfi;
5163                break;
5164        }
5165
5166        tasklet_init(&instance->isr_tasklet, instance->instancet->tasklet,
5167                     (unsigned long)instance);
5168
5169        /*
5170         * Register IRQ
5171         */
5172        if (instance->msix_vectors) {
5173                cpu = cpumask_first(cpu_online_mask);
5174                for (i = 0 ; i < instance->msix_vectors; i++) {
5175                        instance->irq_context[i].instance = instance;
5176                        instance->irq_context[i].MSIxIndex = i;
5177                        if (request_irq(instance->msixentry[i].vector,
5178                                        instance->instancet->service_isr, 0,
5179                                        "megasas",
5180                                        &instance->irq_context[i])) {
5181                                printk(KERN_DEBUG "megasas: Failed to "
5182                                       "register IRQ for vector %d.\n", i);
5183                                for (j = 0; j < i; j++) {
5184                                        irq_set_affinity_hint(
5185                                                instance->msixentry[j].vector, NULL);
5186                                        free_irq(
5187                                                instance->msixentry[j].vector,
5188                                                &instance->irq_context[j]);
5189                                }
5190                                goto fail_irq;
5191                        }
5192
5193                        if (irq_set_affinity_hint(instance->msixentry[i].vector,
5194                                get_cpu_mask(cpu)))
5195                                dev_err(&instance->pdev->dev, "Error setting"
5196                                        "affinity hint for cpu %d\n", cpu);
5197                        cpu = cpumask_next(cpu, cpu_online_mask);
5198                }
5199        } else {
5200                instance->irq_context[0].instance = instance;
5201                instance->irq_context[0].MSIxIndex = 0;
5202                if (request_irq(pdev->irq, instance->instancet->service_isr,
5203                                IRQF_SHARED, "megasas",
5204                                &instance->irq_context[0])) {
5205                        printk(KERN_DEBUG "megasas: Failed to register IRQ\n");
5206                        goto fail_irq;
5207                }
5208        }
5209
5210        /* Re-launch SR-IOV heartbeat timer */
5211        if (instance->requestorId) {
5212                if (!megasas_sriov_start_heartbeat(instance, 0))
5213                        megasas_start_timer(instance,
5214                                            &instance->sriov_heartbeat_timer,
5215                                            megasas_sriov_heartbeat_handler,
5216                                            MEGASAS_SRIOV_HEARTBEAT_INTERVAL_VF);
5217                else
5218                        instance->skip_heartbeat_timer_del = 1;
5219        }
5220
5221        instance->instancet->enable_intr(instance);
5222        instance->unload = 0;
5223
5224        /*
5225         * Initiate AEN (Asynchronous Event Notification)
5226         */
5227        if (megasas_start_aen(instance))
5228                printk(KERN_ERR "megasas: Start AEN failed\n");
5229
5230        return 0;
5231
5232fail_irq:
5233fail_init_mfi:
5234        if (instance->evt_detail)
5235                pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
5236                                instance->evt_detail,
5237                                instance->evt_detail_h);
5238
5239        if (instance->producer)
5240                pci_free_consistent(pdev, sizeof(u32), instance->producer,
5241                                instance->producer_h);
5242        if (instance->consumer)
5243                pci_free_consistent(pdev, sizeof(u32), instance->consumer,
5244                                instance->consumer_h);
5245        scsi_host_put(host);
5246
5247fail_set_dma_mask:
5248fail_ready_state:
5249
5250        pci_disable_device(pdev);
5251
5252        return -ENODEV;
5253}
5254#else
5255#define megasas_suspend NULL
5256#define megasas_resume  NULL
5257#endif
5258
5259/**
5260 * megasas_detach_one - PCI hot"un"plug entry point
5261 * @pdev:               PCI device structure
5262 */
5263static void megasas_detach_one(struct pci_dev *pdev)
5264{
5265        int i;
5266        struct Scsi_Host *host;
5267        struct megasas_instance *instance;
5268        struct fusion_context *fusion;
5269
5270        instance = pci_get_drvdata(pdev);
5271        instance->unload = 1;
5272        host = instance->host;
5273        fusion = instance->ctrl_context;
5274
5275        /* Shutdown SR-IOV heartbeat timer */
5276        if (instance->requestorId && !instance->skip_heartbeat_timer_del)
5277                del_timer_sync(&instance->sriov_heartbeat_timer);
5278
5279        scsi_remove_host(instance->host);
5280        megasas_flush_cache(instance);
5281        megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
5282
5283        /* cancel the delayed work if this work still in queue*/
5284        if (instance->ev != NULL) {
5285                struct megasas_aen_event *ev = instance->ev;
5286                cancel_delayed_work_sync(&ev->hotplug_work);
5287                instance->ev = NULL;
5288        }
5289
5290        /* cancel all wait events */
5291        wake_up_all(&instance->int_cmd_wait_q);
5292
5293        tasklet_kill(&instance->isr_tasklet);
5294
5295        /*
5296         * Take the instance off the instance array. Note that we will not
5297         * decrement the max_index. We let this array be sparse array
5298         */
5299        for (i = 0; i < megasas_mgmt_info.max_index; i++) {
5300                if (megasas_mgmt_info.instance[i] == instance) {
5301                        megasas_mgmt_info.count--;
5302                        megasas_mgmt_info.instance[i] = NULL;
5303
5304                        break;
5305                }
5306        }
5307
5308        instance->instancet->disable_intr(instance);
5309
5310        if (instance->msix_vectors)
5311                for (i = 0; i < instance->msix_vectors; i++) {
5312                        irq_set_affinity_hint(
5313                                instance->msixentry[i].vector, NULL);
5314                        free_irq(instance->msixentry[i].vector,
5315                                 &instance->irq_context[i]);
5316                }
5317        else
5318                free_irq(instance->pdev->irq, &instance->irq_context[0]);
5319        if (instance->msix_vectors)
5320                pci_disable_msix(instance->pdev);
5321
5322        switch (instance->pdev->device) {
5323        case PCI_DEVICE_ID_LSI_FUSION:
5324        case PCI_DEVICE_ID_LSI_PLASMA:
5325        case PCI_DEVICE_ID_LSI_INVADER:
5326        case PCI_DEVICE_ID_LSI_FURY:
5327                megasas_release_fusion(instance);
5328                for (i = 0; i < 2 ; i++)
5329                        if (fusion->ld_map[i])
5330                                dma_free_coherent(&instance->pdev->dev,
5331                                                  fusion->map_sz,
5332                                                  fusion->ld_map[i],
5333                                                  fusion->
5334                                                  ld_map_phys[i]);
5335                kfree(instance->ctrl_context);
5336                break;
5337        default:
5338                megasas_release_mfi(instance);
5339                pci_free_consistent(pdev, sizeof(u32),
5340                                    instance->producer,
5341                                    instance->producer_h);
5342                pci_free_consistent(pdev, sizeof(u32),
5343                                    instance->consumer,
5344                                    instance->consumer_h);
5345                break;
5346        }
5347
5348        if (instance->evt_detail)
5349                pci_free_consistent(pdev, sizeof(struct megasas_evt_detail),
5350                                instance->evt_detail, instance->evt_detail_h);
5351
5352        if (instance->vf_affiliation)
5353                pci_free_consistent(pdev, (MAX_LOGICAL_DRIVES + 1) *
5354                                    sizeof(struct MR_LD_VF_AFFILIATION),
5355                                    instance->vf_affiliation,
5356                                    instance->vf_affiliation_h);
5357
5358        if (instance->vf_affiliation_111)
5359                pci_free_consistent(pdev,
5360                                    sizeof(struct MR_LD_VF_AFFILIATION_111),
5361                                    instance->vf_affiliation_111,
5362                                    instance->vf_affiliation_111_h);
5363
5364        if (instance->hb_host_mem)
5365                pci_free_consistent(pdev, sizeof(struct MR_CTRL_HB_HOST_MEM),
5366                                    instance->hb_host_mem,
5367                                    instance->hb_host_mem_h);
5368
5369        scsi_host_put(host);
5370
5371        pci_disable_device(pdev);
5372
5373        return;
5374}
5375
5376/**
5377 * megasas_shutdown -   Shutdown entry point
5378 * @device:             Generic device structure
5379 */
5380static void megasas_shutdown(struct pci_dev *pdev)
5381{
5382        int i;
5383        struct megasas_instance *instance = pci_get_drvdata(pdev);
5384
5385        instance->unload = 1;
5386        megasas_flush_cache(instance);
5387        megasas_shutdown_controller(instance, MR_DCMD_CTRL_SHUTDOWN);
5388        instance->instancet->disable_intr(instance);
5389        if (instance->msix_vectors)
5390                for (i = 0; i < instance->msix_vectors; i++) {
5391                        irq_set_affinity_hint(
5392                                instance->msixentry[i].vector, NULL);
5393                        free_irq(instance->msixentry[i].vector,
5394                                 &instance->irq_context[i]);
5395                }
5396        else
5397                free_irq(instance->pdev->irq, &instance->irq_context[0]);
5398        if (instance->msix_vectors)
5399                pci_disable_msix(instance->pdev);
5400}
5401
5402/**
5403 * megasas_mgmt_open -  char node "open" entry point
5404 */
5405static int megasas_mgmt_open(struct inode *inode, struct file *filep)
5406{
5407        /*
5408         * Allow only those users with admin rights
5409         */
5410        if (!capable(CAP_SYS_ADMIN))
5411                return -EACCES;
5412
5413        return 0;
5414}
5415
5416/**
5417 * megasas_mgmt_fasync -        Async notifier registration from applications
5418 *
5419 * This function adds the calling process to a driver global queue. When an
5420 * event occurs, SIGIO will be sent to all processes in this queue.
5421 */
5422static int megasas_mgmt_fasync(int fd, struct file *filep, int mode)
5423{
5424        int rc;
5425
5426        mutex_lock(&megasas_async_queue_mutex);
5427
5428        rc = fasync_helper(fd, filep, mode, &megasas_async_queue);
5429
5430        mutex_unlock(&megasas_async_queue_mutex);
5431
5432        if (rc >= 0) {
5433                /* For sanity check when we get ioctl */
5434                filep->private_data = filep;
5435                return 0;
5436        }
5437
5438        printk(KERN_DEBUG "megasas: fasync_helper failed [%d]\n", rc);
5439
5440        return rc;
5441}
5442
5443/**
5444 * megasas_mgmt_poll -  char node "poll" entry point
5445 * */
5446static unsigned int megasas_mgmt_poll(struct file *file, poll_table *wait)
5447{
5448        unsigned int mask;
5449        unsigned long flags;
5450        poll_wait(file, &megasas_poll_wait, wait);
5451        spin_lock_irqsave(&poll_aen_lock, flags);
5452        if (megasas_poll_wait_aen)
5453                mask =   (POLLIN | POLLRDNORM);
5454        else
5455                mask = 0;
5456        spin_unlock_irqrestore(&poll_aen_lock, flags);
5457        return mask;
5458}
5459
5460/**
5461 * megasas_mgmt_fw_ioctl -      Issues management ioctls to FW
5462 * @instance:                   Adapter soft state
5463 * @argp:                       User's ioctl packet
5464 */
5465static int
5466megasas_mgmt_fw_ioctl(struct megasas_instance *instance,
5467                      struct megasas_iocpacket __user * user_ioc,
5468                      struct megasas_iocpacket *ioc)
5469{
5470        struct megasas_sge32 *kern_sge32;
5471        struct megasas_cmd *cmd;
5472        void *kbuff_arr[MAX_IOCTL_SGE];
5473        dma_addr_t buf_handle = 0;
5474        int error = 0, i;
5475        void *sense = NULL;
5476        dma_addr_t sense_handle;
5477        unsigned long *sense_ptr;
5478
5479        memset(kbuff_arr, 0, sizeof(kbuff_arr));
5480
5481        if (ioc->sge_count > MAX_IOCTL_SGE) {
5482                printk(KERN_DEBUG "megasas: SGE count [%d] >  max limit [%d]\n",
5483                       ioc->sge_count, MAX_IOCTL_SGE);
5484                return -EINVAL;
5485        }
5486
5487        cmd = megasas_get_cmd(instance);
5488        if (!cmd) {
5489                printk(KERN_DEBUG "megasas: Failed to get a cmd packet\n");
5490                return -ENOMEM;
5491        }
5492
5493        /*
5494         * User's IOCTL packet has 2 frames (maximum). Copy those two
5495         * frames into our cmd's frames. cmd->frame's context will get
5496         * overwritten when we copy from user's frames. So set that value
5497         * alone separately
5498         */
5499        memcpy(cmd->frame, ioc->frame.raw, 2 * MEGAMFI_FRAME_SIZE);
5500        cmd->frame->hdr.context = cpu_to_le32(cmd->index);
5501        cmd->frame->hdr.pad_0 = 0;
5502        cmd->frame->hdr.flags &= cpu_to_le16(~(MFI_FRAME_IEEE |
5503                                               MFI_FRAME_SGL64 |
5504                                               MFI_FRAME_SENSE64));
5505
5506        /*
5507         * The management interface between applications and the fw uses
5508         * MFI frames. E.g, RAID configuration changes, LD property changes
5509         * etc are accomplishes through different kinds of MFI frames. The
5510         * driver needs to care only about substituting user buffers with
5511         * kernel buffers in SGLs. The location of SGL is embedded in the
5512         * struct iocpacket itself.
5513         */
5514        kern_sge32 = (struct megasas_sge32 *)
5515            ((unsigned long)cmd->frame + ioc->sgl_off);
5516
5517        /*
5518         * For each user buffer, create a mirror buffer and copy in
5519         */
5520        for (i = 0; i < ioc->sge_count; i++) {
5521                if (!ioc->sgl[i].iov_len)
5522                        continue;
5523
5524                kbuff_arr[i] = dma_alloc_coherent(&instance->pdev->dev,
5525                                                    ioc->sgl[i].iov_len,
5526                                                    &buf_handle, GFP_KERNEL);
5527                if (!kbuff_arr[i]) {
5528                        printk(KERN_DEBUG "megasas: Failed to alloc "
5529                               "kernel SGL buffer for IOCTL \n");
5530                        error = -ENOMEM;
5531                        goto out;
5532                }
5533
5534                /*
5535                 * We don't change the dma_coherent_mask, so
5536                 * pci_alloc_consistent only returns 32bit addresses
5537                 */
5538                kern_sge32[i].phys_addr = cpu_to_le32(buf_handle);
5539                kern_sge32[i].length = cpu_to_le32(ioc->sgl[i].iov_len);
5540
5541                /*
5542                 * We created a kernel buffer corresponding to the
5543                 * user buffer. Now copy in from the user buffer
5544                 */
5545                if (copy_from_user(kbuff_arr[i], ioc->sgl[i].iov_base,
5546                                   (u32) (ioc->sgl[i].iov_len))) {
5547                        error = -EFAULT;
5548                        goto out;
5549                }
5550        }
5551
5552        if (ioc->sense_len) {
5553                sense = dma_alloc_coherent(&instance->pdev->dev, ioc->sense_len,
5554                                             &sense_handle, GFP_KERNEL);
5555                if (!sense) {
5556                        error = -ENOMEM;
5557                        goto out;
5558                }
5559
5560                sense_ptr =
5561                (unsigned long *) ((unsigned long)cmd->frame + ioc->sense_off);
5562                *sense_ptr = cpu_to_le32(sense_handle);
5563        }
5564
5565        /*
5566         * Set the sync_cmd flag so that the ISR knows not to complete this
5567         * cmd to the SCSI mid-layer
5568         */
5569        cmd->sync_cmd = 1;
5570        megasas_issue_blocked_cmd(instance, cmd, 0);
5571        cmd->sync_cmd = 0;
5572
5573        /*
5574         * copy out the kernel buffers to user buffers
5575         */
5576        for (i = 0; i < ioc->sge_count; i++) {
5577                if (copy_to_user(ioc->sgl[i].iov_base, kbuff_arr[i],
5578                                 ioc->sgl[i].iov_len)) {
5579                        error = -EFAULT;
5580                        goto out;
5581                }
5582        }
5583
5584        /*
5585         * copy out the sense
5586         */
5587        if (ioc->sense_len) {
5588                /*
5589                 * sense_ptr points to the location that has the user
5590                 * sense buffer address
5591                 */
5592                sense_ptr = (unsigned long *) ((unsigned long)ioc->frame.raw +
5593                                ioc->sense_off);
5594
5595                if (copy_to_user((void __user *)((unsigned long)(*sense_ptr)),
5596                                 sense, ioc->sense_len)) {
5597                        printk(KERN_ERR "megasas: Failed to copy out to user "
5598                                        "sense data\n");
5599                        error = -EFAULT;
5600                        goto out;
5601                }
5602        }
5603
5604        /*
5605         * copy the status codes returned by the fw
5606         */
5607        if (copy_to_user(&user_ioc->frame.hdr.cmd_status,
5608                         &cmd->frame->hdr.cmd_status, sizeof(u8))) {
5609                printk(KERN_DEBUG "megasas: Error copying out cmd_status\n");
5610                error = -EFAULT;
5611        }
5612
5613      out:
5614        if (sense) {
5615                dma_free_coherent(&instance->pdev->dev, ioc->sense_len,
5616                                    sense, sense_handle);
5617        }
5618
5619        for (i = 0; i < ioc->sge_count; i++) {
5620                if (kbuff_arr[i])
5621                        dma_free_coherent(&instance->pdev->dev,
5622                                          le32_to_cpu(kern_sge32[i].length),
5623                                          kbuff_arr[i],
5624                                          le32_to_cpu(kern_sge32[i].phys_addr));
5625        }
5626
5627        megasas_return_cmd(instance, cmd);
5628        return error;
5629}
5630
5631static int megasas_mgmt_ioctl_fw(struct file *file, unsigned long arg)
5632{
5633        struct megasas_iocpacket __user *user_ioc =
5634            (struct megasas_iocpacket __user *)arg;
5635        struct megasas_iocpacket *ioc;
5636        struct megasas_instance *instance;
5637        int error;
5638        int i;
5639        unsigned long flags;
5640        u32 wait_time = MEGASAS_RESET_WAIT_TIME;
5641
5642        ioc = kmalloc(sizeof(*ioc), GFP_KERNEL);
5643        if (!ioc)
5644                return -ENOMEM;
5645
5646        if (copy_from_user(ioc, user_ioc, sizeof(*ioc))) {
5647                error = -EFAULT;
5648                goto out_kfree_ioc;
5649        }
5650
5651        instance = megasas_lookup_instance(ioc->host_no);
5652        if (!instance) {
5653                error = -ENODEV;
5654                goto out_kfree_ioc;
5655        }
5656
5657        /* Adjust ioctl wait time for VF mode */
5658        if (instance->requestorId)
5659                wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF;
5660
5661        /* Block ioctls in VF mode */
5662        if (instance->requestorId && !allow_vf_ioctls) {
5663                error = -ENODEV;
5664                goto out_kfree_ioc;
5665        }
5666
5667        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
5668                printk(KERN_ERR "Controller in crit error\n");
5669                error = -ENODEV;
5670                goto out_kfree_ioc;
5671        }
5672
5673        if (instance->unload == 1) {
5674                error = -ENODEV;
5675                goto out_kfree_ioc;
5676        }
5677
5678        /*
5679         * We will allow only MEGASAS_INT_CMDS number of parallel ioctl cmds
5680         */
5681        if (down_interruptible(&instance->ioctl_sem)) {
5682                error = -ERESTARTSYS;
5683                goto out_kfree_ioc;
5684        }
5685
5686        for (i = 0; i < wait_time; i++) {
5687
5688                spin_lock_irqsave(&instance->hba_lock, flags);
5689                if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
5690                        spin_unlock_irqrestore(&instance->hba_lock, flags);
5691                        break;
5692                }
5693                spin_unlock_irqrestore(&instance->hba_lock, flags);
5694
5695                if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
5696                        printk(KERN_NOTICE "megasas: waiting"
5697                                "for controller reset to finish\n");
5698                }
5699
5700                msleep(1000);
5701        }
5702
5703        spin_lock_irqsave(&instance->hba_lock, flags);
5704        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
5705                spin_unlock_irqrestore(&instance->hba_lock, flags);
5706
5707                printk(KERN_ERR "megaraid_sas: timed out while"
5708                        "waiting for HBA to recover\n");
5709                error = -ENODEV;
5710                goto out_up;
5711        }
5712        spin_unlock_irqrestore(&instance->hba_lock, flags);
5713
5714        error = megasas_mgmt_fw_ioctl(instance, user_ioc, ioc);
5715      out_up:
5716        up(&instance->ioctl_sem);
5717
5718      out_kfree_ioc:
5719        kfree(ioc);
5720        return error;
5721}
5722
5723static int megasas_mgmt_ioctl_aen(struct file *file, unsigned long arg)
5724{
5725        struct megasas_instance *instance;
5726        struct megasas_aen aen;
5727        int error;
5728        int i;
5729        unsigned long flags;
5730        u32 wait_time = MEGASAS_RESET_WAIT_TIME;
5731
5732        if (file->private_data != file) {
5733                printk(KERN_DEBUG "megasas: fasync_helper was not "
5734                       "called first\n");
5735                return -EINVAL;
5736        }
5737
5738        if (copy_from_user(&aen, (void __user *)arg, sizeof(aen)))
5739                return -EFAULT;
5740
5741        instance = megasas_lookup_instance(aen.host_no);
5742
5743        if (!instance)
5744                return -ENODEV;
5745
5746        if (instance->adprecovery == MEGASAS_HW_CRITICAL_ERROR) {
5747                return -ENODEV;
5748        }
5749
5750        if (instance->unload == 1) {
5751                return -ENODEV;
5752        }
5753
5754        for (i = 0; i < wait_time; i++) {
5755
5756                spin_lock_irqsave(&instance->hba_lock, flags);
5757                if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL) {
5758                        spin_unlock_irqrestore(&instance->hba_lock,
5759                                                flags);
5760                        break;
5761                }
5762
5763                spin_unlock_irqrestore(&instance->hba_lock, flags);
5764
5765                if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
5766                        printk(KERN_NOTICE "megasas: waiting for"
5767                                "controller reset to finish\n");
5768                }
5769
5770                msleep(1000);
5771        }
5772
5773        spin_lock_irqsave(&instance->hba_lock, flags);
5774        if (instance->adprecovery != MEGASAS_HBA_OPERATIONAL) {
5775                spin_unlock_irqrestore(&instance->hba_lock, flags);
5776                printk(KERN_ERR "megaraid_sas: timed out while waiting"
5777                                "for HBA to recover.\n");
5778                return -ENODEV;
5779        }
5780        spin_unlock_irqrestore(&instance->hba_lock, flags);
5781
5782        mutex_lock(&instance->aen_mutex);
5783        error = megasas_register_aen(instance, aen.seq_num,
5784                                     aen.class_locale_word);
5785        mutex_unlock(&instance->aen_mutex);
5786        return error;
5787}
5788
5789/**
5790 * megasas_mgmt_ioctl - char node ioctl entry point
5791 */
5792static long
5793megasas_mgmt_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
5794{
5795        switch (cmd) {
5796        case MEGASAS_IOC_FIRMWARE:
5797                return megasas_mgmt_ioctl_fw(file, arg);
5798
5799        case MEGASAS_IOC_GET_AEN:
5800                return megasas_mgmt_ioctl_aen(file, arg);
5801        }
5802
5803        return -ENOTTY;
5804}
5805
5806#ifdef CONFIG_COMPAT
5807static int megasas_mgmt_compat_ioctl_fw(struct file *file, unsigned long arg)
5808{
5809        struct compat_megasas_iocpacket __user *cioc =
5810            (struct compat_megasas_iocpacket __user *)arg;
5811        struct megasas_iocpacket __user *ioc =
5812            compat_alloc_user_space(sizeof(struct megasas_iocpacket));
5813        int i;
5814        int error = 0;
5815        compat_uptr_t ptr;
5816
5817        if (clear_user(ioc, sizeof(*ioc)))
5818                return -EFAULT;
5819
5820        if (copy_in_user(&ioc->host_no, &cioc->host_no, sizeof(u16)) ||
5821            copy_in_user(&ioc->sgl_off, &cioc->sgl_off, sizeof(u32)) ||
5822            copy_in_user(&ioc->sense_off, &cioc->sense_off, sizeof(u32)) ||
5823            copy_in_user(&ioc->sense_len, &cioc->sense_len, sizeof(u32)) ||
5824            copy_in_user(ioc->frame.raw, cioc->frame.raw, 128) ||
5825            copy_in_user(&ioc->sge_count, &cioc->sge_count, sizeof(u32)))
5826                return -EFAULT;
5827
5828        /*
5829         * The sense_ptr is used in megasas_mgmt_fw_ioctl only when
5830         * sense_len is not null, so prepare the 64bit value under
5831         * the same condition.
5832         */
5833        if (ioc->sense_len) {
5834                void __user **sense_ioc_ptr =
5835                        (void __user **)(ioc->frame.raw + ioc->sense_off);
5836                compat_uptr_t *sense_cioc_ptr =
5837                        (compat_uptr_t *)(cioc->frame.raw + cioc->sense_off);
5838                if (get_user(ptr, sense_cioc_ptr) ||
5839                    put_user(compat_ptr(ptr), sense_ioc_ptr))
5840                        return -EFAULT;
5841        }
5842
5843        for (i = 0; i < MAX_IOCTL_SGE; i++) {
5844                if (get_user(ptr, &cioc->sgl[i].iov_base) ||
5845                    put_user(compat_ptr(ptr), &ioc->sgl[i].iov_base) ||
5846                    copy_in_user(&ioc->sgl[i].iov_len,
5847                                 &cioc->sgl[i].iov_len, sizeof(compat_size_t)))
5848                        return -EFAULT;
5849        }
5850
5851        error = megasas_mgmt_ioctl_fw(file, (unsigned long)ioc);
5852
5853        if (copy_in_user(&cioc->frame.hdr.cmd_status,
5854                         &ioc->frame.hdr.cmd_status, sizeof(u8))) {
5855                printk(KERN_DEBUG "megasas: error copy_in_user cmd_status\n");
5856                return -EFAULT;
5857        }
5858        return error;
5859}
5860
5861static long
5862megasas_mgmt_compat_ioctl(struct file *file, unsigned int cmd,
5863                          unsigned long arg)
5864{
5865        switch (cmd) {
5866        case MEGASAS_IOC_FIRMWARE32:
5867                return megasas_mgmt_compat_ioctl_fw(file, arg);
5868        case MEGASAS_IOC_GET_AEN:
5869                return megasas_mgmt_ioctl_aen(file, arg);
5870        }
5871
5872        return -ENOTTY;
5873}
5874#endif
5875
5876/*
5877 * File operations structure for management interface
5878 */
5879static const struct file_operations megasas_mgmt_fops = {
5880        .owner = THIS_MODULE,
5881        .open = megasas_mgmt_open,
5882        .fasync = megasas_mgmt_fasync,
5883        .unlocked_ioctl = megasas_mgmt_ioctl,
5884        .poll = megasas_mgmt_poll,
5885#ifdef CONFIG_COMPAT
5886        .compat_ioctl = megasas_mgmt_compat_ioctl,
5887#endif
5888        .llseek = noop_llseek,
5889};
5890
5891/*
5892 * PCI hotplug support registration structure
5893 */
5894static struct pci_driver megasas_pci_driver = {
5895
5896        .name = "megaraid_sas",
5897        .id_table = megasas_pci_table,
5898        .probe = megasas_probe_one,
5899        .remove = megasas_detach_one,
5900        .suspend = megasas_suspend,
5901        .resume = megasas_resume,
5902        .shutdown = megasas_shutdown,
5903};
5904
5905/*
5906 * Sysfs driver attributes
5907 */
5908static ssize_t megasas_sysfs_show_version(struct device_driver *dd, char *buf)
5909{
5910        return snprintf(buf, strlen(MEGASAS_VERSION) + 2, "%s\n",
5911                        MEGASAS_VERSION);
5912}
5913
5914static DRIVER_ATTR(version, S_IRUGO, megasas_sysfs_show_version, NULL);
5915
5916static ssize_t
5917megasas_sysfs_show_release_date(struct device_driver *dd, char *buf)
5918{
5919        return snprintf(buf, strlen(MEGASAS_RELDATE) + 2, "%s\n",
5920                        MEGASAS_RELDATE);
5921}
5922
5923static DRIVER_ATTR(release_date, S_IRUGO, megasas_sysfs_show_release_date,
5924                   NULL);
5925
5926static ssize_t
5927megasas_sysfs_show_support_poll_for_event(struct device_driver *dd, char *buf)
5928{
5929        return sprintf(buf, "%u\n", support_poll_for_event);
5930}
5931
5932static DRIVER_ATTR(support_poll_for_event, S_IRUGO,
5933                        megasas_sysfs_show_support_poll_for_event, NULL);
5934
5935 static ssize_t
5936megasas_sysfs_show_support_device_change(struct device_driver *dd, char *buf)
5937{
5938        return sprintf(buf, "%u\n", support_device_change);
5939}
5940
5941static DRIVER_ATTR(support_device_change, S_IRUGO,
5942                        megasas_sysfs_show_support_device_change, NULL);
5943
5944static ssize_t
5945megasas_sysfs_show_dbg_lvl(struct device_driver *dd, char *buf)
5946{
5947        return sprintf(buf, "%u\n", megasas_dbg_lvl);
5948}
5949
5950static ssize_t
5951megasas_sysfs_set_dbg_lvl(struct device_driver *dd, const char *buf, size_t count)
5952{
5953        int retval = count;
5954        if(sscanf(buf,"%u",&megasas_dbg_lvl)<1){
5955                printk(KERN_ERR "megasas: could not set dbg_lvl\n");
5956                retval = -EINVAL;
5957        }
5958        return retval;
5959}
5960
5961static DRIVER_ATTR(dbg_lvl, S_IRUGO|S_IWUSR, megasas_sysfs_show_dbg_lvl,
5962                megasas_sysfs_set_dbg_lvl);
5963
5964static void
5965megasas_aen_polling(struct work_struct *work)
5966{
5967        struct megasas_aen_event *ev =
5968                container_of(work, struct megasas_aen_event, hotplug_work.work);
5969        struct megasas_instance *instance = ev->instance;
5970        union megasas_evt_class_locale class_locale;
5971        struct  Scsi_Host *host;
5972        struct  scsi_device *sdev1;
5973        u16     pd_index = 0;
5974        u16     ld_index = 0;
5975        int     i, j, doscan = 0;
5976        u32 seq_num, wait_time = MEGASAS_RESET_WAIT_TIME;
5977        int error;
5978
5979        if (!instance) {
5980                printk(KERN_ERR "invalid instance!\n");
5981                kfree(ev);
5982                return;
5983        }
5984
5985        /* Adjust event workqueue thread wait time for VF mode */
5986        if (instance->requestorId)
5987                wait_time = MEGASAS_ROUTINE_WAIT_TIME_VF;
5988
5989        /* Don't run the event workqueue thread if OCR is running */
5990        for (i = 0; i < wait_time; i++) {
5991                if (instance->adprecovery == MEGASAS_HBA_OPERATIONAL)
5992                        break;
5993                if (!(i % MEGASAS_RESET_NOTICE_INTERVAL)) {
5994                        printk(KERN_NOTICE "megasas: %s waiting for "
5995                               "controller reset to finish for scsi%d\n",
5996                               __func__, instance->host->host_no);
5997                }
5998                msleep(1000);
5999        }
6000
6001        instance->ev = NULL;
6002        host = instance->host;
6003        if (instance->evt_detail) {
6004
6005                switch (le32_to_cpu(instance->evt_detail->code)) {
6006                case MR_EVT_PD_INSERTED:
6007                        if (megasas_get_pd_list(instance) == 0) {
6008                        for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6009                                for (j = 0;
6010                                j < MEGASAS_MAX_DEV_PER_CHANNEL;
6011                                j++) {
6012
6013                                pd_index =
6014                                (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6015
6016                                sdev1 =
6017                                scsi_device_lookup(host, i, j, 0);
6018
6019                                if (instance->pd_list[pd_index].driveState
6020                                                == MR_PD_STATE_SYSTEM) {
6021                                                if (!sdev1) {
6022                                                scsi_add_device(host, i, j, 0);
6023                                                }
6024
6025                                        if (sdev1)
6026                                                scsi_device_put(sdev1);
6027                                        }
6028                                }
6029                        }
6030                        }
6031                        doscan = 0;
6032                        break;
6033
6034                case MR_EVT_PD_REMOVED:
6035                        if (megasas_get_pd_list(instance) == 0) {
6036                        for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6037                                for (j = 0;
6038                                j < MEGASAS_MAX_DEV_PER_CHANNEL;
6039                                j++) {
6040
6041                                pd_index =
6042                                (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6043
6044                                sdev1 =
6045                                scsi_device_lookup(host, i, j, 0);
6046
6047                                if (instance->pd_list[pd_index].driveState
6048                                        == MR_PD_STATE_SYSTEM) {
6049                                        if (sdev1) {
6050                                                scsi_device_put(sdev1);
6051                                        }
6052                                } else {
6053                                        if (sdev1) {
6054                                                scsi_remove_device(sdev1);
6055                                                scsi_device_put(sdev1);
6056                                        }
6057                                }
6058                                }
6059                        }
6060                        }
6061                        doscan = 0;
6062                        break;
6063
6064                case MR_EVT_LD_OFFLINE:
6065                case MR_EVT_CFG_CLEARED:
6066                case MR_EVT_LD_DELETED:
6067                        if (!instance->requestorId ||
6068                            (instance->requestorId &&
6069                             megasas_get_ld_vf_affiliation(instance, 0))) {
6070                                if (megasas_ld_list_query(instance,
6071                                                          MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6072                                        megasas_get_ld_list(instance);
6073                                for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6074                                        for (j = 0;
6075                                             j < MEGASAS_MAX_DEV_PER_CHANNEL;
6076                                             j++) {
6077
6078                                                ld_index =
6079                                                        (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6080
6081                                                sdev1 = scsi_device_lookup(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6082
6083                                                if (instance->ld_ids[ld_index]
6084                                                    != 0xff) {
6085                                                        if (sdev1)
6086                                                                scsi_device_put(sdev1);
6087                                                } else {
6088                                                        if (sdev1) {
6089                                                                scsi_remove_device(sdev1);
6090                                                                scsi_device_put(sdev1);
6091                                                        }
6092                                                }
6093                                        }
6094                                }
6095                                doscan = 0;
6096                        }
6097                        break;
6098                case MR_EVT_LD_CREATED:
6099                        if (!instance->requestorId ||
6100                            (instance->requestorId &&
6101                             megasas_get_ld_vf_affiliation(instance, 0))) {
6102                                if (megasas_ld_list_query(instance,
6103                                                          MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6104                                        megasas_get_ld_list(instance);
6105                                for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6106                                        for (j = 0;
6107                                             j < MEGASAS_MAX_DEV_PER_CHANNEL;
6108                                             j++) {
6109                                                ld_index =
6110                                                        (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6111
6112                                                sdev1 = scsi_device_lookup(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6113
6114                                                if (instance->ld_ids[ld_index]
6115                                                    != 0xff) {
6116                                                        if (!sdev1)
6117                                                                scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6118                                                }
6119                                                if (sdev1)
6120                                                        scsi_device_put(sdev1);
6121                                        }
6122                                }
6123                                doscan = 0;
6124                        }
6125                        break;
6126                case MR_EVT_CTRL_HOST_BUS_SCAN_REQUESTED:
6127                case MR_EVT_FOREIGN_CFG_IMPORTED:
6128                case MR_EVT_LD_STATE_CHANGE:
6129                        doscan = 1;
6130                        break;
6131                default:
6132                        doscan = 0;
6133                        break;
6134                }
6135        } else {
6136                printk(KERN_ERR "invalid evt_detail!\n");
6137                kfree(ev);
6138                return;
6139        }
6140
6141        if (doscan) {
6142                printk(KERN_INFO "megaraid_sas: scanning for scsi%d...\n",
6143                       instance->host->host_no);
6144                if (megasas_get_pd_list(instance) == 0) {
6145                        for (i = 0; i < MEGASAS_MAX_PD_CHANNELS; i++) {
6146                                for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL; j++) {
6147                                        pd_index = i*MEGASAS_MAX_DEV_PER_CHANNEL + j;
6148                                        sdev1 = scsi_device_lookup(host, i, j, 0);
6149                                        if (instance->pd_list[pd_index].driveState ==
6150                                            MR_PD_STATE_SYSTEM) {
6151                                                if (!sdev1) {
6152                                                        scsi_add_device(host, i, j, 0);
6153                                                }
6154                                                if (sdev1)
6155                                                        scsi_device_put(sdev1);
6156                                        } else {
6157                                                if (sdev1) {
6158                                                        scsi_remove_device(sdev1);
6159                                                        scsi_device_put(sdev1);
6160                                                }
6161                                        }
6162                                }
6163                        }
6164                }
6165
6166                if (!instance->requestorId ||
6167                    (instance->requestorId &&
6168                     megasas_get_ld_vf_affiliation(instance, 0))) {
6169                        if (megasas_ld_list_query(instance,
6170                                                  MR_LD_QUERY_TYPE_EXPOSED_TO_HOST))
6171                                megasas_get_ld_list(instance);
6172                        for (i = 0; i < MEGASAS_MAX_LD_CHANNELS; i++) {
6173                                for (j = 0; j < MEGASAS_MAX_DEV_PER_CHANNEL;
6174                                     j++) {
6175                                        ld_index =
6176                                                (i * MEGASAS_MAX_DEV_PER_CHANNEL) + j;
6177
6178                                        sdev1 = scsi_device_lookup(host,
6179                                                                   MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6180                                        if (instance->ld_ids[ld_index]
6181                                            != 0xff) {
6182                                                if (!sdev1)
6183                                                        scsi_add_device(host, MEGASAS_MAX_PD_CHANNELS + i, j, 0);
6184                                                else
6185                                                        scsi_device_put(sdev1);
6186                                        } else {
6187                                                if (sdev1) {
6188                                                        scsi_remove_device(sdev1);
6189                                                        scsi_device_put(sdev1);
6190                                                }
6191                                        }
6192                                }
6193                        }
6194                }
6195        }
6196
6197        if ( instance->aen_cmd != NULL ) {
6198                kfree(ev);
6199                return ;
6200        }
6201
6202        seq_num = le32_to_cpu(instance->evt_detail->seq_num) + 1;
6203
6204        /* Register AEN with FW for latest sequence number plus 1 */
6205        class_locale.members.reserved = 0;
6206        class_locale.members.locale = MR_EVT_LOCALE_ALL;
6207        class_locale.members.class = MR_EVT_CLASS_DEBUG;
6208        mutex_lock(&instance->aen_mutex);
6209        error = megasas_register_aen(instance, seq_num,
6210                                        class_locale.word);
6211        mutex_unlock(&instance->aen_mutex);
6212
6213        if (error)
6214                printk(KERN_ERR "register aen failed error %x\n", error);
6215
6216        kfree(ev);
6217}
6218
6219/**
6220 * megasas_init - Driver load entry point
6221 */
6222static int __init megasas_init(void)
6223{
6224        int rval;
6225
6226        /*
6227         * Announce driver version and other information
6228         */
6229        printk(KERN_INFO "megasas: %s %s\n", MEGASAS_VERSION,
6230               MEGASAS_EXT_VERSION);
6231
6232        spin_lock_init(&poll_aen_lock);
6233
6234        support_poll_for_event = 2;
6235        support_device_change = 1;
6236
6237        memset(&megasas_mgmt_info, 0, sizeof(megasas_mgmt_info));
6238
6239        /*
6240         * Register character device node
6241         */
6242        rval = register_chrdev(0, "megaraid_sas_ioctl", &megasas_mgmt_fops);
6243
6244        if (rval < 0) {
6245                printk(KERN_DEBUG "megasas: failed to open device node\n");
6246                return rval;
6247        }
6248
6249        megasas_mgmt_majorno = rval;
6250
6251        /*
6252         * Register ourselves as PCI hotplug module
6253         */
6254        rval = pci_register_driver(&megasas_pci_driver);
6255
6256        if (rval) {
6257                printk(KERN_DEBUG "megasas: PCI hotplug regisration failed \n");
6258                goto err_pcidrv;
6259        }
6260
6261        rval = driver_create_file(&megasas_pci_driver.driver,
6262                                  &driver_attr_version);
6263        if (rval)
6264                goto err_dcf_attr_ver;
6265        rval = driver_create_file(&megasas_pci_driver.driver,
6266                                  &driver_attr_release_date);
6267        if (rval)
6268                goto err_dcf_rel_date;
6269
6270        rval = driver_create_file(&megasas_pci_driver.driver,
6271                                &driver_attr_support_poll_for_event);
6272        if (rval)
6273                goto err_dcf_support_poll_for_event;
6274
6275        rval = driver_create_file(&megasas_pci_driver.driver,
6276                                  &driver_attr_dbg_lvl);
6277        if (rval)
6278                goto err_dcf_dbg_lvl;
6279        rval = driver_create_file(&megasas_pci_driver.driver,
6280                                &driver_attr_support_device_change);
6281        if (rval)
6282                goto err_dcf_support_device_change;
6283
6284        return rval;
6285
6286err_dcf_support_device_change:
6287        driver_remove_file(&megasas_pci_driver.driver,
6288                           &driver_attr_dbg_lvl);
6289err_dcf_dbg_lvl:
6290        driver_remove_file(&megasas_pci_driver.driver,
6291                        &driver_attr_support_poll_for_event);
6292
6293err_dcf_support_poll_for_event:
6294        driver_remove_file(&megasas_pci_driver.driver,
6295                           &driver_attr_release_date);
6296
6297err_dcf_rel_date:
6298        driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
6299err_dcf_attr_ver:
6300        pci_unregister_driver(&megasas_pci_driver);
6301err_pcidrv:
6302        unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
6303        return rval;
6304}
6305
6306/**
6307 * megasas_exit - Driver unload entry point
6308 */
6309static void __exit megasas_exit(void)
6310{
6311        driver_remove_file(&megasas_pci_driver.driver,
6312                           &driver_attr_dbg_lvl);
6313        driver_remove_file(&megasas_pci_driver.driver,
6314                        &driver_attr_support_poll_for_event);
6315        driver_remove_file(&megasas_pci_driver.driver,
6316                        &driver_attr_support_device_change);
6317        driver_remove_file(&megasas_pci_driver.driver,
6318                           &driver_attr_release_date);
6319        driver_remove_file(&megasas_pci_driver.driver, &driver_attr_version);
6320
6321        pci_unregister_driver(&megasas_pci_driver);
6322        unregister_chrdev(megasas_mgmt_majorno, "megaraid_sas_ioctl");
6323}
6324
6325module_init(megasas_init);
6326module_exit(megasas_exit);
6327