linux/drivers/scsi/smartpqi/smartpqi_init.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *    driver for Microchip PQI-based storage controllers
   4 *    Copyright (c) 2019-2021 Microchip Technology Inc. and its subsidiaries
   5 *    Copyright (c) 2016-2018 Microsemi Corporation
   6 *    Copyright (c) 2016 PMC-Sierra, Inc.
   7 *
   8 *    Questions/Comments/Bugfixes to storagedev@microchip.com
   9 *
  10 */
  11
  12#include <linux/module.h>
  13#include <linux/kernel.h>
  14#include <linux/pci.h>
  15#include <linux/delay.h>
  16#include <linux/interrupt.h>
  17#include <linux/sched.h>
  18#include <linux/rtc.h>
  19#include <linux/bcd.h>
  20#include <linux/reboot.h>
  21#include <linux/cciss_ioctl.h>
  22#include <linux/blk-mq-pci.h>
  23#include <scsi/scsi_host.h>
  24#include <scsi/scsi_cmnd.h>
  25#include <scsi/scsi_device.h>
  26#include <scsi/scsi_eh.h>
  27#include <scsi/scsi_transport_sas.h>
  28#include <asm/unaligned.h>
  29#include "smartpqi.h"
  30#include "smartpqi_sis.h"
  31
  32#if !defined(BUILD_TIMESTAMP)
  33#define BUILD_TIMESTAMP
  34#endif
  35
  36#define DRIVER_VERSION          "2.1.10-020"
  37#define DRIVER_MAJOR            2
  38#define DRIVER_MINOR            1
  39#define DRIVER_RELEASE          10
  40#define DRIVER_REVISION         20
  41
  42#define DRIVER_NAME             "Microchip SmartPQI Driver (v" \
  43                                DRIVER_VERSION BUILD_TIMESTAMP ")"
  44#define DRIVER_NAME_SHORT       "smartpqi"
  45
  46#define PQI_EXTRA_SGL_MEMORY    (12 * sizeof(struct pqi_sg_descriptor))
  47
  48#define PQI_POST_RESET_DELAY_SECS                       5
  49#define PQI_POST_OFA_RESET_DELAY_UPON_TIMEOUT_SECS      10
  50
  51MODULE_AUTHOR("Microchip");
  52MODULE_DESCRIPTION("Driver for Microchip Smart Family Controller version "
  53        DRIVER_VERSION);
  54MODULE_VERSION(DRIVER_VERSION);
  55MODULE_LICENSE("GPL");
  56
  57static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info);
  58static void pqi_ctrl_offline_worker(struct work_struct *work);
  59static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info);
  60static void pqi_scan_start(struct Scsi_Host *shost);
  61static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
  62        struct pqi_queue_group *queue_group, enum pqi_io_path path,
  63        struct pqi_io_request *io_request);
  64static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
  65        struct pqi_iu_header *request, unsigned int flags,
  66        struct pqi_raid_error_info *error_info);
  67static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
  68        struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
  69        unsigned int cdb_length, struct pqi_queue_group *queue_group,
  70        struct pqi_encryption_info *encryption_info, bool raid_bypass);
  71static  int pqi_aio_submit_r1_write_io(struct pqi_ctrl_info *ctrl_info,
  72        struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
  73        struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
  74        struct pqi_scsi_dev_raid_map_data *rmd);
  75static int pqi_aio_submit_r56_write_io(struct pqi_ctrl_info *ctrl_info,
  76        struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
  77        struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
  78        struct pqi_scsi_dev_raid_map_data *rmd);
  79static void pqi_ofa_ctrl_quiesce(struct pqi_ctrl_info *ctrl_info);
  80static void pqi_ofa_ctrl_unquiesce(struct pqi_ctrl_info *ctrl_info);
  81static int pqi_ofa_ctrl_restart(struct pqi_ctrl_info *ctrl_info, unsigned int delay_secs);
  82static void pqi_ofa_setup_host_buffer(struct pqi_ctrl_info *ctrl_info);
  83static void pqi_ofa_free_host_buffer(struct pqi_ctrl_info *ctrl_info);
  84static int pqi_ofa_host_memory_update(struct pqi_ctrl_info *ctrl_info);
  85static int pqi_device_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
  86        struct pqi_scsi_dev *device, unsigned long timeout_msecs);
  87
  88/* for flags argument to pqi_submit_raid_request_synchronous() */
  89#define PQI_SYNC_FLAGS_INTERRUPTABLE    0x1
  90
  91static struct scsi_transport_template *pqi_sas_transport_template;
  92
  93static atomic_t pqi_controller_count = ATOMIC_INIT(0);
  94
  95enum pqi_lockup_action {
  96        NONE,
  97        REBOOT,
  98        PANIC
  99};
 100
 101static enum pqi_lockup_action pqi_lockup_action = NONE;
 102
 103static struct {
 104        enum pqi_lockup_action  action;
 105        char                    *name;
 106} pqi_lockup_actions[] = {
 107        {
 108                .action = NONE,
 109                .name = "none",
 110        },
 111        {
 112                .action = REBOOT,
 113                .name = "reboot",
 114        },
 115        {
 116                .action = PANIC,
 117                .name = "panic",
 118        },
 119};
 120
 121static unsigned int pqi_supported_event_types[] = {
 122        PQI_EVENT_TYPE_HOTPLUG,
 123        PQI_EVENT_TYPE_HARDWARE,
 124        PQI_EVENT_TYPE_PHYSICAL_DEVICE,
 125        PQI_EVENT_TYPE_LOGICAL_DEVICE,
 126        PQI_EVENT_TYPE_OFA,
 127        PQI_EVENT_TYPE_AIO_STATE_CHANGE,
 128        PQI_EVENT_TYPE_AIO_CONFIG_CHANGE,
 129};
 130
 131static int pqi_disable_device_id_wildcards;
 132module_param_named(disable_device_id_wildcards,
 133        pqi_disable_device_id_wildcards, int, 0644);
 134MODULE_PARM_DESC(disable_device_id_wildcards,
 135        "Disable device ID wildcards.");
 136
 137static int pqi_disable_heartbeat;
 138module_param_named(disable_heartbeat,
 139        pqi_disable_heartbeat, int, 0644);
 140MODULE_PARM_DESC(disable_heartbeat,
 141        "Disable heartbeat.");
 142
 143static int pqi_disable_ctrl_shutdown;
 144module_param_named(disable_ctrl_shutdown,
 145        pqi_disable_ctrl_shutdown, int, 0644);
 146MODULE_PARM_DESC(disable_ctrl_shutdown,
 147        "Disable controller shutdown when controller locked up.");
 148
 149static char *pqi_lockup_action_param;
 150module_param_named(lockup_action,
 151        pqi_lockup_action_param, charp, 0644);
 152MODULE_PARM_DESC(lockup_action, "Action to take when controller locked up.\n"
 153        "\t\tSupported: none, reboot, panic\n"
 154        "\t\tDefault: none");
 155
 156static int pqi_expose_ld_first;
 157module_param_named(expose_ld_first,
 158        pqi_expose_ld_first, int, 0644);
 159MODULE_PARM_DESC(expose_ld_first, "Expose logical drives before physical drives.");
 160
 161static int pqi_hide_vsep;
 162module_param_named(hide_vsep,
 163        pqi_hide_vsep, int, 0644);
 164MODULE_PARM_DESC(hide_vsep, "Hide the virtual SEP for direct attached drives.");
 165
 166static char *raid_levels[] = {
 167        "RAID-0",
 168        "RAID-4",
 169        "RAID-1(1+0)",
 170        "RAID-5",
 171        "RAID-5+1",
 172        "RAID-6",
 173        "RAID-1(Triple)",
 174};
 175
 176static char *pqi_raid_level_to_string(u8 raid_level)
 177{
 178        if (raid_level < ARRAY_SIZE(raid_levels))
 179                return raid_levels[raid_level];
 180
 181        return "RAID UNKNOWN";
 182}
 183
 184#define SA_RAID_0               0
 185#define SA_RAID_4               1
 186#define SA_RAID_1               2       /* also used for RAID 10 */
 187#define SA_RAID_5               3       /* also used for RAID 50 */
 188#define SA_RAID_51              4
 189#define SA_RAID_6               5       /* also used for RAID 60 */
 190#define SA_RAID_TRIPLE          6       /* also used for RAID 1+0 Triple */
 191#define SA_RAID_MAX             SA_RAID_TRIPLE
 192#define SA_RAID_UNKNOWN         0xff
 193
 194static inline void pqi_scsi_done(struct scsi_cmnd *scmd)
 195{
 196        pqi_prep_for_scsi_done(scmd);
 197        scmd->scsi_done(scmd);
 198}
 199
 200static inline void pqi_disable_write_same(struct scsi_device *sdev)
 201{
 202        sdev->no_write_same = 1;
 203}
 204
 205static inline bool pqi_scsi3addr_equal(u8 *scsi3addr1, u8 *scsi3addr2)
 206{
 207        return memcmp(scsi3addr1, scsi3addr2, 8) == 0;
 208}
 209
 210static inline bool pqi_is_logical_device(struct pqi_scsi_dev *device)
 211{
 212        return !device->is_physical_device;
 213}
 214
 215static inline bool pqi_is_external_raid_addr(u8 *scsi3addr)
 216{
 217        return scsi3addr[2] != 0;
 218}
 219
 220static inline bool pqi_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
 221{
 222        return !ctrl_info->controller_online;
 223}
 224
 225static inline void pqi_check_ctrl_health(struct pqi_ctrl_info *ctrl_info)
 226{
 227        if (ctrl_info->controller_online)
 228                if (!sis_is_firmware_running(ctrl_info))
 229                        pqi_take_ctrl_offline(ctrl_info);
 230}
 231
 232static inline bool pqi_is_hba_lunid(u8 *scsi3addr)
 233{
 234        return pqi_scsi3addr_equal(scsi3addr, RAID_CTLR_LUNID);
 235}
 236
 237static inline enum pqi_ctrl_mode pqi_get_ctrl_mode(struct pqi_ctrl_info *ctrl_info)
 238{
 239        return sis_read_driver_scratch(ctrl_info);
 240}
 241
 242static inline void pqi_save_ctrl_mode(struct pqi_ctrl_info *ctrl_info,
 243        enum pqi_ctrl_mode mode)
 244{
 245        sis_write_driver_scratch(ctrl_info, mode);
 246}
 247
 248static inline void pqi_ctrl_block_scan(struct pqi_ctrl_info *ctrl_info)
 249{
 250        ctrl_info->scan_blocked = true;
 251        mutex_lock(&ctrl_info->scan_mutex);
 252}
 253
 254static inline void pqi_ctrl_unblock_scan(struct pqi_ctrl_info *ctrl_info)
 255{
 256        ctrl_info->scan_blocked = false;
 257        mutex_unlock(&ctrl_info->scan_mutex);
 258}
 259
 260static inline bool pqi_ctrl_scan_blocked(struct pqi_ctrl_info *ctrl_info)
 261{
 262        return ctrl_info->scan_blocked;
 263}
 264
 265static inline void pqi_ctrl_block_device_reset(struct pqi_ctrl_info *ctrl_info)
 266{
 267        mutex_lock(&ctrl_info->lun_reset_mutex);
 268}
 269
 270static inline void pqi_ctrl_unblock_device_reset(struct pqi_ctrl_info *ctrl_info)
 271{
 272        mutex_unlock(&ctrl_info->lun_reset_mutex);
 273}
 274
 275static inline void pqi_scsi_block_requests(struct pqi_ctrl_info *ctrl_info)
 276{
 277        struct Scsi_Host *shost;
 278        unsigned int num_loops;
 279        int msecs_sleep;
 280
 281        shost = ctrl_info->scsi_host;
 282
 283        scsi_block_requests(shost);
 284
 285        num_loops = 0;
 286        msecs_sleep = 20;
 287        while (scsi_host_busy(shost)) {
 288                num_loops++;
 289                if (num_loops == 10)
 290                        msecs_sleep = 500;
 291                msleep(msecs_sleep);
 292        }
 293}
 294
 295static inline void pqi_scsi_unblock_requests(struct pqi_ctrl_info *ctrl_info)
 296{
 297        scsi_unblock_requests(ctrl_info->scsi_host);
 298}
 299
 300static inline void pqi_ctrl_busy(struct pqi_ctrl_info *ctrl_info)
 301{
 302        atomic_inc(&ctrl_info->num_busy_threads);
 303}
 304
 305static inline void pqi_ctrl_unbusy(struct pqi_ctrl_info *ctrl_info)
 306{
 307        atomic_dec(&ctrl_info->num_busy_threads);
 308}
 309
 310static inline bool pqi_ctrl_blocked(struct pqi_ctrl_info *ctrl_info)
 311{
 312        return ctrl_info->block_requests;
 313}
 314
 315static inline void pqi_ctrl_block_requests(struct pqi_ctrl_info *ctrl_info)
 316{
 317        ctrl_info->block_requests = true;
 318}
 319
 320static inline void pqi_ctrl_unblock_requests(struct pqi_ctrl_info *ctrl_info)
 321{
 322        ctrl_info->block_requests = false;
 323        wake_up_all(&ctrl_info->block_requests_wait);
 324}
 325
 326static void pqi_wait_if_ctrl_blocked(struct pqi_ctrl_info *ctrl_info)
 327{
 328        if (!pqi_ctrl_blocked(ctrl_info))
 329                return;
 330
 331        atomic_inc(&ctrl_info->num_blocked_threads);
 332        wait_event(ctrl_info->block_requests_wait,
 333                !pqi_ctrl_blocked(ctrl_info));
 334        atomic_dec(&ctrl_info->num_blocked_threads);
 335}
 336
 337#define PQI_QUIESCE_WARNING_TIMEOUT_SECS                10
 338
 339static inline void pqi_ctrl_wait_until_quiesced(struct pqi_ctrl_info *ctrl_info)
 340{
 341        unsigned long start_jiffies;
 342        unsigned long warning_timeout;
 343        bool displayed_warning;
 344
 345        displayed_warning = false;
 346        start_jiffies = jiffies;
 347        warning_timeout = (PQI_QUIESCE_WARNING_TIMEOUT_SECS * PQI_HZ) + start_jiffies;
 348
 349        while (atomic_read(&ctrl_info->num_busy_threads) >
 350                atomic_read(&ctrl_info->num_blocked_threads)) {
 351                if (time_after(jiffies, warning_timeout)) {
 352                        dev_warn(&ctrl_info->pci_dev->dev,
 353                                "waiting %u seconds for driver activity to quiesce\n",
 354                                jiffies_to_msecs(jiffies - start_jiffies) / 1000);
 355                        displayed_warning = true;
 356                        warning_timeout = (PQI_QUIESCE_WARNING_TIMEOUT_SECS * PQI_HZ) + jiffies;
 357                }
 358                usleep_range(1000, 2000);
 359        }
 360
 361        if (displayed_warning)
 362                dev_warn(&ctrl_info->pci_dev->dev,
 363                        "driver activity quiesced after waiting for %u seconds\n",
 364                        jiffies_to_msecs(jiffies - start_jiffies) / 1000);
 365}
 366
 367static inline bool pqi_device_offline(struct pqi_scsi_dev *device)
 368{
 369        return device->device_offline;
 370}
 371
 372static inline void pqi_ctrl_ofa_start(struct pqi_ctrl_info *ctrl_info)
 373{
 374        mutex_lock(&ctrl_info->ofa_mutex);
 375}
 376
 377static inline void pqi_ctrl_ofa_done(struct pqi_ctrl_info *ctrl_info)
 378{
 379        mutex_unlock(&ctrl_info->ofa_mutex);
 380}
 381
 382static inline void pqi_wait_until_ofa_finished(struct pqi_ctrl_info *ctrl_info)
 383{
 384        mutex_lock(&ctrl_info->ofa_mutex);
 385        mutex_unlock(&ctrl_info->ofa_mutex);
 386}
 387
 388static inline bool pqi_ofa_in_progress(struct pqi_ctrl_info *ctrl_info)
 389{
 390        return mutex_is_locked(&ctrl_info->ofa_mutex);
 391}
 392
 393static inline void pqi_device_remove_start(struct pqi_scsi_dev *device)
 394{
 395        device->in_remove = true;
 396}
 397
 398static inline bool pqi_device_in_remove(struct pqi_scsi_dev *device)
 399{
 400        return device->in_remove;
 401}
 402
 403static inline int pqi_event_type_to_event_index(unsigned int event_type)
 404{
 405        int index;
 406
 407        for (index = 0; index < ARRAY_SIZE(pqi_supported_event_types); index++)
 408                if (event_type == pqi_supported_event_types[index])
 409                        return index;
 410
 411        return -1;
 412}
 413
 414static inline bool pqi_is_supported_event(unsigned int event_type)
 415{
 416        return pqi_event_type_to_event_index(event_type) != -1;
 417}
 418
 419static inline void pqi_schedule_rescan_worker_with_delay(struct pqi_ctrl_info *ctrl_info,
 420        unsigned long delay)
 421{
 422        if (pqi_ctrl_offline(ctrl_info))
 423                return;
 424
 425        schedule_delayed_work(&ctrl_info->rescan_work, delay);
 426}
 427
 428static inline void pqi_schedule_rescan_worker(struct pqi_ctrl_info *ctrl_info)
 429{
 430        pqi_schedule_rescan_worker_with_delay(ctrl_info, 0);
 431}
 432
 433#define PQI_RESCAN_WORK_DELAY   (10 * PQI_HZ)
 434
 435static inline void pqi_schedule_rescan_worker_delayed(struct pqi_ctrl_info *ctrl_info)
 436{
 437        pqi_schedule_rescan_worker_with_delay(ctrl_info, PQI_RESCAN_WORK_DELAY);
 438}
 439
 440static inline void pqi_cancel_rescan_worker(struct pqi_ctrl_info *ctrl_info)
 441{
 442        cancel_delayed_work_sync(&ctrl_info->rescan_work);
 443}
 444
 445static inline u32 pqi_read_heartbeat_counter(struct pqi_ctrl_info *ctrl_info)
 446{
 447        if (!ctrl_info->heartbeat_counter)
 448                return 0;
 449
 450        return readl(ctrl_info->heartbeat_counter);
 451}
 452
 453static inline u8 pqi_read_soft_reset_status(struct pqi_ctrl_info *ctrl_info)
 454{
 455        return readb(ctrl_info->soft_reset_status);
 456}
 457
 458static inline void pqi_clear_soft_reset_status(struct pqi_ctrl_info *ctrl_info)
 459{
 460        u8 status;
 461
 462        status = pqi_read_soft_reset_status(ctrl_info);
 463        status &= ~PQI_SOFT_RESET_ABORT;
 464        writeb(status, ctrl_info->soft_reset_status);
 465}
 466
 467static int pqi_map_single(struct pci_dev *pci_dev,
 468        struct pqi_sg_descriptor *sg_descriptor, void *buffer,
 469        size_t buffer_length, enum dma_data_direction data_direction)
 470{
 471        dma_addr_t bus_address;
 472
 473        if (!buffer || buffer_length == 0 || data_direction == DMA_NONE)
 474                return 0;
 475
 476        bus_address = dma_map_single(&pci_dev->dev, buffer, buffer_length,
 477                data_direction);
 478        if (dma_mapping_error(&pci_dev->dev, bus_address))
 479                return -ENOMEM;
 480
 481        put_unaligned_le64((u64)bus_address, &sg_descriptor->address);
 482        put_unaligned_le32(buffer_length, &sg_descriptor->length);
 483        put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
 484
 485        return 0;
 486}
 487
 488static void pqi_pci_unmap(struct pci_dev *pci_dev,
 489        struct pqi_sg_descriptor *descriptors, int num_descriptors,
 490        enum dma_data_direction data_direction)
 491{
 492        int i;
 493
 494        if (data_direction == DMA_NONE)
 495                return;
 496
 497        for (i = 0; i < num_descriptors; i++)
 498                dma_unmap_single(&pci_dev->dev,
 499                        (dma_addr_t)get_unaligned_le64(&descriptors[i].address),
 500                        get_unaligned_le32(&descriptors[i].length),
 501                        data_direction);
 502}
 503
 504static int pqi_build_raid_path_request(struct pqi_ctrl_info *ctrl_info,
 505        struct pqi_raid_path_request *request, u8 cmd,
 506        u8 *scsi3addr, void *buffer, size_t buffer_length,
 507        u16 vpd_page, enum dma_data_direction *dir)
 508{
 509        u8 *cdb;
 510        size_t cdb_length = buffer_length;
 511
 512        memset(request, 0, sizeof(*request));
 513
 514        request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
 515        put_unaligned_le16(offsetof(struct pqi_raid_path_request,
 516                sg_descriptors[1]) - PQI_REQUEST_HEADER_LENGTH,
 517                &request->header.iu_length);
 518        put_unaligned_le32(buffer_length, &request->buffer_length);
 519        memcpy(request->lun_number, scsi3addr, sizeof(request->lun_number));
 520        request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
 521        request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
 522
 523        cdb = request->cdb;
 524
 525        switch (cmd) {
 526        case INQUIRY:
 527                request->data_direction = SOP_READ_FLAG;
 528                cdb[0] = INQUIRY;
 529                if (vpd_page & VPD_PAGE) {
 530                        cdb[1] = 0x1;
 531                        cdb[2] = (u8)vpd_page;
 532                }
 533                cdb[4] = (u8)cdb_length;
 534                break;
 535        case CISS_REPORT_LOG:
 536        case CISS_REPORT_PHYS:
 537                request->data_direction = SOP_READ_FLAG;
 538                cdb[0] = cmd;
 539                if (cmd == CISS_REPORT_PHYS)
 540                        cdb[1] = CISS_REPORT_PHYS_FLAG_OTHER;
 541                else
 542                        cdb[1] = ctrl_info->ciss_report_log_flags;
 543                put_unaligned_be32(cdb_length, &cdb[6]);
 544                break;
 545        case CISS_GET_RAID_MAP:
 546                request->data_direction = SOP_READ_FLAG;
 547                cdb[0] = CISS_READ;
 548                cdb[1] = CISS_GET_RAID_MAP;
 549                put_unaligned_be32(cdb_length, &cdb[6]);
 550                break;
 551        case SA_FLUSH_CACHE:
 552                request->header.driver_flags = PQI_DRIVER_NONBLOCKABLE_REQUEST;
 553                request->data_direction = SOP_WRITE_FLAG;
 554                cdb[0] = BMIC_WRITE;
 555                cdb[6] = BMIC_FLUSH_CACHE;
 556                put_unaligned_be16(cdb_length, &cdb[7]);
 557                break;
 558        case BMIC_SENSE_DIAG_OPTIONS:
 559                cdb_length = 0;
 560                fallthrough;
 561        case BMIC_IDENTIFY_CONTROLLER:
 562        case BMIC_IDENTIFY_PHYSICAL_DEVICE:
 563        case BMIC_SENSE_SUBSYSTEM_INFORMATION:
 564        case BMIC_SENSE_FEATURE:
 565                request->data_direction = SOP_READ_FLAG;
 566                cdb[0] = BMIC_READ;
 567                cdb[6] = cmd;
 568                put_unaligned_be16(cdb_length, &cdb[7]);
 569                break;
 570        case BMIC_SET_DIAG_OPTIONS:
 571                cdb_length = 0;
 572                fallthrough;
 573        case BMIC_WRITE_HOST_WELLNESS:
 574                request->data_direction = SOP_WRITE_FLAG;
 575                cdb[0] = BMIC_WRITE;
 576                cdb[6] = cmd;
 577                put_unaligned_be16(cdb_length, &cdb[7]);
 578                break;
 579        case BMIC_CSMI_PASSTHRU:
 580                request->data_direction = SOP_BIDIRECTIONAL;
 581                cdb[0] = BMIC_WRITE;
 582                cdb[5] = CSMI_CC_SAS_SMP_PASSTHRU;
 583                cdb[6] = cmd;
 584                put_unaligned_be16(cdb_length, &cdb[7]);
 585                break;
 586        default:
 587                dev_err(&ctrl_info->pci_dev->dev, "unknown command 0x%c\n", cmd);
 588                break;
 589        }
 590
 591        switch (request->data_direction) {
 592        case SOP_READ_FLAG:
 593                *dir = DMA_FROM_DEVICE;
 594                break;
 595        case SOP_WRITE_FLAG:
 596                *dir = DMA_TO_DEVICE;
 597                break;
 598        case SOP_NO_DIRECTION_FLAG:
 599                *dir = DMA_NONE;
 600                break;
 601        default:
 602                *dir = DMA_BIDIRECTIONAL;
 603                break;
 604        }
 605
 606        return pqi_map_single(ctrl_info->pci_dev, &request->sg_descriptors[0],
 607                buffer, buffer_length, *dir);
 608}
 609
 610static inline void pqi_reinit_io_request(struct pqi_io_request *io_request)
 611{
 612        io_request->scmd = NULL;
 613        io_request->status = 0;
 614        io_request->error_info = NULL;
 615        io_request->raid_bypass = false;
 616}
 617
 618static struct pqi_io_request *pqi_alloc_io_request(
 619        struct pqi_ctrl_info *ctrl_info)
 620{
 621        struct pqi_io_request *io_request;
 622        u16 i = ctrl_info->next_io_request_slot;        /* benignly racy */
 623
 624        while (1) {
 625                io_request = &ctrl_info->io_request_pool[i];
 626                if (atomic_inc_return(&io_request->refcount) == 1)
 627                        break;
 628                atomic_dec(&io_request->refcount);
 629                i = (i + 1) % ctrl_info->max_io_slots;
 630        }
 631
 632        /* benignly racy */
 633        ctrl_info->next_io_request_slot = (i + 1) % ctrl_info->max_io_slots;
 634
 635        pqi_reinit_io_request(io_request);
 636
 637        return io_request;
 638}
 639
 640static void pqi_free_io_request(struct pqi_io_request *io_request)
 641{
 642        atomic_dec(&io_request->refcount);
 643}
 644
 645static int pqi_send_scsi_raid_request(struct pqi_ctrl_info *ctrl_info, u8 cmd,
 646        u8 *scsi3addr, void *buffer, size_t buffer_length, u16 vpd_page,
 647        struct pqi_raid_error_info *error_info)
 648{
 649        int rc;
 650        struct pqi_raid_path_request request;
 651        enum dma_data_direction dir;
 652
 653        rc = pqi_build_raid_path_request(ctrl_info, &request, cmd, scsi3addr,
 654                buffer, buffer_length, vpd_page, &dir);
 655        if (rc)
 656                return rc;
 657
 658        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, error_info);
 659
 660        pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
 661
 662        return rc;
 663}
 664
 665/* helper functions for pqi_send_scsi_raid_request */
 666
 667static inline int pqi_send_ctrl_raid_request(struct pqi_ctrl_info *ctrl_info,
 668        u8 cmd, void *buffer, size_t buffer_length)
 669{
 670        return pqi_send_scsi_raid_request(ctrl_info, cmd, RAID_CTLR_LUNID,
 671                buffer, buffer_length, 0, NULL);
 672}
 673
 674static inline int pqi_send_ctrl_raid_with_error(struct pqi_ctrl_info *ctrl_info,
 675        u8 cmd, void *buffer, size_t buffer_length,
 676        struct pqi_raid_error_info *error_info)
 677{
 678        return pqi_send_scsi_raid_request(ctrl_info, cmd, RAID_CTLR_LUNID,
 679                buffer, buffer_length, 0, error_info);
 680}
 681
 682static inline int pqi_identify_controller(struct pqi_ctrl_info *ctrl_info,
 683        struct bmic_identify_controller *buffer)
 684{
 685        return pqi_send_ctrl_raid_request(ctrl_info, BMIC_IDENTIFY_CONTROLLER,
 686                buffer, sizeof(*buffer));
 687}
 688
 689static inline int pqi_sense_subsystem_info(struct  pqi_ctrl_info *ctrl_info,
 690        struct bmic_sense_subsystem_info *sense_info)
 691{
 692        return pqi_send_ctrl_raid_request(ctrl_info,
 693                BMIC_SENSE_SUBSYSTEM_INFORMATION, sense_info,
 694                sizeof(*sense_info));
 695}
 696
 697static inline int pqi_scsi_inquiry(struct pqi_ctrl_info *ctrl_info,
 698        u8 *scsi3addr, u16 vpd_page, void *buffer, size_t buffer_length)
 699{
 700        return pqi_send_scsi_raid_request(ctrl_info, INQUIRY, scsi3addr,
 701                buffer, buffer_length, vpd_page, NULL);
 702}
 703
 704static int pqi_identify_physical_device(struct pqi_ctrl_info *ctrl_info,
 705        struct pqi_scsi_dev *device,
 706        struct bmic_identify_physical_device *buffer, size_t buffer_length)
 707{
 708        int rc;
 709        enum dma_data_direction dir;
 710        u16 bmic_device_index;
 711        struct pqi_raid_path_request request;
 712
 713        rc = pqi_build_raid_path_request(ctrl_info, &request,
 714                BMIC_IDENTIFY_PHYSICAL_DEVICE, RAID_CTLR_LUNID, buffer,
 715                buffer_length, 0, &dir);
 716        if (rc)
 717                return rc;
 718
 719        bmic_device_index = CISS_GET_DRIVE_NUMBER(device->scsi3addr);
 720        request.cdb[2] = (u8)bmic_device_index;
 721        request.cdb[9] = (u8)(bmic_device_index >> 8);
 722
 723        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
 724
 725        pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
 726
 727        return rc;
 728}
 729
 730static inline u32 pqi_aio_limit_to_bytes(__le16 *limit)
 731{
 732        u32 bytes;
 733
 734        bytes = get_unaligned_le16(limit);
 735        if (bytes == 0)
 736                bytes = ~0;
 737        else
 738                bytes *= 1024;
 739
 740        return bytes;
 741}
 742
 743#pragma pack(1)
 744
 745struct bmic_sense_feature_buffer {
 746        struct bmic_sense_feature_buffer_header header;
 747        struct bmic_sense_feature_io_page_aio_subpage aio_subpage;
 748};
 749
 750#pragma pack()
 751
 752#define MINIMUM_AIO_SUBPAGE_BUFFER_LENGTH       \
 753        offsetofend(struct bmic_sense_feature_buffer, \
 754                aio_subpage.max_write_raid_1_10_3drive)
 755
 756#define MINIMUM_AIO_SUBPAGE_LENGTH      \
 757        (offsetofend(struct bmic_sense_feature_io_page_aio_subpage, \
 758                max_write_raid_1_10_3drive) - \
 759                sizeof_field(struct bmic_sense_feature_io_page_aio_subpage, header))
 760
 761static int pqi_get_advanced_raid_bypass_config(struct pqi_ctrl_info *ctrl_info)
 762{
 763        int rc;
 764        enum dma_data_direction dir;
 765        struct pqi_raid_path_request request;
 766        struct bmic_sense_feature_buffer *buffer;
 767
 768        buffer = kmalloc(sizeof(*buffer), GFP_KERNEL);
 769        if (!buffer)
 770                return -ENOMEM;
 771
 772        rc = pqi_build_raid_path_request(ctrl_info, &request, BMIC_SENSE_FEATURE, RAID_CTLR_LUNID,
 773                buffer, sizeof(*buffer), 0, &dir);
 774        if (rc)
 775                goto error;
 776
 777        request.cdb[2] = BMIC_SENSE_FEATURE_IO_PAGE;
 778        request.cdb[3] = BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE;
 779
 780        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
 781
 782        pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1, dir);
 783
 784        if (rc)
 785                goto error;
 786
 787        if (buffer->header.page_code != BMIC_SENSE_FEATURE_IO_PAGE ||
 788                buffer->header.subpage_code !=
 789                        BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE ||
 790                get_unaligned_le16(&buffer->header.buffer_length) <
 791                        MINIMUM_AIO_SUBPAGE_BUFFER_LENGTH ||
 792                buffer->aio_subpage.header.page_code !=
 793                        BMIC_SENSE_FEATURE_IO_PAGE ||
 794                buffer->aio_subpage.header.subpage_code !=
 795                        BMIC_SENSE_FEATURE_IO_PAGE_AIO_SUBPAGE ||
 796                get_unaligned_le16(&buffer->aio_subpage.header.page_length) <
 797                        MINIMUM_AIO_SUBPAGE_LENGTH) {
 798                goto error;
 799        }
 800
 801        ctrl_info->max_transfer_encrypted_sas_sata =
 802                pqi_aio_limit_to_bytes(
 803                        &buffer->aio_subpage.max_transfer_encrypted_sas_sata);
 804
 805        ctrl_info->max_transfer_encrypted_nvme =
 806                pqi_aio_limit_to_bytes(
 807                        &buffer->aio_subpage.max_transfer_encrypted_nvme);
 808
 809        ctrl_info->max_write_raid_5_6 =
 810                pqi_aio_limit_to_bytes(
 811                        &buffer->aio_subpage.max_write_raid_5_6);
 812
 813        ctrl_info->max_write_raid_1_10_2drive =
 814                pqi_aio_limit_to_bytes(
 815                        &buffer->aio_subpage.max_write_raid_1_10_2drive);
 816
 817        ctrl_info->max_write_raid_1_10_3drive =
 818                pqi_aio_limit_to_bytes(
 819                        &buffer->aio_subpage.max_write_raid_1_10_3drive);
 820
 821error:
 822        kfree(buffer);
 823
 824        return rc;
 825}
 826
 827static int pqi_flush_cache(struct pqi_ctrl_info *ctrl_info,
 828        enum bmic_flush_cache_shutdown_event shutdown_event)
 829{
 830        int rc;
 831        struct bmic_flush_cache *flush_cache;
 832
 833        flush_cache = kzalloc(sizeof(*flush_cache), GFP_KERNEL);
 834        if (!flush_cache)
 835                return -ENOMEM;
 836
 837        flush_cache->shutdown_event = shutdown_event;
 838
 839        rc = pqi_send_ctrl_raid_request(ctrl_info, SA_FLUSH_CACHE, flush_cache,
 840                sizeof(*flush_cache));
 841
 842        kfree(flush_cache);
 843
 844        return rc;
 845}
 846
 847int pqi_csmi_smp_passthru(struct pqi_ctrl_info *ctrl_info,
 848        struct bmic_csmi_smp_passthru_buffer *buffer, size_t buffer_length,
 849        struct pqi_raid_error_info *error_info)
 850{
 851        return pqi_send_ctrl_raid_with_error(ctrl_info, BMIC_CSMI_PASSTHRU,
 852                buffer, buffer_length, error_info);
 853}
 854
 855#define PQI_FETCH_PTRAID_DATA           (1 << 31)
 856
 857static int pqi_set_diag_rescan(struct pqi_ctrl_info *ctrl_info)
 858{
 859        int rc;
 860        struct bmic_diag_options *diag;
 861
 862        diag = kzalloc(sizeof(*diag), GFP_KERNEL);
 863        if (!diag)
 864                return -ENOMEM;
 865
 866        rc = pqi_send_ctrl_raid_request(ctrl_info, BMIC_SENSE_DIAG_OPTIONS,
 867                diag, sizeof(*diag));
 868        if (rc)
 869                goto out;
 870
 871        diag->options |= cpu_to_le32(PQI_FETCH_PTRAID_DATA);
 872
 873        rc = pqi_send_ctrl_raid_request(ctrl_info, BMIC_SET_DIAG_OPTIONS, diag,
 874                sizeof(*diag));
 875
 876out:
 877        kfree(diag);
 878
 879        return rc;
 880}
 881
 882static inline int pqi_write_host_wellness(struct pqi_ctrl_info *ctrl_info,
 883        void *buffer, size_t buffer_length)
 884{
 885        return pqi_send_ctrl_raid_request(ctrl_info, BMIC_WRITE_HOST_WELLNESS,
 886                buffer, buffer_length);
 887}
 888
 889#pragma pack(1)
 890
 891struct bmic_host_wellness_driver_version {
 892        u8      start_tag[4];
 893        u8      driver_version_tag[2];
 894        __le16  driver_version_length;
 895        char    driver_version[32];
 896        u8      dont_write_tag[2];
 897        u8      end_tag[2];
 898};
 899
 900#pragma pack()
 901
 902static int pqi_write_driver_version_to_host_wellness(
 903        struct pqi_ctrl_info *ctrl_info)
 904{
 905        int rc;
 906        struct bmic_host_wellness_driver_version *buffer;
 907        size_t buffer_length;
 908
 909        buffer_length = sizeof(*buffer);
 910
 911        buffer = kmalloc(buffer_length, GFP_KERNEL);
 912        if (!buffer)
 913                return -ENOMEM;
 914
 915        buffer->start_tag[0] = '<';
 916        buffer->start_tag[1] = 'H';
 917        buffer->start_tag[2] = 'W';
 918        buffer->start_tag[3] = '>';
 919        buffer->driver_version_tag[0] = 'D';
 920        buffer->driver_version_tag[1] = 'V';
 921        put_unaligned_le16(sizeof(buffer->driver_version),
 922                &buffer->driver_version_length);
 923        strncpy(buffer->driver_version, "Linux " DRIVER_VERSION,
 924                sizeof(buffer->driver_version) - 1);
 925        buffer->driver_version[sizeof(buffer->driver_version) - 1] = '\0';
 926        buffer->dont_write_tag[0] = 'D';
 927        buffer->dont_write_tag[1] = 'W';
 928        buffer->end_tag[0] = 'Z';
 929        buffer->end_tag[1] = 'Z';
 930
 931        rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
 932
 933        kfree(buffer);
 934
 935        return rc;
 936}
 937
 938#pragma pack(1)
 939
 940struct bmic_host_wellness_time {
 941        u8      start_tag[4];
 942        u8      time_tag[2];
 943        __le16  time_length;
 944        u8      time[8];
 945        u8      dont_write_tag[2];
 946        u8      end_tag[2];
 947};
 948
 949#pragma pack()
 950
 951static int pqi_write_current_time_to_host_wellness(
 952        struct pqi_ctrl_info *ctrl_info)
 953{
 954        int rc;
 955        struct bmic_host_wellness_time *buffer;
 956        size_t buffer_length;
 957        time64_t local_time;
 958        unsigned int year;
 959        struct tm tm;
 960
 961        buffer_length = sizeof(*buffer);
 962
 963        buffer = kmalloc(buffer_length, GFP_KERNEL);
 964        if (!buffer)
 965                return -ENOMEM;
 966
 967        buffer->start_tag[0] = '<';
 968        buffer->start_tag[1] = 'H';
 969        buffer->start_tag[2] = 'W';
 970        buffer->start_tag[3] = '>';
 971        buffer->time_tag[0] = 'T';
 972        buffer->time_tag[1] = 'D';
 973        put_unaligned_le16(sizeof(buffer->time),
 974                &buffer->time_length);
 975
 976        local_time = ktime_get_real_seconds();
 977        time64_to_tm(local_time, -sys_tz.tz_minuteswest * 60, &tm);
 978        year = tm.tm_year + 1900;
 979
 980        buffer->time[0] = bin2bcd(tm.tm_hour);
 981        buffer->time[1] = bin2bcd(tm.tm_min);
 982        buffer->time[2] = bin2bcd(tm.tm_sec);
 983        buffer->time[3] = 0;
 984        buffer->time[4] = bin2bcd(tm.tm_mon + 1);
 985        buffer->time[5] = bin2bcd(tm.tm_mday);
 986        buffer->time[6] = bin2bcd(year / 100);
 987        buffer->time[7] = bin2bcd(year % 100);
 988
 989        buffer->dont_write_tag[0] = 'D';
 990        buffer->dont_write_tag[1] = 'W';
 991        buffer->end_tag[0] = 'Z';
 992        buffer->end_tag[1] = 'Z';
 993
 994        rc = pqi_write_host_wellness(ctrl_info, buffer, buffer_length);
 995
 996        kfree(buffer);
 997
 998        return rc;
 999}
1000
1001#define PQI_UPDATE_TIME_WORK_INTERVAL   (24UL * 60 * 60 * PQI_HZ)
1002
1003static void pqi_update_time_worker(struct work_struct *work)
1004{
1005        int rc;
1006        struct pqi_ctrl_info *ctrl_info;
1007
1008        ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
1009                update_time_work);
1010
1011        rc = pqi_write_current_time_to_host_wellness(ctrl_info);
1012        if (rc)
1013                dev_warn(&ctrl_info->pci_dev->dev,
1014                        "error updating time on controller\n");
1015
1016        schedule_delayed_work(&ctrl_info->update_time_work,
1017                PQI_UPDATE_TIME_WORK_INTERVAL);
1018}
1019
1020static inline void pqi_schedule_update_time_worker(struct pqi_ctrl_info *ctrl_info)
1021{
1022        schedule_delayed_work(&ctrl_info->update_time_work, 0);
1023}
1024
1025static inline void pqi_cancel_update_time_worker(struct pqi_ctrl_info *ctrl_info)
1026{
1027        cancel_delayed_work_sync(&ctrl_info->update_time_work);
1028}
1029
1030static inline int pqi_report_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd, void *buffer,
1031        size_t buffer_length)
1032{
1033        return pqi_send_ctrl_raid_request(ctrl_info, cmd, buffer, buffer_length);
1034}
1035
1036static int pqi_report_phys_logical_luns(struct pqi_ctrl_info *ctrl_info, u8 cmd, void **buffer)
1037{
1038        int rc;
1039        size_t lun_list_length;
1040        size_t lun_data_length;
1041        size_t new_lun_list_length;
1042        void *lun_data = NULL;
1043        struct report_lun_header *report_lun_header;
1044
1045        report_lun_header = kmalloc(sizeof(*report_lun_header), GFP_KERNEL);
1046        if (!report_lun_header) {
1047                rc = -ENOMEM;
1048                goto out;
1049        }
1050
1051        rc = pqi_report_luns(ctrl_info, cmd, report_lun_header, sizeof(*report_lun_header));
1052        if (rc)
1053                goto out;
1054
1055        lun_list_length = get_unaligned_be32(&report_lun_header->list_length);
1056
1057again:
1058        lun_data_length = sizeof(struct report_lun_header) + lun_list_length;
1059
1060        lun_data = kmalloc(lun_data_length, GFP_KERNEL);
1061        if (!lun_data) {
1062                rc = -ENOMEM;
1063                goto out;
1064        }
1065
1066        if (lun_list_length == 0) {
1067                memcpy(lun_data, report_lun_header, sizeof(*report_lun_header));
1068                goto out;
1069        }
1070
1071        rc = pqi_report_luns(ctrl_info, cmd, lun_data, lun_data_length);
1072        if (rc)
1073                goto out;
1074
1075        new_lun_list_length =
1076                get_unaligned_be32(&((struct report_lun_header *)lun_data)->list_length);
1077
1078        if (new_lun_list_length > lun_list_length) {
1079                lun_list_length = new_lun_list_length;
1080                kfree(lun_data);
1081                goto again;
1082        }
1083
1084out:
1085        kfree(report_lun_header);
1086
1087        if (rc) {
1088                kfree(lun_data);
1089                lun_data = NULL;
1090        }
1091
1092        *buffer = lun_data;
1093
1094        return rc;
1095}
1096
1097static inline int pqi_report_phys_luns(struct pqi_ctrl_info *ctrl_info, void **buffer)
1098{
1099        return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_PHYS, buffer);
1100}
1101
1102static inline int pqi_report_logical_luns(struct pqi_ctrl_info *ctrl_info, void **buffer)
1103{
1104        return pqi_report_phys_logical_luns(ctrl_info, CISS_REPORT_LOG, buffer);
1105}
1106
1107static int pqi_get_device_lists(struct pqi_ctrl_info *ctrl_info,
1108        struct report_phys_lun_extended **physdev_list,
1109        struct report_log_lun_extended **logdev_list)
1110{
1111        int rc;
1112        size_t logdev_list_length;
1113        size_t logdev_data_length;
1114        struct report_log_lun_extended *internal_logdev_list;
1115        struct report_log_lun_extended *logdev_data;
1116        struct report_lun_header report_lun_header;
1117
1118        rc = pqi_report_phys_luns(ctrl_info, (void **)physdev_list);
1119        if (rc)
1120                dev_err(&ctrl_info->pci_dev->dev,
1121                        "report physical LUNs failed\n");
1122
1123        rc = pqi_report_logical_luns(ctrl_info, (void **)logdev_list);
1124        if (rc)
1125                dev_err(&ctrl_info->pci_dev->dev,
1126                        "report logical LUNs failed\n");
1127
1128        /*
1129         * Tack the controller itself onto the end of the logical device list.
1130         */
1131
1132        logdev_data = *logdev_list;
1133
1134        if (logdev_data) {
1135                logdev_list_length =
1136                        get_unaligned_be32(&logdev_data->header.list_length);
1137        } else {
1138                memset(&report_lun_header, 0, sizeof(report_lun_header));
1139                logdev_data =
1140                        (struct report_log_lun_extended *)&report_lun_header;
1141                logdev_list_length = 0;
1142        }
1143
1144        logdev_data_length = sizeof(struct report_lun_header) +
1145                logdev_list_length;
1146
1147        internal_logdev_list = kmalloc(logdev_data_length +
1148                sizeof(struct report_log_lun_extended), GFP_KERNEL);
1149        if (!internal_logdev_list) {
1150                kfree(*logdev_list);
1151                *logdev_list = NULL;
1152                return -ENOMEM;
1153        }
1154
1155        memcpy(internal_logdev_list, logdev_data, logdev_data_length);
1156        memset((u8 *)internal_logdev_list + logdev_data_length, 0,
1157                sizeof(struct report_log_lun_extended_entry));
1158        put_unaligned_be32(logdev_list_length +
1159                sizeof(struct report_log_lun_extended_entry),
1160                &internal_logdev_list->header.list_length);
1161
1162        kfree(*logdev_list);
1163        *logdev_list = internal_logdev_list;
1164
1165        return 0;
1166}
1167
1168static inline void pqi_set_bus_target_lun(struct pqi_scsi_dev *device,
1169        int bus, int target, int lun)
1170{
1171        device->bus = bus;
1172        device->target = target;
1173        device->lun = lun;
1174}
1175
1176static void pqi_assign_bus_target_lun(struct pqi_scsi_dev *device)
1177{
1178        u8 *scsi3addr;
1179        u32 lunid;
1180        int bus;
1181        int target;
1182        int lun;
1183
1184        scsi3addr = device->scsi3addr;
1185        lunid = get_unaligned_le32(scsi3addr);
1186
1187        if (pqi_is_hba_lunid(scsi3addr)) {
1188                /* The specified device is the controller. */
1189                pqi_set_bus_target_lun(device, PQI_HBA_BUS, 0, lunid & 0x3fff);
1190                device->target_lun_valid = true;
1191                return;
1192        }
1193
1194        if (pqi_is_logical_device(device)) {
1195                if (device->is_external_raid_device) {
1196                        bus = PQI_EXTERNAL_RAID_VOLUME_BUS;
1197                        target = (lunid >> 16) & 0x3fff;
1198                        lun = lunid & 0xff;
1199                } else {
1200                        bus = PQI_RAID_VOLUME_BUS;
1201                        target = 0;
1202                        lun = lunid & 0x3fff;
1203                }
1204                pqi_set_bus_target_lun(device, bus, target, lun);
1205                device->target_lun_valid = true;
1206                return;
1207        }
1208
1209        /*
1210         * Defer target and LUN assignment for non-controller physical devices
1211         * because the SAS transport layer will make these assignments later.
1212         */
1213        pqi_set_bus_target_lun(device, PQI_PHYSICAL_DEVICE_BUS, 0, 0);
1214}
1215
1216static void pqi_get_raid_level(struct pqi_ctrl_info *ctrl_info,
1217        struct pqi_scsi_dev *device)
1218{
1219        int rc;
1220        u8 raid_level;
1221        u8 *buffer;
1222
1223        raid_level = SA_RAID_UNKNOWN;
1224
1225        buffer = kmalloc(64, GFP_KERNEL);
1226        if (buffer) {
1227                rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1228                        VPD_PAGE | CISS_VPD_LV_DEVICE_GEOMETRY, buffer, 64);
1229                if (rc == 0) {
1230                        raid_level = buffer[8];
1231                        if (raid_level > SA_RAID_MAX)
1232                                raid_level = SA_RAID_UNKNOWN;
1233                }
1234                kfree(buffer);
1235        }
1236
1237        device->raid_level = raid_level;
1238}
1239
1240static int pqi_validate_raid_map(struct pqi_ctrl_info *ctrl_info,
1241        struct pqi_scsi_dev *device, struct raid_map *raid_map)
1242{
1243        char *err_msg;
1244        u32 raid_map_size;
1245        u32 r5or6_blocks_per_row;
1246
1247        raid_map_size = get_unaligned_le32(&raid_map->structure_size);
1248
1249        if (raid_map_size < offsetof(struct raid_map, disk_data)) {
1250                err_msg = "RAID map too small";
1251                goto bad_raid_map;
1252        }
1253
1254        if (device->raid_level == SA_RAID_1) {
1255                if (get_unaligned_le16(&raid_map->layout_map_count) != 2) {
1256                        err_msg = "invalid RAID-1 map";
1257                        goto bad_raid_map;
1258                }
1259        } else if (device->raid_level == SA_RAID_TRIPLE) {
1260                if (get_unaligned_le16(&raid_map->layout_map_count) != 3) {
1261                        err_msg = "invalid RAID-1(Triple) map";
1262                        goto bad_raid_map;
1263                }
1264        } else if ((device->raid_level == SA_RAID_5 ||
1265                device->raid_level == SA_RAID_6) &&
1266                get_unaligned_le16(&raid_map->layout_map_count) > 1) {
1267                /* RAID 50/60 */
1268                r5or6_blocks_per_row =
1269                        get_unaligned_le16(&raid_map->strip_size) *
1270                        get_unaligned_le16(&raid_map->data_disks_per_row);
1271                if (r5or6_blocks_per_row == 0) {
1272                        err_msg = "invalid RAID-5 or RAID-6 map";
1273                        goto bad_raid_map;
1274                }
1275        }
1276
1277        return 0;
1278
1279bad_raid_map:
1280        dev_warn(&ctrl_info->pci_dev->dev,
1281                "logical device %08x%08x %s\n",
1282                *((u32 *)&device->scsi3addr),
1283                *((u32 *)&device->scsi3addr[4]), err_msg);
1284
1285        return -EINVAL;
1286}
1287
1288static int pqi_get_raid_map(struct pqi_ctrl_info *ctrl_info,
1289        struct pqi_scsi_dev *device)
1290{
1291        int rc;
1292        u32 raid_map_size;
1293        struct raid_map *raid_map;
1294
1295        raid_map = kmalloc(sizeof(*raid_map), GFP_KERNEL);
1296        if (!raid_map)
1297                return -ENOMEM;
1298
1299        rc = pqi_send_scsi_raid_request(ctrl_info, CISS_GET_RAID_MAP,
1300                device->scsi3addr, raid_map, sizeof(*raid_map), 0, NULL);
1301        if (rc)
1302                goto error;
1303
1304        raid_map_size = get_unaligned_le32(&raid_map->structure_size);
1305
1306        if (raid_map_size > sizeof(*raid_map)) {
1307
1308                kfree(raid_map);
1309
1310                raid_map = kmalloc(raid_map_size, GFP_KERNEL);
1311                if (!raid_map)
1312                        return -ENOMEM;
1313
1314                rc = pqi_send_scsi_raid_request(ctrl_info, CISS_GET_RAID_MAP,
1315                        device->scsi3addr, raid_map, raid_map_size, 0, NULL);
1316                if (rc)
1317                        goto error;
1318
1319                if (get_unaligned_le32(&raid_map->structure_size)
1320                        != raid_map_size) {
1321                        dev_warn(&ctrl_info->pci_dev->dev,
1322                                "requested %u bytes, received %u bytes\n",
1323                                raid_map_size,
1324                                get_unaligned_le32(&raid_map->structure_size));
1325                        rc = -EINVAL;
1326                        goto error;
1327                }
1328        }
1329
1330        rc = pqi_validate_raid_map(ctrl_info, device, raid_map);
1331        if (rc)
1332                goto error;
1333
1334        device->raid_map = raid_map;
1335
1336        return 0;
1337
1338error:
1339        kfree(raid_map);
1340
1341        return rc;
1342}
1343
1344static void pqi_set_max_transfer_encrypted(struct pqi_ctrl_info *ctrl_info,
1345        struct pqi_scsi_dev *device)
1346{
1347        if (!ctrl_info->lv_drive_type_mix_valid) {
1348                device->max_transfer_encrypted = ~0;
1349                return;
1350        }
1351
1352        switch (LV_GET_DRIVE_TYPE_MIX(device->scsi3addr)) {
1353        case LV_DRIVE_TYPE_MIX_SAS_HDD_ONLY:
1354        case LV_DRIVE_TYPE_MIX_SATA_HDD_ONLY:
1355        case LV_DRIVE_TYPE_MIX_SAS_OR_SATA_SSD_ONLY:
1356        case LV_DRIVE_TYPE_MIX_SAS_SSD_ONLY:
1357        case LV_DRIVE_TYPE_MIX_SATA_SSD_ONLY:
1358        case LV_DRIVE_TYPE_MIX_SAS_ONLY:
1359        case LV_DRIVE_TYPE_MIX_SATA_ONLY:
1360                device->max_transfer_encrypted =
1361                        ctrl_info->max_transfer_encrypted_sas_sata;
1362                break;
1363        case LV_DRIVE_TYPE_MIX_NVME_ONLY:
1364                device->max_transfer_encrypted =
1365                        ctrl_info->max_transfer_encrypted_nvme;
1366                break;
1367        case LV_DRIVE_TYPE_MIX_UNKNOWN:
1368        case LV_DRIVE_TYPE_MIX_NO_RESTRICTION:
1369        default:
1370                device->max_transfer_encrypted =
1371                        min(ctrl_info->max_transfer_encrypted_sas_sata,
1372                                ctrl_info->max_transfer_encrypted_nvme);
1373                break;
1374        }
1375}
1376
1377static void pqi_get_raid_bypass_status(struct pqi_ctrl_info *ctrl_info,
1378        struct pqi_scsi_dev *device)
1379{
1380        int rc;
1381        u8 *buffer;
1382        u8 bypass_status;
1383
1384        buffer = kmalloc(64, GFP_KERNEL);
1385        if (!buffer)
1386                return;
1387
1388        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1389                VPD_PAGE | CISS_VPD_LV_BYPASS_STATUS, buffer, 64);
1390        if (rc)
1391                goto out;
1392
1393#define RAID_BYPASS_STATUS              4
1394#define RAID_BYPASS_CONFIGURED          0x1
1395#define RAID_BYPASS_ENABLED             0x2
1396
1397        bypass_status = buffer[RAID_BYPASS_STATUS];
1398        device->raid_bypass_configured =
1399                (bypass_status & RAID_BYPASS_CONFIGURED) != 0;
1400        if (device->raid_bypass_configured &&
1401                (bypass_status & RAID_BYPASS_ENABLED) &&
1402                pqi_get_raid_map(ctrl_info, device) == 0) {
1403                device->raid_bypass_enabled = true;
1404                if (get_unaligned_le16(&device->raid_map->flags) &
1405                        RAID_MAP_ENCRYPTION_ENABLED)
1406                        pqi_set_max_transfer_encrypted(ctrl_info, device);
1407        }
1408
1409out:
1410        kfree(buffer);
1411}
1412
1413/*
1414 * Use vendor-specific VPD to determine online/offline status of a volume.
1415 */
1416
1417static void pqi_get_volume_status(struct pqi_ctrl_info *ctrl_info,
1418        struct pqi_scsi_dev *device)
1419{
1420        int rc;
1421        size_t page_length;
1422        u8 volume_status = CISS_LV_STATUS_UNAVAILABLE;
1423        bool volume_offline = true;
1424        u32 volume_flags;
1425        struct ciss_vpd_logical_volume_status *vpd;
1426
1427        vpd = kmalloc(sizeof(*vpd), GFP_KERNEL);
1428        if (!vpd)
1429                goto no_buffer;
1430
1431        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1432                VPD_PAGE | CISS_VPD_LV_STATUS, vpd, sizeof(*vpd));
1433        if (rc)
1434                goto out;
1435
1436        if (vpd->page_code != CISS_VPD_LV_STATUS)
1437                goto out;
1438
1439        page_length = offsetof(struct ciss_vpd_logical_volume_status,
1440                volume_status) + vpd->page_length;
1441        if (page_length < sizeof(*vpd))
1442                goto out;
1443
1444        volume_status = vpd->volume_status;
1445        volume_flags = get_unaligned_be32(&vpd->flags);
1446        volume_offline = (volume_flags & CISS_LV_FLAGS_NO_HOST_IO) != 0;
1447
1448out:
1449        kfree(vpd);
1450no_buffer:
1451        device->volume_status = volume_status;
1452        device->volume_offline = volume_offline;
1453}
1454
1455#define PQI_DEVICE_PHY_MAP_SUPPORTED    0x10
1456
1457static int pqi_get_physical_device_info(struct pqi_ctrl_info *ctrl_info,
1458        struct pqi_scsi_dev *device,
1459        struct bmic_identify_physical_device *id_phys)
1460{
1461        int rc;
1462
1463        memset(id_phys, 0, sizeof(*id_phys));
1464
1465        rc = pqi_identify_physical_device(ctrl_info, device,
1466                id_phys, sizeof(*id_phys));
1467        if (rc) {
1468                device->queue_depth = PQI_PHYSICAL_DISK_DEFAULT_MAX_QUEUE_DEPTH;
1469                return rc;
1470        }
1471
1472        scsi_sanitize_inquiry_string(&id_phys->model[0], 8);
1473        scsi_sanitize_inquiry_string(&id_phys->model[8], 16);
1474
1475        memcpy(device->vendor, &id_phys->model[0], sizeof(device->vendor));
1476        memcpy(device->model, &id_phys->model[8], sizeof(device->model));
1477
1478        device->box_index = id_phys->box_index;
1479        device->phys_box_on_bus = id_phys->phys_box_on_bus;
1480        device->phy_connected_dev_type = id_phys->phy_connected_dev_type[0];
1481        device->queue_depth =
1482                get_unaligned_le16(&id_phys->current_queue_depth_limit);
1483        device->active_path_index = id_phys->active_path_number;
1484        device->path_map = id_phys->redundant_path_present_map;
1485        memcpy(&device->box,
1486                &id_phys->alternate_paths_phys_box_on_port,
1487                sizeof(device->box));
1488        memcpy(&device->phys_connector,
1489                &id_phys->alternate_paths_phys_connector,
1490                sizeof(device->phys_connector));
1491        device->bay = id_phys->phys_bay_in_box;
1492
1493        memcpy(&device->page_83_identifier, &id_phys->page_83_identifier,
1494                sizeof(device->page_83_identifier));
1495
1496        if ((id_phys->even_more_flags & PQI_DEVICE_PHY_MAP_SUPPORTED) &&
1497                id_phys->phy_count)
1498                device->phy_id =
1499                        id_phys->phy_to_phy_map[device->active_path_index];
1500        else
1501                device->phy_id = 0xFF;
1502
1503        return 0;
1504}
1505
1506static int pqi_get_logical_device_info(struct pqi_ctrl_info *ctrl_info,
1507        struct pqi_scsi_dev *device)
1508{
1509        int rc;
1510        u8 *buffer;
1511
1512        buffer = kmalloc(64, GFP_KERNEL);
1513        if (!buffer)
1514                return -ENOMEM;
1515
1516        /* Send an inquiry to the device to see what it is. */
1517        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr, 0, buffer, 64);
1518        if (rc)
1519                goto out;
1520
1521        scsi_sanitize_inquiry_string(&buffer[8], 8);
1522        scsi_sanitize_inquiry_string(&buffer[16], 16);
1523
1524        device->devtype = buffer[0] & 0x1f;
1525        memcpy(device->vendor, &buffer[8], sizeof(device->vendor));
1526        memcpy(device->model, &buffer[16], sizeof(device->model));
1527
1528        if (device->devtype == TYPE_DISK) {
1529                if (device->is_external_raid_device) {
1530                        device->raid_level = SA_RAID_UNKNOWN;
1531                        device->volume_status = CISS_LV_OK;
1532                        device->volume_offline = false;
1533                } else {
1534                        pqi_get_raid_level(ctrl_info, device);
1535                        pqi_get_raid_bypass_status(ctrl_info, device);
1536                        pqi_get_volume_status(ctrl_info, device);
1537                }
1538        }
1539
1540out:
1541        kfree(buffer);
1542
1543        return rc;
1544}
1545
1546static int pqi_get_device_info(struct pqi_ctrl_info *ctrl_info,
1547        struct pqi_scsi_dev *device,
1548        struct bmic_identify_physical_device *id_phys)
1549{
1550        int rc;
1551
1552        if (device->is_expander_smp_device)
1553                return 0;
1554
1555        if (pqi_is_logical_device(device))
1556                rc = pqi_get_logical_device_info(ctrl_info, device);
1557        else
1558                rc = pqi_get_physical_device_info(ctrl_info, device, id_phys);
1559
1560        return rc;
1561}
1562
1563static void pqi_show_volume_status(struct pqi_ctrl_info *ctrl_info,
1564        struct pqi_scsi_dev *device)
1565{
1566        char *status;
1567        static const char unknown_state_str[] =
1568                "Volume is in an unknown state (%u)";
1569        char unknown_state_buffer[sizeof(unknown_state_str) + 10];
1570
1571        switch (device->volume_status) {
1572        case CISS_LV_OK:
1573                status = "Volume online";
1574                break;
1575        case CISS_LV_FAILED:
1576                status = "Volume failed";
1577                break;
1578        case CISS_LV_NOT_CONFIGURED:
1579                status = "Volume not configured";
1580                break;
1581        case CISS_LV_DEGRADED:
1582                status = "Volume degraded";
1583                break;
1584        case CISS_LV_READY_FOR_RECOVERY:
1585                status = "Volume ready for recovery operation";
1586                break;
1587        case CISS_LV_UNDERGOING_RECOVERY:
1588                status = "Volume undergoing recovery";
1589                break;
1590        case CISS_LV_WRONG_PHYSICAL_DRIVE_REPLACED:
1591                status = "Wrong physical drive was replaced";
1592                break;
1593        case CISS_LV_PHYSICAL_DRIVE_CONNECTION_PROBLEM:
1594                status = "A physical drive not properly connected";
1595                break;
1596        case CISS_LV_HARDWARE_OVERHEATING:
1597                status = "Hardware is overheating";
1598                break;
1599        case CISS_LV_HARDWARE_HAS_OVERHEATED:
1600                status = "Hardware has overheated";
1601                break;
1602        case CISS_LV_UNDERGOING_EXPANSION:
1603                status = "Volume undergoing expansion";
1604                break;
1605        case CISS_LV_NOT_AVAILABLE:
1606                status = "Volume waiting for transforming volume";
1607                break;
1608        case CISS_LV_QUEUED_FOR_EXPANSION:
1609                status = "Volume queued for expansion";
1610                break;
1611        case CISS_LV_DISABLED_SCSI_ID_CONFLICT:
1612                status = "Volume disabled due to SCSI ID conflict";
1613                break;
1614        case CISS_LV_EJECTED:
1615                status = "Volume has been ejected";
1616                break;
1617        case CISS_LV_UNDERGOING_ERASE:
1618                status = "Volume undergoing background erase";
1619                break;
1620        case CISS_LV_READY_FOR_PREDICTIVE_SPARE_REBUILD:
1621                status = "Volume ready for predictive spare rebuild";
1622                break;
1623        case CISS_LV_UNDERGOING_RPI:
1624                status = "Volume undergoing rapid parity initialization";
1625                break;
1626        case CISS_LV_PENDING_RPI:
1627                status = "Volume queued for rapid parity initialization";
1628                break;
1629        case CISS_LV_ENCRYPTED_NO_KEY:
1630                status = "Encrypted volume inaccessible - key not present";
1631                break;
1632        case CISS_LV_UNDERGOING_ENCRYPTION:
1633                status = "Volume undergoing encryption process";
1634                break;
1635        case CISS_LV_UNDERGOING_ENCRYPTION_REKEYING:
1636                status = "Volume undergoing encryption re-keying process";
1637                break;
1638        case CISS_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
1639                status = "Volume encrypted but encryption is disabled";
1640                break;
1641        case CISS_LV_PENDING_ENCRYPTION:
1642                status = "Volume pending migration to encrypted state";
1643                break;
1644        case CISS_LV_PENDING_ENCRYPTION_REKEYING:
1645                status = "Volume pending encryption rekeying";
1646                break;
1647        case CISS_LV_NOT_SUPPORTED:
1648                status = "Volume not supported on this controller";
1649                break;
1650        case CISS_LV_STATUS_UNAVAILABLE:
1651                status = "Volume status not available";
1652                break;
1653        default:
1654                snprintf(unknown_state_buffer, sizeof(unknown_state_buffer),
1655                        unknown_state_str, device->volume_status);
1656                status = unknown_state_buffer;
1657                break;
1658        }
1659
1660        dev_info(&ctrl_info->pci_dev->dev,
1661                "scsi %d:%d:%d:%d %s\n",
1662                ctrl_info->scsi_host->host_no,
1663                device->bus, device->target, device->lun, status);
1664}
1665
1666static void pqi_rescan_worker(struct work_struct *work)
1667{
1668        struct pqi_ctrl_info *ctrl_info;
1669
1670        ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
1671                rescan_work);
1672
1673        pqi_scan_scsi_devices(ctrl_info);
1674}
1675
1676static int pqi_add_device(struct pqi_ctrl_info *ctrl_info,
1677        struct pqi_scsi_dev *device)
1678{
1679        int rc;
1680
1681        if (pqi_is_logical_device(device))
1682                rc = scsi_add_device(ctrl_info->scsi_host, device->bus,
1683                        device->target, device->lun);
1684        else
1685                rc = pqi_add_sas_device(ctrl_info->sas_host, device);
1686
1687        return rc;
1688}
1689
1690#define PQI_REMOVE_DEVICE_PENDING_IO_TIMEOUT_MSECS      (20 * 1000)
1691
1692static inline void pqi_remove_device(struct pqi_ctrl_info *ctrl_info, struct pqi_scsi_dev *device)
1693{
1694        int rc;
1695
1696        pqi_device_remove_start(device);
1697
1698        rc = pqi_device_wait_for_pending_io(ctrl_info, device,
1699                PQI_REMOVE_DEVICE_PENDING_IO_TIMEOUT_MSECS);
1700        if (rc)
1701                dev_err(&ctrl_info->pci_dev->dev,
1702                        "scsi %d:%d:%d:%d removing device with %d outstanding command(s)\n",
1703                        ctrl_info->scsi_host->host_no, device->bus,
1704                        device->target, device->lun,
1705                        atomic_read(&device->scsi_cmds_outstanding));
1706
1707        if (pqi_is_logical_device(device))
1708                scsi_remove_device(device->sdev);
1709        else
1710                pqi_remove_sas_device(device);
1711}
1712
1713/* Assumes the SCSI device list lock is held. */
1714
1715static struct pqi_scsi_dev *pqi_find_scsi_dev(struct pqi_ctrl_info *ctrl_info,
1716        int bus, int target, int lun)
1717{
1718        struct pqi_scsi_dev *device;
1719
1720        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1721                if (device->bus == bus && device->target == target && device->lun == lun)
1722                        return device;
1723
1724        return NULL;
1725}
1726
1727static inline bool pqi_device_equal(struct pqi_scsi_dev *dev1, struct pqi_scsi_dev *dev2)
1728{
1729        if (dev1->is_physical_device != dev2->is_physical_device)
1730                return false;
1731
1732        if (dev1->is_physical_device)
1733                return dev1->wwid == dev2->wwid;
1734
1735        return memcmp(dev1->volume_id, dev2->volume_id, sizeof(dev1->volume_id)) == 0;
1736}
1737
1738enum pqi_find_result {
1739        DEVICE_NOT_FOUND,
1740        DEVICE_CHANGED,
1741        DEVICE_SAME,
1742};
1743
1744static enum pqi_find_result pqi_scsi_find_entry(struct pqi_ctrl_info *ctrl_info,
1745        struct pqi_scsi_dev *device_to_find, struct pqi_scsi_dev **matching_device)
1746{
1747        struct pqi_scsi_dev *device;
1748
1749        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
1750                if (pqi_scsi3addr_equal(device_to_find->scsi3addr, device->scsi3addr)) {
1751                        *matching_device = device;
1752                        if (pqi_device_equal(device_to_find, device)) {
1753                                if (device_to_find->volume_offline)
1754                                        return DEVICE_CHANGED;
1755                                return DEVICE_SAME;
1756                        }
1757                        return DEVICE_CHANGED;
1758                }
1759        }
1760
1761        return DEVICE_NOT_FOUND;
1762}
1763
1764static inline const char *pqi_device_type(struct pqi_scsi_dev *device)
1765{
1766        if (device->is_expander_smp_device)
1767                return "Enclosure SMP    ";
1768
1769        return scsi_device_type(device->devtype);
1770}
1771
1772#define PQI_DEV_INFO_BUFFER_LENGTH      128
1773
1774static void pqi_dev_info(struct pqi_ctrl_info *ctrl_info,
1775        char *action, struct pqi_scsi_dev *device)
1776{
1777        ssize_t count;
1778        char buffer[PQI_DEV_INFO_BUFFER_LENGTH];
1779
1780        count = scnprintf(buffer, PQI_DEV_INFO_BUFFER_LENGTH,
1781                "%d:%d:", ctrl_info->scsi_host->host_no, device->bus);
1782
1783        if (device->target_lun_valid)
1784                count += scnprintf(buffer + count,
1785                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1786                        "%d:%d",
1787                        device->target,
1788                        device->lun);
1789        else
1790                count += scnprintf(buffer + count,
1791                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1792                        "-:-");
1793
1794        if (pqi_is_logical_device(device))
1795                count += scnprintf(buffer + count,
1796                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1797                        " %08x%08x",
1798                        *((u32 *)&device->scsi3addr),
1799                        *((u32 *)&device->scsi3addr[4]));
1800        else
1801                count += scnprintf(buffer + count,
1802                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1803                        " %016llx", device->sas_address);
1804
1805        count += scnprintf(buffer + count, PQI_DEV_INFO_BUFFER_LENGTH - count,
1806                " %s %.8s %.16s ",
1807                pqi_device_type(device),
1808                device->vendor,
1809                device->model);
1810
1811        if (pqi_is_logical_device(device)) {
1812                if (device->devtype == TYPE_DISK)
1813                        count += scnprintf(buffer + count,
1814                                PQI_DEV_INFO_BUFFER_LENGTH - count,
1815                                "SSDSmartPathCap%c En%c %-12s",
1816                                device->raid_bypass_configured ? '+' : '-',
1817                                device->raid_bypass_enabled ? '+' : '-',
1818                                pqi_raid_level_to_string(device->raid_level));
1819        } else {
1820                count += scnprintf(buffer + count,
1821                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1822                        "AIO%c", device->aio_enabled ? '+' : '-');
1823                if (device->devtype == TYPE_DISK ||
1824                        device->devtype == TYPE_ZBC)
1825                        count += scnprintf(buffer + count,
1826                                PQI_DEV_INFO_BUFFER_LENGTH - count,
1827                                " qd=%-6d", device->queue_depth);
1828        }
1829
1830        dev_info(&ctrl_info->pci_dev->dev, "%s %s\n", action, buffer);
1831}
1832
1833/* Assumes the SCSI device list lock is held. */
1834
1835static void pqi_scsi_update_device(struct pqi_scsi_dev *existing_device,
1836        struct pqi_scsi_dev *new_device)
1837{
1838        existing_device->device_type = new_device->device_type;
1839        existing_device->bus = new_device->bus;
1840        if (new_device->target_lun_valid) {
1841                existing_device->target = new_device->target;
1842                existing_device->lun = new_device->lun;
1843                existing_device->target_lun_valid = true;
1844        }
1845
1846        if ((existing_device->volume_status == CISS_LV_QUEUED_FOR_EXPANSION ||
1847                existing_device->volume_status == CISS_LV_UNDERGOING_EXPANSION) &&
1848                new_device->volume_status == CISS_LV_OK)
1849                existing_device->rescan = true;
1850
1851        /* By definition, the scsi3addr and wwid fields are already the same. */
1852
1853        existing_device->is_physical_device = new_device->is_physical_device;
1854        existing_device->is_external_raid_device =
1855                new_device->is_external_raid_device;
1856        existing_device->is_expander_smp_device =
1857                new_device->is_expander_smp_device;
1858        existing_device->aio_enabled = new_device->aio_enabled;
1859        memcpy(existing_device->vendor, new_device->vendor,
1860                sizeof(existing_device->vendor));
1861        memcpy(existing_device->model, new_device->model,
1862                sizeof(existing_device->model));
1863        existing_device->sas_address = new_device->sas_address;
1864        existing_device->raid_level = new_device->raid_level;
1865        existing_device->queue_depth = new_device->queue_depth;
1866        existing_device->aio_handle = new_device->aio_handle;
1867        existing_device->volume_status = new_device->volume_status;
1868        existing_device->active_path_index = new_device->active_path_index;
1869        existing_device->phy_id = new_device->phy_id;
1870        existing_device->path_map = new_device->path_map;
1871        existing_device->bay = new_device->bay;
1872        existing_device->box_index = new_device->box_index;
1873        existing_device->phys_box_on_bus = new_device->phys_box_on_bus;
1874        existing_device->phy_connected_dev_type = new_device->phy_connected_dev_type;
1875        memcpy(existing_device->box, new_device->box,
1876                sizeof(existing_device->box));
1877        memcpy(existing_device->phys_connector, new_device->phys_connector,
1878                sizeof(existing_device->phys_connector));
1879        existing_device->next_bypass_group = 0;
1880        kfree(existing_device->raid_map);
1881        existing_device->raid_map = new_device->raid_map;
1882        existing_device->raid_bypass_configured =
1883                new_device->raid_bypass_configured;
1884        existing_device->raid_bypass_enabled =
1885                new_device->raid_bypass_enabled;
1886        existing_device->device_offline = false;
1887
1888        /* To prevent this from being freed later. */
1889        new_device->raid_map = NULL;
1890}
1891
1892static inline void pqi_free_device(struct pqi_scsi_dev *device)
1893{
1894        if (device) {
1895                kfree(device->raid_map);
1896                kfree(device);
1897        }
1898}
1899
1900/*
1901 * Called when exposing a new device to the OS fails in order to re-adjust
1902 * our internal SCSI device list to match the SCSI ML's view.
1903 */
1904
1905static inline void pqi_fixup_botched_add(struct pqi_ctrl_info *ctrl_info,
1906        struct pqi_scsi_dev *device)
1907{
1908        unsigned long flags;
1909
1910        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1911        list_del(&device->scsi_device_list_entry);
1912        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1913
1914        /* Allow the device structure to be freed later. */
1915        device->keep_device = false;
1916}
1917
1918static inline bool pqi_is_device_added(struct pqi_scsi_dev *device)
1919{
1920        if (device->is_expander_smp_device)
1921                return device->sas_port != NULL;
1922
1923        return device->sdev != NULL;
1924}
1925
1926static void pqi_update_device_list(struct pqi_ctrl_info *ctrl_info,
1927        struct pqi_scsi_dev *new_device_list[], unsigned int num_new_devices)
1928{
1929        int rc;
1930        unsigned int i;
1931        unsigned long flags;
1932        enum pqi_find_result find_result;
1933        struct pqi_scsi_dev *device;
1934        struct pqi_scsi_dev *next;
1935        struct pqi_scsi_dev *matching_device;
1936        LIST_HEAD(add_list);
1937        LIST_HEAD(delete_list);
1938
1939        /*
1940         * The idea here is to do as little work as possible while holding the
1941         * spinlock.  That's why we go to great pains to defer anything other
1942         * than updating the internal device list until after we release the
1943         * spinlock.
1944         */
1945
1946        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1947
1948        /* Assume that all devices in the existing list have gone away. */
1949        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1950                device->device_gone = true;
1951
1952        for (i = 0; i < num_new_devices; i++) {
1953                device = new_device_list[i];
1954
1955                find_result = pqi_scsi_find_entry(ctrl_info, device,
1956                        &matching_device);
1957
1958                switch (find_result) {
1959                case DEVICE_SAME:
1960                        /*
1961                         * The newly found device is already in the existing
1962                         * device list.
1963                         */
1964                        device->new_device = false;
1965                        matching_device->device_gone = false;
1966                        pqi_scsi_update_device(matching_device, device);
1967                        break;
1968                case DEVICE_NOT_FOUND:
1969                        /*
1970                         * The newly found device is NOT in the existing device
1971                         * list.
1972                         */
1973                        device->new_device = true;
1974                        break;
1975                case DEVICE_CHANGED:
1976                        /*
1977                         * The original device has gone away and we need to add
1978                         * the new device.
1979                         */
1980                        device->new_device = true;
1981                        break;
1982                }
1983        }
1984
1985        /* Process all devices that have gone away. */
1986        list_for_each_entry_safe(device, next, &ctrl_info->scsi_device_list,
1987                scsi_device_list_entry) {
1988                if (device->device_gone) {
1989                        list_del_init(&device->scsi_device_list_entry);
1990                        list_add_tail(&device->delete_list_entry, &delete_list);
1991                }
1992        }
1993
1994        /* Process all new devices. */
1995        for (i = 0; i < num_new_devices; i++) {
1996                device = new_device_list[i];
1997                if (!device->new_device)
1998                        continue;
1999                if (device->volume_offline)
2000                        continue;
2001                list_add_tail(&device->scsi_device_list_entry,
2002                        &ctrl_info->scsi_device_list);
2003                list_add_tail(&device->add_list_entry, &add_list);
2004                /* To prevent this device structure from being freed later. */
2005                device->keep_device = true;
2006        }
2007
2008        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
2009
2010        /*
2011         * If OFA is in progress and there are devices that need to be deleted,
2012         * allow any pending reset operations to continue and unblock any SCSI
2013         * requests before removal.
2014         */
2015        if (pqi_ofa_in_progress(ctrl_info)) {
2016                list_for_each_entry_safe(device, next, &delete_list, delete_list_entry)
2017                        if (pqi_is_device_added(device))
2018                                pqi_device_remove_start(device);
2019                pqi_ctrl_unblock_device_reset(ctrl_info);
2020                pqi_scsi_unblock_requests(ctrl_info);
2021        }
2022
2023        /* Remove all devices that have gone away. */
2024        list_for_each_entry_safe(device, next, &delete_list, delete_list_entry) {
2025                if (device->volume_offline) {
2026                        pqi_dev_info(ctrl_info, "offline", device);
2027                        pqi_show_volume_status(ctrl_info, device);
2028                }
2029                list_del(&device->delete_list_entry);
2030                if (pqi_is_device_added(device)) {
2031                        pqi_remove_device(ctrl_info, device);
2032                } else {
2033                        if (!device->volume_offline)
2034                                pqi_dev_info(ctrl_info, "removed", device);
2035                        pqi_free_device(device);
2036                }
2037        }
2038
2039        /*
2040         * Notify the SCSI ML if the queue depth of any existing device has
2041         * changed.
2042         */
2043        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
2044                if (device->sdev && device->queue_depth != device->advertised_queue_depth) {
2045                        device->advertised_queue_depth = device->queue_depth;
2046                        scsi_change_queue_depth(device->sdev, device->advertised_queue_depth);
2047                        if (device->rescan) {
2048                                scsi_rescan_device(&device->sdev->sdev_gendev);
2049                                device->rescan = false;
2050                        }
2051                }
2052        }
2053
2054        /* Expose any new devices. */
2055        list_for_each_entry_safe(device, next, &add_list, add_list_entry) {
2056                if (!pqi_is_device_added(device)) {
2057                        rc = pqi_add_device(ctrl_info, device);
2058                        if (rc == 0) {
2059                                pqi_dev_info(ctrl_info, "added", device);
2060                        } else {
2061                                dev_warn(&ctrl_info->pci_dev->dev,
2062                                        "scsi %d:%d:%d:%d addition failed, device not added\n",
2063                                        ctrl_info->scsi_host->host_no,
2064                                        device->bus, device->target,
2065                                        device->lun);
2066                                pqi_fixup_botched_add(ctrl_info, device);
2067                        }
2068                }
2069        }
2070}
2071
2072static inline bool pqi_is_supported_device(struct pqi_scsi_dev *device)
2073{
2074        /*
2075         * Only support the HBA controller itself as a RAID
2076         * controller.  If it's a RAID controller other than
2077         * the HBA itself (an external RAID controller, for
2078         * example), we don't support it.
2079         */
2080        if (device->device_type == SA_DEVICE_TYPE_CONTROLLER &&
2081                !pqi_is_hba_lunid(device->scsi3addr))
2082                        return false;
2083
2084        return true;
2085}
2086
2087static inline bool pqi_skip_device(u8 *scsi3addr)
2088{
2089        /* Ignore all masked devices. */
2090        if (MASKED_DEVICE(scsi3addr))
2091                return true;
2092
2093        return false;
2094}
2095
2096static inline void pqi_mask_device(u8 *scsi3addr)
2097{
2098        scsi3addr[3] |= 0xc0;
2099}
2100
2101static inline bool pqi_is_device_with_sas_address(struct pqi_scsi_dev *device)
2102{
2103        switch (device->device_type) {
2104        case SA_DEVICE_TYPE_SAS:
2105        case SA_DEVICE_TYPE_EXPANDER_SMP:
2106        case SA_DEVICE_TYPE_SES:
2107                return true;
2108        }
2109
2110        return false;
2111}
2112
2113static inline bool pqi_expose_device(struct pqi_scsi_dev *device)
2114{
2115        return !device->is_physical_device || !pqi_skip_device(device->scsi3addr);
2116}
2117
2118static inline void pqi_set_physical_device_wwid(struct pqi_ctrl_info *ctrl_info,
2119        struct pqi_scsi_dev *device, struct report_phys_lun_extended_entry *phys_lun_ext_entry)
2120{
2121        if (ctrl_info->unique_wwid_in_report_phys_lun_supported ||
2122                pqi_is_device_with_sas_address(device))
2123                device->wwid = phys_lun_ext_entry->wwid;
2124        else
2125                device->wwid = cpu_to_be64(get_unaligned_be64(&device->page_83_identifier));
2126}
2127
2128static int pqi_update_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2129{
2130        int i;
2131        int rc;
2132        LIST_HEAD(new_device_list_head);
2133        struct report_phys_lun_extended *physdev_list = NULL;
2134        struct report_log_lun_extended *logdev_list = NULL;
2135        struct report_phys_lun_extended_entry *phys_lun_ext_entry;
2136        struct report_log_lun_extended_entry *log_lun_ext_entry;
2137        struct bmic_identify_physical_device *id_phys = NULL;
2138        u32 num_physicals;
2139        u32 num_logicals;
2140        struct pqi_scsi_dev **new_device_list = NULL;
2141        struct pqi_scsi_dev *device;
2142        struct pqi_scsi_dev *next;
2143        unsigned int num_new_devices;
2144        unsigned int num_valid_devices;
2145        bool is_physical_device;
2146        u8 *scsi3addr;
2147        unsigned int physical_index;
2148        unsigned int logical_index;
2149        static char *out_of_memory_msg =
2150                "failed to allocate memory, device discovery stopped";
2151
2152        rc = pqi_get_device_lists(ctrl_info, &physdev_list, &logdev_list);
2153        if (rc)
2154                goto out;
2155
2156        if (physdev_list)
2157                num_physicals =
2158                        get_unaligned_be32(&physdev_list->header.list_length)
2159                                / sizeof(physdev_list->lun_entries[0]);
2160        else
2161                num_physicals = 0;
2162
2163        if (logdev_list)
2164                num_logicals =
2165                        get_unaligned_be32(&logdev_list->header.list_length)
2166                                / sizeof(logdev_list->lun_entries[0]);
2167        else
2168                num_logicals = 0;
2169
2170        if (num_physicals) {
2171                /*
2172                 * We need this buffer for calls to pqi_get_physical_disk_info()
2173                 * below.  We allocate it here instead of inside
2174                 * pqi_get_physical_disk_info() because it's a fairly large
2175                 * buffer.
2176                 */
2177                id_phys = kmalloc(sizeof(*id_phys), GFP_KERNEL);
2178                if (!id_phys) {
2179                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2180                                out_of_memory_msg);
2181                        rc = -ENOMEM;
2182                        goto out;
2183                }
2184
2185                if (pqi_hide_vsep) {
2186                        for (i = num_physicals - 1; i >= 0; i--) {
2187                                phys_lun_ext_entry =
2188                                                &physdev_list->lun_entries[i];
2189                                if (CISS_GET_DRIVE_NUMBER(phys_lun_ext_entry->lunid) == PQI_VSEP_CISS_BTL) {
2190                                        pqi_mask_device(phys_lun_ext_entry->lunid);
2191                                        break;
2192                                }
2193                        }
2194                }
2195        }
2196
2197        if (num_logicals &&
2198                (logdev_list->header.flags & CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX))
2199                ctrl_info->lv_drive_type_mix_valid = true;
2200
2201        num_new_devices = num_physicals + num_logicals;
2202
2203        new_device_list = kmalloc_array(num_new_devices,
2204                                        sizeof(*new_device_list),
2205                                        GFP_KERNEL);
2206        if (!new_device_list) {
2207                dev_warn(&ctrl_info->pci_dev->dev, "%s\n", out_of_memory_msg);
2208                rc = -ENOMEM;
2209                goto out;
2210        }
2211
2212        for (i = 0; i < num_new_devices; i++) {
2213                device = kzalloc(sizeof(*device), GFP_KERNEL);
2214                if (!device) {
2215                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2216                                out_of_memory_msg);
2217                        rc = -ENOMEM;
2218                        goto out;
2219                }
2220                list_add_tail(&device->new_device_list_entry,
2221                        &new_device_list_head);
2222        }
2223
2224        device = NULL;
2225        num_valid_devices = 0;
2226        physical_index = 0;
2227        logical_index = 0;
2228
2229        for (i = 0; i < num_new_devices; i++) {
2230
2231                if ((!pqi_expose_ld_first && i < num_physicals) ||
2232                        (pqi_expose_ld_first && i >= num_logicals)) {
2233                        is_physical_device = true;
2234                        phys_lun_ext_entry =
2235                                &physdev_list->lun_entries[physical_index++];
2236                        log_lun_ext_entry = NULL;
2237                        scsi3addr = phys_lun_ext_entry->lunid;
2238                } else {
2239                        is_physical_device = false;
2240                        phys_lun_ext_entry = NULL;
2241                        log_lun_ext_entry =
2242                                &logdev_list->lun_entries[logical_index++];
2243                        scsi3addr = log_lun_ext_entry->lunid;
2244                }
2245
2246                if (is_physical_device && pqi_skip_device(scsi3addr))
2247                        continue;
2248
2249                if (device)
2250                        device = list_next_entry(device, new_device_list_entry);
2251                else
2252                        device = list_first_entry(&new_device_list_head,
2253                                struct pqi_scsi_dev, new_device_list_entry);
2254
2255                memcpy(device->scsi3addr, scsi3addr, sizeof(device->scsi3addr));
2256                device->is_physical_device = is_physical_device;
2257                if (is_physical_device) {
2258                        device->device_type = phys_lun_ext_entry->device_type;
2259                        if (device->device_type == SA_DEVICE_TYPE_EXPANDER_SMP)
2260                                device->is_expander_smp_device = true;
2261                } else {
2262                        device->is_external_raid_device =
2263                                pqi_is_external_raid_addr(scsi3addr);
2264                }
2265
2266                if (!pqi_is_supported_device(device))
2267                        continue;
2268
2269                /* Gather information about the device. */
2270                rc = pqi_get_device_info(ctrl_info, device, id_phys);
2271                if (rc == -ENOMEM) {
2272                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2273                                out_of_memory_msg);
2274                        goto out;
2275                }
2276                if (rc) {
2277                        if (device->is_physical_device)
2278                                dev_warn(&ctrl_info->pci_dev->dev,
2279                                        "obtaining device info failed, skipping physical device %016llx\n",
2280                                        get_unaligned_be64(&phys_lun_ext_entry->wwid));
2281                        else
2282                                dev_warn(&ctrl_info->pci_dev->dev,
2283                                        "obtaining device info failed, skipping logical device %08x%08x\n",
2284                                        *((u32 *)&device->scsi3addr),
2285                                        *((u32 *)&device->scsi3addr[4]));
2286                        rc = 0;
2287                        continue;
2288                }
2289
2290                pqi_assign_bus_target_lun(device);
2291
2292                if (device->is_physical_device) {
2293                        pqi_set_physical_device_wwid(ctrl_info, device, phys_lun_ext_entry);
2294                        if ((phys_lun_ext_entry->device_flags &
2295                                CISS_REPORT_PHYS_DEV_FLAG_AIO_ENABLED) &&
2296                                phys_lun_ext_entry->aio_handle) {
2297                                        device->aio_enabled = true;
2298                                        device->aio_handle =
2299                                                phys_lun_ext_entry->aio_handle;
2300                        }
2301                } else {
2302                        memcpy(device->volume_id, log_lun_ext_entry->volume_id,
2303                                sizeof(device->volume_id));
2304                }
2305
2306                if (pqi_is_device_with_sas_address(device))
2307                        device->sas_address = get_unaligned_be64(&device->wwid);
2308
2309                new_device_list[num_valid_devices++] = device;
2310        }
2311
2312        pqi_update_device_list(ctrl_info, new_device_list, num_valid_devices);
2313
2314out:
2315        list_for_each_entry_safe(device, next, &new_device_list_head,
2316                new_device_list_entry) {
2317                if (device->keep_device)
2318                        continue;
2319                list_del(&device->new_device_list_entry);
2320                pqi_free_device(device);
2321        }
2322
2323        kfree(new_device_list);
2324        kfree(physdev_list);
2325        kfree(logdev_list);
2326        kfree(id_phys);
2327
2328        return rc;
2329}
2330
2331static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2332{
2333        int rc;
2334        int mutex_acquired;
2335
2336        if (pqi_ctrl_offline(ctrl_info))
2337                return -ENXIO;
2338
2339        mutex_acquired = mutex_trylock(&ctrl_info->scan_mutex);
2340
2341        if (!mutex_acquired) {
2342                if (pqi_ctrl_scan_blocked(ctrl_info))
2343                        return -EBUSY;
2344                pqi_schedule_rescan_worker_delayed(ctrl_info);
2345                return -EINPROGRESS;
2346        }
2347
2348        rc = pqi_update_scsi_devices(ctrl_info);
2349        if (rc && !pqi_ctrl_scan_blocked(ctrl_info))
2350                pqi_schedule_rescan_worker_delayed(ctrl_info);
2351
2352        mutex_unlock(&ctrl_info->scan_mutex);
2353
2354        return rc;
2355}
2356
2357static void pqi_scan_start(struct Scsi_Host *shost)
2358{
2359        struct pqi_ctrl_info *ctrl_info;
2360
2361        ctrl_info = shost_to_hba(shost);
2362
2363        pqi_scan_scsi_devices(ctrl_info);
2364}
2365
2366/* Returns TRUE if scan is finished. */
2367
2368static int pqi_scan_finished(struct Scsi_Host *shost,
2369        unsigned long elapsed_time)
2370{
2371        struct pqi_ctrl_info *ctrl_info;
2372
2373        ctrl_info = shost_priv(shost);
2374
2375        return !mutex_is_locked(&ctrl_info->scan_mutex);
2376}
2377
2378static inline void pqi_set_encryption_info(struct pqi_encryption_info *encryption_info,
2379        struct raid_map *raid_map, u64 first_block)
2380{
2381        u32 volume_blk_size;
2382
2383        /*
2384         * Set the encryption tweak values based on logical block address.
2385         * If the block size is 512, the tweak value is equal to the LBA.
2386         * For other block sizes, tweak value is (LBA * block size) / 512.
2387         */
2388        volume_blk_size = get_unaligned_le32(&raid_map->volume_blk_size);
2389        if (volume_blk_size != 512)
2390                first_block = (first_block * volume_blk_size) / 512;
2391
2392        encryption_info->data_encryption_key_index =
2393                get_unaligned_le16(&raid_map->data_encryption_key_index);
2394        encryption_info->encrypt_tweak_lower = lower_32_bits(first_block);
2395        encryption_info->encrypt_tweak_upper = upper_32_bits(first_block);
2396}
2397
2398/*
2399 * Attempt to perform RAID bypass mapping for a logical volume I/O.
2400 */
2401
2402static bool pqi_aio_raid_level_supported(struct pqi_ctrl_info *ctrl_info,
2403        struct pqi_scsi_dev_raid_map_data *rmd)
2404{
2405        bool is_supported = true;
2406
2407        switch (rmd->raid_level) {
2408        case SA_RAID_0:
2409                break;
2410        case SA_RAID_1:
2411                if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2412                        rmd->data_length > ctrl_info->max_write_raid_1_10_2drive))
2413                        is_supported = false;
2414                break;
2415        case SA_RAID_TRIPLE:
2416                if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2417                        rmd->data_length > ctrl_info->max_write_raid_1_10_3drive))
2418                        is_supported = false;
2419                break;
2420        case SA_RAID_5:
2421                if (rmd->is_write && (!ctrl_info->enable_r5_writes ||
2422                        rmd->data_length > ctrl_info->max_write_raid_5_6))
2423                        is_supported = false;
2424                break;
2425        case SA_RAID_6:
2426                if (rmd->is_write && (!ctrl_info->enable_r6_writes ||
2427                        rmd->data_length > ctrl_info->max_write_raid_5_6))
2428                        is_supported = false;
2429                break;
2430        default:
2431                is_supported = false;
2432                break;
2433        }
2434
2435        return is_supported;
2436}
2437
2438#define PQI_RAID_BYPASS_INELIGIBLE      1
2439
2440static int pqi_get_aio_lba_and_block_count(struct scsi_cmnd *scmd,
2441        struct pqi_scsi_dev_raid_map_data *rmd)
2442{
2443        /* Check for valid opcode, get LBA and block count. */
2444        switch (scmd->cmnd[0]) {
2445        case WRITE_6:
2446                rmd->is_write = true;
2447                fallthrough;
2448        case READ_6:
2449                rmd->first_block = (u64)(((scmd->cmnd[1] & 0x1f) << 16) |
2450                        (scmd->cmnd[2] << 8) | scmd->cmnd[3]);
2451                rmd->block_cnt = (u32)scmd->cmnd[4];
2452                if (rmd->block_cnt == 0)
2453                        rmd->block_cnt = 256;
2454                break;
2455        case WRITE_10:
2456                rmd->is_write = true;
2457                fallthrough;
2458        case READ_10:
2459                rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2460                rmd->block_cnt = (u32)get_unaligned_be16(&scmd->cmnd[7]);
2461                break;
2462        case WRITE_12:
2463                rmd->is_write = true;
2464                fallthrough;
2465        case READ_12:
2466                rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2467                rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[6]);
2468                break;
2469        case WRITE_16:
2470                rmd->is_write = true;
2471                fallthrough;
2472        case READ_16:
2473                rmd->first_block = get_unaligned_be64(&scmd->cmnd[2]);
2474                rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[10]);
2475                break;
2476        default:
2477                /* Process via normal I/O path. */
2478                return PQI_RAID_BYPASS_INELIGIBLE;
2479        }
2480
2481        put_unaligned_le32(scsi_bufflen(scmd), &rmd->data_length);
2482
2483        return 0;
2484}
2485
2486static int pci_get_aio_common_raid_map_values(struct pqi_ctrl_info *ctrl_info,
2487        struct pqi_scsi_dev_raid_map_data *rmd, struct raid_map *raid_map)
2488{
2489#if BITS_PER_LONG == 32
2490        u64 tmpdiv;
2491#endif
2492
2493        rmd->last_block = rmd->first_block + rmd->block_cnt - 1;
2494
2495        /* Check for invalid block or wraparound. */
2496        if (rmd->last_block >=
2497                get_unaligned_le64(&raid_map->volume_blk_cnt) ||
2498                rmd->last_block < rmd->first_block)
2499                return PQI_RAID_BYPASS_INELIGIBLE;
2500
2501        rmd->data_disks_per_row =
2502                get_unaligned_le16(&raid_map->data_disks_per_row);
2503        rmd->strip_size = get_unaligned_le16(&raid_map->strip_size);
2504        rmd->layout_map_count = get_unaligned_le16(&raid_map->layout_map_count);
2505
2506        /* Calculate stripe information for the request. */
2507        rmd->blocks_per_row = rmd->data_disks_per_row * rmd->strip_size;
2508        if (rmd->blocks_per_row == 0) /* Used as a divisor in many calculations */
2509                return PQI_RAID_BYPASS_INELIGIBLE;
2510#if BITS_PER_LONG == 32
2511        tmpdiv = rmd->first_block;
2512        do_div(tmpdiv, rmd->blocks_per_row);
2513        rmd->first_row = tmpdiv;
2514        tmpdiv = rmd->last_block;
2515        do_div(tmpdiv, rmd->blocks_per_row);
2516        rmd->last_row = tmpdiv;
2517        rmd->first_row_offset = (u32)(rmd->first_block - (rmd->first_row * rmd->blocks_per_row));
2518        rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row * rmd->blocks_per_row));
2519        tmpdiv = rmd->first_row_offset;
2520        do_div(tmpdiv, rmd->strip_size);
2521        rmd->first_column = tmpdiv;
2522        tmpdiv = rmd->last_row_offset;
2523        do_div(tmpdiv, rmd->strip_size);
2524        rmd->last_column = tmpdiv;
2525#else
2526        rmd->first_row = rmd->first_block / rmd->blocks_per_row;
2527        rmd->last_row = rmd->last_block / rmd->blocks_per_row;
2528        rmd->first_row_offset = (u32)(rmd->first_block -
2529                (rmd->first_row * rmd->blocks_per_row));
2530        rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row *
2531                rmd->blocks_per_row));
2532        rmd->first_column = rmd->first_row_offset / rmd->strip_size;
2533        rmd->last_column = rmd->last_row_offset / rmd->strip_size;
2534#endif
2535
2536        /* If this isn't a single row/column then give to the controller. */
2537        if (rmd->first_row != rmd->last_row ||
2538                rmd->first_column != rmd->last_column)
2539                return PQI_RAID_BYPASS_INELIGIBLE;
2540
2541        /* Proceeding with driver mapping. */
2542        rmd->total_disks_per_row = rmd->data_disks_per_row +
2543                get_unaligned_le16(&raid_map->metadata_disks_per_row);
2544        rmd->map_row = ((u32)(rmd->first_row >>
2545                raid_map->parity_rotation_shift)) %
2546                get_unaligned_le16(&raid_map->row_cnt);
2547        rmd->map_index = (rmd->map_row * rmd->total_disks_per_row) +
2548                rmd->first_column;
2549
2550        return 0;
2551}
2552
2553static int pqi_calc_aio_r5_or_r6(struct pqi_scsi_dev_raid_map_data *rmd,
2554        struct raid_map *raid_map)
2555{
2556#if BITS_PER_LONG == 32
2557        u64 tmpdiv;
2558#endif
2559
2560        if (rmd->blocks_per_row == 0) /* Used as a divisor in many calculations */
2561                return PQI_RAID_BYPASS_INELIGIBLE;
2562
2563        /* RAID 50/60 */
2564        /* Verify first and last block are in same RAID group. */
2565        rmd->stripesize = rmd->blocks_per_row * rmd->layout_map_count;
2566#if BITS_PER_LONG == 32
2567        tmpdiv = rmd->first_block;
2568        rmd->first_group = do_div(tmpdiv, rmd->stripesize);
2569        tmpdiv = rmd->first_group;
2570        do_div(tmpdiv, rmd->blocks_per_row);
2571        rmd->first_group = tmpdiv;
2572        tmpdiv = rmd->last_block;
2573        rmd->last_group = do_div(tmpdiv, rmd->stripesize);
2574        tmpdiv = rmd->last_group;
2575        do_div(tmpdiv, rmd->blocks_per_row);
2576        rmd->last_group = tmpdiv;
2577#else
2578        rmd->first_group = (rmd->first_block % rmd->stripesize) / rmd->blocks_per_row;
2579        rmd->last_group = (rmd->last_block % rmd->stripesize) / rmd->blocks_per_row;
2580#endif
2581        if (rmd->first_group != rmd->last_group)
2582                return PQI_RAID_BYPASS_INELIGIBLE;
2583
2584        /* Verify request is in a single row of RAID 5/6. */
2585#if BITS_PER_LONG == 32
2586        tmpdiv = rmd->first_block;
2587        do_div(tmpdiv, rmd->stripesize);
2588        rmd->first_row = tmpdiv;
2589        rmd->r5or6_first_row = tmpdiv;
2590        tmpdiv = rmd->last_block;
2591        do_div(tmpdiv, rmd->stripesize);
2592        rmd->r5or6_last_row = tmpdiv;
2593#else
2594        rmd->first_row = rmd->r5or6_first_row =
2595                rmd->first_block / rmd->stripesize;
2596        rmd->r5or6_last_row = rmd->last_block / rmd->stripesize;
2597#endif
2598        if (rmd->r5or6_first_row != rmd->r5or6_last_row)
2599                return PQI_RAID_BYPASS_INELIGIBLE;
2600
2601        /* Verify request is in a single column. */
2602#if BITS_PER_LONG == 32
2603        tmpdiv = rmd->first_block;
2604        rmd->first_row_offset = do_div(tmpdiv, rmd->stripesize);
2605        tmpdiv = rmd->first_row_offset;
2606        rmd->first_row_offset = (u32)do_div(tmpdiv, rmd->blocks_per_row);
2607        rmd->r5or6_first_row_offset = rmd->first_row_offset;
2608        tmpdiv = rmd->last_block;
2609        rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->stripesize);
2610        tmpdiv = rmd->r5or6_last_row_offset;
2611        rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->blocks_per_row);
2612        tmpdiv = rmd->r5or6_first_row_offset;
2613        do_div(tmpdiv, rmd->strip_size);
2614        rmd->first_column = rmd->r5or6_first_column = tmpdiv;
2615        tmpdiv = rmd->r5or6_last_row_offset;
2616        do_div(tmpdiv, rmd->strip_size);
2617        rmd->r5or6_last_column = tmpdiv;
2618#else
2619        rmd->first_row_offset = rmd->r5or6_first_row_offset =
2620                (u32)((rmd->first_block % rmd->stripesize) %
2621                rmd->blocks_per_row);
2622
2623        rmd->r5or6_last_row_offset =
2624                (u32)((rmd->last_block % rmd->stripesize) %
2625                rmd->blocks_per_row);
2626
2627        rmd->first_column =
2628                rmd->r5or6_first_row_offset / rmd->strip_size;
2629        rmd->r5or6_first_column = rmd->first_column;
2630        rmd->r5or6_last_column = rmd->r5or6_last_row_offset / rmd->strip_size;
2631#endif
2632        if (rmd->r5or6_first_column != rmd->r5or6_last_column)
2633                return PQI_RAID_BYPASS_INELIGIBLE;
2634
2635        /* Request is eligible. */
2636        rmd->map_row =
2637                ((u32)(rmd->first_row >> raid_map->parity_rotation_shift)) %
2638                get_unaligned_le16(&raid_map->row_cnt);
2639
2640        rmd->map_index = (rmd->first_group *
2641                (get_unaligned_le16(&raid_map->row_cnt) *
2642                rmd->total_disks_per_row)) +
2643                (rmd->map_row * rmd->total_disks_per_row) + rmd->first_column;
2644
2645        if (rmd->is_write) {
2646                u32 index;
2647
2648                /*
2649                 * p_parity_it_nexus and q_parity_it_nexus are pointers to the
2650                 * parity entries inside the device's raid_map.
2651                 *
2652                 * A device's RAID map is bounded by: number of RAID disks squared.
2653                 *
2654                 * The devices RAID map size is checked during device
2655                 * initialization.
2656                 */
2657                index = DIV_ROUND_UP(rmd->map_index + 1, rmd->total_disks_per_row);
2658                index *= rmd->total_disks_per_row;
2659                index -= get_unaligned_le16(&raid_map->metadata_disks_per_row);
2660
2661                rmd->p_parity_it_nexus = raid_map->disk_data[index].aio_handle;
2662                if (rmd->raid_level == SA_RAID_6) {
2663                        rmd->q_parity_it_nexus = raid_map->disk_data[index + 1].aio_handle;
2664                        rmd->xor_mult = raid_map->disk_data[rmd->map_index].xor_mult[1];
2665                }
2666#if BITS_PER_LONG == 32
2667                tmpdiv = rmd->first_block;
2668                do_div(tmpdiv, rmd->blocks_per_row);
2669                rmd->row = tmpdiv;
2670#else
2671                rmd->row = rmd->first_block / rmd->blocks_per_row;
2672#endif
2673        }
2674
2675        return 0;
2676}
2677
2678static void pqi_set_aio_cdb(struct pqi_scsi_dev_raid_map_data *rmd)
2679{
2680        /* Build the new CDB for the physical disk I/O. */
2681        if (rmd->disk_block > 0xffffffff) {
2682                rmd->cdb[0] = rmd->is_write ? WRITE_16 : READ_16;
2683                rmd->cdb[1] = 0;
2684                put_unaligned_be64(rmd->disk_block, &rmd->cdb[2]);
2685                put_unaligned_be32(rmd->disk_block_cnt, &rmd->cdb[10]);
2686                rmd->cdb[14] = 0;
2687                rmd->cdb[15] = 0;
2688                rmd->cdb_length = 16;
2689        } else {
2690                rmd->cdb[0] = rmd->is_write ? WRITE_10 : READ_10;
2691                rmd->cdb[1] = 0;
2692                put_unaligned_be32((u32)rmd->disk_block, &rmd->cdb[2]);
2693                rmd->cdb[6] = 0;
2694                put_unaligned_be16((u16)rmd->disk_block_cnt, &rmd->cdb[7]);
2695                rmd->cdb[9] = 0;
2696                rmd->cdb_length = 10;
2697        }
2698}
2699
2700static void pqi_calc_aio_r1_nexus(struct raid_map *raid_map,
2701        struct pqi_scsi_dev_raid_map_data *rmd)
2702{
2703        u32 index;
2704        u32 group;
2705
2706        group = rmd->map_index / rmd->data_disks_per_row;
2707
2708        index = rmd->map_index - (group * rmd->data_disks_per_row);
2709        rmd->it_nexus[0] = raid_map->disk_data[index].aio_handle;
2710        index += rmd->data_disks_per_row;
2711        rmd->it_nexus[1] = raid_map->disk_data[index].aio_handle;
2712        if (rmd->layout_map_count > 2) {
2713                index += rmd->data_disks_per_row;
2714                rmd->it_nexus[2] = raid_map->disk_data[index].aio_handle;
2715        }
2716
2717        rmd->num_it_nexus_entries = rmd->layout_map_count;
2718}
2719
2720static int pqi_raid_bypass_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
2721        struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
2722        struct pqi_queue_group *queue_group)
2723{
2724        int rc;
2725        struct raid_map *raid_map;
2726        u32 group;
2727        u32 next_bypass_group;
2728        struct pqi_encryption_info *encryption_info_ptr;
2729        struct pqi_encryption_info encryption_info;
2730        struct pqi_scsi_dev_raid_map_data rmd = { 0 };
2731
2732        rc = pqi_get_aio_lba_and_block_count(scmd, &rmd);
2733        if (rc)
2734                return PQI_RAID_BYPASS_INELIGIBLE;
2735
2736        rmd.raid_level = device->raid_level;
2737
2738        if (!pqi_aio_raid_level_supported(ctrl_info, &rmd))
2739                return PQI_RAID_BYPASS_INELIGIBLE;
2740
2741        if (unlikely(rmd.block_cnt == 0))
2742                return PQI_RAID_BYPASS_INELIGIBLE;
2743
2744        raid_map = device->raid_map;
2745
2746        rc = pci_get_aio_common_raid_map_values(ctrl_info, &rmd, raid_map);
2747        if (rc)
2748                return PQI_RAID_BYPASS_INELIGIBLE;
2749
2750        if (device->raid_level == SA_RAID_1 ||
2751                device->raid_level == SA_RAID_TRIPLE) {
2752                if (rmd.is_write) {
2753                        pqi_calc_aio_r1_nexus(raid_map, &rmd);
2754                } else {
2755                        group = device->next_bypass_group;
2756                        next_bypass_group = group + 1;
2757                        if (next_bypass_group >= rmd.layout_map_count)
2758                                next_bypass_group = 0;
2759                        device->next_bypass_group = next_bypass_group;
2760                        rmd.map_index += group * rmd.data_disks_per_row;
2761                }
2762        } else if ((device->raid_level == SA_RAID_5 ||
2763                device->raid_level == SA_RAID_6) &&
2764                (rmd.layout_map_count > 1 || rmd.is_write)) {
2765                rc = pqi_calc_aio_r5_or_r6(&rmd, raid_map);
2766                if (rc)
2767                        return PQI_RAID_BYPASS_INELIGIBLE;
2768        }
2769
2770        if (unlikely(rmd.map_index >= RAID_MAP_MAX_ENTRIES))
2771                return PQI_RAID_BYPASS_INELIGIBLE;
2772
2773        rmd.aio_handle = raid_map->disk_data[rmd.map_index].aio_handle;
2774        rmd.disk_block = get_unaligned_le64(&raid_map->disk_starting_blk) +
2775                rmd.first_row * rmd.strip_size +
2776                (rmd.first_row_offset - rmd.first_column * rmd.strip_size);
2777        rmd.disk_block_cnt = rmd.block_cnt;
2778
2779        /* Handle differing logical/physical block sizes. */
2780        if (raid_map->phys_blk_shift) {
2781                rmd.disk_block <<= raid_map->phys_blk_shift;
2782                rmd.disk_block_cnt <<= raid_map->phys_blk_shift;
2783        }
2784
2785        if (unlikely(rmd.disk_block_cnt > 0xffff))
2786                return PQI_RAID_BYPASS_INELIGIBLE;
2787
2788        pqi_set_aio_cdb(&rmd);
2789
2790        if (get_unaligned_le16(&raid_map->flags) & RAID_MAP_ENCRYPTION_ENABLED) {
2791                if (rmd.data_length > device->max_transfer_encrypted)
2792                        return PQI_RAID_BYPASS_INELIGIBLE;
2793                pqi_set_encryption_info(&encryption_info, raid_map, rmd.first_block);
2794                encryption_info_ptr = &encryption_info;
2795        } else {
2796                encryption_info_ptr = NULL;
2797        }
2798
2799        if (rmd.is_write) {
2800                switch (device->raid_level) {
2801                case SA_RAID_1:
2802                case SA_RAID_TRIPLE:
2803                        return pqi_aio_submit_r1_write_io(ctrl_info, scmd, queue_group,
2804                                encryption_info_ptr, device, &rmd);
2805                case SA_RAID_5:
2806                case SA_RAID_6:
2807                        return pqi_aio_submit_r56_write_io(ctrl_info, scmd, queue_group,
2808                                encryption_info_ptr, device, &rmd);
2809                }
2810        }
2811
2812        return pqi_aio_submit_io(ctrl_info, scmd, rmd.aio_handle,
2813                rmd.cdb, rmd.cdb_length, queue_group,
2814                encryption_info_ptr, true);
2815}
2816
2817#define PQI_STATUS_IDLE         0x0
2818
2819#define PQI_CREATE_ADMIN_QUEUE_PAIR     1
2820#define PQI_DELETE_ADMIN_QUEUE_PAIR     2
2821
2822#define PQI_DEVICE_STATE_POWER_ON_AND_RESET             0x0
2823#define PQI_DEVICE_STATE_STATUS_AVAILABLE               0x1
2824#define PQI_DEVICE_STATE_ALL_REGISTERS_READY            0x2
2825#define PQI_DEVICE_STATE_ADMIN_QUEUE_PAIR_READY         0x3
2826#define PQI_DEVICE_STATE_ERROR                          0x4
2827
2828#define PQI_MODE_READY_TIMEOUT_SECS             30
2829#define PQI_MODE_READY_POLL_INTERVAL_MSECS      1
2830
2831static int pqi_wait_for_pqi_mode_ready(struct pqi_ctrl_info *ctrl_info)
2832{
2833        struct pqi_device_registers __iomem *pqi_registers;
2834        unsigned long timeout;
2835        u64 signature;
2836        u8 status;
2837
2838        pqi_registers = ctrl_info->pqi_registers;
2839        timeout = (PQI_MODE_READY_TIMEOUT_SECS * PQI_HZ) + jiffies;
2840
2841        while (1) {
2842                signature = readq(&pqi_registers->signature);
2843                if (memcmp(&signature, PQI_DEVICE_SIGNATURE,
2844                        sizeof(signature)) == 0)
2845                        break;
2846                if (time_after(jiffies, timeout)) {
2847                        dev_err(&ctrl_info->pci_dev->dev,
2848                                "timed out waiting for PQI signature\n");
2849                        return -ETIMEDOUT;
2850                }
2851                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2852        }
2853
2854        while (1) {
2855                status = readb(&pqi_registers->function_and_status_code);
2856                if (status == PQI_STATUS_IDLE)
2857                        break;
2858                if (time_after(jiffies, timeout)) {
2859                        dev_err(&ctrl_info->pci_dev->dev,
2860                                "timed out waiting for PQI IDLE\n");
2861                        return -ETIMEDOUT;
2862                }
2863                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2864        }
2865
2866        while (1) {
2867                if (readl(&pqi_registers->device_status) ==
2868                        PQI_DEVICE_STATE_ALL_REGISTERS_READY)
2869                        break;
2870                if (time_after(jiffies, timeout)) {
2871                        dev_err(&ctrl_info->pci_dev->dev,
2872                                "timed out waiting for PQI all registers ready\n");
2873                        return -ETIMEDOUT;
2874                }
2875                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2876        }
2877
2878        return 0;
2879}
2880
2881static inline void pqi_aio_path_disabled(struct pqi_io_request *io_request)
2882{
2883        struct pqi_scsi_dev *device;
2884
2885        device = io_request->scmd->device->hostdata;
2886        device->raid_bypass_enabled = false;
2887        device->aio_enabled = false;
2888}
2889
2890static inline void pqi_take_device_offline(struct scsi_device *sdev, char *path)
2891{
2892        struct pqi_ctrl_info *ctrl_info;
2893        struct pqi_scsi_dev *device;
2894
2895        device = sdev->hostdata;
2896        if (device->device_offline)
2897                return;
2898
2899        device->device_offline = true;
2900        ctrl_info = shost_to_hba(sdev->host);
2901        pqi_schedule_rescan_worker(ctrl_info);
2902        dev_err(&ctrl_info->pci_dev->dev, "re-scanning %s scsi %d:%d:%d:%d\n",
2903                path, ctrl_info->scsi_host->host_no, device->bus,
2904                device->target, device->lun);
2905}
2906
2907static void pqi_process_raid_io_error(struct pqi_io_request *io_request)
2908{
2909        u8 scsi_status;
2910        u8 host_byte;
2911        struct scsi_cmnd *scmd;
2912        struct pqi_raid_error_info *error_info;
2913        size_t sense_data_length;
2914        int residual_count;
2915        int xfer_count;
2916        struct scsi_sense_hdr sshdr;
2917
2918        scmd = io_request->scmd;
2919        if (!scmd)
2920                return;
2921
2922        error_info = io_request->error_info;
2923        scsi_status = error_info->status;
2924        host_byte = DID_OK;
2925
2926        switch (error_info->data_out_result) {
2927        case PQI_DATA_IN_OUT_GOOD:
2928                break;
2929        case PQI_DATA_IN_OUT_UNDERFLOW:
2930                xfer_count =
2931                        get_unaligned_le32(&error_info->data_out_transferred);
2932                residual_count = scsi_bufflen(scmd) - xfer_count;
2933                scsi_set_resid(scmd, residual_count);
2934                if (xfer_count < scmd->underflow)
2935                        host_byte = DID_SOFT_ERROR;
2936                break;
2937        case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
2938        case PQI_DATA_IN_OUT_ABORTED:
2939                host_byte = DID_ABORT;
2940                break;
2941        case PQI_DATA_IN_OUT_TIMEOUT:
2942                host_byte = DID_TIME_OUT;
2943                break;
2944        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
2945        case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
2946        case PQI_DATA_IN_OUT_BUFFER_ERROR:
2947        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
2948        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
2949        case PQI_DATA_IN_OUT_ERROR:
2950        case PQI_DATA_IN_OUT_HARDWARE_ERROR:
2951        case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
2952        case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
2953        case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
2954        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
2955        case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
2956        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
2957        case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
2958        case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
2959        case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
2960        default:
2961                host_byte = DID_ERROR;
2962                break;
2963        }
2964
2965        sense_data_length = get_unaligned_le16(&error_info->sense_data_length);
2966        if (sense_data_length == 0)
2967                sense_data_length =
2968                        get_unaligned_le16(&error_info->response_data_length);
2969        if (sense_data_length) {
2970                if (sense_data_length > sizeof(error_info->data))
2971                        sense_data_length = sizeof(error_info->data);
2972
2973                if (scsi_status == SAM_STAT_CHECK_CONDITION &&
2974                        scsi_normalize_sense(error_info->data,
2975                                sense_data_length, &sshdr) &&
2976                                sshdr.sense_key == HARDWARE_ERROR &&
2977                                sshdr.asc == 0x3e) {
2978                        struct pqi_ctrl_info *ctrl_info = shost_to_hba(scmd->device->host);
2979                        struct pqi_scsi_dev *device = scmd->device->hostdata;
2980
2981                        switch (sshdr.ascq) {
2982                        case 0x1: /* LOGICAL UNIT FAILURE */
2983                                if (printk_ratelimit())
2984                                        scmd_printk(KERN_ERR, scmd, "received 'logical unit failure' from controller for scsi %d:%d:%d:%d\n",
2985                                                ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2986                                pqi_take_device_offline(scmd->device, "RAID");
2987                                host_byte = DID_NO_CONNECT;
2988                                break;
2989
2990                        default: /* See http://www.t10.org/lists/asc-num.htm#ASC_3E */
2991                                if (printk_ratelimit())
2992                                        scmd_printk(KERN_ERR, scmd, "received unhandled error %d from controller for scsi %d:%d:%d:%d\n",
2993                                                sshdr.ascq, ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2994                                break;
2995                        }
2996                }
2997
2998                if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
2999                        sense_data_length = SCSI_SENSE_BUFFERSIZE;
3000                memcpy(scmd->sense_buffer, error_info->data,
3001                        sense_data_length);
3002        }
3003
3004        scmd->result = scsi_status;
3005        set_host_byte(scmd, host_byte);
3006}
3007
3008static void pqi_process_aio_io_error(struct pqi_io_request *io_request)
3009{
3010        u8 scsi_status;
3011        u8 host_byte;
3012        struct scsi_cmnd *scmd;
3013        struct pqi_aio_error_info *error_info;
3014        size_t sense_data_length;
3015        int residual_count;
3016        int xfer_count;
3017        bool device_offline;
3018
3019        scmd = io_request->scmd;
3020        error_info = io_request->error_info;
3021        host_byte = DID_OK;
3022        sense_data_length = 0;
3023        device_offline = false;
3024
3025        switch (error_info->service_response) {
3026        case PQI_AIO_SERV_RESPONSE_COMPLETE:
3027                scsi_status = error_info->status;
3028                break;
3029        case PQI_AIO_SERV_RESPONSE_FAILURE:
3030                switch (error_info->status) {
3031                case PQI_AIO_STATUS_IO_ABORTED:
3032                        scsi_status = SAM_STAT_TASK_ABORTED;
3033                        break;
3034                case PQI_AIO_STATUS_UNDERRUN:
3035                        scsi_status = SAM_STAT_GOOD;
3036                        residual_count = get_unaligned_le32(
3037                                                &error_info->residual_count);
3038                        scsi_set_resid(scmd, residual_count);
3039                        xfer_count = scsi_bufflen(scmd) - residual_count;
3040                        if (xfer_count < scmd->underflow)
3041                                host_byte = DID_SOFT_ERROR;
3042                        break;
3043                case PQI_AIO_STATUS_OVERRUN:
3044                        scsi_status = SAM_STAT_GOOD;
3045                        break;
3046                case PQI_AIO_STATUS_AIO_PATH_DISABLED:
3047                        pqi_aio_path_disabled(io_request);
3048                        scsi_status = SAM_STAT_GOOD;
3049                        io_request->status = -EAGAIN;
3050                        break;
3051                case PQI_AIO_STATUS_NO_PATH_TO_DEVICE:
3052                case PQI_AIO_STATUS_INVALID_DEVICE:
3053                        if (!io_request->raid_bypass) {
3054                                device_offline = true;
3055                                pqi_take_device_offline(scmd->device, "AIO");
3056                                host_byte = DID_NO_CONNECT;
3057                        }
3058                        scsi_status = SAM_STAT_CHECK_CONDITION;
3059                        break;
3060                case PQI_AIO_STATUS_IO_ERROR:
3061                default:
3062                        scsi_status = SAM_STAT_CHECK_CONDITION;
3063                        break;
3064                }
3065                break;
3066        case PQI_AIO_SERV_RESPONSE_TMF_COMPLETE:
3067        case PQI_AIO_SERV_RESPONSE_TMF_SUCCEEDED:
3068                scsi_status = SAM_STAT_GOOD;
3069                break;
3070        case PQI_AIO_SERV_RESPONSE_TMF_REJECTED:
3071        case PQI_AIO_SERV_RESPONSE_TMF_INCORRECT_LUN:
3072        default:
3073                scsi_status = SAM_STAT_CHECK_CONDITION;
3074                break;
3075        }
3076
3077        if (error_info->data_present) {
3078                sense_data_length =
3079                        get_unaligned_le16(&error_info->data_length);
3080                if (sense_data_length) {
3081                        if (sense_data_length > sizeof(error_info->data))
3082                                sense_data_length = sizeof(error_info->data);
3083                        if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
3084                                sense_data_length = SCSI_SENSE_BUFFERSIZE;
3085                        memcpy(scmd->sense_buffer, error_info->data,
3086                                sense_data_length);
3087                }
3088        }
3089
3090        if (device_offline && sense_data_length == 0)
3091                scsi_build_sense(scmd, 0, HARDWARE_ERROR, 0x3e, 0x1);
3092
3093        scmd->result = scsi_status;
3094        set_host_byte(scmd, host_byte);
3095}
3096
3097static void pqi_process_io_error(unsigned int iu_type,
3098        struct pqi_io_request *io_request)
3099{
3100        switch (iu_type) {
3101        case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3102                pqi_process_raid_io_error(io_request);
3103                break;
3104        case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3105                pqi_process_aio_io_error(io_request);
3106                break;
3107        }
3108}
3109
3110static int pqi_interpret_task_management_response(struct pqi_ctrl_info *ctrl_info,
3111        struct pqi_task_management_response *response)
3112{
3113        int rc;
3114
3115        switch (response->response_code) {
3116        case SOP_TMF_COMPLETE:
3117        case SOP_TMF_FUNCTION_SUCCEEDED:
3118                rc = 0;
3119                break;
3120        case SOP_TMF_REJECTED:
3121                rc = -EAGAIN;
3122                break;
3123        default:
3124                rc = -EIO;
3125                break;
3126        }
3127
3128        if (rc)
3129                dev_err(&ctrl_info->pci_dev->dev,
3130                        "Task Management Function error: %d (response code: %u)\n", rc, response->response_code);
3131
3132        return rc;
3133}
3134
3135static inline void pqi_invalid_response(struct pqi_ctrl_info *ctrl_info)
3136{
3137        pqi_take_ctrl_offline(ctrl_info);
3138}
3139
3140static int pqi_process_io_intr(struct pqi_ctrl_info *ctrl_info, struct pqi_queue_group *queue_group)
3141{
3142        int num_responses;
3143        pqi_index_t oq_pi;
3144        pqi_index_t oq_ci;
3145        struct pqi_io_request *io_request;
3146        struct pqi_io_response *response;
3147        u16 request_id;
3148
3149        num_responses = 0;
3150        oq_ci = queue_group->oq_ci_copy;
3151
3152        while (1) {
3153                oq_pi = readl(queue_group->oq_pi);
3154                if (oq_pi >= ctrl_info->num_elements_per_oq) {
3155                        pqi_invalid_response(ctrl_info);
3156                        dev_err(&ctrl_info->pci_dev->dev,
3157                                "I/O interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3158                                oq_pi, ctrl_info->num_elements_per_oq - 1, oq_ci);
3159                        return -1;
3160                }
3161                if (oq_pi == oq_ci)
3162                        break;
3163
3164                num_responses++;
3165                response = queue_group->oq_element_array +
3166                        (oq_ci * PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
3167
3168                request_id = get_unaligned_le16(&response->request_id);
3169                if (request_id >= ctrl_info->max_io_slots) {
3170                        pqi_invalid_response(ctrl_info);
3171                        dev_err(&ctrl_info->pci_dev->dev,
3172                                "request ID in response (%u) out of range (0-%u): producer index: %u  consumer index: %u\n",
3173                                request_id, ctrl_info->max_io_slots - 1, oq_pi, oq_ci);
3174                        return -1;
3175                }
3176
3177                io_request = &ctrl_info->io_request_pool[request_id];
3178                if (atomic_read(&io_request->refcount) == 0) {
3179                        pqi_invalid_response(ctrl_info);
3180                        dev_err(&ctrl_info->pci_dev->dev,
3181                                "request ID in response (%u) does not match an outstanding I/O request: producer index: %u  consumer index: %u\n",
3182                                request_id, oq_pi, oq_ci);
3183                        return -1;
3184                }
3185
3186                switch (response->header.iu_type) {
3187                case PQI_RESPONSE_IU_RAID_PATH_IO_SUCCESS:
3188                case PQI_RESPONSE_IU_AIO_PATH_IO_SUCCESS:
3189                        if (io_request->scmd)
3190                                io_request->scmd->result = 0;
3191                        fallthrough;
3192                case PQI_RESPONSE_IU_GENERAL_MANAGEMENT:
3193                        break;
3194                case PQI_RESPONSE_IU_VENDOR_GENERAL:
3195                        io_request->status =
3196                                get_unaligned_le16(
3197                                &((struct pqi_vendor_general_response *)response)->status);
3198                        break;
3199                case PQI_RESPONSE_IU_TASK_MANAGEMENT:
3200                        io_request->status = pqi_interpret_task_management_response(ctrl_info,
3201                                (void *)response);
3202                        break;
3203                case PQI_RESPONSE_IU_AIO_PATH_DISABLED:
3204                        pqi_aio_path_disabled(io_request);
3205                        io_request->status = -EAGAIN;
3206                        break;
3207                case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3208                case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3209                        io_request->error_info = ctrl_info->error_buffer +
3210                                (get_unaligned_le16(&response->error_index) *
3211                                PQI_ERROR_BUFFER_ELEMENT_LENGTH);
3212                        pqi_process_io_error(response->header.iu_type, io_request);
3213                        break;
3214                default:
3215                        pqi_invalid_response(ctrl_info);
3216                        dev_err(&ctrl_info->pci_dev->dev,
3217                                "unexpected IU type: 0x%x: producer index: %u  consumer index: %u\n",
3218                                response->header.iu_type, oq_pi, oq_ci);
3219                        return -1;
3220                }
3221
3222                io_request->io_complete_callback(io_request, io_request->context);
3223
3224                /*
3225                 * Note that the I/O request structure CANNOT BE TOUCHED after
3226                 * returning from the I/O completion callback!
3227                 */
3228                oq_ci = (oq_ci + 1) % ctrl_info->num_elements_per_oq;
3229        }
3230
3231        if (num_responses) {
3232                queue_group->oq_ci_copy = oq_ci;
3233                writel(oq_ci, queue_group->oq_ci);
3234        }
3235
3236        return num_responses;
3237}
3238
3239static inline unsigned int pqi_num_elements_free(unsigned int pi,
3240        unsigned int ci, unsigned int elements_in_queue)
3241{
3242        unsigned int num_elements_used;
3243
3244        if (pi >= ci)
3245                num_elements_used = pi - ci;
3246        else
3247                num_elements_used = elements_in_queue - ci + pi;
3248
3249        return elements_in_queue - num_elements_used - 1;
3250}
3251
3252static void pqi_send_event_ack(struct pqi_ctrl_info *ctrl_info,
3253        struct pqi_event_acknowledge_request *iu, size_t iu_length)
3254{
3255        pqi_index_t iq_pi;
3256        pqi_index_t iq_ci;
3257        unsigned long flags;
3258        void *next_element;
3259        struct pqi_queue_group *queue_group;
3260
3261        queue_group = &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP];
3262        put_unaligned_le16(queue_group->oq_id, &iu->header.response_queue_id);
3263
3264        while (1) {
3265                spin_lock_irqsave(&queue_group->submit_lock[RAID_PATH], flags);
3266
3267                iq_pi = queue_group->iq_pi_copy[RAID_PATH];
3268                iq_ci = readl(queue_group->iq_ci[RAID_PATH]);
3269
3270                if (pqi_num_elements_free(iq_pi, iq_ci,
3271                        ctrl_info->num_elements_per_iq))
3272                        break;
3273
3274                spin_unlock_irqrestore(
3275                        &queue_group->submit_lock[RAID_PATH], flags);
3276
3277                if (pqi_ctrl_offline(ctrl_info))
3278                        return;
3279        }
3280
3281        next_element = queue_group->iq_element_array[RAID_PATH] +
3282                (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3283
3284        memcpy(next_element, iu, iu_length);
3285
3286        iq_pi = (iq_pi + 1) % ctrl_info->num_elements_per_iq;
3287        queue_group->iq_pi_copy[RAID_PATH] = iq_pi;
3288
3289        /*
3290         * This write notifies the controller that an IU is available to be
3291         * processed.
3292         */
3293        writel(iq_pi, queue_group->iq_pi[RAID_PATH]);
3294
3295        spin_unlock_irqrestore(&queue_group->submit_lock[RAID_PATH], flags);
3296}
3297
3298static void pqi_acknowledge_event(struct pqi_ctrl_info *ctrl_info,
3299        struct pqi_event *event)
3300{
3301        struct pqi_event_acknowledge_request request;
3302
3303        memset(&request, 0, sizeof(request));
3304
3305        request.header.iu_type = PQI_REQUEST_IU_ACKNOWLEDGE_VENDOR_EVENT;
3306        put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
3307                &request.header.iu_length);
3308        request.event_type = event->event_type;
3309        put_unaligned_le16(event->event_id, &request.event_id);
3310        put_unaligned_le32(event->additional_event_id, &request.additional_event_id);
3311
3312        pqi_send_event_ack(ctrl_info, &request, sizeof(request));
3313}
3314
3315#define PQI_SOFT_RESET_STATUS_TIMEOUT_SECS              30
3316#define PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS        1
3317
3318static enum pqi_soft_reset_status pqi_poll_for_soft_reset_status(
3319        struct pqi_ctrl_info *ctrl_info)
3320{
3321        u8 status;
3322        unsigned long timeout;
3323
3324        timeout = (PQI_SOFT_RESET_STATUS_TIMEOUT_SECS * PQI_HZ) + jiffies;
3325
3326        while (1) {
3327                status = pqi_read_soft_reset_status(ctrl_info);
3328                if (status & PQI_SOFT_RESET_INITIATE)
3329                        return RESET_INITIATE_DRIVER;
3330
3331                if (status & PQI_SOFT_RESET_ABORT)
3332                        return RESET_ABORT;
3333
3334                if (!sis_is_firmware_running(ctrl_info))
3335                        return RESET_NORESPONSE;
3336
3337                if (time_after(jiffies, timeout)) {
3338                        dev_warn(&ctrl_info->pci_dev->dev,
3339                                "timed out waiting for soft reset status\n");
3340                        return RESET_TIMEDOUT;
3341                }
3342
3343                ssleep(PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS);
3344        }
3345}
3346
3347static void pqi_process_soft_reset(struct pqi_ctrl_info *ctrl_info)
3348{
3349        int rc;
3350        unsigned int delay_secs;
3351        enum pqi_soft_reset_status reset_status;
3352
3353        if (ctrl_info->soft_reset_handshake_supported)
3354                reset_status = pqi_poll_for_soft_reset_status(ctrl_info);
3355        else
3356                reset_status = RESET_INITIATE_FIRMWARE;
3357
3358        delay_secs = PQI_POST_RESET_DELAY_SECS;
3359
3360        switch (reset_status) {
3361        case RESET_TIMEDOUT:
3362                delay_secs = PQI_POST_OFA_RESET_DELAY_UPON_TIMEOUT_SECS;
3363                fallthrough;
3364        case RESET_INITIATE_DRIVER:
3365                dev_info(&ctrl_info->pci_dev->dev,
3366                                "Online Firmware Activation: resetting controller\n");
3367                sis_soft_reset(ctrl_info);
3368                fallthrough;
3369        case RESET_INITIATE_FIRMWARE:
3370                ctrl_info->pqi_mode_enabled = false;
3371                pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
3372                rc = pqi_ofa_ctrl_restart(ctrl_info, delay_secs);
3373                pqi_ofa_free_host_buffer(ctrl_info);
3374                pqi_ctrl_ofa_done(ctrl_info);
3375                dev_info(&ctrl_info->pci_dev->dev,
3376                                "Online Firmware Activation: %s\n",
3377                                rc == 0 ? "SUCCESS" : "FAILED");
3378                break;
3379        case RESET_ABORT:
3380                dev_info(&ctrl_info->pci_dev->dev,
3381                                "Online Firmware Activation ABORTED\n");
3382                if (ctrl_info->soft_reset_handshake_supported)
3383                        pqi_clear_soft_reset_status(ctrl_info);
3384                pqi_ofa_free_host_buffer(ctrl_info);
3385                pqi_ctrl_ofa_done(ctrl_info);
3386                pqi_ofa_ctrl_unquiesce(ctrl_info);
3387                break;
3388        case RESET_NORESPONSE:
3389                fallthrough;
3390        default:
3391                dev_err(&ctrl_info->pci_dev->dev,
3392                        "unexpected Online Firmware Activation reset status: 0x%x\n",
3393                        reset_status);
3394                pqi_ofa_free_host_buffer(ctrl_info);
3395                pqi_ctrl_ofa_done(ctrl_info);
3396                pqi_ofa_ctrl_unquiesce(ctrl_info);
3397                pqi_take_ctrl_offline(ctrl_info);
3398                break;
3399        }
3400}
3401
3402static void pqi_ofa_memory_alloc_worker(struct work_struct *work)
3403{
3404        struct pqi_ctrl_info *ctrl_info;
3405
3406        ctrl_info = container_of(work, struct pqi_ctrl_info, ofa_memory_alloc_work);
3407
3408        pqi_ctrl_ofa_start(ctrl_info);
3409        pqi_ofa_setup_host_buffer(ctrl_info);
3410        pqi_ofa_host_memory_update(ctrl_info);
3411}
3412
3413static void pqi_ofa_quiesce_worker(struct work_struct *work)
3414{
3415        struct pqi_ctrl_info *ctrl_info;
3416        struct pqi_event *event;
3417
3418        ctrl_info = container_of(work, struct pqi_ctrl_info, ofa_quiesce_work);
3419
3420        event = &ctrl_info->events[pqi_event_type_to_event_index(PQI_EVENT_TYPE_OFA)];
3421
3422        pqi_ofa_ctrl_quiesce(ctrl_info);
3423        pqi_acknowledge_event(ctrl_info, event);
3424        pqi_process_soft_reset(ctrl_info);
3425}
3426
3427static bool pqi_ofa_process_event(struct pqi_ctrl_info *ctrl_info,
3428        struct pqi_event *event)
3429{
3430        bool ack_event;
3431
3432        ack_event = true;
3433
3434        switch (event->event_id) {
3435        case PQI_EVENT_OFA_MEMORY_ALLOCATION:
3436                dev_info(&ctrl_info->pci_dev->dev,
3437                        "received Online Firmware Activation memory allocation request\n");
3438                schedule_work(&ctrl_info->ofa_memory_alloc_work);
3439                break;
3440        case PQI_EVENT_OFA_QUIESCE:
3441                dev_info(&ctrl_info->pci_dev->dev,
3442                        "received Online Firmware Activation quiesce request\n");
3443                schedule_work(&ctrl_info->ofa_quiesce_work);
3444                ack_event = false;
3445                break;
3446        case PQI_EVENT_OFA_CANCELED:
3447                dev_info(&ctrl_info->pci_dev->dev,
3448                        "received Online Firmware Activation cancel request: reason: %u\n",
3449                        ctrl_info->ofa_cancel_reason);
3450                pqi_ofa_free_host_buffer(ctrl_info);
3451                pqi_ctrl_ofa_done(ctrl_info);
3452                break;
3453        default:
3454                dev_err(&ctrl_info->pci_dev->dev,
3455                        "received unknown Online Firmware Activation request: event ID: %u\n",
3456                        event->event_id);
3457                break;
3458        }
3459
3460        return ack_event;
3461}
3462
3463static void pqi_event_worker(struct work_struct *work)
3464{
3465        unsigned int i;
3466        bool rescan_needed;
3467        struct pqi_ctrl_info *ctrl_info;
3468        struct pqi_event *event;
3469        bool ack_event;
3470
3471        ctrl_info = container_of(work, struct pqi_ctrl_info, event_work);
3472
3473        pqi_ctrl_busy(ctrl_info);
3474        pqi_wait_if_ctrl_blocked(ctrl_info);
3475        if (pqi_ctrl_offline(ctrl_info))
3476                goto out;
3477
3478        rescan_needed = false;
3479        event = ctrl_info->events;
3480        for (i = 0; i < PQI_NUM_SUPPORTED_EVENTS; i++) {
3481                if (event->pending) {
3482                        event->pending = false;
3483                        if (event->event_type == PQI_EVENT_TYPE_OFA) {
3484                                ack_event = pqi_ofa_process_event(ctrl_info, event);
3485                        } else {
3486                                ack_event = true;
3487                                rescan_needed = true;
3488                        }
3489                        if (ack_event)
3490                                pqi_acknowledge_event(ctrl_info, event);
3491                }
3492                event++;
3493        }
3494
3495        if (rescan_needed)
3496                pqi_schedule_rescan_worker_delayed(ctrl_info);
3497
3498out:
3499        pqi_ctrl_unbusy(ctrl_info);
3500}
3501
3502#define PQI_HEARTBEAT_TIMER_INTERVAL    (10 * PQI_HZ)
3503
3504static void pqi_heartbeat_timer_handler(struct timer_list *t)
3505{
3506        int num_interrupts;
3507        u32 heartbeat_count;
3508        struct pqi_ctrl_info *ctrl_info = from_timer(ctrl_info, t, heartbeat_timer);
3509
3510        pqi_check_ctrl_health(ctrl_info);
3511        if (pqi_ctrl_offline(ctrl_info))
3512                return;
3513
3514        num_interrupts = atomic_read(&ctrl_info->num_interrupts);
3515        heartbeat_count = pqi_read_heartbeat_counter(ctrl_info);
3516
3517        if (num_interrupts == ctrl_info->previous_num_interrupts) {
3518                if (heartbeat_count == ctrl_info->previous_heartbeat_count) {
3519                        dev_err(&ctrl_info->pci_dev->dev,
3520                                "no heartbeat detected - last heartbeat count: %u\n",
3521                                heartbeat_count);
3522                        pqi_take_ctrl_offline(ctrl_info);
3523                        return;
3524                }
3525        } else {
3526                ctrl_info->previous_num_interrupts = num_interrupts;
3527        }
3528
3529        ctrl_info->previous_heartbeat_count = heartbeat_count;
3530        mod_timer(&ctrl_info->heartbeat_timer,
3531                jiffies + PQI_HEARTBEAT_TIMER_INTERVAL);
3532}
3533
3534static void pqi_start_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3535{
3536        if (!ctrl_info->heartbeat_counter)
3537                return;
3538
3539        ctrl_info->previous_num_interrupts =
3540                atomic_read(&ctrl_info->num_interrupts);
3541        ctrl_info->previous_heartbeat_count =
3542                pqi_read_heartbeat_counter(ctrl_info);
3543
3544        ctrl_info->heartbeat_timer.expires =
3545                jiffies + PQI_HEARTBEAT_TIMER_INTERVAL;
3546        add_timer(&ctrl_info->heartbeat_timer);
3547}
3548
3549static inline void pqi_stop_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3550{
3551        del_timer_sync(&ctrl_info->heartbeat_timer);
3552}
3553
3554static void pqi_ofa_capture_event_payload(struct pqi_ctrl_info *ctrl_info,
3555        struct pqi_event *event, struct pqi_event_response *response)
3556{
3557        switch (event->event_id) {
3558        case PQI_EVENT_OFA_MEMORY_ALLOCATION:
3559                ctrl_info->ofa_bytes_requested =
3560                        get_unaligned_le32(&response->data.ofa_memory_allocation.bytes_requested);
3561                break;
3562        case PQI_EVENT_OFA_CANCELED:
3563                ctrl_info->ofa_cancel_reason =
3564                        get_unaligned_le16(&response->data.ofa_cancelled.reason);
3565                break;
3566        }
3567}
3568
3569static int pqi_process_event_intr(struct pqi_ctrl_info *ctrl_info)
3570{
3571        int num_events;
3572        pqi_index_t oq_pi;
3573        pqi_index_t oq_ci;
3574        struct pqi_event_queue *event_queue;
3575        struct pqi_event_response *response;
3576        struct pqi_event *event;
3577        int event_index;
3578
3579        event_queue = &ctrl_info->event_queue;
3580        num_events = 0;
3581        oq_ci = event_queue->oq_ci_copy;
3582
3583        while (1) {
3584                oq_pi = readl(event_queue->oq_pi);
3585                if (oq_pi >= PQI_NUM_EVENT_QUEUE_ELEMENTS) {
3586                        pqi_invalid_response(ctrl_info);
3587                        dev_err(&ctrl_info->pci_dev->dev,
3588                                "event interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3589                                oq_pi, PQI_NUM_EVENT_QUEUE_ELEMENTS - 1, oq_ci);
3590                        return -1;
3591                }
3592
3593                if (oq_pi == oq_ci)
3594                        break;
3595
3596                num_events++;
3597                response = event_queue->oq_element_array + (oq_ci * PQI_EVENT_OQ_ELEMENT_LENGTH);
3598
3599                event_index = pqi_event_type_to_event_index(response->event_type);
3600
3601                if (event_index >= 0 && response->request_acknowledge) {
3602                        event = &ctrl_info->events[event_index];
3603                        event->pending = true;
3604                        event->event_type = response->event_type;
3605                        event->event_id = get_unaligned_le16(&response->event_id);
3606                        event->additional_event_id =
3607                                get_unaligned_le32(&response->additional_event_id);
3608                        if (event->event_type == PQI_EVENT_TYPE_OFA)
3609                                pqi_ofa_capture_event_payload(ctrl_info, event, response);
3610                }
3611
3612                oq_ci = (oq_ci + 1) % PQI_NUM_EVENT_QUEUE_ELEMENTS;
3613        }
3614
3615        if (num_events) {
3616                event_queue->oq_ci_copy = oq_ci;
3617                writel(oq_ci, event_queue->oq_ci);
3618                schedule_work(&ctrl_info->event_work);
3619        }
3620
3621        return num_events;
3622}
3623
3624#define PQI_LEGACY_INTX_MASK    0x1
3625
3626static inline void pqi_configure_legacy_intx(struct pqi_ctrl_info *ctrl_info, bool enable_intx)
3627{
3628        u32 intx_mask;
3629        struct pqi_device_registers __iomem *pqi_registers;
3630        volatile void __iomem *register_addr;
3631
3632        pqi_registers = ctrl_info->pqi_registers;
3633
3634        if (enable_intx)
3635                register_addr = &pqi_registers->legacy_intx_mask_clear;
3636        else
3637                register_addr = &pqi_registers->legacy_intx_mask_set;
3638
3639        intx_mask = readl(register_addr);
3640        intx_mask |= PQI_LEGACY_INTX_MASK;
3641        writel(intx_mask, register_addr);
3642}
3643
3644static void pqi_change_irq_mode(struct pqi_ctrl_info *ctrl_info,
3645        enum pqi_irq_mode new_mode)
3646{
3647        switch (ctrl_info->irq_mode) {
3648        case IRQ_MODE_MSIX:
3649                switch (new_mode) {
3650                case IRQ_MODE_MSIX:
3651                        break;
3652                case IRQ_MODE_INTX:
3653                        pqi_configure_legacy_intx(ctrl_info, true);
3654                        sis_enable_intx(ctrl_info);
3655                        break;
3656                case IRQ_MODE_NONE:
3657                        break;
3658                }
3659                break;
3660        case IRQ_MODE_INTX:
3661                switch (new_mode) {
3662                case IRQ_MODE_MSIX:
3663                        pqi_configure_legacy_intx(ctrl_info, false);
3664                        sis_enable_msix(ctrl_info);
3665                        break;
3666                case IRQ_MODE_INTX:
3667                        break;
3668                case IRQ_MODE_NONE:
3669                        pqi_configure_legacy_intx(ctrl_info, false);
3670                        break;
3671                }
3672                break;
3673        case IRQ_MODE_NONE:
3674                switch (new_mode) {
3675                case IRQ_MODE_MSIX:
3676                        sis_enable_msix(ctrl_info);
3677                        break;
3678                case IRQ_MODE_INTX:
3679                        pqi_configure_legacy_intx(ctrl_info, true);
3680                        sis_enable_intx(ctrl_info);
3681                        break;
3682                case IRQ_MODE_NONE:
3683                        break;
3684                }
3685                break;
3686        }
3687
3688        ctrl_info->irq_mode = new_mode;
3689}
3690
3691#define PQI_LEGACY_INTX_PENDING         0x1
3692
3693static inline bool pqi_is_valid_irq(struct pqi_ctrl_info *ctrl_info)
3694{
3695        bool valid_irq;
3696        u32 intx_status;
3697
3698        switch (ctrl_info->irq_mode) {
3699        case IRQ_MODE_MSIX:
3700                valid_irq = true;
3701                break;
3702        case IRQ_MODE_INTX:
3703                intx_status = readl(&ctrl_info->pqi_registers->legacy_intx_status);
3704                if (intx_status & PQI_LEGACY_INTX_PENDING)
3705                        valid_irq = true;
3706                else
3707                        valid_irq = false;
3708                break;
3709        case IRQ_MODE_NONE:
3710        default:
3711                valid_irq = false;
3712                break;
3713        }
3714
3715        return valid_irq;
3716}
3717
3718static irqreturn_t pqi_irq_handler(int irq, void *data)
3719{
3720        struct pqi_ctrl_info *ctrl_info;
3721        struct pqi_queue_group *queue_group;
3722        int num_io_responses_handled;
3723        int num_events_handled;
3724
3725        queue_group = data;
3726        ctrl_info = queue_group->ctrl_info;
3727
3728        if (!pqi_is_valid_irq(ctrl_info))
3729                return IRQ_NONE;
3730
3731        num_io_responses_handled = pqi_process_io_intr(ctrl_info, queue_group);
3732        if (num_io_responses_handled < 0)
3733                goto out;
3734
3735        if (irq == ctrl_info->event_irq) {
3736                num_events_handled = pqi_process_event_intr(ctrl_info);
3737                if (num_events_handled < 0)
3738                        goto out;
3739        } else {
3740                num_events_handled = 0;
3741        }
3742
3743        if (num_io_responses_handled + num_events_handled > 0)
3744                atomic_inc(&ctrl_info->num_interrupts);
3745
3746        pqi_start_io(ctrl_info, queue_group, RAID_PATH, NULL);
3747        pqi_start_io(ctrl_info, queue_group, AIO_PATH, NULL);
3748
3749out:
3750        return IRQ_HANDLED;
3751}
3752
3753static int pqi_request_irqs(struct pqi_ctrl_info *ctrl_info)
3754{
3755        struct pci_dev *pci_dev = ctrl_info->pci_dev;
3756        int i;
3757        int rc;
3758
3759        ctrl_info->event_irq = pci_irq_vector(pci_dev, 0);
3760
3761        for (i = 0; i < ctrl_info->num_msix_vectors_enabled; i++) {
3762                rc = request_irq(pci_irq_vector(pci_dev, i), pqi_irq_handler, 0,
3763                        DRIVER_NAME_SHORT, &ctrl_info->queue_groups[i]);
3764                if (rc) {
3765                        dev_err(&pci_dev->dev,
3766                                "irq %u init failed with error %d\n",
3767                                pci_irq_vector(pci_dev, i), rc);
3768                        return rc;
3769                }
3770                ctrl_info->num_msix_vectors_initialized++;
3771        }
3772
3773        return 0;
3774}
3775
3776static void pqi_free_irqs(struct pqi_ctrl_info *ctrl_info)
3777{
3778        int i;
3779
3780        for (i = 0; i < ctrl_info->num_msix_vectors_initialized; i++)
3781                free_irq(pci_irq_vector(ctrl_info->pci_dev, i),
3782                        &ctrl_info->queue_groups[i]);
3783
3784        ctrl_info->num_msix_vectors_initialized = 0;
3785}
3786
3787static int pqi_enable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3788{
3789        int num_vectors_enabled;
3790
3791        num_vectors_enabled = pci_alloc_irq_vectors(ctrl_info->pci_dev,
3792                        PQI_MIN_MSIX_VECTORS, ctrl_info->num_queue_groups,
3793                        PCI_IRQ_MSIX | PCI_IRQ_AFFINITY);
3794        if (num_vectors_enabled < 0) {
3795                dev_err(&ctrl_info->pci_dev->dev,
3796                        "MSI-X init failed with error %d\n",
3797                        num_vectors_enabled);
3798                return num_vectors_enabled;
3799        }
3800
3801        ctrl_info->num_msix_vectors_enabled = num_vectors_enabled;
3802        ctrl_info->irq_mode = IRQ_MODE_MSIX;
3803        return 0;
3804}
3805
3806static void pqi_disable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3807{
3808        if (ctrl_info->num_msix_vectors_enabled) {
3809                pci_free_irq_vectors(ctrl_info->pci_dev);
3810                ctrl_info->num_msix_vectors_enabled = 0;
3811        }
3812}
3813
3814static int pqi_alloc_operational_queues(struct pqi_ctrl_info *ctrl_info)
3815{
3816        unsigned int i;
3817        size_t alloc_length;
3818        size_t element_array_length_per_iq;
3819        size_t element_array_length_per_oq;
3820        void *element_array;
3821        void __iomem *next_queue_index;
3822        void *aligned_pointer;
3823        unsigned int num_inbound_queues;
3824        unsigned int num_outbound_queues;
3825        unsigned int num_queue_indexes;
3826        struct pqi_queue_group *queue_group;
3827
3828        element_array_length_per_iq =
3829                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH *
3830                ctrl_info->num_elements_per_iq;
3831        element_array_length_per_oq =
3832                PQI_OPERATIONAL_OQ_ELEMENT_LENGTH *
3833                ctrl_info->num_elements_per_oq;
3834        num_inbound_queues = ctrl_info->num_queue_groups * 2;
3835        num_outbound_queues = ctrl_info->num_queue_groups;
3836        num_queue_indexes = (ctrl_info->num_queue_groups * 3) + 1;
3837
3838        aligned_pointer = NULL;
3839
3840        for (i = 0; i < num_inbound_queues; i++) {
3841                aligned_pointer = PTR_ALIGN(aligned_pointer,
3842                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3843                aligned_pointer += element_array_length_per_iq;
3844        }
3845
3846        for (i = 0; i < num_outbound_queues; i++) {
3847                aligned_pointer = PTR_ALIGN(aligned_pointer,
3848                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3849                aligned_pointer += element_array_length_per_oq;
3850        }
3851
3852        aligned_pointer = PTR_ALIGN(aligned_pointer,
3853                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3854        aligned_pointer += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3855                PQI_EVENT_OQ_ELEMENT_LENGTH;
3856
3857        for (i = 0; i < num_queue_indexes; i++) {
3858                aligned_pointer = PTR_ALIGN(aligned_pointer,
3859                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3860                aligned_pointer += sizeof(pqi_index_t);
3861        }
3862
3863        alloc_length = (size_t)aligned_pointer +
3864                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3865
3866        alloc_length += PQI_EXTRA_SGL_MEMORY;
3867
3868        ctrl_info->queue_memory_base =
3869                dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
3870                                   &ctrl_info->queue_memory_base_dma_handle,
3871                                   GFP_KERNEL);
3872
3873        if (!ctrl_info->queue_memory_base)
3874                return -ENOMEM;
3875
3876        ctrl_info->queue_memory_length = alloc_length;
3877
3878        element_array = PTR_ALIGN(ctrl_info->queue_memory_base,
3879                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3880
3881        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3882                queue_group = &ctrl_info->queue_groups[i];
3883                queue_group->iq_element_array[RAID_PATH] = element_array;
3884                queue_group->iq_element_array_bus_addr[RAID_PATH] =
3885                        ctrl_info->queue_memory_base_dma_handle +
3886                                (element_array - ctrl_info->queue_memory_base);
3887                element_array += element_array_length_per_iq;
3888                element_array = PTR_ALIGN(element_array,
3889                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3890                queue_group->iq_element_array[AIO_PATH] = element_array;
3891                queue_group->iq_element_array_bus_addr[AIO_PATH] =
3892                        ctrl_info->queue_memory_base_dma_handle +
3893                        (element_array - ctrl_info->queue_memory_base);
3894                element_array += element_array_length_per_iq;
3895                element_array = PTR_ALIGN(element_array,
3896                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3897        }
3898
3899        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3900                queue_group = &ctrl_info->queue_groups[i];
3901                queue_group->oq_element_array = element_array;
3902                queue_group->oq_element_array_bus_addr =
3903                        ctrl_info->queue_memory_base_dma_handle +
3904                        (element_array - ctrl_info->queue_memory_base);
3905                element_array += element_array_length_per_oq;
3906                element_array = PTR_ALIGN(element_array,
3907                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3908        }
3909
3910        ctrl_info->event_queue.oq_element_array = element_array;
3911        ctrl_info->event_queue.oq_element_array_bus_addr =
3912                ctrl_info->queue_memory_base_dma_handle +
3913                (element_array - ctrl_info->queue_memory_base);
3914        element_array += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3915                PQI_EVENT_OQ_ELEMENT_LENGTH;
3916
3917        next_queue_index = (void __iomem *)PTR_ALIGN(element_array,
3918                PQI_OPERATIONAL_INDEX_ALIGNMENT);
3919
3920        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3921                queue_group = &ctrl_info->queue_groups[i];
3922                queue_group->iq_ci[RAID_PATH] = next_queue_index;
3923                queue_group->iq_ci_bus_addr[RAID_PATH] =
3924                        ctrl_info->queue_memory_base_dma_handle +
3925                        (next_queue_index -
3926                        (void __iomem *)ctrl_info->queue_memory_base);
3927                next_queue_index += sizeof(pqi_index_t);
3928                next_queue_index = PTR_ALIGN(next_queue_index,
3929                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3930                queue_group->iq_ci[AIO_PATH] = next_queue_index;
3931                queue_group->iq_ci_bus_addr[AIO_PATH] =
3932                        ctrl_info->queue_memory_base_dma_handle +
3933                        (next_queue_index -
3934                        (void __iomem *)ctrl_info->queue_memory_base);
3935                next_queue_index += sizeof(pqi_index_t);
3936                next_queue_index = PTR_ALIGN(next_queue_index,
3937                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3938                queue_group->oq_pi = next_queue_index;
3939                queue_group->oq_pi_bus_addr =
3940                        ctrl_info->queue_memory_base_dma_handle +
3941                        (next_queue_index -
3942                        (void __iomem *)ctrl_info->queue_memory_base);
3943                next_queue_index += sizeof(pqi_index_t);
3944                next_queue_index = PTR_ALIGN(next_queue_index,
3945                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3946        }
3947
3948        ctrl_info->event_queue.oq_pi = next_queue_index;
3949        ctrl_info->event_queue.oq_pi_bus_addr =
3950                ctrl_info->queue_memory_base_dma_handle +
3951                (next_queue_index -
3952                (void __iomem *)ctrl_info->queue_memory_base);
3953
3954        return 0;
3955}
3956
3957static void pqi_init_operational_queues(struct pqi_ctrl_info *ctrl_info)
3958{
3959        unsigned int i;
3960        u16 next_iq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3961        u16 next_oq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3962
3963        /*
3964         * Initialize the backpointers to the controller structure in
3965         * each operational queue group structure.
3966         */
3967        for (i = 0; i < ctrl_info->num_queue_groups; i++)
3968                ctrl_info->queue_groups[i].ctrl_info = ctrl_info;
3969
3970        /*
3971         * Assign IDs to all operational queues.  Note that the IDs
3972         * assigned to operational IQs are independent of the IDs
3973         * assigned to operational OQs.
3974         */
3975        ctrl_info->event_queue.oq_id = next_oq_id++;
3976        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3977                ctrl_info->queue_groups[i].iq_id[RAID_PATH] = next_iq_id++;
3978                ctrl_info->queue_groups[i].iq_id[AIO_PATH] = next_iq_id++;
3979                ctrl_info->queue_groups[i].oq_id = next_oq_id++;
3980        }
3981
3982        /*
3983         * Assign MSI-X table entry indexes to all queues.  Note that the
3984         * interrupt for the event queue is shared with the first queue group.
3985         */
3986        ctrl_info->event_queue.int_msg_num = 0;
3987        for (i = 0; i < ctrl_info->num_queue_groups; i++)
3988                ctrl_info->queue_groups[i].int_msg_num = i;
3989
3990        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3991                spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[0]);
3992                spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[1]);
3993                INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[0]);
3994                INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[1]);
3995        }
3996}
3997
3998static int pqi_alloc_admin_queues(struct pqi_ctrl_info *ctrl_info)
3999{
4000        size_t alloc_length;
4001        struct pqi_admin_queues_aligned *admin_queues_aligned;
4002        struct pqi_admin_queues *admin_queues;
4003
4004        alloc_length = sizeof(struct pqi_admin_queues_aligned) +
4005                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
4006
4007        ctrl_info->admin_queue_memory_base =
4008                dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
4009                                   &ctrl_info->admin_queue_memory_base_dma_handle,
4010                                   GFP_KERNEL);
4011
4012        if (!ctrl_info->admin_queue_memory_base)
4013                return -ENOMEM;
4014
4015        ctrl_info->admin_queue_memory_length = alloc_length;
4016
4017        admin_queues = &ctrl_info->admin_queues;
4018        admin_queues_aligned = PTR_ALIGN(ctrl_info->admin_queue_memory_base,
4019                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
4020        admin_queues->iq_element_array =
4021                &admin_queues_aligned->iq_element_array;
4022        admin_queues->oq_element_array =
4023                &admin_queues_aligned->oq_element_array;
4024        admin_queues->iq_ci =
4025                (pqi_index_t __iomem *)&admin_queues_aligned->iq_ci;
4026        admin_queues->oq_pi =
4027                (pqi_index_t __iomem *)&admin_queues_aligned->oq_pi;
4028
4029        admin_queues->iq_element_array_bus_addr =
4030                ctrl_info->admin_queue_memory_base_dma_handle +
4031                (admin_queues->iq_element_array -
4032                ctrl_info->admin_queue_memory_base);
4033        admin_queues->oq_element_array_bus_addr =
4034                ctrl_info->admin_queue_memory_base_dma_handle +
4035                (admin_queues->oq_element_array -
4036                ctrl_info->admin_queue_memory_base);
4037        admin_queues->iq_ci_bus_addr =
4038                ctrl_info->admin_queue_memory_base_dma_handle +
4039                ((void __iomem *)admin_queues->iq_ci -
4040                (void __iomem *)ctrl_info->admin_queue_memory_base);
4041        admin_queues->oq_pi_bus_addr =
4042                ctrl_info->admin_queue_memory_base_dma_handle +
4043                ((void __iomem *)admin_queues->oq_pi -
4044                (void __iomem *)ctrl_info->admin_queue_memory_base);
4045
4046        return 0;
4047}
4048
4049#define PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES          PQI_HZ
4050#define PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS      1
4051
4052static int pqi_create_admin_queues(struct pqi_ctrl_info *ctrl_info)
4053{
4054        struct pqi_device_registers __iomem *pqi_registers;
4055        struct pqi_admin_queues *admin_queues;
4056        unsigned long timeout;
4057        u8 status;
4058        u32 reg;
4059
4060        pqi_registers = ctrl_info->pqi_registers;
4061        admin_queues = &ctrl_info->admin_queues;
4062
4063        writeq((u64)admin_queues->iq_element_array_bus_addr,
4064                &pqi_registers->admin_iq_element_array_addr);
4065        writeq((u64)admin_queues->oq_element_array_bus_addr,
4066                &pqi_registers->admin_oq_element_array_addr);
4067        writeq((u64)admin_queues->iq_ci_bus_addr,
4068                &pqi_registers->admin_iq_ci_addr);
4069        writeq((u64)admin_queues->oq_pi_bus_addr,
4070                &pqi_registers->admin_oq_pi_addr);
4071
4072        reg = PQI_ADMIN_IQ_NUM_ELEMENTS |
4073                (PQI_ADMIN_OQ_NUM_ELEMENTS << 8) |
4074                (admin_queues->int_msg_num << 16);
4075        writel(reg, &pqi_registers->admin_iq_num_elements);
4076
4077        writel(PQI_CREATE_ADMIN_QUEUE_PAIR,
4078                &pqi_registers->function_and_status_code);
4079
4080        timeout = PQI_ADMIN_QUEUE_CREATE_TIMEOUT_JIFFIES + jiffies;
4081        while (1) {
4082                status = readb(&pqi_registers->function_and_status_code);
4083                if (status == PQI_STATUS_IDLE)
4084                        break;
4085                if (time_after(jiffies, timeout))
4086                        return -ETIMEDOUT;
4087                msleep(PQI_ADMIN_QUEUE_CREATE_POLL_INTERVAL_MSECS);
4088        }
4089
4090        /*
4091         * The offset registers are not initialized to the correct
4092         * offsets until *after* the create admin queue pair command
4093         * completes successfully.
4094         */
4095        admin_queues->iq_pi = ctrl_info->iomem_base +
4096                PQI_DEVICE_REGISTERS_OFFSET +
4097                readq(&pqi_registers->admin_iq_pi_offset);
4098        admin_queues->oq_ci = ctrl_info->iomem_base +
4099                PQI_DEVICE_REGISTERS_OFFSET +
4100                readq(&pqi_registers->admin_oq_ci_offset);
4101
4102        return 0;
4103}
4104
4105static void pqi_submit_admin_request(struct pqi_ctrl_info *ctrl_info,
4106        struct pqi_general_admin_request *request)
4107{
4108        struct pqi_admin_queues *admin_queues;
4109        void *next_element;
4110        pqi_index_t iq_pi;
4111
4112        admin_queues = &ctrl_info->admin_queues;
4113        iq_pi = admin_queues->iq_pi_copy;
4114
4115        next_element = admin_queues->iq_element_array +
4116                (iq_pi * PQI_ADMIN_IQ_ELEMENT_LENGTH);
4117
4118        memcpy(next_element, request, sizeof(*request));
4119
4120        iq_pi = (iq_pi + 1) % PQI_ADMIN_IQ_NUM_ELEMENTS;
4121        admin_queues->iq_pi_copy = iq_pi;
4122
4123        /*
4124         * This write notifies the controller that an IU is available to be
4125         * processed.
4126         */
4127        writel(iq_pi, admin_queues->iq_pi);
4128}
4129
4130#define PQI_ADMIN_REQUEST_TIMEOUT_SECS  60
4131
4132static int pqi_poll_for_admin_response(struct pqi_ctrl_info *ctrl_info,
4133        struct pqi_general_admin_response *response)
4134{
4135        struct pqi_admin_queues *admin_queues;
4136        pqi_index_t oq_pi;
4137        pqi_index_t oq_ci;
4138        unsigned long timeout;
4139
4140        admin_queues = &ctrl_info->admin_queues;
4141        oq_ci = admin_queues->oq_ci_copy;
4142
4143        timeout = (PQI_ADMIN_REQUEST_TIMEOUT_SECS * PQI_HZ) + jiffies;
4144
4145        while (1) {
4146                oq_pi = readl(admin_queues->oq_pi);
4147                if (oq_pi != oq_ci)
4148                        break;
4149                if (time_after(jiffies, timeout)) {
4150                        dev_err(&ctrl_info->pci_dev->dev,
4151                                "timed out waiting for admin response\n");
4152                        return -ETIMEDOUT;
4153                }
4154                if (!sis_is_firmware_running(ctrl_info))
4155                        return -ENXIO;
4156                usleep_range(1000, 2000);
4157        }
4158
4159        memcpy(response, admin_queues->oq_element_array +
4160                (oq_ci * PQI_ADMIN_OQ_ELEMENT_LENGTH), sizeof(*response));
4161
4162        oq_ci = (oq_ci + 1) % PQI_ADMIN_OQ_NUM_ELEMENTS;
4163        admin_queues->oq_ci_copy = oq_ci;
4164        writel(oq_ci, admin_queues->oq_ci);
4165
4166        return 0;
4167}
4168
4169static void pqi_start_io(struct pqi_ctrl_info *ctrl_info,
4170        struct pqi_queue_group *queue_group, enum pqi_io_path path,
4171        struct pqi_io_request *io_request)
4172{
4173        struct pqi_io_request *next;
4174        void *next_element;
4175        pqi_index_t iq_pi;
4176        pqi_index_t iq_ci;
4177        size_t iu_length;
4178        unsigned long flags;
4179        unsigned int num_elements_needed;
4180        unsigned int num_elements_to_end_of_queue;
4181        size_t copy_count;
4182        struct pqi_iu_header *request;
4183
4184        spin_lock_irqsave(&queue_group->submit_lock[path], flags);
4185
4186        if (io_request) {
4187                io_request->queue_group = queue_group;
4188                list_add_tail(&io_request->request_list_entry,
4189                        &queue_group->request_list[path]);
4190        }
4191
4192        iq_pi = queue_group->iq_pi_copy[path];
4193
4194        list_for_each_entry_safe(io_request, next,
4195                &queue_group->request_list[path], request_list_entry) {
4196
4197                request = io_request->iu;
4198
4199                iu_length = get_unaligned_le16(&request->iu_length) +
4200                        PQI_REQUEST_HEADER_LENGTH;
4201                num_elements_needed =
4202                        DIV_ROUND_UP(iu_length,
4203                                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4204
4205                iq_ci = readl(queue_group->iq_ci[path]);
4206
4207                if (num_elements_needed > pqi_num_elements_free(iq_pi, iq_ci,
4208                        ctrl_info->num_elements_per_iq))
4209                        break;
4210
4211                put_unaligned_le16(queue_group->oq_id,
4212                        &request->response_queue_id);
4213
4214                next_element = queue_group->iq_element_array[path] +
4215                        (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4216
4217                num_elements_to_end_of_queue =
4218                        ctrl_info->num_elements_per_iq - iq_pi;
4219
4220                if (num_elements_needed <= num_elements_to_end_of_queue) {
4221                        memcpy(next_element, request, iu_length);
4222                } else {
4223                        copy_count = num_elements_to_end_of_queue *
4224                                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
4225                        memcpy(next_element, request, copy_count);
4226                        memcpy(queue_group->iq_element_array[path],
4227                                (u8 *)request + copy_count,
4228                                iu_length - copy_count);
4229                }
4230
4231                iq_pi = (iq_pi + num_elements_needed) %
4232                        ctrl_info->num_elements_per_iq;
4233
4234                list_del(&io_request->request_list_entry);
4235        }
4236
4237        if (iq_pi != queue_group->iq_pi_copy[path]) {
4238                queue_group->iq_pi_copy[path] = iq_pi;
4239                /*
4240                 * This write notifies the controller that one or more IUs are
4241                 * available to be processed.
4242                 */
4243                writel(iq_pi, queue_group->iq_pi[path]);
4244        }
4245
4246        spin_unlock_irqrestore(&queue_group->submit_lock[path], flags);
4247}
4248
4249#define PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS         10
4250
4251static int pqi_wait_for_completion_io(struct pqi_ctrl_info *ctrl_info,
4252        struct completion *wait)
4253{
4254        int rc;
4255
4256        while (1) {
4257                if (wait_for_completion_io_timeout(wait,
4258                        PQI_WAIT_FOR_COMPLETION_IO_TIMEOUT_SECS * PQI_HZ)) {
4259                        rc = 0;
4260                        break;
4261                }
4262
4263                pqi_check_ctrl_health(ctrl_info);
4264                if (pqi_ctrl_offline(ctrl_info)) {
4265                        rc = -ENXIO;
4266                        break;
4267                }
4268        }
4269
4270        return rc;
4271}
4272
4273static void pqi_raid_synchronous_complete(struct pqi_io_request *io_request,
4274        void *context)
4275{
4276        struct completion *waiting = context;
4277
4278        complete(waiting);
4279}
4280
4281static int pqi_process_raid_io_error_synchronous(
4282        struct pqi_raid_error_info *error_info)
4283{
4284        int rc = -EIO;
4285
4286        switch (error_info->data_out_result) {
4287        case PQI_DATA_IN_OUT_GOOD:
4288                if (error_info->status == SAM_STAT_GOOD)
4289                        rc = 0;
4290                break;
4291        case PQI_DATA_IN_OUT_UNDERFLOW:
4292                if (error_info->status == SAM_STAT_GOOD ||
4293                        error_info->status == SAM_STAT_CHECK_CONDITION)
4294                        rc = 0;
4295                break;
4296        case PQI_DATA_IN_OUT_ABORTED:
4297                rc = PQI_CMD_STATUS_ABORTED;
4298                break;
4299        }
4300
4301        return rc;
4302}
4303
4304static inline bool pqi_is_blockable_request(struct pqi_iu_header *request)
4305{
4306        return (request->driver_flags & PQI_DRIVER_NONBLOCKABLE_REQUEST) == 0;
4307}
4308
4309static int pqi_submit_raid_request_synchronous(struct pqi_ctrl_info *ctrl_info,
4310        struct pqi_iu_header *request, unsigned int flags,
4311        struct pqi_raid_error_info *error_info)
4312{
4313        int rc = 0;
4314        struct pqi_io_request *io_request;
4315        size_t iu_length;
4316        DECLARE_COMPLETION_ONSTACK(wait);
4317
4318        if (flags & PQI_SYNC_FLAGS_INTERRUPTABLE) {
4319                if (down_interruptible(&ctrl_info->sync_request_sem))
4320                        return -ERESTARTSYS;
4321        } else {
4322                down(&ctrl_info->sync_request_sem);
4323        }
4324
4325        pqi_ctrl_busy(ctrl_info);
4326        /*
4327         * Wait for other admin queue updates such as;
4328         * config table changes, OFA memory updates, ...
4329         */
4330        if (pqi_is_blockable_request(request))
4331                pqi_wait_if_ctrl_blocked(ctrl_info);
4332
4333        if (pqi_ctrl_offline(ctrl_info)) {
4334                rc = -ENXIO;
4335                goto out;
4336        }
4337
4338        io_request = pqi_alloc_io_request(ctrl_info);
4339
4340        put_unaligned_le16(io_request->index,
4341                &(((struct pqi_raid_path_request *)request)->request_id));
4342
4343        if (request->iu_type == PQI_REQUEST_IU_RAID_PATH_IO)
4344                ((struct pqi_raid_path_request *)request)->error_index =
4345                        ((struct pqi_raid_path_request *)request)->request_id;
4346
4347        iu_length = get_unaligned_le16(&request->iu_length) +
4348                PQI_REQUEST_HEADER_LENGTH;
4349        memcpy(io_request->iu, request, iu_length);
4350
4351        io_request->io_complete_callback = pqi_raid_synchronous_complete;
4352        io_request->context = &wait;
4353
4354        pqi_start_io(ctrl_info, &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
4355                io_request);
4356
4357        pqi_wait_for_completion_io(ctrl_info, &wait);
4358
4359        if (error_info) {
4360                if (io_request->error_info)
4361                        memcpy(error_info, io_request->error_info, sizeof(*error_info));
4362                else
4363                        memset(error_info, 0, sizeof(*error_info));
4364        } else if (rc == 0 && io_request->error_info) {
4365                rc = pqi_process_raid_io_error_synchronous(io_request->error_info);
4366        }
4367
4368        pqi_free_io_request(io_request);
4369
4370out:
4371        pqi_ctrl_unbusy(ctrl_info);
4372        up(&ctrl_info->sync_request_sem);
4373
4374        return rc;
4375}
4376
4377static int pqi_validate_admin_response(
4378        struct pqi_general_admin_response *response, u8 expected_function_code)
4379{
4380        if (response->header.iu_type != PQI_RESPONSE_IU_GENERAL_ADMIN)
4381                return -EINVAL;
4382
4383        if (get_unaligned_le16(&response->header.iu_length) !=
4384                PQI_GENERAL_ADMIN_IU_LENGTH)
4385                return -EINVAL;
4386
4387        if (response->function_code != expected_function_code)
4388                return -EINVAL;
4389
4390        if (response->status != PQI_GENERAL_ADMIN_STATUS_SUCCESS)
4391                return -EINVAL;
4392
4393        return 0;
4394}
4395
4396static int pqi_submit_admin_request_synchronous(
4397        struct pqi_ctrl_info *ctrl_info,
4398        struct pqi_general_admin_request *request,
4399        struct pqi_general_admin_response *response)
4400{
4401        int rc;
4402
4403        pqi_submit_admin_request(ctrl_info, request);
4404
4405        rc = pqi_poll_for_admin_response(ctrl_info, response);
4406
4407        if (rc == 0)
4408                rc = pqi_validate_admin_response(response, request->function_code);
4409
4410        return rc;
4411}
4412
4413static int pqi_report_device_capability(struct pqi_ctrl_info *ctrl_info)
4414{
4415        int rc;
4416        struct pqi_general_admin_request request;
4417        struct pqi_general_admin_response response;
4418        struct pqi_device_capability *capability;
4419        struct pqi_iu_layer_descriptor *sop_iu_layer_descriptor;
4420
4421        capability = kmalloc(sizeof(*capability), GFP_KERNEL);
4422        if (!capability)
4423                return -ENOMEM;
4424
4425        memset(&request, 0, sizeof(request));
4426
4427        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4428        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4429                &request.header.iu_length);
4430        request.function_code =
4431                PQI_GENERAL_ADMIN_FUNCTION_REPORT_DEVICE_CAPABILITY;
4432        put_unaligned_le32(sizeof(*capability),
4433                &request.data.report_device_capability.buffer_length);
4434
4435        rc = pqi_map_single(ctrl_info->pci_dev,
4436                &request.data.report_device_capability.sg_descriptor,
4437                capability, sizeof(*capability),
4438                DMA_FROM_DEVICE);
4439        if (rc)
4440                goto out;
4441
4442        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request, &response);
4443
4444        pqi_pci_unmap(ctrl_info->pci_dev,
4445                &request.data.report_device_capability.sg_descriptor, 1,
4446                DMA_FROM_DEVICE);
4447
4448        if (rc)
4449                goto out;
4450
4451        if (response.status != PQI_GENERAL_ADMIN_STATUS_SUCCESS) {
4452                rc = -EIO;
4453                goto out;
4454        }
4455
4456        ctrl_info->max_inbound_queues =
4457                get_unaligned_le16(&capability->max_inbound_queues);
4458        ctrl_info->max_elements_per_iq =
4459                get_unaligned_le16(&capability->max_elements_per_iq);
4460        ctrl_info->max_iq_element_length =
4461                get_unaligned_le16(&capability->max_iq_element_length)
4462                * 16;
4463        ctrl_info->max_outbound_queues =
4464                get_unaligned_le16(&capability->max_outbound_queues);
4465        ctrl_info->max_elements_per_oq =
4466                get_unaligned_le16(&capability->max_elements_per_oq);
4467        ctrl_info->max_oq_element_length =
4468                get_unaligned_le16(&capability->max_oq_element_length)
4469                * 16;
4470
4471        sop_iu_layer_descriptor =
4472                &capability->iu_layer_descriptors[PQI_PROTOCOL_SOP];
4473
4474        ctrl_info->max_inbound_iu_length_per_firmware =
4475                get_unaligned_le16(
4476                        &sop_iu_layer_descriptor->max_inbound_iu_length);
4477        ctrl_info->inbound_spanning_supported =
4478                sop_iu_layer_descriptor->inbound_spanning_supported;
4479        ctrl_info->outbound_spanning_supported =
4480                sop_iu_layer_descriptor->outbound_spanning_supported;
4481
4482out:
4483        kfree(capability);
4484
4485        return rc;
4486}
4487
4488static int pqi_validate_device_capability(struct pqi_ctrl_info *ctrl_info)
4489{
4490        if (ctrl_info->max_iq_element_length <
4491                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
4492                dev_err(&ctrl_info->pci_dev->dev,
4493                        "max. inbound queue element length of %d is less than the required length of %d\n",
4494                        ctrl_info->max_iq_element_length,
4495                        PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4496                return -EINVAL;
4497        }
4498
4499        if (ctrl_info->max_oq_element_length <
4500                PQI_OPERATIONAL_OQ_ELEMENT_LENGTH) {
4501                dev_err(&ctrl_info->pci_dev->dev,
4502                        "max. outbound queue element length of %d is less than the required length of %d\n",
4503                        ctrl_info->max_oq_element_length,
4504                        PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
4505                return -EINVAL;
4506        }
4507
4508        if (ctrl_info->max_inbound_iu_length_per_firmware <
4509                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) {
4510                dev_err(&ctrl_info->pci_dev->dev,
4511                        "max. inbound IU length of %u is less than the min. required length of %d\n",
4512                        ctrl_info->max_inbound_iu_length_per_firmware,
4513                        PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4514                return -EINVAL;
4515        }
4516
4517        if (!ctrl_info->inbound_spanning_supported) {
4518                dev_err(&ctrl_info->pci_dev->dev,
4519                        "the controller does not support inbound spanning\n");
4520                return -EINVAL;
4521        }
4522
4523        if (ctrl_info->outbound_spanning_supported) {
4524                dev_err(&ctrl_info->pci_dev->dev,
4525                        "the controller supports outbound spanning but this driver does not\n");
4526                return -EINVAL;
4527        }
4528
4529        return 0;
4530}
4531
4532static int pqi_create_event_queue(struct pqi_ctrl_info *ctrl_info)
4533{
4534        int rc;
4535        struct pqi_event_queue *event_queue;
4536        struct pqi_general_admin_request request;
4537        struct pqi_general_admin_response response;
4538
4539        event_queue = &ctrl_info->event_queue;
4540
4541        /*
4542         * Create OQ (Outbound Queue - device to host queue) to dedicate
4543         * to events.
4544         */
4545        memset(&request, 0, sizeof(request));
4546        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4547        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4548                &request.header.iu_length);
4549        request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
4550        put_unaligned_le16(event_queue->oq_id,
4551                &request.data.create_operational_oq.queue_id);
4552        put_unaligned_le64((u64)event_queue->oq_element_array_bus_addr,
4553                &request.data.create_operational_oq.element_array_addr);
4554        put_unaligned_le64((u64)event_queue->oq_pi_bus_addr,
4555                &request.data.create_operational_oq.pi_addr);
4556        put_unaligned_le16(PQI_NUM_EVENT_QUEUE_ELEMENTS,
4557                &request.data.create_operational_oq.num_elements);
4558        put_unaligned_le16(PQI_EVENT_OQ_ELEMENT_LENGTH / 16,
4559                &request.data.create_operational_oq.element_length);
4560        request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
4561        put_unaligned_le16(event_queue->int_msg_num,
4562                &request.data.create_operational_oq.int_msg_num);
4563
4564        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4565                &response);
4566        if (rc)
4567                return rc;
4568
4569        event_queue->oq_ci = ctrl_info->iomem_base +
4570                PQI_DEVICE_REGISTERS_OFFSET +
4571                get_unaligned_le64(
4572                        &response.data.create_operational_oq.oq_ci_offset);
4573
4574        return 0;
4575}
4576
4577static int pqi_create_queue_group(struct pqi_ctrl_info *ctrl_info,
4578        unsigned int group_number)
4579{
4580        int rc;
4581        struct pqi_queue_group *queue_group;
4582        struct pqi_general_admin_request request;
4583        struct pqi_general_admin_response response;
4584
4585        queue_group = &ctrl_info->queue_groups[group_number];
4586
4587        /*
4588         * Create IQ (Inbound Queue - host to device queue) for
4589         * RAID path.
4590         */
4591        memset(&request, 0, sizeof(request));
4592        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4593        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4594                &request.header.iu_length);
4595        request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
4596        put_unaligned_le16(queue_group->iq_id[RAID_PATH],
4597                &request.data.create_operational_iq.queue_id);
4598        put_unaligned_le64(
4599                (u64)queue_group->iq_element_array_bus_addr[RAID_PATH],
4600                &request.data.create_operational_iq.element_array_addr);
4601        put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[RAID_PATH],
4602                &request.data.create_operational_iq.ci_addr);
4603        put_unaligned_le16(ctrl_info->num_elements_per_iq,
4604                &request.data.create_operational_iq.num_elements);
4605        put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4606                &request.data.create_operational_iq.element_length);
4607        request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4608
4609        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4610                &response);
4611        if (rc) {
4612                dev_err(&ctrl_info->pci_dev->dev,
4613                        "error creating inbound RAID queue\n");
4614                return rc;
4615        }
4616
4617        queue_group->iq_pi[RAID_PATH] = ctrl_info->iomem_base +
4618                PQI_DEVICE_REGISTERS_OFFSET +
4619                get_unaligned_le64(
4620                        &response.data.create_operational_iq.iq_pi_offset);
4621
4622        /*
4623         * Create IQ (Inbound Queue - host to device queue) for
4624         * Advanced I/O (AIO) path.
4625         */
4626        memset(&request, 0, sizeof(request));
4627        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4628        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4629                &request.header.iu_length);
4630        request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_IQ;
4631        put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4632                &request.data.create_operational_iq.queue_id);
4633        put_unaligned_le64((u64)queue_group->
4634                iq_element_array_bus_addr[AIO_PATH],
4635                &request.data.create_operational_iq.element_array_addr);
4636        put_unaligned_le64((u64)queue_group->iq_ci_bus_addr[AIO_PATH],
4637                &request.data.create_operational_iq.ci_addr);
4638        put_unaligned_le16(ctrl_info->num_elements_per_iq,
4639                &request.data.create_operational_iq.num_elements);
4640        put_unaligned_le16(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH / 16,
4641                &request.data.create_operational_iq.element_length);
4642        request.data.create_operational_iq.queue_protocol = PQI_PROTOCOL_SOP;
4643
4644        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4645                &response);
4646        if (rc) {
4647                dev_err(&ctrl_info->pci_dev->dev,
4648                        "error creating inbound AIO queue\n");
4649                return rc;
4650        }
4651
4652        queue_group->iq_pi[AIO_PATH] = ctrl_info->iomem_base +
4653                PQI_DEVICE_REGISTERS_OFFSET +
4654                get_unaligned_le64(
4655                        &response.data.create_operational_iq.iq_pi_offset);
4656
4657        /*
4658         * Designate the 2nd IQ as the AIO path.  By default, all IQs are
4659         * assumed to be for RAID path I/O unless we change the queue's
4660         * property.
4661         */
4662        memset(&request, 0, sizeof(request));
4663        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4664        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4665                &request.header.iu_length);
4666        request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CHANGE_IQ_PROPERTY;
4667        put_unaligned_le16(queue_group->iq_id[AIO_PATH],
4668                &request.data.change_operational_iq_properties.queue_id);
4669        put_unaligned_le32(PQI_IQ_PROPERTY_IS_AIO_QUEUE,
4670                &request.data.change_operational_iq_properties.vendor_specific);
4671
4672        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4673                &response);
4674        if (rc) {
4675                dev_err(&ctrl_info->pci_dev->dev,
4676                        "error changing queue property\n");
4677                return rc;
4678        }
4679
4680        /*
4681         * Create OQ (Outbound Queue - device to host queue).
4682         */
4683        memset(&request, 0, sizeof(request));
4684        request.header.iu_type = PQI_REQUEST_IU_GENERAL_ADMIN;
4685        put_unaligned_le16(PQI_GENERAL_ADMIN_IU_LENGTH,
4686                &request.header.iu_length);
4687        request.function_code = PQI_GENERAL_ADMIN_FUNCTION_CREATE_OQ;
4688        put_unaligned_le16(queue_group->oq_id,
4689                &request.data.create_operational_oq.queue_id);
4690        put_unaligned_le64((u64)queue_group->oq_element_array_bus_addr,
4691                &request.data.create_operational_oq.element_array_addr);
4692        put_unaligned_le64((u64)queue_group->oq_pi_bus_addr,
4693                &request.data.create_operational_oq.pi_addr);
4694        put_unaligned_le16(ctrl_info->num_elements_per_oq,
4695                &request.data.create_operational_oq.num_elements);
4696        put_unaligned_le16(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH / 16,
4697                &request.data.create_operational_oq.element_length);
4698        request.data.create_operational_oq.queue_protocol = PQI_PROTOCOL_SOP;
4699        put_unaligned_le16(queue_group->int_msg_num,
4700                &request.data.create_operational_oq.int_msg_num);
4701
4702        rc = pqi_submit_admin_request_synchronous(ctrl_info, &request,
4703                &response);
4704        if (rc) {
4705                dev_err(&ctrl_info->pci_dev->dev,
4706                        "error creating outbound queue\n");
4707                return rc;
4708        }
4709
4710        queue_group->oq_ci = ctrl_info->iomem_base +
4711                PQI_DEVICE_REGISTERS_OFFSET +
4712                get_unaligned_le64(
4713                        &response.data.create_operational_oq.oq_ci_offset);
4714
4715        return 0;
4716}
4717
4718static int pqi_create_queues(struct pqi_ctrl_info *ctrl_info)
4719{
4720        int rc;
4721        unsigned int i;
4722
4723        rc = pqi_create_event_queue(ctrl_info);
4724        if (rc) {
4725                dev_err(&ctrl_info->pci_dev->dev,
4726                        "error creating event queue\n");
4727                return rc;
4728        }
4729
4730        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
4731                rc = pqi_create_queue_group(ctrl_info, i);
4732                if (rc) {
4733                        dev_err(&ctrl_info->pci_dev->dev,
4734                                "error creating queue group number %u/%u\n",
4735                                i, ctrl_info->num_queue_groups);
4736                        return rc;
4737                }
4738        }
4739
4740        return 0;
4741}
4742
4743#define PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH   \
4744        struct_size((struct pqi_event_config *)0, descriptors, PQI_MAX_EVENT_DESCRIPTORS)
4745
4746static int pqi_configure_events(struct pqi_ctrl_info *ctrl_info,
4747        bool enable_events)
4748{
4749        int rc;
4750        unsigned int i;
4751        struct pqi_event_config *event_config;
4752        struct pqi_event_descriptor *event_descriptor;
4753        struct pqi_general_management_request request;
4754
4755        event_config = kmalloc(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4756                GFP_KERNEL);
4757        if (!event_config)
4758                return -ENOMEM;
4759
4760        memset(&request, 0, sizeof(request));
4761
4762        request.header.iu_type = PQI_REQUEST_IU_REPORT_VENDOR_EVENT_CONFIG;
4763        put_unaligned_le16(offsetof(struct pqi_general_management_request,
4764                data.report_event_configuration.sg_descriptors[1]) -
4765                PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4766        put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4767                &request.data.report_event_configuration.buffer_length);
4768
4769        rc = pqi_map_single(ctrl_info->pci_dev,
4770                request.data.report_event_configuration.sg_descriptors,
4771                event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4772                DMA_FROM_DEVICE);
4773        if (rc)
4774                goto out;
4775
4776        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
4777
4778        pqi_pci_unmap(ctrl_info->pci_dev,
4779                request.data.report_event_configuration.sg_descriptors, 1,
4780                DMA_FROM_DEVICE);
4781
4782        if (rc)
4783                goto out;
4784
4785        for (i = 0; i < event_config->num_event_descriptors; i++) {
4786                event_descriptor = &event_config->descriptors[i];
4787                if (enable_events &&
4788                        pqi_is_supported_event(event_descriptor->event_type))
4789                                put_unaligned_le16(ctrl_info->event_queue.oq_id,
4790                                        &event_descriptor->oq_id);
4791                else
4792                        put_unaligned_le16(0, &event_descriptor->oq_id);
4793        }
4794
4795        memset(&request, 0, sizeof(request));
4796
4797        request.header.iu_type = PQI_REQUEST_IU_SET_VENDOR_EVENT_CONFIG;
4798        put_unaligned_le16(offsetof(struct pqi_general_management_request,
4799                data.report_event_configuration.sg_descriptors[1]) -
4800                PQI_REQUEST_HEADER_LENGTH, &request.header.iu_length);
4801        put_unaligned_le32(PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4802                &request.data.report_event_configuration.buffer_length);
4803
4804        rc = pqi_map_single(ctrl_info->pci_dev,
4805                request.data.report_event_configuration.sg_descriptors,
4806                event_config, PQI_REPORT_EVENT_CONFIG_BUFFER_LENGTH,
4807                DMA_TO_DEVICE);
4808        if (rc)
4809                goto out;
4810
4811        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
4812
4813        pqi_pci_unmap(ctrl_info->pci_dev,
4814                request.data.report_event_configuration.sg_descriptors, 1,
4815                DMA_TO_DEVICE);
4816
4817out:
4818        kfree(event_config);
4819
4820        return rc;
4821}
4822
4823static inline int pqi_enable_events(struct pqi_ctrl_info *ctrl_info)
4824{
4825        return pqi_configure_events(ctrl_info, true);
4826}
4827
4828static void pqi_free_all_io_requests(struct pqi_ctrl_info *ctrl_info)
4829{
4830        unsigned int i;
4831        struct device *dev;
4832        size_t sg_chain_buffer_length;
4833        struct pqi_io_request *io_request;
4834
4835        if (!ctrl_info->io_request_pool)
4836                return;
4837
4838        dev = &ctrl_info->pci_dev->dev;
4839        sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4840        io_request = ctrl_info->io_request_pool;
4841
4842        for (i = 0; i < ctrl_info->max_io_slots; i++) {
4843                kfree(io_request->iu);
4844                if (!io_request->sg_chain_buffer)
4845                        break;
4846                dma_free_coherent(dev, sg_chain_buffer_length,
4847                        io_request->sg_chain_buffer,
4848                        io_request->sg_chain_buffer_dma_handle);
4849                io_request++;
4850        }
4851
4852        kfree(ctrl_info->io_request_pool);
4853        ctrl_info->io_request_pool = NULL;
4854}
4855
4856static inline int pqi_alloc_error_buffer(struct pqi_ctrl_info *ctrl_info)
4857{
4858        ctrl_info->error_buffer = dma_alloc_coherent(&ctrl_info->pci_dev->dev,
4859                                     ctrl_info->error_buffer_length,
4860                                     &ctrl_info->error_buffer_dma_handle,
4861                                     GFP_KERNEL);
4862        if (!ctrl_info->error_buffer)
4863                return -ENOMEM;
4864
4865        return 0;
4866}
4867
4868static int pqi_alloc_io_resources(struct pqi_ctrl_info *ctrl_info)
4869{
4870        unsigned int i;
4871        void *sg_chain_buffer;
4872        size_t sg_chain_buffer_length;
4873        dma_addr_t sg_chain_buffer_dma_handle;
4874        struct device *dev;
4875        struct pqi_io_request *io_request;
4876
4877        ctrl_info->io_request_pool = kcalloc(ctrl_info->max_io_slots,
4878                sizeof(ctrl_info->io_request_pool[0]), GFP_KERNEL);
4879
4880        if (!ctrl_info->io_request_pool) {
4881                dev_err(&ctrl_info->pci_dev->dev,
4882                        "failed to allocate I/O request pool\n");
4883                goto error;
4884        }
4885
4886        dev = &ctrl_info->pci_dev->dev;
4887        sg_chain_buffer_length = ctrl_info->sg_chain_buffer_length;
4888        io_request = ctrl_info->io_request_pool;
4889
4890        for (i = 0; i < ctrl_info->max_io_slots; i++) {
4891                io_request->iu = kmalloc(ctrl_info->max_inbound_iu_length, GFP_KERNEL);
4892
4893                if (!io_request->iu) {
4894                        dev_err(&ctrl_info->pci_dev->dev,
4895                                "failed to allocate IU buffers\n");
4896                        goto error;
4897                }
4898
4899                sg_chain_buffer = dma_alloc_coherent(dev,
4900                        sg_chain_buffer_length, &sg_chain_buffer_dma_handle,
4901                        GFP_KERNEL);
4902
4903                if (!sg_chain_buffer) {
4904                        dev_err(&ctrl_info->pci_dev->dev,
4905                                "failed to allocate PQI scatter-gather chain buffers\n");
4906                        goto error;
4907                }
4908
4909                io_request->index = i;
4910                io_request->sg_chain_buffer = sg_chain_buffer;
4911                io_request->sg_chain_buffer_dma_handle = sg_chain_buffer_dma_handle;
4912                io_request++;
4913        }
4914
4915        return 0;
4916
4917error:
4918        pqi_free_all_io_requests(ctrl_info);
4919
4920        return -ENOMEM;
4921}
4922
4923/*
4924 * Calculate required resources that are sized based on max. outstanding
4925 * requests and max. transfer size.
4926 */
4927
4928static void pqi_calculate_io_resources(struct pqi_ctrl_info *ctrl_info)
4929{
4930        u32 max_transfer_size;
4931        u32 max_sg_entries;
4932
4933        ctrl_info->scsi_ml_can_queue =
4934                ctrl_info->max_outstanding_requests - PQI_RESERVED_IO_SLOTS;
4935        ctrl_info->max_io_slots = ctrl_info->max_outstanding_requests;
4936
4937        ctrl_info->error_buffer_length =
4938                ctrl_info->max_io_slots * PQI_ERROR_BUFFER_ELEMENT_LENGTH;
4939
4940        if (reset_devices)
4941                max_transfer_size = min(ctrl_info->max_transfer_size,
4942                        PQI_MAX_TRANSFER_SIZE_KDUMP);
4943        else
4944                max_transfer_size = min(ctrl_info->max_transfer_size,
4945                        PQI_MAX_TRANSFER_SIZE);
4946
4947        max_sg_entries = max_transfer_size / PAGE_SIZE;
4948
4949        /* +1 to cover when the buffer is not page-aligned. */
4950        max_sg_entries++;
4951
4952        max_sg_entries = min(ctrl_info->max_sg_entries, max_sg_entries);
4953
4954        max_transfer_size = (max_sg_entries - 1) * PAGE_SIZE;
4955
4956        ctrl_info->sg_chain_buffer_length =
4957                (max_sg_entries * sizeof(struct pqi_sg_descriptor)) +
4958                PQI_EXTRA_SGL_MEMORY;
4959        ctrl_info->sg_tablesize = max_sg_entries;
4960        ctrl_info->max_sectors = max_transfer_size / 512;
4961}
4962
4963static void pqi_calculate_queue_resources(struct pqi_ctrl_info *ctrl_info)
4964{
4965        int num_queue_groups;
4966        u16 num_elements_per_iq;
4967        u16 num_elements_per_oq;
4968
4969        if (reset_devices) {
4970                num_queue_groups = 1;
4971        } else {
4972                int num_cpus;
4973                int max_queue_groups;
4974
4975                max_queue_groups = min(ctrl_info->max_inbound_queues / 2,
4976                        ctrl_info->max_outbound_queues - 1);
4977                max_queue_groups = min(max_queue_groups, PQI_MAX_QUEUE_GROUPS);
4978
4979                num_cpus = num_online_cpus();
4980                num_queue_groups = min(num_cpus, ctrl_info->max_msix_vectors);
4981                num_queue_groups = min(num_queue_groups, max_queue_groups);
4982        }
4983
4984        ctrl_info->num_queue_groups = num_queue_groups;
4985        ctrl_info->max_hw_queue_index = num_queue_groups - 1;
4986
4987        /*
4988         * Make sure that the max. inbound IU length is an even multiple
4989         * of our inbound element length.
4990         */
4991        ctrl_info->max_inbound_iu_length =
4992                (ctrl_info->max_inbound_iu_length_per_firmware /
4993                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) *
4994                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH;
4995
4996        num_elements_per_iq =
4997                (ctrl_info->max_inbound_iu_length /
4998                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
4999
5000        /* Add one because one element in each queue is unusable. */
5001        num_elements_per_iq++;
5002
5003        num_elements_per_iq = min(num_elements_per_iq,
5004                ctrl_info->max_elements_per_iq);
5005
5006        num_elements_per_oq = ((num_elements_per_iq - 1) * 2) + 1;
5007        num_elements_per_oq = min(num_elements_per_oq,
5008                ctrl_info->max_elements_per_oq);
5009
5010        ctrl_info->num_elements_per_iq = num_elements_per_iq;
5011        ctrl_info->num_elements_per_oq = num_elements_per_oq;
5012
5013        ctrl_info->max_sg_per_iu =
5014                ((ctrl_info->max_inbound_iu_length -
5015                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) /
5016                sizeof(struct pqi_sg_descriptor)) +
5017                PQI_MAX_EMBEDDED_SG_DESCRIPTORS;
5018
5019        ctrl_info->max_sg_per_r56_iu =
5020                ((ctrl_info->max_inbound_iu_length -
5021                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH) /
5022                sizeof(struct pqi_sg_descriptor)) +
5023                PQI_MAX_EMBEDDED_R56_SG_DESCRIPTORS;
5024}
5025
5026static inline void pqi_set_sg_descriptor(struct pqi_sg_descriptor *sg_descriptor,
5027        struct scatterlist *sg)
5028{
5029        u64 address = (u64)sg_dma_address(sg);
5030        unsigned int length = sg_dma_len(sg);
5031
5032        put_unaligned_le64(address, &sg_descriptor->address);
5033        put_unaligned_le32(length, &sg_descriptor->length);
5034        put_unaligned_le32(0, &sg_descriptor->flags);
5035}
5036
5037static unsigned int pqi_build_sg_list(struct pqi_sg_descriptor *sg_descriptor,
5038        struct scatterlist *sg, int sg_count, struct pqi_io_request *io_request,
5039        int max_sg_per_iu, bool *chained)
5040{
5041        int i;
5042        unsigned int num_sg_in_iu;
5043
5044        *chained = false;
5045        i = 0;
5046        num_sg_in_iu = 0;
5047        max_sg_per_iu--;        /* Subtract 1 to leave room for chain marker. */
5048
5049        while (1) {
5050                pqi_set_sg_descriptor(sg_descriptor, sg);
5051                if (!*chained)
5052                        num_sg_in_iu++;
5053                i++;
5054                if (i == sg_count)
5055                        break;
5056                sg_descriptor++;
5057                if (i == max_sg_per_iu) {
5058                        put_unaligned_le64((u64)io_request->sg_chain_buffer_dma_handle,
5059                                &sg_descriptor->address);
5060                        put_unaligned_le32((sg_count - num_sg_in_iu) * sizeof(*sg_descriptor),
5061                                &sg_descriptor->length);
5062                        put_unaligned_le32(CISS_SG_CHAIN, &sg_descriptor->flags);
5063                        *chained = true;
5064                        num_sg_in_iu++;
5065                        sg_descriptor = io_request->sg_chain_buffer;
5066                }
5067                sg = sg_next(sg);
5068        }
5069
5070        put_unaligned_le32(CISS_SG_LAST, &sg_descriptor->flags);
5071
5072        return num_sg_in_iu;
5073}
5074
5075static int pqi_build_raid_sg_list(struct pqi_ctrl_info *ctrl_info,
5076        struct pqi_raid_path_request *request, struct scsi_cmnd *scmd,
5077        struct pqi_io_request *io_request)
5078{
5079        u16 iu_length;
5080        int sg_count;
5081        bool chained;
5082        unsigned int num_sg_in_iu;
5083        struct scatterlist *sg;
5084        struct pqi_sg_descriptor *sg_descriptor;
5085
5086        sg_count = scsi_dma_map(scmd);
5087        if (sg_count < 0)
5088                return sg_count;
5089
5090        iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
5091                PQI_REQUEST_HEADER_LENGTH;
5092
5093        if (sg_count == 0)
5094                goto out;
5095
5096        sg = scsi_sglist(scmd);
5097        sg_descriptor = request->sg_descriptors;
5098
5099        num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5100                ctrl_info->max_sg_per_iu, &chained);
5101
5102        request->partial = chained;
5103        iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5104
5105out:
5106        put_unaligned_le16(iu_length, &request->header.iu_length);
5107
5108        return 0;
5109}
5110
5111static int pqi_build_aio_r1_sg_list(struct pqi_ctrl_info *ctrl_info,
5112        struct pqi_aio_r1_path_request *request, struct scsi_cmnd *scmd,
5113        struct pqi_io_request *io_request)
5114{
5115        u16 iu_length;
5116        int sg_count;
5117        bool chained;
5118        unsigned int num_sg_in_iu;
5119        struct scatterlist *sg;
5120        struct pqi_sg_descriptor *sg_descriptor;
5121
5122        sg_count = scsi_dma_map(scmd);
5123        if (sg_count < 0)
5124                return sg_count;
5125
5126        iu_length = offsetof(struct pqi_aio_r1_path_request, sg_descriptors) -
5127                PQI_REQUEST_HEADER_LENGTH;
5128        num_sg_in_iu = 0;
5129
5130        if (sg_count == 0)
5131                goto out;
5132
5133        sg = scsi_sglist(scmd);
5134        sg_descriptor = request->sg_descriptors;
5135
5136        num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5137                ctrl_info->max_sg_per_iu, &chained);
5138
5139        request->partial = chained;
5140        iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5141
5142out:
5143        put_unaligned_le16(iu_length, &request->header.iu_length);
5144        request->num_sg_descriptors = num_sg_in_iu;
5145
5146        return 0;
5147}
5148
5149static int pqi_build_aio_r56_sg_list(struct pqi_ctrl_info *ctrl_info,
5150        struct pqi_aio_r56_path_request *request, struct scsi_cmnd *scmd,
5151        struct pqi_io_request *io_request)
5152{
5153        u16 iu_length;
5154        int sg_count;
5155        bool chained;
5156        unsigned int num_sg_in_iu;
5157        struct scatterlist *sg;
5158        struct pqi_sg_descriptor *sg_descriptor;
5159
5160        sg_count = scsi_dma_map(scmd);
5161        if (sg_count < 0)
5162                return sg_count;
5163
5164        iu_length = offsetof(struct pqi_aio_r56_path_request, sg_descriptors) -
5165                PQI_REQUEST_HEADER_LENGTH;
5166        num_sg_in_iu = 0;
5167
5168        if (sg_count != 0) {
5169                sg = scsi_sglist(scmd);
5170                sg_descriptor = request->sg_descriptors;
5171
5172                num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5173                        ctrl_info->max_sg_per_r56_iu, &chained);
5174
5175                request->partial = chained;
5176                iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5177        }
5178
5179        put_unaligned_le16(iu_length, &request->header.iu_length);
5180        request->num_sg_descriptors = num_sg_in_iu;
5181
5182        return 0;
5183}
5184
5185static int pqi_build_aio_sg_list(struct pqi_ctrl_info *ctrl_info,
5186        struct pqi_aio_path_request *request, struct scsi_cmnd *scmd,
5187        struct pqi_io_request *io_request)
5188{
5189        u16 iu_length;
5190        int sg_count;
5191        bool chained;
5192        unsigned int num_sg_in_iu;
5193        struct scatterlist *sg;
5194        struct pqi_sg_descriptor *sg_descriptor;
5195
5196        sg_count = scsi_dma_map(scmd);
5197        if (sg_count < 0)
5198                return sg_count;
5199
5200        iu_length = offsetof(struct pqi_aio_path_request, sg_descriptors) -
5201                PQI_REQUEST_HEADER_LENGTH;
5202        num_sg_in_iu = 0;
5203
5204        if (sg_count == 0)
5205                goto out;
5206
5207        sg = scsi_sglist(scmd);
5208        sg_descriptor = request->sg_descriptors;
5209
5210        num_sg_in_iu = pqi_build_sg_list(sg_descriptor, sg, sg_count, io_request,
5211                ctrl_info->max_sg_per_iu, &chained);
5212
5213        request->partial = chained;
5214        iu_length += num_sg_in_iu * sizeof(*sg_descriptor);
5215
5216out:
5217        put_unaligned_le16(iu_length, &request->header.iu_length);
5218        request->num_sg_descriptors = num_sg_in_iu;
5219
5220        return 0;
5221}
5222
5223static void pqi_raid_io_complete(struct pqi_io_request *io_request,
5224        void *context)
5225{
5226        struct scsi_cmnd *scmd;
5227
5228        scmd = io_request->scmd;
5229        pqi_free_io_request(io_request);
5230        scsi_dma_unmap(scmd);
5231        pqi_scsi_done(scmd);
5232}
5233
5234static int pqi_raid_submit_scsi_cmd_with_io_request(
5235        struct pqi_ctrl_info *ctrl_info, struct pqi_io_request *io_request,
5236        struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5237        struct pqi_queue_group *queue_group)
5238{
5239        int rc;
5240        size_t cdb_length;
5241        struct pqi_raid_path_request *request;
5242
5243        io_request->io_complete_callback = pqi_raid_io_complete;
5244        io_request->scmd = scmd;
5245
5246        request = io_request->iu;
5247        memset(request, 0, offsetof(struct pqi_raid_path_request, sg_descriptors));
5248
5249        request->header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
5250        put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
5251        request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5252        put_unaligned_le16(io_request->index, &request->request_id);
5253        request->error_index = request->request_id;
5254        memcpy(request->lun_number, device->scsi3addr, sizeof(request->lun_number));
5255
5256        cdb_length = min_t(size_t, scmd->cmd_len, sizeof(request->cdb));
5257        memcpy(request->cdb, scmd->cmnd, cdb_length);
5258
5259        switch (cdb_length) {
5260        case 6:
5261        case 10:
5262        case 12:
5263        case 16:
5264                request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
5265                break;
5266        case 20:
5267                request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_4;
5268                break;
5269        case 24:
5270                request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_8;
5271                break;
5272        case 28:
5273                request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_12;
5274                break;
5275        case 32:
5276        default:
5277                request->additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_16;
5278                break;
5279        }
5280
5281        switch (scmd->sc_data_direction) {
5282        case DMA_TO_DEVICE:
5283                request->data_direction = SOP_READ_FLAG;
5284                break;
5285        case DMA_FROM_DEVICE:
5286                request->data_direction = SOP_WRITE_FLAG;
5287                break;
5288        case DMA_NONE:
5289                request->data_direction = SOP_NO_DIRECTION_FLAG;
5290                break;
5291        case DMA_BIDIRECTIONAL:
5292                request->data_direction = SOP_BIDIRECTIONAL;
5293                break;
5294        default:
5295                dev_err(&ctrl_info->pci_dev->dev,
5296                        "unknown data direction: %d\n",
5297                        scmd->sc_data_direction);
5298                break;
5299        }
5300
5301        rc = pqi_build_raid_sg_list(ctrl_info, request, scmd, io_request);
5302        if (rc) {
5303                pqi_free_io_request(io_request);
5304                return SCSI_MLQUEUE_HOST_BUSY;
5305        }
5306
5307        pqi_start_io(ctrl_info, queue_group, RAID_PATH, io_request);
5308
5309        return 0;
5310}
5311
5312static inline int pqi_raid_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
5313        struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5314        struct pqi_queue_group *queue_group)
5315{
5316        struct pqi_io_request *io_request;
5317
5318        io_request = pqi_alloc_io_request(ctrl_info);
5319
5320        return pqi_raid_submit_scsi_cmd_with_io_request(ctrl_info, io_request,
5321                device, scmd, queue_group);
5322}
5323
5324static bool pqi_raid_bypass_retry_needed(struct pqi_io_request *io_request)
5325{
5326        struct scsi_cmnd *scmd;
5327        struct pqi_scsi_dev *device;
5328        struct pqi_ctrl_info *ctrl_info;
5329
5330        if (!io_request->raid_bypass)
5331                return false;
5332
5333        scmd = io_request->scmd;
5334        if ((scmd->result & 0xff) == SAM_STAT_GOOD)
5335                return false;
5336        if (host_byte(scmd->result) == DID_NO_CONNECT)
5337                return false;
5338
5339        device = scmd->device->hostdata;
5340        if (pqi_device_offline(device) || pqi_device_in_remove(device))
5341                return false;
5342
5343        ctrl_info = shost_to_hba(scmd->device->host);
5344        if (pqi_ctrl_offline(ctrl_info))
5345                return false;
5346
5347        return true;
5348}
5349
5350static void pqi_aio_io_complete(struct pqi_io_request *io_request,
5351        void *context)
5352{
5353        struct scsi_cmnd *scmd;
5354
5355        scmd = io_request->scmd;
5356        scsi_dma_unmap(scmd);
5357        if (io_request->status == -EAGAIN || pqi_raid_bypass_retry_needed(io_request)) {
5358                set_host_byte(scmd, DID_IMM_RETRY);
5359                scmd->SCp.this_residual++;
5360        }
5361
5362        pqi_free_io_request(io_request);
5363        pqi_scsi_done(scmd);
5364}
5365
5366static inline int pqi_aio_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
5367        struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
5368        struct pqi_queue_group *queue_group)
5369{
5370        return pqi_aio_submit_io(ctrl_info, scmd, device->aio_handle,
5371                scmd->cmnd, scmd->cmd_len, queue_group, NULL, false);
5372}
5373
5374static int pqi_aio_submit_io(struct pqi_ctrl_info *ctrl_info,
5375        struct scsi_cmnd *scmd, u32 aio_handle, u8 *cdb,
5376        unsigned int cdb_length, struct pqi_queue_group *queue_group,
5377        struct pqi_encryption_info *encryption_info, bool raid_bypass)
5378{
5379        int rc;
5380        struct pqi_io_request *io_request;
5381        struct pqi_aio_path_request *request;
5382
5383        io_request = pqi_alloc_io_request(ctrl_info);
5384        io_request->io_complete_callback = pqi_aio_io_complete;
5385        io_request->scmd = scmd;
5386        io_request->raid_bypass = raid_bypass;
5387
5388        request = io_request->iu;
5389        memset(request, 0, offsetof(struct pqi_raid_path_request, sg_descriptors));
5390
5391        request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_IO;
5392        put_unaligned_le32(aio_handle, &request->nexus_id);
5393        put_unaligned_le32(scsi_bufflen(scmd), &request->buffer_length);
5394        request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5395        put_unaligned_le16(io_request->index, &request->request_id);
5396        request->error_index = request->request_id;
5397        if (cdb_length > sizeof(request->cdb))
5398                cdb_length = sizeof(request->cdb);
5399        request->cdb_length = cdb_length;
5400        memcpy(request->cdb, cdb, cdb_length);
5401
5402        switch (scmd->sc_data_direction) {
5403        case DMA_TO_DEVICE:
5404                request->data_direction = SOP_READ_FLAG;
5405                break;
5406        case DMA_FROM_DEVICE:
5407                request->data_direction = SOP_WRITE_FLAG;
5408                break;
5409        case DMA_NONE:
5410                request->data_direction = SOP_NO_DIRECTION_FLAG;
5411                break;
5412        case DMA_BIDIRECTIONAL:
5413                request->data_direction = SOP_BIDIRECTIONAL;
5414                break;
5415        default:
5416                dev_err(&ctrl_info->pci_dev->dev,
5417                        "unknown data direction: %d\n",
5418                        scmd->sc_data_direction);
5419                break;
5420        }
5421
5422        if (encryption_info) {
5423                request->encryption_enable = true;
5424                put_unaligned_le16(encryption_info->data_encryption_key_index,
5425                        &request->data_encryption_key_index);
5426                put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5427                        &request->encrypt_tweak_lower);
5428                put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5429                        &request->encrypt_tweak_upper);
5430        }
5431
5432        rc = pqi_build_aio_sg_list(ctrl_info, request, scmd, io_request);
5433        if (rc) {
5434                pqi_free_io_request(io_request);
5435                return SCSI_MLQUEUE_HOST_BUSY;
5436        }
5437
5438        pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5439
5440        return 0;
5441}
5442
5443static  int pqi_aio_submit_r1_write_io(struct pqi_ctrl_info *ctrl_info,
5444        struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
5445        struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
5446        struct pqi_scsi_dev_raid_map_data *rmd)
5447{
5448        int rc;
5449        struct pqi_io_request *io_request;
5450        struct pqi_aio_r1_path_request *r1_request;
5451
5452        io_request = pqi_alloc_io_request(ctrl_info);
5453        io_request->io_complete_callback = pqi_aio_io_complete;
5454        io_request->scmd = scmd;
5455        io_request->raid_bypass = true;
5456
5457        r1_request = io_request->iu;
5458        memset(r1_request, 0, offsetof(struct pqi_aio_r1_path_request, sg_descriptors));
5459
5460        r1_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID1_IO;
5461        put_unaligned_le16(*(u16 *)device->scsi3addr & 0x3fff, &r1_request->volume_id);
5462        r1_request->num_drives = rmd->num_it_nexus_entries;
5463        put_unaligned_le32(rmd->it_nexus[0], &r1_request->it_nexus_1);
5464        put_unaligned_le32(rmd->it_nexus[1], &r1_request->it_nexus_2);
5465        if (rmd->num_it_nexus_entries == 3)
5466                put_unaligned_le32(rmd->it_nexus[2], &r1_request->it_nexus_3);
5467
5468        put_unaligned_le32(scsi_bufflen(scmd), &r1_request->data_length);
5469        r1_request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5470        put_unaligned_le16(io_request->index, &r1_request->request_id);
5471        r1_request->error_index = r1_request->request_id;
5472        if (rmd->cdb_length > sizeof(r1_request->cdb))
5473                rmd->cdb_length = sizeof(r1_request->cdb);
5474        r1_request->cdb_length = rmd->cdb_length;
5475        memcpy(r1_request->cdb, rmd->cdb, rmd->cdb_length);
5476
5477        /* The direction is always write. */
5478        r1_request->data_direction = SOP_READ_FLAG;
5479
5480        if (encryption_info) {
5481                r1_request->encryption_enable = true;
5482                put_unaligned_le16(encryption_info->data_encryption_key_index,
5483                                &r1_request->data_encryption_key_index);
5484                put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5485                                &r1_request->encrypt_tweak_lower);
5486                put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5487                                &r1_request->encrypt_tweak_upper);
5488        }
5489
5490        rc = pqi_build_aio_r1_sg_list(ctrl_info, r1_request, scmd, io_request);
5491        if (rc) {
5492                pqi_free_io_request(io_request);
5493                return SCSI_MLQUEUE_HOST_BUSY;
5494        }
5495
5496        pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5497
5498        return 0;
5499}
5500
5501static int pqi_aio_submit_r56_write_io(struct pqi_ctrl_info *ctrl_info,
5502        struct scsi_cmnd *scmd, struct pqi_queue_group *queue_group,
5503        struct pqi_encryption_info *encryption_info, struct pqi_scsi_dev *device,
5504        struct pqi_scsi_dev_raid_map_data *rmd)
5505{
5506        int rc;
5507        struct pqi_io_request *io_request;
5508        struct pqi_aio_r56_path_request *r56_request;
5509
5510        io_request = pqi_alloc_io_request(ctrl_info);
5511        io_request->io_complete_callback = pqi_aio_io_complete;
5512        io_request->scmd = scmd;
5513        io_request->raid_bypass = true;
5514
5515        r56_request = io_request->iu;
5516        memset(r56_request, 0, offsetof(struct pqi_aio_r56_path_request, sg_descriptors));
5517
5518        if (device->raid_level == SA_RAID_5 || device->raid_level == SA_RAID_51)
5519                r56_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID5_IO;
5520        else
5521                r56_request->header.iu_type = PQI_REQUEST_IU_AIO_PATH_RAID6_IO;
5522
5523        put_unaligned_le16(*(u16 *)device->scsi3addr & 0x3fff, &r56_request->volume_id);
5524        put_unaligned_le32(rmd->aio_handle, &r56_request->data_it_nexus);
5525        put_unaligned_le32(rmd->p_parity_it_nexus, &r56_request->p_parity_it_nexus);
5526        if (rmd->raid_level == SA_RAID_6) {
5527                put_unaligned_le32(rmd->q_parity_it_nexus, &r56_request->q_parity_it_nexus);
5528                r56_request->xor_multiplier = rmd->xor_mult;
5529        }
5530        put_unaligned_le32(scsi_bufflen(scmd), &r56_request->data_length);
5531        r56_request->task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
5532        put_unaligned_le64(rmd->row, &r56_request->row);
5533
5534        put_unaligned_le16(io_request->index, &r56_request->request_id);
5535        r56_request->error_index = r56_request->request_id;
5536
5537        if (rmd->cdb_length > sizeof(r56_request->cdb))
5538                rmd->cdb_length = sizeof(r56_request->cdb);
5539        r56_request->cdb_length = rmd->cdb_length;
5540        memcpy(r56_request->cdb, rmd->cdb, rmd->cdb_length);
5541
5542        /* The direction is always write. */
5543        r56_request->data_direction = SOP_READ_FLAG;
5544
5545        if (encryption_info) {
5546                r56_request->encryption_enable = true;
5547                put_unaligned_le16(encryption_info->data_encryption_key_index,
5548                                &r56_request->data_encryption_key_index);
5549                put_unaligned_le32(encryption_info->encrypt_tweak_lower,
5550                                &r56_request->encrypt_tweak_lower);
5551                put_unaligned_le32(encryption_info->encrypt_tweak_upper,
5552                                &r56_request->encrypt_tweak_upper);
5553        }
5554
5555        rc = pqi_build_aio_r56_sg_list(ctrl_info, r56_request, scmd, io_request);
5556        if (rc) {
5557                pqi_free_io_request(io_request);
5558                return SCSI_MLQUEUE_HOST_BUSY;
5559        }
5560
5561        pqi_start_io(ctrl_info, queue_group, AIO_PATH, io_request);
5562
5563        return 0;
5564}
5565
5566static inline u16 pqi_get_hw_queue(struct pqi_ctrl_info *ctrl_info,
5567        struct scsi_cmnd *scmd)
5568{
5569        u16 hw_queue;
5570
5571        hw_queue = blk_mq_unique_tag_to_hwq(blk_mq_unique_tag(scsi_cmd_to_rq(scmd)));
5572        if (hw_queue > ctrl_info->max_hw_queue_index)
5573                hw_queue = 0;
5574
5575        return hw_queue;
5576}
5577
5578static inline bool pqi_is_bypass_eligible_request(struct scsi_cmnd *scmd)
5579{
5580        if (blk_rq_is_passthrough(scsi_cmd_to_rq(scmd)))
5581                return false;
5582
5583        return scmd->SCp.this_residual == 0;
5584}
5585
5586/*
5587 * This function gets called just before we hand the completed SCSI request
5588 * back to the SML.
5589 */
5590
5591void pqi_prep_for_scsi_done(struct scsi_cmnd *scmd)
5592{
5593        struct pqi_scsi_dev *device;
5594
5595        if (!scmd->device) {
5596                set_host_byte(scmd, DID_NO_CONNECT);
5597                return;
5598        }
5599
5600        device = scmd->device->hostdata;
5601        if (!device) {
5602                set_host_byte(scmd, DID_NO_CONNECT);
5603                return;
5604        }
5605
5606        atomic_dec(&device->scsi_cmds_outstanding);
5607}
5608
5609static bool pqi_is_parity_write_stream(struct pqi_ctrl_info *ctrl_info,
5610        struct scsi_cmnd *scmd)
5611{
5612        u32 oldest_jiffies;
5613        u8 lru_index;
5614        int i;
5615        int rc;
5616        struct pqi_scsi_dev *device;
5617        struct pqi_stream_data *pqi_stream_data;
5618        struct pqi_scsi_dev_raid_map_data rmd;
5619
5620        if (!ctrl_info->enable_stream_detection)
5621                return false;
5622
5623        rc = pqi_get_aio_lba_and_block_count(scmd, &rmd);
5624        if (rc)
5625                return false;
5626
5627        /* Check writes only. */
5628        if (!rmd.is_write)
5629                return false;
5630
5631        device = scmd->device->hostdata;
5632
5633        /* Check for RAID 5/6 streams. */
5634        if (device->raid_level != SA_RAID_5 && device->raid_level != SA_RAID_6)
5635                return false;
5636
5637        /*
5638         * If controller does not support AIO RAID{5,6} writes, need to send
5639         * requests down non-AIO path.
5640         */
5641        if ((device->raid_level == SA_RAID_5 && !ctrl_info->enable_r5_writes) ||
5642                (device->raid_level == SA_RAID_6 && !ctrl_info->enable_r6_writes))
5643                return true;
5644
5645        lru_index = 0;
5646        oldest_jiffies = INT_MAX;
5647        for (i = 0; i < NUM_STREAMS_PER_LUN; i++) {
5648                pqi_stream_data = &device->stream_data[i];
5649                /*
5650                 * Check for adjacent request or request is within
5651                 * the previous request.
5652                 */
5653                if ((pqi_stream_data->next_lba &&
5654                        rmd.first_block >= pqi_stream_data->next_lba) &&
5655                        rmd.first_block <= pqi_stream_data->next_lba +
5656                                rmd.block_cnt) {
5657                        pqi_stream_data->next_lba = rmd.first_block +
5658                                rmd.block_cnt;
5659                        pqi_stream_data->last_accessed = jiffies;
5660                        return true;
5661                }
5662
5663                /* unused entry */
5664                if (pqi_stream_data->last_accessed == 0) {
5665                        lru_index = i;
5666                        break;
5667                }
5668
5669                /* Find entry with oldest last accessed time. */
5670                if (pqi_stream_data->last_accessed <= oldest_jiffies) {
5671                        oldest_jiffies = pqi_stream_data->last_accessed;
5672                        lru_index = i;
5673                }
5674        }
5675
5676        /* Set LRU entry. */
5677        pqi_stream_data = &device->stream_data[lru_index];
5678        pqi_stream_data->last_accessed = jiffies;
5679        pqi_stream_data->next_lba = rmd.first_block + rmd.block_cnt;
5680
5681        return false;
5682}
5683
5684static int pqi_scsi_queue_command(struct Scsi_Host *shost, struct scsi_cmnd *scmd)
5685{
5686        int rc;
5687        struct pqi_ctrl_info *ctrl_info;
5688        struct pqi_scsi_dev *device;
5689        u16 hw_queue;
5690        struct pqi_queue_group *queue_group;
5691        bool raid_bypassed;
5692
5693        device = scmd->device->hostdata;
5694
5695        if (!device) {
5696                set_host_byte(scmd, DID_NO_CONNECT);
5697                pqi_scsi_done(scmd);
5698                return 0;
5699        }
5700
5701        atomic_inc(&device->scsi_cmds_outstanding);
5702
5703        ctrl_info = shost_to_hba(shost);
5704
5705        if (pqi_ctrl_offline(ctrl_info) || pqi_device_in_remove(device)) {
5706                set_host_byte(scmd, DID_NO_CONNECT);
5707                pqi_scsi_done(scmd);
5708                return 0;
5709        }
5710
5711        if (pqi_ctrl_blocked(ctrl_info)) {
5712                rc = SCSI_MLQUEUE_HOST_BUSY;
5713                goto out;
5714        }
5715
5716        /*
5717         * This is necessary because the SML doesn't zero out this field during
5718         * error recovery.
5719         */
5720        scmd->result = 0;
5721
5722        hw_queue = pqi_get_hw_queue(ctrl_info, scmd);
5723        queue_group = &ctrl_info->queue_groups[hw_queue];
5724
5725        if (pqi_is_logical_device(device)) {
5726                raid_bypassed = false;
5727                if (device->raid_bypass_enabled &&
5728                        pqi_is_bypass_eligible_request(scmd) &&
5729                        !pqi_is_parity_write_stream(ctrl_info, scmd)) {
5730                        rc = pqi_raid_bypass_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5731                        if (rc == 0 || rc == SCSI_MLQUEUE_HOST_BUSY) {
5732                                raid_bypassed = true;
5733                                atomic_inc(&device->raid_bypass_cnt);
5734                        }
5735                }
5736                if (!raid_bypassed)
5737                        rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5738        } else {
5739                if (device->aio_enabled)
5740                        rc = pqi_aio_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5741                else
5742                        rc = pqi_raid_submit_scsi_cmd(ctrl_info, device, scmd, queue_group);
5743        }
5744
5745out:
5746        if (rc)
5747                atomic_dec(&device->scsi_cmds_outstanding);
5748
5749        return rc;
5750}
5751
5752static int pqi_wait_until_queued_io_drained(struct pqi_ctrl_info *ctrl_info,
5753        struct pqi_queue_group *queue_group)
5754{
5755        unsigned int path;
5756        unsigned long flags;
5757        bool list_is_empty;
5758
5759        for (path = 0; path < 2; path++) {
5760                while (1) {
5761                        spin_lock_irqsave(
5762                                &queue_group->submit_lock[path], flags);
5763                        list_is_empty =
5764                                list_empty(&queue_group->request_list[path]);
5765                        spin_unlock_irqrestore(
5766                                &queue_group->submit_lock[path], flags);
5767                        if (list_is_empty)
5768                                break;
5769                        pqi_check_ctrl_health(ctrl_info);
5770                        if (pqi_ctrl_offline(ctrl_info))
5771                                return -ENXIO;
5772                        usleep_range(1000, 2000);
5773                }
5774        }
5775
5776        return 0;
5777}
5778
5779static int pqi_wait_until_inbound_queues_empty(struct pqi_ctrl_info *ctrl_info)
5780{
5781        int rc;
5782        unsigned int i;
5783        unsigned int path;
5784        struct pqi_queue_group *queue_group;
5785        pqi_index_t iq_pi;
5786        pqi_index_t iq_ci;
5787
5788        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5789                queue_group = &ctrl_info->queue_groups[i];
5790
5791                rc = pqi_wait_until_queued_io_drained(ctrl_info, queue_group);
5792                if (rc)
5793                        return rc;
5794
5795                for (path = 0; path < 2; path++) {
5796                        iq_pi = queue_group->iq_pi_copy[path];
5797
5798                        while (1) {
5799                                iq_ci = readl(queue_group->iq_ci[path]);
5800                                if (iq_ci == iq_pi)
5801                                        break;
5802                                pqi_check_ctrl_health(ctrl_info);
5803                                if (pqi_ctrl_offline(ctrl_info))
5804                                        return -ENXIO;
5805                                usleep_range(1000, 2000);
5806                        }
5807                }
5808        }
5809
5810        return 0;
5811}
5812
5813static void pqi_fail_io_queued_for_device(struct pqi_ctrl_info *ctrl_info,
5814        struct pqi_scsi_dev *device)
5815{
5816        unsigned int i;
5817        unsigned int path;
5818        struct pqi_queue_group *queue_group;
5819        unsigned long flags;
5820        struct pqi_io_request *io_request;
5821        struct pqi_io_request *next;
5822        struct scsi_cmnd *scmd;
5823        struct pqi_scsi_dev *scsi_device;
5824
5825        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
5826                queue_group = &ctrl_info->queue_groups[i];
5827
5828                for (path = 0; path < 2; path++) {
5829                        spin_lock_irqsave(
5830                                &queue_group->submit_lock[path], flags);
5831
5832                        list_for_each_entry_safe(io_request, next,
5833                                &queue_group->request_list[path],
5834                                request_list_entry) {
5835
5836                                scmd = io_request->scmd;
5837                                if (!scmd)
5838                                        continue;
5839
5840                                scsi_device = scmd->device->hostdata;
5841                                if (scsi_device != device)
5842                                        continue;
5843
5844                                list_del(&io_request->request_list_entry);
5845                                set_host_byte(scmd, DID_RESET);
5846                                pqi_free_io_request(io_request);
5847                                scsi_dma_unmap(scmd);
5848                                pqi_scsi_done(scmd);
5849                        }
5850
5851                        spin_unlock_irqrestore(
5852                                &queue_group->submit_lock[path], flags);
5853                }
5854        }
5855}
5856
5857#define PQI_PENDING_IO_WARNING_TIMEOUT_SECS     10
5858
5859static int pqi_device_wait_for_pending_io(struct pqi_ctrl_info *ctrl_info,
5860        struct pqi_scsi_dev *device, unsigned long timeout_msecs)
5861{
5862        int cmds_outstanding;
5863        unsigned long start_jiffies;
5864        unsigned long warning_timeout;
5865        unsigned long msecs_waiting;
5866
5867        start_jiffies = jiffies;
5868        warning_timeout = (PQI_PENDING_IO_WARNING_TIMEOUT_SECS * PQI_HZ) + start_jiffies;
5869
5870        while ((cmds_outstanding = atomic_read(&device->scsi_cmds_outstanding)) > 0) {
5871                pqi_check_ctrl_health(ctrl_info);
5872                if (pqi_ctrl_offline(ctrl_info))
5873                        return -ENXIO;
5874                msecs_waiting = jiffies_to_msecs(jiffies - start_jiffies);
5875                if (msecs_waiting > timeout_msecs) {
5876                        dev_err(&ctrl_info->pci_dev->dev,
5877                                "scsi %d:%d:%d:%d: timed out after %lu seconds waiting for %d outstanding command(s)\n",
5878                                ctrl_info->scsi_host->host_no, device->bus, device->target,
5879                                device->lun, msecs_waiting / 1000, cmds_outstanding);
5880                        return -ETIMEDOUT;
5881                }
5882                if (time_after(jiffies, warning_timeout)) {
5883                        dev_warn(&ctrl_info->pci_dev->dev,
5884                                "scsi %d:%d:%d:%d: waiting %lu seconds for %d outstanding command(s)\n",
5885                                ctrl_info->scsi_host->host_no, device->bus, device->target,
5886                                device->lun, msecs_waiting / 1000, cmds_outstanding);
5887                        warning_timeout = (PQI_PENDING_IO_WARNING_TIMEOUT_SECS * PQI_HZ) + jiffies;
5888                }
5889                usleep_range(1000, 2000);
5890        }
5891
5892        return 0;
5893}
5894
5895static void pqi_lun_reset_complete(struct pqi_io_request *io_request,
5896        void *context)
5897{
5898        struct completion *waiting = context;
5899
5900        complete(waiting);
5901}
5902
5903#define PQI_LUN_RESET_POLL_COMPLETION_SECS      10
5904
5905static int pqi_wait_for_lun_reset_completion(struct pqi_ctrl_info *ctrl_info,
5906        struct pqi_scsi_dev *device, struct completion *wait)
5907{
5908        int rc;
5909        unsigned int wait_secs;
5910
5911        wait_secs = 0;
5912
5913        while (1) {
5914                if (wait_for_completion_io_timeout(wait,
5915                        PQI_LUN_RESET_POLL_COMPLETION_SECS * PQI_HZ)) {
5916                        rc = 0;
5917                        break;
5918                }
5919
5920                pqi_check_ctrl_health(ctrl_info);
5921                if (pqi_ctrl_offline(ctrl_info)) {
5922                        rc = -ENXIO;
5923                        break;
5924                }
5925
5926                wait_secs += PQI_LUN_RESET_POLL_COMPLETION_SECS;
5927
5928                dev_warn(&ctrl_info->pci_dev->dev,
5929                        "scsi %d:%d:%d:%d: waiting %u seconds for LUN reset to complete\n",
5930                        ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun,
5931                        wait_secs);
5932        }
5933
5934        return rc;
5935}
5936
5937#define PQI_LUN_RESET_FIRMWARE_TIMEOUT_SECS     30
5938
5939static int pqi_lun_reset(struct pqi_ctrl_info *ctrl_info, struct pqi_scsi_dev *device)
5940{
5941        int rc;
5942        struct pqi_io_request *io_request;
5943        DECLARE_COMPLETION_ONSTACK(wait);
5944        struct pqi_task_management_request *request;
5945
5946        io_request = pqi_alloc_io_request(ctrl_info);
5947        io_request->io_complete_callback = pqi_lun_reset_complete;
5948        io_request->context = &wait;
5949
5950        request = io_request->iu;
5951        memset(request, 0, sizeof(*request));
5952
5953        request->header.iu_type = PQI_REQUEST_IU_TASK_MANAGEMENT;
5954        put_unaligned_le16(sizeof(*request) - PQI_REQUEST_HEADER_LENGTH,
5955                &request->header.iu_length);
5956        put_unaligned_le16(io_request->index, &request->request_id);
5957        memcpy(request->lun_number, device->scsi3addr,
5958                sizeof(request->lun_number));
5959        request->task_management_function = SOP_TASK_MANAGEMENT_LUN_RESET;
5960        if (ctrl_info->tmf_iu_timeout_supported)
5961                put_unaligned_le16(PQI_LUN_RESET_FIRMWARE_TIMEOUT_SECS, &request->timeout);
5962
5963        pqi_start_io(ctrl_info, &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP], RAID_PATH,
5964                io_request);
5965
5966        rc = pqi_wait_for_lun_reset_completion(ctrl_info, device, &wait);
5967        if (rc == 0)
5968                rc = io_request->status;
5969
5970        pqi_free_io_request(io_request);
5971
5972        return rc;
5973}
5974
5975#define PQI_LUN_RESET_RETRIES                           3
5976#define PQI_LUN_RESET_RETRY_INTERVAL_MSECS              (10 * 1000)
5977#define PQI_LUN_RESET_PENDING_IO_TIMEOUT_MSECS          (10 * 60 * 1000)
5978#define PQI_LUN_RESET_FAILED_PENDING_IO_TIMEOUT_MSECS   (2 * 60 * 1000)
5979
5980static int pqi_lun_reset_with_retries(struct pqi_ctrl_info *ctrl_info, struct pqi_scsi_dev *device)
5981{
5982        int reset_rc;
5983        int wait_rc;
5984        unsigned int retries;
5985        unsigned long timeout_msecs;
5986
5987        for (retries = 0;;) {
5988                reset_rc = pqi_lun_reset(ctrl_info, device);
5989                if (reset_rc == 0 || ++retries > PQI_LUN_RESET_RETRIES)
5990                        break;
5991                msleep(PQI_LUN_RESET_RETRY_INTERVAL_MSECS);
5992        }
5993
5994        timeout_msecs = reset_rc ? PQI_LUN_RESET_FAILED_PENDING_IO_TIMEOUT_MSECS :
5995                PQI_LUN_RESET_PENDING_IO_TIMEOUT_MSECS;
5996
5997        wait_rc = pqi_device_wait_for_pending_io(ctrl_info, device, timeout_msecs);
5998        if (wait_rc && reset_rc == 0)
5999                reset_rc = wait_rc;
6000
6001        return reset_rc == 0 ? SUCCESS : FAILED;
6002}
6003
6004static int pqi_device_reset(struct pqi_ctrl_info *ctrl_info,
6005        struct pqi_scsi_dev *device)
6006{
6007        int rc;
6008
6009        pqi_ctrl_block_requests(ctrl_info);
6010        pqi_ctrl_wait_until_quiesced(ctrl_info);
6011        pqi_fail_io_queued_for_device(ctrl_info, device);
6012        rc = pqi_wait_until_inbound_queues_empty(ctrl_info);
6013        if (rc)
6014                rc = FAILED;
6015        else
6016                rc = pqi_lun_reset_with_retries(ctrl_info, device);
6017        pqi_ctrl_unblock_requests(ctrl_info);
6018
6019        return rc;
6020}
6021
6022static int pqi_eh_device_reset_handler(struct scsi_cmnd *scmd)
6023{
6024        int rc;
6025        struct Scsi_Host *shost;
6026        struct pqi_ctrl_info *ctrl_info;
6027        struct pqi_scsi_dev *device;
6028
6029        shost = scmd->device->host;
6030        ctrl_info = shost_to_hba(shost);
6031        device = scmd->device->hostdata;
6032
6033        mutex_lock(&ctrl_info->lun_reset_mutex);
6034
6035        dev_err(&ctrl_info->pci_dev->dev,
6036                "resetting scsi %d:%d:%d:%d due to cmd 0x%02x\n",
6037                shost->host_no,
6038                device->bus, device->target, device->lun,
6039                scmd->cmd_len > 0 ? scmd->cmnd[0] : 0xff);
6040
6041        pqi_check_ctrl_health(ctrl_info);
6042        if (pqi_ctrl_offline(ctrl_info))
6043                rc = FAILED;
6044        else
6045                rc = pqi_device_reset(ctrl_info, device);
6046
6047        dev_err(&ctrl_info->pci_dev->dev,
6048                "reset of scsi %d:%d:%d:%d: %s\n",
6049                shost->host_no, device->bus, device->target, device->lun,
6050                rc == SUCCESS ? "SUCCESS" : "FAILED");
6051
6052        mutex_unlock(&ctrl_info->lun_reset_mutex);
6053
6054        return rc;
6055}
6056
6057static int pqi_slave_alloc(struct scsi_device *sdev)
6058{
6059        struct pqi_scsi_dev *device;
6060        unsigned long flags;
6061        struct pqi_ctrl_info *ctrl_info;
6062        struct scsi_target *starget;
6063        struct sas_rphy *rphy;
6064
6065        ctrl_info = shost_to_hba(sdev->host);
6066
6067        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6068
6069        if (sdev_channel(sdev) == PQI_PHYSICAL_DEVICE_BUS) {
6070                starget = scsi_target(sdev);
6071                rphy = target_to_rphy(starget);
6072                device = pqi_find_device_by_sas_rphy(ctrl_info, rphy);
6073                if (device) {
6074                        device->target = sdev_id(sdev);
6075                        device->lun = sdev->lun;
6076                        device->target_lun_valid = true;
6077                }
6078        } else {
6079                device = pqi_find_scsi_dev(ctrl_info, sdev_channel(sdev),
6080                        sdev_id(sdev), sdev->lun);
6081        }
6082
6083        if (device) {
6084                sdev->hostdata = device;
6085                device->sdev = sdev;
6086                if (device->queue_depth) {
6087                        device->advertised_queue_depth = device->queue_depth;
6088                        scsi_change_queue_depth(sdev,
6089                                device->advertised_queue_depth);
6090                }
6091                if (pqi_is_logical_device(device)) {
6092                        pqi_disable_write_same(sdev);
6093                } else {
6094                        sdev->allow_restart = 1;
6095                        if (device->device_type == SA_DEVICE_TYPE_NVME)
6096                                pqi_disable_write_same(sdev);
6097                }
6098        }
6099
6100        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6101
6102        return 0;
6103}
6104
6105static int pqi_map_queues(struct Scsi_Host *shost)
6106{
6107        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6108
6109        return blk_mq_pci_map_queues(&shost->tag_set.map[HCTX_TYPE_DEFAULT],
6110                                        ctrl_info->pci_dev, 0);
6111}
6112
6113static int pqi_slave_configure(struct scsi_device *sdev)
6114{
6115        struct pqi_scsi_dev *device;
6116
6117        device = sdev->hostdata;
6118        device->devtype = sdev->type;
6119
6120        return 0;
6121}
6122
6123static void pqi_slave_destroy(struct scsi_device *sdev)
6124{
6125        unsigned long flags;
6126        struct pqi_scsi_dev *device;
6127        struct pqi_ctrl_info *ctrl_info;
6128
6129        ctrl_info = shost_to_hba(sdev->host);
6130
6131        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6132
6133        device = sdev->hostdata;
6134        if (device) {
6135                sdev->hostdata = NULL;
6136                if (!list_empty(&device->scsi_device_list_entry))
6137                        list_del(&device->scsi_device_list_entry);
6138        }
6139
6140        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6141
6142        if (device) {
6143                pqi_dev_info(ctrl_info, "removed", device);
6144                pqi_free_device(device);
6145        }
6146}
6147
6148static int pqi_getpciinfo_ioctl(struct pqi_ctrl_info *ctrl_info, void __user *arg)
6149{
6150        struct pci_dev *pci_dev;
6151        u32 subsystem_vendor;
6152        u32 subsystem_device;
6153        cciss_pci_info_struct pciinfo;
6154
6155        if (!arg)
6156                return -EINVAL;
6157
6158        pci_dev = ctrl_info->pci_dev;
6159
6160        pciinfo.domain = pci_domain_nr(pci_dev->bus);
6161        pciinfo.bus = pci_dev->bus->number;
6162        pciinfo.dev_fn = pci_dev->devfn;
6163        subsystem_vendor = pci_dev->subsystem_vendor;
6164        subsystem_device = pci_dev->subsystem_device;
6165        pciinfo.board_id = ((subsystem_device << 16) & 0xffff0000) | subsystem_vendor;
6166
6167        if (copy_to_user(arg, &pciinfo, sizeof(pciinfo)))
6168                return -EFAULT;
6169
6170        return 0;
6171}
6172
6173static int pqi_getdrivver_ioctl(void __user *arg)
6174{
6175        u32 version;
6176
6177        if (!arg)
6178                return -EINVAL;
6179
6180        version = (DRIVER_MAJOR << 28) | (DRIVER_MINOR << 24) |
6181                (DRIVER_RELEASE << 16) | DRIVER_REVISION;
6182
6183        if (copy_to_user(arg, &version, sizeof(version)))
6184                return -EFAULT;
6185
6186        return 0;
6187}
6188
6189struct ciss_error_info {
6190        u8      scsi_status;
6191        int     command_status;
6192        size_t  sense_data_length;
6193};
6194
6195static void pqi_error_info_to_ciss(struct pqi_raid_error_info *pqi_error_info,
6196        struct ciss_error_info *ciss_error_info)
6197{
6198        int ciss_cmd_status;
6199        size_t sense_data_length;
6200
6201        switch (pqi_error_info->data_out_result) {
6202        case PQI_DATA_IN_OUT_GOOD:
6203                ciss_cmd_status = CISS_CMD_STATUS_SUCCESS;
6204                break;
6205        case PQI_DATA_IN_OUT_UNDERFLOW:
6206                ciss_cmd_status = CISS_CMD_STATUS_DATA_UNDERRUN;
6207                break;
6208        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
6209                ciss_cmd_status = CISS_CMD_STATUS_DATA_OVERRUN;
6210                break;
6211        case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
6212        case PQI_DATA_IN_OUT_BUFFER_ERROR:
6213        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
6214        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
6215        case PQI_DATA_IN_OUT_ERROR:
6216                ciss_cmd_status = CISS_CMD_STATUS_PROTOCOL_ERROR;
6217                break;
6218        case PQI_DATA_IN_OUT_HARDWARE_ERROR:
6219        case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
6220        case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
6221        case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
6222        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
6223        case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
6224        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
6225        case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
6226        case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
6227        case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
6228                ciss_cmd_status = CISS_CMD_STATUS_HARDWARE_ERROR;
6229                break;
6230        case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
6231                ciss_cmd_status = CISS_CMD_STATUS_UNSOLICITED_ABORT;
6232                break;
6233        case PQI_DATA_IN_OUT_ABORTED:
6234                ciss_cmd_status = CISS_CMD_STATUS_ABORTED;
6235                break;
6236        case PQI_DATA_IN_OUT_TIMEOUT:
6237                ciss_cmd_status = CISS_CMD_STATUS_TIMEOUT;
6238                break;
6239        default:
6240                ciss_cmd_status = CISS_CMD_STATUS_TARGET_STATUS;
6241                break;
6242        }
6243
6244        sense_data_length =
6245                get_unaligned_le16(&pqi_error_info->sense_data_length);
6246        if (sense_data_length == 0)
6247                sense_data_length =
6248                get_unaligned_le16(&pqi_error_info->response_data_length);
6249        if (sense_data_length)
6250                if (sense_data_length > sizeof(pqi_error_info->data))
6251                        sense_data_length = sizeof(pqi_error_info->data);
6252
6253        ciss_error_info->scsi_status = pqi_error_info->status;
6254        ciss_error_info->command_status = ciss_cmd_status;
6255        ciss_error_info->sense_data_length = sense_data_length;
6256}
6257
6258static int pqi_passthru_ioctl(struct pqi_ctrl_info *ctrl_info, void __user *arg)
6259{
6260        int rc;
6261        char *kernel_buffer = NULL;
6262        u16 iu_length;
6263        size_t sense_data_length;
6264        IOCTL_Command_struct iocommand;
6265        struct pqi_raid_path_request request;
6266        struct pqi_raid_error_info pqi_error_info;
6267        struct ciss_error_info ciss_error_info;
6268
6269        if (pqi_ctrl_offline(ctrl_info))
6270                return -ENXIO;
6271        if (pqi_ofa_in_progress(ctrl_info) && pqi_ctrl_blocked(ctrl_info))
6272                return -EBUSY;
6273        if (!arg)
6274                return -EINVAL;
6275        if (!capable(CAP_SYS_RAWIO))
6276                return -EPERM;
6277        if (copy_from_user(&iocommand, arg, sizeof(iocommand)))
6278                return -EFAULT;
6279        if (iocommand.buf_size < 1 &&
6280                iocommand.Request.Type.Direction != XFER_NONE)
6281                return -EINVAL;
6282        if (iocommand.Request.CDBLen > sizeof(request.cdb))
6283                return -EINVAL;
6284        if (iocommand.Request.Type.Type != TYPE_CMD)
6285                return -EINVAL;
6286
6287        switch (iocommand.Request.Type.Direction) {
6288        case XFER_NONE:
6289        case XFER_WRITE:
6290        case XFER_READ:
6291        case XFER_READ | XFER_WRITE:
6292                break;
6293        default:
6294                return -EINVAL;
6295        }
6296
6297        if (iocommand.buf_size > 0) {
6298                kernel_buffer = kmalloc(iocommand.buf_size, GFP_KERNEL);
6299                if (!kernel_buffer)
6300                        return -ENOMEM;
6301                if (iocommand.Request.Type.Direction & XFER_WRITE) {
6302                        if (copy_from_user(kernel_buffer, iocommand.buf,
6303                                iocommand.buf_size)) {
6304                                rc = -EFAULT;
6305                                goto out;
6306                        }
6307                } else {
6308                        memset(kernel_buffer, 0, iocommand.buf_size);
6309                }
6310        }
6311
6312        memset(&request, 0, sizeof(request));
6313
6314        request.header.iu_type = PQI_REQUEST_IU_RAID_PATH_IO;
6315        iu_length = offsetof(struct pqi_raid_path_request, sg_descriptors) -
6316                PQI_REQUEST_HEADER_LENGTH;
6317        memcpy(request.lun_number, iocommand.LUN_info.LunAddrBytes,
6318                sizeof(request.lun_number));
6319        memcpy(request.cdb, iocommand.Request.CDB, iocommand.Request.CDBLen);
6320        request.additional_cdb_bytes_usage = SOP_ADDITIONAL_CDB_BYTES_0;
6321
6322        switch (iocommand.Request.Type.Direction) {
6323        case XFER_NONE:
6324                request.data_direction = SOP_NO_DIRECTION_FLAG;
6325                break;
6326        case XFER_WRITE:
6327                request.data_direction = SOP_WRITE_FLAG;
6328                break;
6329        case XFER_READ:
6330                request.data_direction = SOP_READ_FLAG;
6331                break;
6332        case XFER_READ | XFER_WRITE:
6333                request.data_direction = SOP_BIDIRECTIONAL;
6334                break;
6335        }
6336
6337        request.task_attribute = SOP_TASK_ATTRIBUTE_SIMPLE;
6338
6339        if (iocommand.buf_size > 0) {
6340                put_unaligned_le32(iocommand.buf_size, &request.buffer_length);
6341
6342                rc = pqi_map_single(ctrl_info->pci_dev,
6343                        &request.sg_descriptors[0], kernel_buffer,
6344                        iocommand.buf_size, DMA_BIDIRECTIONAL);
6345                if (rc)
6346                        goto out;
6347
6348                iu_length += sizeof(request.sg_descriptors[0]);
6349        }
6350
6351        put_unaligned_le16(iu_length, &request.header.iu_length);
6352
6353        if (ctrl_info->raid_iu_timeout_supported)
6354                put_unaligned_le32(iocommand.Request.Timeout, &request.timeout);
6355
6356        rc = pqi_submit_raid_request_synchronous(ctrl_info, &request.header,
6357                PQI_SYNC_FLAGS_INTERRUPTABLE, &pqi_error_info);
6358
6359        if (iocommand.buf_size > 0)
6360                pqi_pci_unmap(ctrl_info->pci_dev, request.sg_descriptors, 1,
6361                        DMA_BIDIRECTIONAL);
6362
6363        memset(&iocommand.error_info, 0, sizeof(iocommand.error_info));
6364
6365        if (rc == 0) {
6366                pqi_error_info_to_ciss(&pqi_error_info, &ciss_error_info);
6367                iocommand.error_info.ScsiStatus = ciss_error_info.scsi_status;
6368                iocommand.error_info.CommandStatus =
6369                        ciss_error_info.command_status;
6370                sense_data_length = ciss_error_info.sense_data_length;
6371                if (sense_data_length) {
6372                        if (sense_data_length >
6373                                sizeof(iocommand.error_info.SenseInfo))
6374                                sense_data_length =
6375                                        sizeof(iocommand.error_info.SenseInfo);
6376                        memcpy(iocommand.error_info.SenseInfo,
6377                                pqi_error_info.data, sense_data_length);
6378                        iocommand.error_info.SenseLen = sense_data_length;
6379                }
6380        }
6381
6382        if (copy_to_user(arg, &iocommand, sizeof(iocommand))) {
6383                rc = -EFAULT;
6384                goto out;
6385        }
6386
6387        if (rc == 0 && iocommand.buf_size > 0 &&
6388                (iocommand.Request.Type.Direction & XFER_READ)) {
6389                if (copy_to_user(iocommand.buf, kernel_buffer,
6390                        iocommand.buf_size)) {
6391                        rc = -EFAULT;
6392                }
6393        }
6394
6395out:
6396        kfree(kernel_buffer);
6397
6398        return rc;
6399}
6400
6401static int pqi_ioctl(struct scsi_device *sdev, unsigned int cmd,
6402                     void __user *arg)
6403{
6404        int rc;
6405        struct pqi_ctrl_info *ctrl_info;
6406
6407        ctrl_info = shost_to_hba(sdev->host);
6408
6409        switch (cmd) {
6410        case CCISS_DEREGDISK:
6411        case CCISS_REGNEWDISK:
6412        case CCISS_REGNEWD:
6413                rc = pqi_scan_scsi_devices(ctrl_info);
6414                break;
6415        case CCISS_GETPCIINFO:
6416                rc = pqi_getpciinfo_ioctl(ctrl_info, arg);
6417                break;
6418        case CCISS_GETDRIVVER:
6419                rc = pqi_getdrivver_ioctl(arg);
6420                break;
6421        case CCISS_PASSTHRU:
6422                rc = pqi_passthru_ioctl(ctrl_info, arg);
6423                break;
6424        default:
6425                rc = -EINVAL;
6426                break;
6427        }
6428
6429        return rc;
6430}
6431
6432static ssize_t pqi_firmware_version_show(struct device *dev,
6433        struct device_attribute *attr, char *buffer)
6434{
6435        struct Scsi_Host *shost;
6436        struct pqi_ctrl_info *ctrl_info;
6437
6438        shost = class_to_shost(dev);
6439        ctrl_info = shost_to_hba(shost);
6440
6441        return scnprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->firmware_version);
6442}
6443
6444static ssize_t pqi_driver_version_show(struct device *dev,
6445        struct device_attribute *attr, char *buffer)
6446{
6447        return scnprintf(buffer, PAGE_SIZE, "%s\n", DRIVER_VERSION BUILD_TIMESTAMP);
6448}
6449
6450static ssize_t pqi_serial_number_show(struct device *dev,
6451        struct device_attribute *attr, char *buffer)
6452{
6453        struct Scsi_Host *shost;
6454        struct pqi_ctrl_info *ctrl_info;
6455
6456        shost = class_to_shost(dev);
6457        ctrl_info = shost_to_hba(shost);
6458
6459        return scnprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->serial_number);
6460}
6461
6462static ssize_t pqi_model_show(struct device *dev,
6463        struct device_attribute *attr, char *buffer)
6464{
6465        struct Scsi_Host *shost;
6466        struct pqi_ctrl_info *ctrl_info;
6467
6468        shost = class_to_shost(dev);
6469        ctrl_info = shost_to_hba(shost);
6470
6471        return scnprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->model);
6472}
6473
6474static ssize_t pqi_vendor_show(struct device *dev,
6475        struct device_attribute *attr, char *buffer)
6476{
6477        struct Scsi_Host *shost;
6478        struct pqi_ctrl_info *ctrl_info;
6479
6480        shost = class_to_shost(dev);
6481        ctrl_info = shost_to_hba(shost);
6482
6483        return scnprintf(buffer, PAGE_SIZE, "%s\n", ctrl_info->vendor);
6484}
6485
6486static ssize_t pqi_host_rescan_store(struct device *dev,
6487        struct device_attribute *attr, const char *buffer, size_t count)
6488{
6489        struct Scsi_Host *shost = class_to_shost(dev);
6490
6491        pqi_scan_start(shost);
6492
6493        return count;
6494}
6495
6496static ssize_t pqi_lockup_action_show(struct device *dev,
6497        struct device_attribute *attr, char *buffer)
6498{
6499        int count = 0;
6500        unsigned int i;
6501
6502        for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
6503                if (pqi_lockup_actions[i].action == pqi_lockup_action)
6504                        count += scnprintf(buffer + count, PAGE_SIZE - count,
6505                                "[%s] ", pqi_lockup_actions[i].name);
6506                else
6507                        count += scnprintf(buffer + count, PAGE_SIZE - count,
6508                                "%s ", pqi_lockup_actions[i].name);
6509        }
6510
6511        count += scnprintf(buffer + count, PAGE_SIZE - count, "\n");
6512
6513        return count;
6514}
6515
6516static ssize_t pqi_lockup_action_store(struct device *dev,
6517        struct device_attribute *attr, const char *buffer, size_t count)
6518{
6519        unsigned int i;
6520        char *action_name;
6521        char action_name_buffer[32];
6522
6523        strlcpy(action_name_buffer, buffer, sizeof(action_name_buffer));
6524        action_name = strstrip(action_name_buffer);
6525
6526        for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
6527                if (strcmp(action_name, pqi_lockup_actions[i].name) == 0) {
6528                        pqi_lockup_action = pqi_lockup_actions[i].action;
6529                        return count;
6530                }
6531        }
6532
6533        return -EINVAL;
6534}
6535
6536static ssize_t pqi_host_enable_stream_detection_show(struct device *dev,
6537        struct device_attribute *attr, char *buffer)
6538{
6539        struct Scsi_Host *shost = class_to_shost(dev);
6540        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6541
6542        return scnprintf(buffer, 10, "%x\n",
6543                        ctrl_info->enable_stream_detection);
6544}
6545
6546static ssize_t pqi_host_enable_stream_detection_store(struct device *dev,
6547        struct device_attribute *attr, const char *buffer, size_t count)
6548{
6549        struct Scsi_Host *shost = class_to_shost(dev);
6550        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6551        u8 set_stream_detection = 0;
6552
6553        if (kstrtou8(buffer, 0, &set_stream_detection))
6554                return -EINVAL;
6555
6556        if (set_stream_detection > 0)
6557                set_stream_detection = 1;
6558
6559        ctrl_info->enable_stream_detection = set_stream_detection;
6560
6561        return count;
6562}
6563
6564static ssize_t pqi_host_enable_r5_writes_show(struct device *dev,
6565        struct device_attribute *attr, char *buffer)
6566{
6567        struct Scsi_Host *shost = class_to_shost(dev);
6568        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6569
6570        return scnprintf(buffer, 10, "%x\n", ctrl_info->enable_r5_writes);
6571}
6572
6573static ssize_t pqi_host_enable_r5_writes_store(struct device *dev,
6574        struct device_attribute *attr, const char *buffer, size_t count)
6575{
6576        struct Scsi_Host *shost = class_to_shost(dev);
6577        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6578        u8 set_r5_writes = 0;
6579
6580        if (kstrtou8(buffer, 0, &set_r5_writes))
6581                return -EINVAL;
6582
6583        if (set_r5_writes > 0)
6584                set_r5_writes = 1;
6585
6586        ctrl_info->enable_r5_writes = set_r5_writes;
6587
6588        return count;
6589}
6590
6591static ssize_t pqi_host_enable_r6_writes_show(struct device *dev,
6592        struct device_attribute *attr, char *buffer)
6593{
6594        struct Scsi_Host *shost = class_to_shost(dev);
6595        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6596
6597        return scnprintf(buffer, 10, "%x\n", ctrl_info->enable_r6_writes);
6598}
6599
6600static ssize_t pqi_host_enable_r6_writes_store(struct device *dev,
6601        struct device_attribute *attr, const char *buffer, size_t count)
6602{
6603        struct Scsi_Host *shost = class_to_shost(dev);
6604        struct pqi_ctrl_info *ctrl_info = shost_to_hba(shost);
6605        u8 set_r6_writes = 0;
6606
6607        if (kstrtou8(buffer, 0, &set_r6_writes))
6608                return -EINVAL;
6609
6610        if (set_r6_writes > 0)
6611                set_r6_writes = 1;
6612
6613        ctrl_info->enable_r6_writes = set_r6_writes;
6614
6615        return count;
6616}
6617
6618static DEVICE_ATTR(driver_version, 0444, pqi_driver_version_show, NULL);
6619static DEVICE_ATTR(firmware_version, 0444, pqi_firmware_version_show, NULL);
6620static DEVICE_ATTR(model, 0444, pqi_model_show, NULL);
6621static DEVICE_ATTR(serial_number, 0444, pqi_serial_number_show, NULL);
6622static DEVICE_ATTR(vendor, 0444, pqi_vendor_show, NULL);
6623static DEVICE_ATTR(rescan, 0200, NULL, pqi_host_rescan_store);
6624static DEVICE_ATTR(lockup_action, 0644, pqi_lockup_action_show,
6625        pqi_lockup_action_store);
6626static DEVICE_ATTR(enable_stream_detection, 0644,
6627        pqi_host_enable_stream_detection_show,
6628        pqi_host_enable_stream_detection_store);
6629static DEVICE_ATTR(enable_r5_writes, 0644,
6630        pqi_host_enable_r5_writes_show, pqi_host_enable_r5_writes_store);
6631static DEVICE_ATTR(enable_r6_writes, 0644,
6632        pqi_host_enable_r6_writes_show, pqi_host_enable_r6_writes_store);
6633
6634static struct device_attribute *pqi_shost_attrs[] = {
6635        &dev_attr_driver_version,
6636        &dev_attr_firmware_version,
6637        &dev_attr_model,
6638        &dev_attr_serial_number,
6639        &dev_attr_vendor,
6640        &dev_attr_rescan,
6641        &dev_attr_lockup_action,
6642        &dev_attr_enable_stream_detection,
6643        &dev_attr_enable_r5_writes,
6644        &dev_attr_enable_r6_writes,
6645        NULL
6646};
6647
6648static ssize_t pqi_unique_id_show(struct device *dev,
6649        struct device_attribute *attr, char *buffer)
6650{
6651        struct pqi_ctrl_info *ctrl_info;
6652        struct scsi_device *sdev;
6653        struct pqi_scsi_dev *device;
6654        unsigned long flags;
6655        u8 unique_id[16];
6656
6657        sdev = to_scsi_device(dev);
6658        ctrl_info = shost_to_hba(sdev->host);
6659
6660        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6661
6662        device = sdev->hostdata;
6663        if (!device) {
6664                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6665                return -ENODEV;
6666        }
6667
6668        if (device->is_physical_device) {
6669                memset(unique_id, 0, 8);
6670                memcpy(unique_id + 8, &device->wwid, sizeof(device->wwid));
6671        } else {
6672                memcpy(unique_id, device->volume_id, sizeof(device->volume_id));
6673        }
6674
6675        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6676
6677        return scnprintf(buffer, PAGE_SIZE,
6678                "%02X%02X%02X%02X%02X%02X%02X%02X"
6679                "%02X%02X%02X%02X%02X%02X%02X%02X\n",
6680                unique_id[0], unique_id[1], unique_id[2], unique_id[3],
6681                unique_id[4], unique_id[5], unique_id[6], unique_id[7],
6682                unique_id[8], unique_id[9], unique_id[10], unique_id[11],
6683                unique_id[12], unique_id[13], unique_id[14], unique_id[15]);
6684}
6685
6686static ssize_t pqi_lunid_show(struct device *dev,
6687        struct device_attribute *attr, char *buffer)
6688{
6689        struct pqi_ctrl_info *ctrl_info;
6690        struct scsi_device *sdev;
6691        struct pqi_scsi_dev *device;
6692        unsigned long flags;
6693        u8 lunid[8];
6694
6695        sdev = to_scsi_device(dev);
6696        ctrl_info = shost_to_hba(sdev->host);
6697
6698        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6699
6700        device = sdev->hostdata;
6701        if (!device) {
6702                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6703                return -ENODEV;
6704        }
6705
6706        memcpy(lunid, device->scsi3addr, sizeof(lunid));
6707
6708        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6709
6710        return scnprintf(buffer, PAGE_SIZE, "0x%8phN\n", lunid);
6711}
6712
6713#define MAX_PATHS       8
6714
6715static ssize_t pqi_path_info_show(struct device *dev,
6716        struct device_attribute *attr, char *buf)
6717{
6718        struct pqi_ctrl_info *ctrl_info;
6719        struct scsi_device *sdev;
6720        struct pqi_scsi_dev *device;
6721        unsigned long flags;
6722        int i;
6723        int output_len = 0;
6724        u8 box;
6725        u8 bay;
6726        u8 path_map_index;
6727        char *active;
6728        u8 phys_connector[2];
6729
6730        sdev = to_scsi_device(dev);
6731        ctrl_info = shost_to_hba(sdev->host);
6732
6733        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6734
6735        device = sdev->hostdata;
6736        if (!device) {
6737                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6738                return -ENODEV;
6739        }
6740
6741        bay = device->bay;
6742        for (i = 0; i < MAX_PATHS; i++) {
6743                path_map_index = 1 << i;
6744                if (i == device->active_path_index)
6745                        active = "Active";
6746                else if (device->path_map & path_map_index)
6747                        active = "Inactive";
6748                else
6749                        continue;
6750
6751                output_len += scnprintf(buf + output_len,
6752                                        PAGE_SIZE - output_len,
6753                                        "[%d:%d:%d:%d] %20.20s ",
6754                                        ctrl_info->scsi_host->host_no,
6755                                        device->bus, device->target,
6756                                        device->lun,
6757                                        scsi_device_type(device->devtype));
6758
6759                if (device->devtype == TYPE_RAID ||
6760                        pqi_is_logical_device(device))
6761                        goto end_buffer;
6762
6763                memcpy(&phys_connector, &device->phys_connector[i],
6764                        sizeof(phys_connector));
6765                if (phys_connector[0] < '0')
6766                        phys_connector[0] = '0';
6767                if (phys_connector[1] < '0')
6768                        phys_connector[1] = '0';
6769
6770                output_len += scnprintf(buf + output_len,
6771                                        PAGE_SIZE - output_len,
6772                                        "PORT: %.2s ", phys_connector);
6773
6774                box = device->box[i];
6775                if (box != 0 && box != 0xFF)
6776                        output_len += scnprintf(buf + output_len,
6777                                                PAGE_SIZE - output_len,
6778                                                "BOX: %hhu ", box);
6779
6780                if ((device->devtype == TYPE_DISK ||
6781                        device->devtype == TYPE_ZBC) &&
6782                        pqi_expose_device(device))
6783                        output_len += scnprintf(buf + output_len,
6784                                                PAGE_SIZE - output_len,
6785                                                "BAY: %hhu ", bay);
6786
6787end_buffer:
6788                output_len += scnprintf(buf + output_len,
6789                                        PAGE_SIZE - output_len,
6790                                        "%s\n", active);
6791        }
6792
6793        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6794
6795        return output_len;
6796}
6797
6798static ssize_t pqi_sas_address_show(struct device *dev,
6799        struct device_attribute *attr, char *buffer)
6800{
6801        struct pqi_ctrl_info *ctrl_info;
6802        struct scsi_device *sdev;
6803        struct pqi_scsi_dev *device;
6804        unsigned long flags;
6805        u64 sas_address;
6806
6807        sdev = to_scsi_device(dev);
6808        ctrl_info = shost_to_hba(sdev->host);
6809
6810        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6811
6812        device = sdev->hostdata;
6813        if (!device || !pqi_is_device_with_sas_address(device)) {
6814                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6815                return -ENODEV;
6816        }
6817
6818        sas_address = device->sas_address;
6819
6820        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6821
6822        return scnprintf(buffer, PAGE_SIZE, "0x%016llx\n", sas_address);
6823}
6824
6825static ssize_t pqi_ssd_smart_path_enabled_show(struct device *dev,
6826        struct device_attribute *attr, char *buffer)
6827{
6828        struct pqi_ctrl_info *ctrl_info;
6829        struct scsi_device *sdev;
6830        struct pqi_scsi_dev *device;
6831        unsigned long flags;
6832
6833        sdev = to_scsi_device(dev);
6834        ctrl_info = shost_to_hba(sdev->host);
6835
6836        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6837
6838        device = sdev->hostdata;
6839        if (!device) {
6840                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6841                return -ENODEV;
6842        }
6843
6844        buffer[0] = device->raid_bypass_enabled ? '1' : '0';
6845        buffer[1] = '\n';
6846        buffer[2] = '\0';
6847
6848        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6849
6850        return 2;
6851}
6852
6853static ssize_t pqi_raid_level_show(struct device *dev,
6854        struct device_attribute *attr, char *buffer)
6855{
6856        struct pqi_ctrl_info *ctrl_info;
6857        struct scsi_device *sdev;
6858        struct pqi_scsi_dev *device;
6859        unsigned long flags;
6860        char *raid_level;
6861
6862        sdev = to_scsi_device(dev);
6863        ctrl_info = shost_to_hba(sdev->host);
6864
6865        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6866
6867        device = sdev->hostdata;
6868        if (!device) {
6869                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6870                return -ENODEV;
6871        }
6872
6873        if (pqi_is_logical_device(device))
6874                raid_level = pqi_raid_level_to_string(device->raid_level);
6875        else
6876                raid_level = "N/A";
6877
6878        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6879
6880        return scnprintf(buffer, PAGE_SIZE, "%s\n", raid_level);
6881}
6882
6883static ssize_t pqi_raid_bypass_cnt_show(struct device *dev,
6884        struct device_attribute *attr, char *buffer)
6885{
6886        struct pqi_ctrl_info *ctrl_info;
6887        struct scsi_device *sdev;
6888        struct pqi_scsi_dev *device;
6889        unsigned long flags;
6890        int raid_bypass_cnt;
6891
6892        sdev = to_scsi_device(dev);
6893        ctrl_info = shost_to_hba(sdev->host);
6894
6895        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
6896
6897        device = sdev->hostdata;
6898        if (!device) {
6899                spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6900                return -ENODEV;
6901        }
6902
6903        raid_bypass_cnt = atomic_read(&device->raid_bypass_cnt);
6904
6905        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
6906
6907        return scnprintf(buffer, PAGE_SIZE, "0x%x\n", raid_bypass_cnt);
6908}
6909
6910static DEVICE_ATTR(lunid, 0444, pqi_lunid_show, NULL);
6911static DEVICE_ATTR(unique_id, 0444, pqi_unique_id_show, NULL);
6912static DEVICE_ATTR(path_info, 0444, pqi_path_info_show, NULL);
6913static DEVICE_ATTR(sas_address, 0444, pqi_sas_address_show, NULL);
6914static DEVICE_ATTR(ssd_smart_path_enabled, 0444, pqi_ssd_smart_path_enabled_show, NULL);
6915static DEVICE_ATTR(raid_level, 0444, pqi_raid_level_show, NULL);
6916static DEVICE_ATTR(raid_bypass_cnt, 0444, pqi_raid_bypass_cnt_show, NULL);
6917
6918static struct device_attribute *pqi_sdev_attrs[] = {
6919        &dev_attr_lunid,
6920        &dev_attr_unique_id,
6921        &dev_attr_path_info,
6922        &dev_attr_sas_address,
6923        &dev_attr_ssd_smart_path_enabled,
6924        &dev_attr_raid_level,
6925        &dev_attr_raid_bypass_cnt,
6926        NULL
6927};
6928
6929static struct scsi_host_template pqi_driver_template = {
6930        .module = THIS_MODULE,
6931        .name = DRIVER_NAME_SHORT,
6932        .proc_name = DRIVER_NAME_SHORT,
6933        .queuecommand = pqi_scsi_queue_command,
6934        .scan_start = pqi_scan_start,
6935        .scan_finished = pqi_scan_finished,
6936        .this_id = -1,
6937        .eh_device_reset_handler = pqi_eh_device_reset_handler,
6938        .ioctl = pqi_ioctl,
6939        .slave_alloc = pqi_slave_alloc,
6940        .slave_configure = pqi_slave_configure,
6941        .slave_destroy = pqi_slave_destroy,
6942        .map_queues = pqi_map_queues,
6943        .sdev_attrs = pqi_sdev_attrs,
6944        .shost_attrs = pqi_shost_attrs,
6945};
6946
6947static int pqi_register_scsi(struct pqi_ctrl_info *ctrl_info)
6948{
6949        int rc;
6950        struct Scsi_Host *shost;
6951
6952        shost = scsi_host_alloc(&pqi_driver_template, sizeof(ctrl_info));
6953        if (!shost) {
6954                dev_err(&ctrl_info->pci_dev->dev, "scsi_host_alloc failed\n");
6955                return -ENOMEM;
6956        }
6957
6958        shost->io_port = 0;
6959        shost->n_io_port = 0;
6960        shost->this_id = -1;
6961        shost->max_channel = PQI_MAX_BUS;
6962        shost->max_cmd_len = MAX_COMMAND_SIZE;
6963        shost->max_lun = ~0;
6964        shost->max_id = ~0;
6965        shost->max_sectors = ctrl_info->max_sectors;
6966        shost->can_queue = ctrl_info->scsi_ml_can_queue;
6967        shost->cmd_per_lun = shost->can_queue;
6968        shost->sg_tablesize = ctrl_info->sg_tablesize;
6969        shost->transportt = pqi_sas_transport_template;
6970        shost->irq = pci_irq_vector(ctrl_info->pci_dev, 0);
6971        shost->unique_id = shost->irq;
6972        shost->nr_hw_queues = ctrl_info->num_queue_groups;
6973        shost->host_tagset = 1;
6974        shost->hostdata[0] = (unsigned long)ctrl_info;
6975
6976        rc = scsi_add_host(shost, &ctrl_info->pci_dev->dev);
6977        if (rc) {
6978                dev_err(&ctrl_info->pci_dev->dev, "scsi_add_host failed\n");
6979                goto free_host;
6980        }
6981
6982        rc = pqi_add_sas_host(shost, ctrl_info);
6983        if (rc) {
6984                dev_err(&ctrl_info->pci_dev->dev, "add SAS host failed\n");
6985                goto remove_host;
6986        }
6987
6988        ctrl_info->scsi_host = shost;
6989
6990        return 0;
6991
6992remove_host:
6993        scsi_remove_host(shost);
6994free_host:
6995        scsi_host_put(shost);
6996
6997        return rc;
6998}
6999
7000static void pqi_unregister_scsi(struct pqi_ctrl_info *ctrl_info)
7001{
7002        struct Scsi_Host *shost;
7003
7004        pqi_delete_sas_host(ctrl_info);
7005
7006        shost = ctrl_info->scsi_host;
7007        if (!shost)
7008                return;
7009
7010        scsi_remove_host(shost);
7011        scsi_host_put(shost);
7012}
7013
7014static int pqi_wait_for_pqi_reset_completion(struct pqi_ctrl_info *ctrl_info)
7015{
7016        int rc = 0;
7017        struct pqi_device_registers __iomem *pqi_registers;
7018        unsigned long timeout;
7019        unsigned int timeout_msecs;
7020        union pqi_reset_register reset_reg;
7021
7022        pqi_registers = ctrl_info->pqi_registers;
7023        timeout_msecs = readw(&pqi_registers->max_reset_timeout) * 100;
7024        timeout = msecs_to_jiffies(timeout_msecs) + jiffies;
7025
7026        while (1) {
7027                msleep(PQI_RESET_POLL_INTERVAL_MSECS);
7028                reset_reg.all_bits = readl(&pqi_registers->device_reset);
7029                if (reset_reg.bits.reset_action == PQI_RESET_ACTION_COMPLETED)
7030                        break;
7031                pqi_check_ctrl_health(ctrl_info);
7032                if (pqi_ctrl_offline(ctrl_info)) {
7033                        rc = -ENXIO;
7034                        break;
7035                }
7036                if (time_after(jiffies, timeout)) {
7037                        rc = -ETIMEDOUT;
7038                        break;
7039                }
7040        }
7041
7042        return rc;
7043}
7044
7045static int pqi_reset(struct pqi_ctrl_info *ctrl_info)
7046{
7047        int rc;
7048        union pqi_reset_register reset_reg;
7049
7050        if (ctrl_info->pqi_reset_quiesce_supported) {
7051                rc = sis_pqi_reset_quiesce(ctrl_info);
7052                if (rc) {
7053                        dev_err(&ctrl_info->pci_dev->dev,
7054                                "PQI reset failed during quiesce with error %d\n", rc);
7055                        return rc;
7056                }
7057        }
7058
7059        reset_reg.all_bits = 0;
7060        reset_reg.bits.reset_type = PQI_RESET_TYPE_HARD_RESET;
7061        reset_reg.bits.reset_action = PQI_RESET_ACTION_RESET;
7062
7063        writel(reset_reg.all_bits, &ctrl_info->pqi_registers->device_reset);
7064
7065        rc = pqi_wait_for_pqi_reset_completion(ctrl_info);
7066        if (rc)
7067                dev_err(&ctrl_info->pci_dev->dev,
7068                        "PQI reset failed with error %d\n", rc);
7069
7070        return rc;
7071}
7072
7073static int pqi_get_ctrl_serial_number(struct pqi_ctrl_info *ctrl_info)
7074{
7075        int rc;
7076        struct bmic_sense_subsystem_info *sense_info;
7077
7078        sense_info = kzalloc(sizeof(*sense_info), GFP_KERNEL);
7079        if (!sense_info)
7080                return -ENOMEM;
7081
7082        rc = pqi_sense_subsystem_info(ctrl_info, sense_info);
7083        if (rc)
7084                goto out;
7085
7086        memcpy(ctrl_info->serial_number, sense_info->ctrl_serial_number,
7087                sizeof(sense_info->ctrl_serial_number));
7088        ctrl_info->serial_number[sizeof(sense_info->ctrl_serial_number)] = '\0';
7089
7090out:
7091        kfree(sense_info);
7092
7093        return rc;
7094}
7095
7096static int pqi_get_ctrl_product_details(struct pqi_ctrl_info *ctrl_info)
7097{
7098        int rc;
7099        struct bmic_identify_controller *identify;
7100
7101        identify = kmalloc(sizeof(*identify), GFP_KERNEL);
7102        if (!identify)
7103                return -ENOMEM;
7104
7105        rc = pqi_identify_controller(ctrl_info, identify);
7106        if (rc)
7107                goto out;
7108
7109        if (get_unaligned_le32(&identify->extra_controller_flags) &
7110                BMIC_IDENTIFY_EXTRA_FLAGS_LONG_FW_VERSION_SUPPORTED) {
7111                memcpy(ctrl_info->firmware_version,
7112                        identify->firmware_version_long,
7113                        sizeof(identify->firmware_version_long));
7114        } else {
7115                memcpy(ctrl_info->firmware_version,
7116                        identify->firmware_version_short,
7117                        sizeof(identify->firmware_version_short));
7118                ctrl_info->firmware_version
7119                        [sizeof(identify->firmware_version_short)] = '\0';
7120                snprintf(ctrl_info->firmware_version +
7121                        strlen(ctrl_info->firmware_version),
7122                        sizeof(ctrl_info->firmware_version) -
7123                        sizeof(identify->firmware_version_short),
7124                        "-%u",
7125                        get_unaligned_le16(&identify->firmware_build_number));
7126        }
7127
7128        memcpy(ctrl_info->model, identify->product_id,
7129                sizeof(identify->product_id));
7130        ctrl_info->model[sizeof(identify->product_id)] = '\0';
7131
7132        memcpy(ctrl_info->vendor, identify->vendor_id,
7133                sizeof(identify->vendor_id));
7134        ctrl_info->vendor[sizeof(identify->vendor_id)] = '\0';
7135
7136out:
7137        kfree(identify);
7138
7139        return rc;
7140}
7141
7142struct pqi_config_table_section_info {
7143        struct pqi_ctrl_info *ctrl_info;
7144        void            *section;
7145        u32             section_offset;
7146        void __iomem    *section_iomem_addr;
7147};
7148
7149static inline bool pqi_is_firmware_feature_supported(
7150        struct pqi_config_table_firmware_features *firmware_features,
7151        unsigned int bit_position)
7152{
7153        unsigned int byte_index;
7154
7155        byte_index = bit_position / BITS_PER_BYTE;
7156
7157        if (byte_index >= le16_to_cpu(firmware_features->num_elements))
7158                return false;
7159
7160        return firmware_features->features_supported[byte_index] &
7161                (1 << (bit_position % BITS_PER_BYTE)) ? true : false;
7162}
7163
7164static inline bool pqi_is_firmware_feature_enabled(
7165        struct pqi_config_table_firmware_features *firmware_features,
7166        void __iomem *firmware_features_iomem_addr,
7167        unsigned int bit_position)
7168{
7169        unsigned int byte_index;
7170        u8 __iomem *features_enabled_iomem_addr;
7171
7172        byte_index = (bit_position / BITS_PER_BYTE) +
7173                (le16_to_cpu(firmware_features->num_elements) * 2);
7174
7175        features_enabled_iomem_addr = firmware_features_iomem_addr +
7176                offsetof(struct pqi_config_table_firmware_features,
7177                        features_supported) + byte_index;
7178
7179        return *((__force u8 *)features_enabled_iomem_addr) &
7180                (1 << (bit_position % BITS_PER_BYTE)) ? true : false;
7181}
7182
7183static inline void pqi_request_firmware_feature(
7184        struct pqi_config_table_firmware_features *firmware_features,
7185        unsigned int bit_position)
7186{
7187        unsigned int byte_index;
7188
7189        byte_index = (bit_position / BITS_PER_BYTE) +
7190                le16_to_cpu(firmware_features->num_elements);
7191
7192        firmware_features->features_supported[byte_index] |=
7193                (1 << (bit_position % BITS_PER_BYTE));
7194}
7195
7196static int pqi_config_table_update(struct pqi_ctrl_info *ctrl_info,
7197        u16 first_section, u16 last_section)
7198{
7199        struct pqi_vendor_general_request request;
7200
7201        memset(&request, 0, sizeof(request));
7202
7203        request.header.iu_type = PQI_REQUEST_IU_VENDOR_GENERAL;
7204        put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
7205                &request.header.iu_length);
7206        put_unaligned_le16(PQI_VENDOR_GENERAL_CONFIG_TABLE_UPDATE,
7207                &request.function_code);
7208        put_unaligned_le16(first_section,
7209                &request.data.config_table_update.first_section);
7210        put_unaligned_le16(last_section,
7211                &request.data.config_table_update.last_section);
7212
7213        return pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
7214}
7215
7216static int pqi_enable_firmware_features(struct pqi_ctrl_info *ctrl_info,
7217        struct pqi_config_table_firmware_features *firmware_features,
7218        void __iomem *firmware_features_iomem_addr)
7219{
7220        void *features_requested;
7221        void __iomem *features_requested_iomem_addr;
7222        void __iomem *host_max_known_feature_iomem_addr;
7223
7224        features_requested = firmware_features->features_supported +
7225                le16_to_cpu(firmware_features->num_elements);
7226
7227        features_requested_iomem_addr = firmware_features_iomem_addr +
7228                (features_requested - (void *)firmware_features);
7229
7230        memcpy_toio(features_requested_iomem_addr, features_requested,
7231                le16_to_cpu(firmware_features->num_elements));
7232
7233        if (pqi_is_firmware_feature_supported(firmware_features,
7234                PQI_FIRMWARE_FEATURE_MAX_KNOWN_FEATURE)) {
7235                host_max_known_feature_iomem_addr =
7236                        features_requested_iomem_addr +
7237                        (le16_to_cpu(firmware_features->num_elements) * 2) +
7238                        sizeof(__le16);
7239                writew(PQI_FIRMWARE_FEATURE_MAXIMUM,
7240                        host_max_known_feature_iomem_addr);
7241        }
7242
7243        return pqi_config_table_update(ctrl_info,
7244                PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES,
7245                PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES);
7246}
7247
7248struct pqi_firmware_feature {
7249        char            *feature_name;
7250        unsigned int    feature_bit;
7251        bool            supported;
7252        bool            enabled;
7253        void (*feature_status)(struct pqi_ctrl_info *ctrl_info,
7254                struct pqi_firmware_feature *firmware_feature);
7255};
7256
7257static void pqi_firmware_feature_status(struct pqi_ctrl_info *ctrl_info,
7258        struct pqi_firmware_feature *firmware_feature)
7259{
7260        if (!firmware_feature->supported) {
7261                dev_info(&ctrl_info->pci_dev->dev, "%s not supported by controller\n",
7262                        firmware_feature->feature_name);
7263                return;
7264        }
7265
7266        if (firmware_feature->enabled) {
7267                dev_info(&ctrl_info->pci_dev->dev,
7268                        "%s enabled\n", firmware_feature->feature_name);
7269                return;
7270        }
7271
7272        dev_err(&ctrl_info->pci_dev->dev, "failed to enable %s\n",
7273                firmware_feature->feature_name);
7274}
7275
7276static void pqi_ctrl_update_feature_flags(struct pqi_ctrl_info *ctrl_info,
7277        struct pqi_firmware_feature *firmware_feature)
7278{
7279        switch (firmware_feature->feature_bit) {
7280        case PQI_FIRMWARE_FEATURE_RAID_1_WRITE_BYPASS:
7281                ctrl_info->enable_r1_writes = firmware_feature->enabled;
7282                break;
7283        case PQI_FIRMWARE_FEATURE_RAID_5_WRITE_BYPASS:
7284                ctrl_info->enable_r5_writes = firmware_feature->enabled;
7285                break;
7286        case PQI_FIRMWARE_FEATURE_RAID_6_WRITE_BYPASS:
7287                ctrl_info->enable_r6_writes = firmware_feature->enabled;
7288                break;
7289        case PQI_FIRMWARE_FEATURE_SOFT_RESET_HANDSHAKE:
7290                ctrl_info->soft_reset_handshake_supported =
7291                        firmware_feature->enabled &&
7292                        pqi_read_soft_reset_status(ctrl_info);
7293                break;
7294        case PQI_FIRMWARE_FEATURE_RAID_IU_TIMEOUT:
7295                ctrl_info->raid_iu_timeout_supported = firmware_feature->enabled;
7296                break;
7297        case PQI_FIRMWARE_FEATURE_TMF_IU_TIMEOUT:
7298                ctrl_info->tmf_iu_timeout_supported = firmware_feature->enabled;
7299                break;
7300        case PQI_FIRMWARE_FEATURE_UNIQUE_WWID_IN_REPORT_PHYS_LUN:
7301                ctrl_info->unique_wwid_in_report_phys_lun_supported =
7302                        firmware_feature->enabled;
7303                break;
7304        }
7305
7306        pqi_firmware_feature_status(ctrl_info, firmware_feature);
7307}
7308
7309static inline void pqi_firmware_feature_update(struct pqi_ctrl_info *ctrl_info,
7310        struct pqi_firmware_feature *firmware_feature)
7311{
7312        if (firmware_feature->feature_status)
7313                firmware_feature->feature_status(ctrl_info, firmware_feature);
7314}
7315
7316static DEFINE_MUTEX(pqi_firmware_features_mutex);
7317
7318static struct pqi_firmware_feature pqi_firmware_features[] = {
7319        {
7320                .feature_name = "Online Firmware Activation",
7321                .feature_bit = PQI_FIRMWARE_FEATURE_OFA,
7322                .feature_status = pqi_firmware_feature_status,
7323        },
7324        {
7325                .feature_name = "Serial Management Protocol",
7326                .feature_bit = PQI_FIRMWARE_FEATURE_SMP,
7327                .feature_status = pqi_firmware_feature_status,
7328        },
7329        {
7330                .feature_name = "Maximum Known Feature",
7331                .feature_bit = PQI_FIRMWARE_FEATURE_MAX_KNOWN_FEATURE,
7332                .feature_status = pqi_firmware_feature_status,
7333        },
7334        {
7335                .feature_name = "RAID 0 Read Bypass",
7336                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_0_READ_BYPASS,
7337                .feature_status = pqi_firmware_feature_status,
7338        },
7339        {
7340                .feature_name = "RAID 1 Read Bypass",
7341                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_1_READ_BYPASS,
7342                .feature_status = pqi_firmware_feature_status,
7343        },
7344        {
7345                .feature_name = "RAID 5 Read Bypass",
7346                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_5_READ_BYPASS,
7347                .feature_status = pqi_firmware_feature_status,
7348        },
7349        {
7350                .feature_name = "RAID 6 Read Bypass",
7351                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_6_READ_BYPASS,
7352                .feature_status = pqi_firmware_feature_status,
7353        },
7354        {
7355                .feature_name = "RAID 0 Write Bypass",
7356                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_0_WRITE_BYPASS,
7357                .feature_status = pqi_firmware_feature_status,
7358        },
7359        {
7360                .feature_name = "RAID 1 Write Bypass",
7361                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_1_WRITE_BYPASS,
7362                .feature_status = pqi_ctrl_update_feature_flags,
7363        },
7364        {
7365                .feature_name = "RAID 5 Write Bypass",
7366                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_5_WRITE_BYPASS,
7367                .feature_status = pqi_ctrl_update_feature_flags,
7368        },
7369        {
7370                .feature_name = "RAID 6 Write Bypass",
7371                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_6_WRITE_BYPASS,
7372                .feature_status = pqi_ctrl_update_feature_flags,
7373        },
7374        {
7375                .feature_name = "New Soft Reset Handshake",
7376                .feature_bit = PQI_FIRMWARE_FEATURE_SOFT_RESET_HANDSHAKE,
7377                .feature_status = pqi_ctrl_update_feature_flags,
7378        },
7379        {
7380                .feature_name = "RAID IU Timeout",
7381                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_IU_TIMEOUT,
7382                .feature_status = pqi_ctrl_update_feature_flags,
7383        },
7384        {
7385                .feature_name = "TMF IU Timeout",
7386                .feature_bit = PQI_FIRMWARE_FEATURE_TMF_IU_TIMEOUT,
7387                .feature_status = pqi_ctrl_update_feature_flags,
7388        },
7389        {
7390                .feature_name = "RAID Bypass on encrypted logical volumes on NVMe",
7391                .feature_bit = PQI_FIRMWARE_FEATURE_RAID_BYPASS_ON_ENCRYPTED_NVME,
7392                .feature_status = pqi_firmware_feature_status,
7393        },
7394        {
7395                .feature_name = "Unique WWID in Report Physical LUN",
7396                .feature_bit = PQI_FIRMWARE_FEATURE_UNIQUE_WWID_IN_REPORT_PHYS_LUN,
7397                .feature_status = pqi_ctrl_update_feature_flags,
7398        },
7399};
7400
7401static void pqi_process_firmware_features(
7402        struct pqi_config_table_section_info *section_info)
7403{
7404        int rc;
7405        struct pqi_ctrl_info *ctrl_info;
7406        struct pqi_config_table_firmware_features *firmware_features;
7407        void __iomem *firmware_features_iomem_addr;
7408        unsigned int i;
7409        unsigned int num_features_supported;
7410
7411        ctrl_info = section_info->ctrl_info;
7412        firmware_features = section_info->section;
7413        firmware_features_iomem_addr = section_info->section_iomem_addr;
7414
7415        for (i = 0, num_features_supported = 0;
7416                i < ARRAY_SIZE(pqi_firmware_features); i++) {
7417                if (pqi_is_firmware_feature_supported(firmware_features,
7418                        pqi_firmware_features[i].feature_bit)) {
7419                        pqi_firmware_features[i].supported = true;
7420                        num_features_supported++;
7421                } else {
7422                        pqi_firmware_feature_update(ctrl_info,
7423                                &pqi_firmware_features[i]);
7424                }
7425        }
7426
7427        if (num_features_supported == 0)
7428                return;
7429
7430        for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7431                if (!pqi_firmware_features[i].supported)
7432                        continue;
7433                pqi_request_firmware_feature(firmware_features,
7434                        pqi_firmware_features[i].feature_bit);
7435        }
7436
7437        rc = pqi_enable_firmware_features(ctrl_info, firmware_features,
7438                firmware_features_iomem_addr);
7439        if (rc) {
7440                dev_err(&ctrl_info->pci_dev->dev,
7441                        "failed to enable firmware features in PQI configuration table\n");
7442                for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7443                        if (!pqi_firmware_features[i].supported)
7444                                continue;
7445                        pqi_firmware_feature_update(ctrl_info,
7446                                &pqi_firmware_features[i]);
7447                }
7448                return;
7449        }
7450
7451        for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7452                if (!pqi_firmware_features[i].supported)
7453                        continue;
7454                if (pqi_is_firmware_feature_enabled(firmware_features,
7455                        firmware_features_iomem_addr,
7456                        pqi_firmware_features[i].feature_bit)) {
7457                                pqi_firmware_features[i].enabled = true;
7458                }
7459                pqi_firmware_feature_update(ctrl_info,
7460                        &pqi_firmware_features[i]);
7461        }
7462}
7463
7464static void pqi_init_firmware_features(void)
7465{
7466        unsigned int i;
7467
7468        for (i = 0; i < ARRAY_SIZE(pqi_firmware_features); i++) {
7469                pqi_firmware_features[i].supported = false;
7470                pqi_firmware_features[i].enabled = false;
7471        }
7472}
7473
7474static void pqi_process_firmware_features_section(
7475        struct pqi_config_table_section_info *section_info)
7476{
7477        mutex_lock(&pqi_firmware_features_mutex);
7478        pqi_init_firmware_features();
7479        pqi_process_firmware_features(section_info);
7480        mutex_unlock(&pqi_firmware_features_mutex);
7481}
7482
7483/*
7484 * Reset all controller settings that can be initialized during the processing
7485 * of the PQI Configuration Table.
7486 */
7487
7488static void pqi_ctrl_reset_config(struct pqi_ctrl_info *ctrl_info)
7489{
7490        ctrl_info->heartbeat_counter = NULL;
7491        ctrl_info->soft_reset_status = NULL;
7492        ctrl_info->soft_reset_handshake_supported = false;
7493        ctrl_info->enable_r1_writes = false;
7494        ctrl_info->enable_r5_writes = false;
7495        ctrl_info->enable_r6_writes = false;
7496        ctrl_info->raid_iu_timeout_supported = false;
7497        ctrl_info->tmf_iu_timeout_supported = false;
7498        ctrl_info->unique_wwid_in_report_phys_lun_supported = false;
7499}
7500
7501static int pqi_process_config_table(struct pqi_ctrl_info *ctrl_info)
7502{
7503        u32 table_length;
7504        u32 section_offset;
7505        bool firmware_feature_section_present;
7506        void __iomem *table_iomem_addr;
7507        struct pqi_config_table *config_table;
7508        struct pqi_config_table_section_header *section;
7509        struct pqi_config_table_section_info section_info;
7510        struct pqi_config_table_section_info feature_section_info;
7511
7512        table_length = ctrl_info->config_table_length;
7513        if (table_length == 0)
7514                return 0;
7515
7516        config_table = kmalloc(table_length, GFP_KERNEL);
7517        if (!config_table) {
7518                dev_err(&ctrl_info->pci_dev->dev,
7519                        "failed to allocate memory for PQI configuration table\n");
7520                return -ENOMEM;
7521        }
7522
7523        /*
7524         * Copy the config table contents from I/O memory space into the
7525         * temporary buffer.
7526         */
7527        table_iomem_addr = ctrl_info->iomem_base + ctrl_info->config_table_offset;
7528        memcpy_fromio(config_table, table_iomem_addr, table_length);
7529
7530        firmware_feature_section_present = false;
7531        section_info.ctrl_info = ctrl_info;
7532        section_offset = get_unaligned_le32(&config_table->first_section_offset);
7533
7534        while (section_offset) {
7535                section = (void *)config_table + section_offset;
7536
7537                section_info.section = section;
7538                section_info.section_offset = section_offset;
7539                section_info.section_iomem_addr = table_iomem_addr + section_offset;
7540
7541                switch (get_unaligned_le16(&section->section_id)) {
7542                case PQI_CONFIG_TABLE_SECTION_FIRMWARE_FEATURES:
7543                        firmware_feature_section_present = true;
7544                        feature_section_info = section_info;
7545                        break;
7546                case PQI_CONFIG_TABLE_SECTION_HEARTBEAT:
7547                        if (pqi_disable_heartbeat)
7548                                dev_warn(&ctrl_info->pci_dev->dev,
7549                                "heartbeat disabled by module parameter\n");
7550                        else
7551                                ctrl_info->heartbeat_counter =
7552                                        table_iomem_addr +
7553                                        section_offset +
7554                                        offsetof(struct pqi_config_table_heartbeat,
7555                                                heartbeat_counter);
7556                        break;
7557                case PQI_CONFIG_TABLE_SECTION_SOFT_RESET:
7558                        ctrl_info->soft_reset_status =
7559                                table_iomem_addr +
7560                                section_offset +
7561                                offsetof(struct pqi_config_table_soft_reset,
7562                                        soft_reset_status);
7563                        break;
7564                }
7565
7566                section_offset = get_unaligned_le16(&section->next_section_offset);
7567        }
7568
7569        /*
7570         * We process the firmware feature section after all other sections
7571         * have been processed so that the feature bit callbacks can take
7572         * into account the settings configured by other sections.
7573         */
7574        if (firmware_feature_section_present)
7575                pqi_process_firmware_features_section(&feature_section_info);
7576
7577        kfree(config_table);
7578
7579        return 0;
7580}
7581
7582/* Switches the controller from PQI mode back into SIS mode. */
7583
7584static int pqi_revert_to_sis_mode(struct pqi_ctrl_info *ctrl_info)
7585{
7586        int rc;
7587
7588        pqi_change_irq_mode(ctrl_info, IRQ_MODE_NONE);
7589        rc = pqi_reset(ctrl_info);
7590        if (rc)
7591                return rc;
7592        rc = sis_reenable_sis_mode(ctrl_info);
7593        if (rc) {
7594                dev_err(&ctrl_info->pci_dev->dev,
7595                        "re-enabling SIS mode failed with error %d\n", rc);
7596                return rc;
7597        }
7598        pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
7599
7600        return 0;
7601}
7602
7603/*
7604 * If the controller isn't already in SIS mode, this function forces it into
7605 * SIS mode.
7606 */
7607
7608static int pqi_force_sis_mode(struct pqi_ctrl_info *ctrl_info)
7609{
7610        if (!sis_is_firmware_running(ctrl_info))
7611                return -ENXIO;
7612
7613        if (pqi_get_ctrl_mode(ctrl_info) == SIS_MODE)
7614                return 0;
7615
7616        if (sis_is_kernel_up(ctrl_info)) {
7617                pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
7618                return 0;
7619        }
7620
7621        return pqi_revert_to_sis_mode(ctrl_info);
7622}
7623
7624static int pqi_ctrl_init(struct pqi_ctrl_info *ctrl_info)
7625{
7626        int rc;
7627        u32 product_id;
7628
7629        if (reset_devices) {
7630                sis_soft_reset(ctrl_info);
7631                msleep(PQI_POST_RESET_DELAY_SECS * PQI_HZ);
7632        } else {
7633                rc = pqi_force_sis_mode(ctrl_info);
7634                if (rc)
7635                        return rc;
7636        }
7637
7638        /*
7639         * Wait until the controller is ready to start accepting SIS
7640         * commands.
7641         */
7642        rc = sis_wait_for_ctrl_ready(ctrl_info);
7643        if (rc)
7644                return rc;
7645
7646        /*
7647         * Get the controller properties.  This allows us to determine
7648         * whether or not it supports PQI mode.
7649         */
7650        rc = sis_get_ctrl_properties(ctrl_info);
7651        if (rc) {
7652                dev_err(&ctrl_info->pci_dev->dev,
7653                        "error obtaining controller properties\n");
7654                return rc;
7655        }
7656
7657        rc = sis_get_pqi_capabilities(ctrl_info);
7658        if (rc) {
7659                dev_err(&ctrl_info->pci_dev->dev,
7660                        "error obtaining controller capabilities\n");
7661                return rc;
7662        }
7663
7664        product_id = sis_get_product_id(ctrl_info);
7665        ctrl_info->product_id = (u8)product_id;
7666        ctrl_info->product_revision = (u8)(product_id >> 8);
7667
7668        if (reset_devices) {
7669                if (ctrl_info->max_outstanding_requests >
7670                        PQI_MAX_OUTSTANDING_REQUESTS_KDUMP)
7671                                ctrl_info->max_outstanding_requests =
7672                                        PQI_MAX_OUTSTANDING_REQUESTS_KDUMP;
7673        } else {
7674                if (ctrl_info->max_outstanding_requests >
7675                        PQI_MAX_OUTSTANDING_REQUESTS)
7676                                ctrl_info->max_outstanding_requests =
7677                                        PQI_MAX_OUTSTANDING_REQUESTS;
7678        }
7679
7680        pqi_calculate_io_resources(ctrl_info);
7681
7682        rc = pqi_alloc_error_buffer(ctrl_info);
7683        if (rc) {
7684                dev_err(&ctrl_info->pci_dev->dev,
7685                        "failed to allocate PQI error buffer\n");
7686                return rc;
7687        }
7688
7689        /*
7690         * If the function we are about to call succeeds, the
7691         * controller will transition from legacy SIS mode
7692         * into PQI mode.
7693         */
7694        rc = sis_init_base_struct_addr(ctrl_info);
7695        if (rc) {
7696                dev_err(&ctrl_info->pci_dev->dev,
7697                        "error initializing PQI mode\n");
7698                return rc;
7699        }
7700
7701        /* Wait for the controller to complete the SIS -> PQI transition. */
7702        rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
7703        if (rc) {
7704                dev_err(&ctrl_info->pci_dev->dev,
7705                        "transition to PQI mode failed\n");
7706                return rc;
7707        }
7708
7709        /* From here on, we are running in PQI mode. */
7710        ctrl_info->pqi_mode_enabled = true;
7711        pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
7712
7713        rc = pqi_alloc_admin_queues(ctrl_info);
7714        if (rc) {
7715                dev_err(&ctrl_info->pci_dev->dev,
7716                        "failed to allocate admin queues\n");
7717                return rc;
7718        }
7719
7720        rc = pqi_create_admin_queues(ctrl_info);
7721        if (rc) {
7722                dev_err(&ctrl_info->pci_dev->dev,
7723                        "error creating admin queues\n");
7724                return rc;
7725        }
7726
7727        rc = pqi_report_device_capability(ctrl_info);
7728        if (rc) {
7729                dev_err(&ctrl_info->pci_dev->dev,
7730                        "obtaining device capability failed\n");
7731                return rc;
7732        }
7733
7734        rc = pqi_validate_device_capability(ctrl_info);
7735        if (rc)
7736                return rc;
7737
7738        pqi_calculate_queue_resources(ctrl_info);
7739
7740        rc = pqi_enable_msix_interrupts(ctrl_info);
7741        if (rc)
7742                return rc;
7743
7744        if (ctrl_info->num_msix_vectors_enabled < ctrl_info->num_queue_groups) {
7745                ctrl_info->max_msix_vectors =
7746                        ctrl_info->num_msix_vectors_enabled;
7747                pqi_calculate_queue_resources(ctrl_info);
7748        }
7749
7750        rc = pqi_alloc_io_resources(ctrl_info);
7751        if (rc)
7752                return rc;
7753
7754        rc = pqi_alloc_operational_queues(ctrl_info);
7755        if (rc) {
7756                dev_err(&ctrl_info->pci_dev->dev,
7757                        "failed to allocate operational queues\n");
7758                return rc;
7759        }
7760
7761        pqi_init_operational_queues(ctrl_info);
7762
7763        rc = pqi_create_queues(ctrl_info);
7764        if (rc)
7765                return rc;
7766
7767        rc = pqi_request_irqs(ctrl_info);
7768        if (rc)
7769                return rc;
7770
7771        pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
7772
7773        ctrl_info->controller_online = true;
7774
7775        rc = pqi_process_config_table(ctrl_info);
7776        if (rc)
7777                return rc;
7778
7779        pqi_start_heartbeat_timer(ctrl_info);
7780
7781        if (ctrl_info->enable_r5_writes || ctrl_info->enable_r6_writes) {
7782                rc = pqi_get_advanced_raid_bypass_config(ctrl_info);
7783                if (rc) { /* Supported features not returned correctly. */
7784                        dev_err(&ctrl_info->pci_dev->dev,
7785                                "error obtaining advanced RAID bypass configuration\n");
7786                        return rc;
7787                }
7788                ctrl_info->ciss_report_log_flags |=
7789                        CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX;
7790        }
7791
7792        rc = pqi_enable_events(ctrl_info);
7793        if (rc) {
7794                dev_err(&ctrl_info->pci_dev->dev,
7795                        "error enabling events\n");
7796                return rc;
7797        }
7798
7799        /* Register with the SCSI subsystem. */
7800        rc = pqi_register_scsi(ctrl_info);
7801        if (rc)
7802                return rc;
7803
7804        rc = pqi_get_ctrl_product_details(ctrl_info);
7805        if (rc) {
7806                dev_err(&ctrl_info->pci_dev->dev,
7807                        "error obtaining product details\n");
7808                return rc;
7809        }
7810
7811        rc = pqi_get_ctrl_serial_number(ctrl_info);
7812        if (rc) {
7813                dev_err(&ctrl_info->pci_dev->dev,
7814                        "error obtaining ctrl serial number\n");
7815                return rc;
7816        }
7817
7818        rc = pqi_set_diag_rescan(ctrl_info);
7819        if (rc) {
7820                dev_err(&ctrl_info->pci_dev->dev,
7821                        "error enabling multi-lun rescan\n");
7822                return rc;
7823        }
7824
7825        rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
7826        if (rc) {
7827                dev_err(&ctrl_info->pci_dev->dev,
7828                        "error updating host wellness\n");
7829                return rc;
7830        }
7831
7832        pqi_schedule_update_time_worker(ctrl_info);
7833
7834        pqi_scan_scsi_devices(ctrl_info);
7835
7836        return 0;
7837}
7838
7839static void pqi_reinit_queues(struct pqi_ctrl_info *ctrl_info)
7840{
7841        unsigned int i;
7842        struct pqi_admin_queues *admin_queues;
7843        struct pqi_event_queue *event_queue;
7844
7845        admin_queues = &ctrl_info->admin_queues;
7846        admin_queues->iq_pi_copy = 0;
7847        admin_queues->oq_ci_copy = 0;
7848        writel(0, admin_queues->oq_pi);
7849
7850        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
7851                ctrl_info->queue_groups[i].iq_pi_copy[RAID_PATH] = 0;
7852                ctrl_info->queue_groups[i].iq_pi_copy[AIO_PATH] = 0;
7853                ctrl_info->queue_groups[i].oq_ci_copy = 0;
7854
7855                writel(0, ctrl_info->queue_groups[i].iq_ci[RAID_PATH]);
7856                writel(0, ctrl_info->queue_groups[i].iq_ci[AIO_PATH]);
7857                writel(0, ctrl_info->queue_groups[i].oq_pi);
7858        }
7859
7860        event_queue = &ctrl_info->event_queue;
7861        writel(0, event_queue->oq_pi);
7862        event_queue->oq_ci_copy = 0;
7863}
7864
7865static int pqi_ctrl_init_resume(struct pqi_ctrl_info *ctrl_info)
7866{
7867        int rc;
7868
7869        rc = pqi_force_sis_mode(ctrl_info);
7870        if (rc)
7871                return rc;
7872
7873        /*
7874         * Wait until the controller is ready to start accepting SIS
7875         * commands.
7876         */
7877        rc = sis_wait_for_ctrl_ready_resume(ctrl_info);
7878        if (rc)
7879                return rc;
7880
7881        /*
7882         * Get the controller properties.  This allows us to determine
7883         * whether or not it supports PQI mode.
7884         */
7885        rc = sis_get_ctrl_properties(ctrl_info);
7886        if (rc) {
7887                dev_err(&ctrl_info->pci_dev->dev,
7888                        "error obtaining controller properties\n");
7889                return rc;
7890        }
7891
7892        rc = sis_get_pqi_capabilities(ctrl_info);
7893        if (rc) {
7894                dev_err(&ctrl_info->pci_dev->dev,
7895                        "error obtaining controller capabilities\n");
7896                return rc;
7897        }
7898
7899        /*
7900         * If the function we are about to call succeeds, the
7901         * controller will transition from legacy SIS mode
7902         * into PQI mode.
7903         */
7904        rc = sis_init_base_struct_addr(ctrl_info);
7905        if (rc) {
7906                dev_err(&ctrl_info->pci_dev->dev,
7907                        "error initializing PQI mode\n");
7908                return rc;
7909        }
7910
7911        /* Wait for the controller to complete the SIS -> PQI transition. */
7912        rc = pqi_wait_for_pqi_mode_ready(ctrl_info);
7913        if (rc) {
7914                dev_err(&ctrl_info->pci_dev->dev,
7915                        "transition to PQI mode failed\n");
7916                return rc;
7917        }
7918
7919        /* From here on, we are running in PQI mode. */
7920        ctrl_info->pqi_mode_enabled = true;
7921        pqi_save_ctrl_mode(ctrl_info, PQI_MODE);
7922
7923        pqi_reinit_queues(ctrl_info);
7924
7925        rc = pqi_create_admin_queues(ctrl_info);
7926        if (rc) {
7927                dev_err(&ctrl_info->pci_dev->dev,
7928                        "error creating admin queues\n");
7929                return rc;
7930        }
7931
7932        rc = pqi_create_queues(ctrl_info);
7933        if (rc)
7934                return rc;
7935
7936        pqi_change_irq_mode(ctrl_info, IRQ_MODE_MSIX);
7937
7938        ctrl_info->controller_online = true;
7939        pqi_ctrl_unblock_requests(ctrl_info);
7940
7941        pqi_ctrl_reset_config(ctrl_info);
7942
7943        rc = pqi_process_config_table(ctrl_info);
7944        if (rc)
7945                return rc;
7946
7947        pqi_start_heartbeat_timer(ctrl_info);
7948
7949        if (ctrl_info->enable_r5_writes || ctrl_info->enable_r6_writes) {
7950                rc = pqi_get_advanced_raid_bypass_config(ctrl_info);
7951                if (rc) {
7952                        dev_err(&ctrl_info->pci_dev->dev,
7953                                "error obtaining advanced RAID bypass configuration\n");
7954                        return rc;
7955                }
7956                ctrl_info->ciss_report_log_flags |=
7957                        CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX;
7958        }
7959
7960        rc = pqi_enable_events(ctrl_info);
7961        if (rc) {
7962                dev_err(&ctrl_info->pci_dev->dev,
7963                        "error enabling events\n");
7964                return rc;
7965        }
7966
7967        rc = pqi_get_ctrl_product_details(ctrl_info);
7968        if (rc) {
7969                dev_err(&ctrl_info->pci_dev->dev,
7970                        "error obtaining product details\n");
7971                return rc;
7972        }
7973
7974        rc = pqi_set_diag_rescan(ctrl_info);
7975        if (rc) {
7976                dev_err(&ctrl_info->pci_dev->dev,
7977                        "error enabling multi-lun rescan\n");
7978                return rc;
7979        }
7980
7981        rc = pqi_write_driver_version_to_host_wellness(ctrl_info);
7982        if (rc) {
7983                dev_err(&ctrl_info->pci_dev->dev,
7984                        "error updating host wellness\n");
7985                return rc;
7986        }
7987
7988        if (pqi_ofa_in_progress(ctrl_info))
7989                pqi_ctrl_unblock_scan(ctrl_info);
7990
7991        pqi_scan_scsi_devices(ctrl_info);
7992
7993        return 0;
7994}
7995
7996static inline int pqi_set_pcie_completion_timeout(struct pci_dev *pci_dev, u16 timeout)
7997{
7998        int rc;
7999
8000        rc = pcie_capability_clear_and_set_word(pci_dev, PCI_EXP_DEVCTL2,
8001                PCI_EXP_DEVCTL2_COMP_TIMEOUT, timeout);
8002
8003        return pcibios_err_to_errno(rc);
8004}
8005
8006static int pqi_pci_init(struct pqi_ctrl_info *ctrl_info)
8007{
8008        int rc;
8009        u64 mask;
8010
8011        rc = pci_enable_device(ctrl_info->pci_dev);
8012        if (rc) {
8013                dev_err(&ctrl_info->pci_dev->dev,
8014                        "failed to enable PCI device\n");
8015                return rc;
8016        }
8017
8018        if (sizeof(dma_addr_t) > 4)
8019                mask = DMA_BIT_MASK(64);
8020        else
8021                mask = DMA_BIT_MASK(32);
8022
8023        rc = dma_set_mask_and_coherent(&ctrl_info->pci_dev->dev, mask);
8024        if (rc) {
8025                dev_err(&ctrl_info->pci_dev->dev, "failed to set DMA mask\n");
8026                goto disable_device;
8027        }
8028
8029        rc = pci_request_regions(ctrl_info->pci_dev, DRIVER_NAME_SHORT);
8030        if (rc) {
8031                dev_err(&ctrl_info->pci_dev->dev,
8032                        "failed to obtain PCI resources\n");
8033                goto disable_device;
8034        }
8035
8036        ctrl_info->iomem_base = ioremap(pci_resource_start(
8037                ctrl_info->pci_dev, 0),
8038                sizeof(struct pqi_ctrl_registers));
8039        if (!ctrl_info->iomem_base) {
8040                dev_err(&ctrl_info->pci_dev->dev,
8041                        "failed to map memory for controller registers\n");
8042                rc = -ENOMEM;
8043                goto release_regions;
8044        }
8045
8046#define PCI_EXP_COMP_TIMEOUT_65_TO_210_MS               0x6
8047
8048        /* Increase the PCIe completion timeout. */
8049        rc = pqi_set_pcie_completion_timeout(ctrl_info->pci_dev,
8050                PCI_EXP_COMP_TIMEOUT_65_TO_210_MS);
8051        if (rc) {
8052                dev_err(&ctrl_info->pci_dev->dev,
8053                        "failed to set PCIe completion timeout\n");
8054                goto release_regions;
8055        }
8056
8057        /* Enable bus mastering. */
8058        pci_set_master(ctrl_info->pci_dev);
8059
8060        ctrl_info->registers = ctrl_info->iomem_base;
8061        ctrl_info->pqi_registers = &ctrl_info->registers->pqi_registers;
8062
8063        pci_set_drvdata(ctrl_info->pci_dev, ctrl_info);
8064
8065        return 0;
8066
8067release_regions:
8068        pci_release_regions(ctrl_info->pci_dev);
8069disable_device:
8070        pci_disable_device(ctrl_info->pci_dev);
8071
8072        return rc;
8073}
8074
8075static void pqi_cleanup_pci_init(struct pqi_ctrl_info *ctrl_info)
8076{
8077        iounmap(ctrl_info->iomem_base);
8078        pci_release_regions(ctrl_info->pci_dev);
8079        if (pci_is_enabled(ctrl_info->pci_dev))
8080                pci_disable_device(ctrl_info->pci_dev);
8081        pci_set_drvdata(ctrl_info->pci_dev, NULL);
8082}
8083
8084static struct pqi_ctrl_info *pqi_alloc_ctrl_info(int numa_node)
8085{
8086        struct pqi_ctrl_info *ctrl_info;
8087
8088        ctrl_info = kzalloc_node(sizeof(struct pqi_ctrl_info),
8089                        GFP_KERNEL, numa_node);
8090        if (!ctrl_info)
8091                return NULL;
8092
8093        mutex_init(&ctrl_info->scan_mutex);
8094        mutex_init(&ctrl_info->lun_reset_mutex);
8095        mutex_init(&ctrl_info->ofa_mutex);
8096
8097        INIT_LIST_HEAD(&ctrl_info->scsi_device_list);
8098        spin_lock_init(&ctrl_info->scsi_device_list_lock);
8099
8100        INIT_WORK(&ctrl_info->event_work, pqi_event_worker);
8101        atomic_set(&ctrl_info->num_interrupts, 0);
8102
8103        INIT_DELAYED_WORK(&ctrl_info->rescan_work, pqi_rescan_worker);
8104        INIT_DELAYED_WORK(&ctrl_info->update_time_work, pqi_update_time_worker);
8105
8106        timer_setup(&ctrl_info->heartbeat_timer, pqi_heartbeat_timer_handler, 0);
8107        INIT_WORK(&ctrl_info->ctrl_offline_work, pqi_ctrl_offline_worker);
8108
8109        INIT_WORK(&ctrl_info->ofa_memory_alloc_work, pqi_ofa_memory_alloc_worker);
8110        INIT_WORK(&ctrl_info->ofa_quiesce_work, pqi_ofa_quiesce_worker);
8111
8112        sema_init(&ctrl_info->sync_request_sem,
8113                PQI_RESERVED_IO_SLOTS_SYNCHRONOUS_REQUESTS);
8114        init_waitqueue_head(&ctrl_info->block_requests_wait);
8115
8116        ctrl_info->ctrl_id = atomic_inc_return(&pqi_controller_count) - 1;
8117        ctrl_info->irq_mode = IRQ_MODE_NONE;
8118        ctrl_info->max_msix_vectors = PQI_MAX_MSIX_VECTORS;
8119
8120        ctrl_info->ciss_report_log_flags = CISS_REPORT_LOG_FLAG_UNIQUE_LUN_ID;
8121        ctrl_info->max_transfer_encrypted_sas_sata =
8122                PQI_DEFAULT_MAX_TRANSFER_ENCRYPTED_SAS_SATA;
8123        ctrl_info->max_transfer_encrypted_nvme =
8124                PQI_DEFAULT_MAX_TRANSFER_ENCRYPTED_NVME;
8125        ctrl_info->max_write_raid_5_6 = PQI_DEFAULT_MAX_WRITE_RAID_5_6;
8126        ctrl_info->max_write_raid_1_10_2drive = ~0;
8127        ctrl_info->max_write_raid_1_10_3drive = ~0;
8128
8129        return ctrl_info;
8130}
8131
8132static inline void pqi_free_ctrl_info(struct pqi_ctrl_info *ctrl_info)
8133{
8134        kfree(ctrl_info);
8135}
8136
8137static void pqi_free_interrupts(struct pqi_ctrl_info *ctrl_info)
8138{
8139        pqi_free_irqs(ctrl_info);
8140        pqi_disable_msix_interrupts(ctrl_info);
8141}
8142
8143static void pqi_free_ctrl_resources(struct pqi_ctrl_info *ctrl_info)
8144{
8145        pqi_stop_heartbeat_timer(ctrl_info);
8146        pqi_free_interrupts(ctrl_info);
8147        if (ctrl_info->queue_memory_base)
8148                dma_free_coherent(&ctrl_info->pci_dev->dev,
8149                        ctrl_info->queue_memory_length,
8150                        ctrl_info->queue_memory_base,
8151                        ctrl_info->queue_memory_base_dma_handle);
8152        if (ctrl_info->admin_queue_memory_base)
8153                dma_free_coherent(&ctrl_info->pci_dev->dev,
8154                        ctrl_info->admin_queue_memory_length,
8155                        ctrl_info->admin_queue_memory_base,
8156                        ctrl_info->admin_queue_memory_base_dma_handle);
8157        pqi_free_all_io_requests(ctrl_info);
8158        if (ctrl_info->error_buffer)
8159                dma_free_coherent(&ctrl_info->pci_dev->dev,
8160                        ctrl_info->error_buffer_length,
8161                        ctrl_info->error_buffer,
8162                        ctrl_info->error_buffer_dma_handle);
8163        if (ctrl_info->iomem_base)
8164                pqi_cleanup_pci_init(ctrl_info);
8165        pqi_free_ctrl_info(ctrl_info);
8166}
8167
8168static void pqi_remove_ctrl(struct pqi_ctrl_info *ctrl_info)
8169{
8170        pqi_cancel_rescan_worker(ctrl_info);
8171        pqi_cancel_update_time_worker(ctrl_info);
8172        pqi_unregister_scsi(ctrl_info);
8173        if (ctrl_info->pqi_mode_enabled)
8174                pqi_revert_to_sis_mode(ctrl_info);
8175        pqi_free_ctrl_resources(ctrl_info);
8176}
8177
8178static void pqi_ofa_ctrl_quiesce(struct pqi_ctrl_info *ctrl_info)
8179{
8180        pqi_ctrl_block_scan(ctrl_info);
8181        pqi_scsi_block_requests(ctrl_info);
8182        pqi_ctrl_block_device_reset(ctrl_info);
8183        pqi_ctrl_block_requests(ctrl_info);
8184        pqi_ctrl_wait_until_quiesced(ctrl_info);
8185        pqi_stop_heartbeat_timer(ctrl_info);
8186}
8187
8188static void pqi_ofa_ctrl_unquiesce(struct pqi_ctrl_info *ctrl_info)
8189{
8190        pqi_start_heartbeat_timer(ctrl_info);
8191        pqi_ctrl_unblock_requests(ctrl_info);
8192        pqi_ctrl_unblock_device_reset(ctrl_info);
8193        pqi_scsi_unblock_requests(ctrl_info);
8194        pqi_ctrl_unblock_scan(ctrl_info);
8195}
8196
8197static int pqi_ofa_alloc_mem(struct pqi_ctrl_info *ctrl_info, u32 total_size, u32 chunk_size)
8198{
8199        int i;
8200        u32 sg_count;
8201        struct device *dev;
8202        struct pqi_ofa_memory *ofap;
8203        struct pqi_sg_descriptor *mem_descriptor;
8204        dma_addr_t dma_handle;
8205
8206        ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8207
8208        sg_count = DIV_ROUND_UP(total_size, chunk_size);
8209        if (sg_count == 0 || sg_count > PQI_OFA_MAX_SG_DESCRIPTORS)
8210                goto out;
8211
8212        ctrl_info->pqi_ofa_chunk_virt_addr = kmalloc_array(sg_count, sizeof(void *), GFP_KERNEL);
8213        if (!ctrl_info->pqi_ofa_chunk_virt_addr)
8214                goto out;
8215
8216        dev = &ctrl_info->pci_dev->dev;
8217
8218        for (i = 0; i < sg_count; i++) {
8219                ctrl_info->pqi_ofa_chunk_virt_addr[i] =
8220                        dma_alloc_coherent(dev, chunk_size, &dma_handle, GFP_KERNEL);
8221                if (!ctrl_info->pqi_ofa_chunk_virt_addr[i])
8222                        goto out_free_chunks;
8223                mem_descriptor = &ofap->sg_descriptor[i];
8224                put_unaligned_le64((u64)dma_handle, &mem_descriptor->address);
8225                put_unaligned_le32(chunk_size, &mem_descriptor->length);
8226        }
8227
8228        put_unaligned_le32(CISS_SG_LAST, &mem_descriptor->flags);
8229        put_unaligned_le16(sg_count, &ofap->num_memory_descriptors);
8230        put_unaligned_le32(sg_count * chunk_size, &ofap->bytes_allocated);
8231
8232        return 0;
8233
8234out_free_chunks:
8235        while (--i >= 0) {
8236                mem_descriptor = &ofap->sg_descriptor[i];
8237                dma_free_coherent(dev, chunk_size,
8238                        ctrl_info->pqi_ofa_chunk_virt_addr[i],
8239                        get_unaligned_le64(&mem_descriptor->address));
8240        }
8241        kfree(ctrl_info->pqi_ofa_chunk_virt_addr);
8242
8243out:
8244        return -ENOMEM;
8245}
8246
8247static int pqi_ofa_alloc_host_buffer(struct pqi_ctrl_info *ctrl_info)
8248{
8249        u32 total_size;
8250        u32 chunk_size;
8251        u32 min_chunk_size;
8252
8253        if (ctrl_info->ofa_bytes_requested == 0)
8254                return 0;
8255
8256        total_size = PAGE_ALIGN(ctrl_info->ofa_bytes_requested);
8257        min_chunk_size = DIV_ROUND_UP(total_size, PQI_OFA_MAX_SG_DESCRIPTORS);
8258        min_chunk_size = PAGE_ALIGN(min_chunk_size);
8259
8260        for (chunk_size = total_size; chunk_size >= min_chunk_size;) {
8261                if (pqi_ofa_alloc_mem(ctrl_info, total_size, chunk_size) == 0)
8262                        return 0;
8263                chunk_size /= 2;
8264                chunk_size = PAGE_ALIGN(chunk_size);
8265        }
8266
8267        return -ENOMEM;
8268}
8269
8270static void pqi_ofa_setup_host_buffer(struct pqi_ctrl_info *ctrl_info)
8271{
8272        struct device *dev;
8273        struct pqi_ofa_memory *ofap;
8274
8275        dev = &ctrl_info->pci_dev->dev;
8276
8277        ofap = dma_alloc_coherent(dev, sizeof(*ofap),
8278                &ctrl_info->pqi_ofa_mem_dma_handle, GFP_KERNEL);
8279        if (!ofap)
8280                return;
8281
8282        ctrl_info->pqi_ofa_mem_virt_addr = ofap;
8283
8284        if (pqi_ofa_alloc_host_buffer(ctrl_info) < 0) {
8285                dev_err(dev,
8286                        "failed to allocate host buffer for Online Firmware Activation\n");
8287                dma_free_coherent(dev, sizeof(*ofap), ofap, ctrl_info->pqi_ofa_mem_dma_handle);
8288                ctrl_info->pqi_ofa_mem_virt_addr = NULL;
8289                return;
8290        }
8291
8292        put_unaligned_le16(PQI_OFA_VERSION, &ofap->version);
8293        memcpy(&ofap->signature, PQI_OFA_SIGNATURE, sizeof(ofap->signature));
8294}
8295
8296static void pqi_ofa_free_host_buffer(struct pqi_ctrl_info *ctrl_info)
8297{
8298        unsigned int i;
8299        struct device *dev;
8300        struct pqi_ofa_memory *ofap;
8301        struct pqi_sg_descriptor *mem_descriptor;
8302        unsigned int num_memory_descriptors;
8303
8304        ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8305        if (!ofap)
8306                return;
8307
8308        dev = &ctrl_info->pci_dev->dev;
8309
8310        if (get_unaligned_le32(&ofap->bytes_allocated) == 0)
8311                goto out;
8312
8313        mem_descriptor = ofap->sg_descriptor;
8314        num_memory_descriptors =
8315                get_unaligned_le16(&ofap->num_memory_descriptors);
8316
8317        for (i = 0; i < num_memory_descriptors; i++) {
8318                dma_free_coherent(dev,
8319                        get_unaligned_le32(&mem_descriptor[i].length),
8320                        ctrl_info->pqi_ofa_chunk_virt_addr[i],
8321                        get_unaligned_le64(&mem_descriptor[i].address));
8322        }
8323        kfree(ctrl_info->pqi_ofa_chunk_virt_addr);
8324
8325out:
8326        dma_free_coherent(dev, sizeof(*ofap), ofap,
8327                ctrl_info->pqi_ofa_mem_dma_handle);
8328        ctrl_info->pqi_ofa_mem_virt_addr = NULL;
8329}
8330
8331static int pqi_ofa_host_memory_update(struct pqi_ctrl_info *ctrl_info)
8332{
8333        u32 buffer_length;
8334        struct pqi_vendor_general_request request;
8335        struct pqi_ofa_memory *ofap;
8336
8337        memset(&request, 0, sizeof(request));
8338
8339        request.header.iu_type = PQI_REQUEST_IU_VENDOR_GENERAL;
8340        put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
8341                &request.header.iu_length);
8342        put_unaligned_le16(PQI_VENDOR_GENERAL_HOST_MEMORY_UPDATE,
8343                &request.function_code);
8344
8345        ofap = ctrl_info->pqi_ofa_mem_virt_addr;
8346
8347        if (ofap) {
8348                buffer_length = offsetof(struct pqi_ofa_memory, sg_descriptor) +
8349                        get_unaligned_le16(&ofap->num_memory_descriptors) *
8350                        sizeof(struct pqi_sg_descriptor);
8351
8352                put_unaligned_le64((u64)ctrl_info->pqi_ofa_mem_dma_handle,
8353                        &request.data.ofa_memory_allocation.buffer_address);
8354                put_unaligned_le32(buffer_length,
8355                        &request.data.ofa_memory_allocation.buffer_length);
8356        }
8357
8358        return pqi_submit_raid_request_synchronous(ctrl_info, &request.header, 0, NULL);
8359}
8360
8361static int pqi_ofa_ctrl_restart(struct pqi_ctrl_info *ctrl_info, unsigned int delay_secs)
8362{
8363        ssleep(delay_secs);
8364
8365        return pqi_ctrl_init_resume(ctrl_info);
8366}
8367
8368static void pqi_perform_lockup_action(void)
8369{
8370        switch (pqi_lockup_action) {
8371        case PANIC:
8372                panic("FATAL: Smart Family Controller lockup detected");
8373                break;
8374        case REBOOT:
8375                emergency_restart();
8376                break;
8377        case NONE:
8378        default:
8379                break;
8380        }
8381}
8382
8383static struct pqi_raid_error_info pqi_ctrl_offline_raid_error_info = {
8384        .data_out_result = PQI_DATA_IN_OUT_HARDWARE_ERROR,
8385        .status = SAM_STAT_CHECK_CONDITION,
8386};
8387
8388static void pqi_fail_all_outstanding_requests(struct pqi_ctrl_info *ctrl_info)
8389{
8390        unsigned int i;
8391        struct pqi_io_request *io_request;
8392        struct scsi_cmnd *scmd;
8393
8394        for (i = 0; i < ctrl_info->max_io_slots; i++) {
8395                io_request = &ctrl_info->io_request_pool[i];
8396                if (atomic_read(&io_request->refcount) == 0)
8397                        continue;
8398
8399                scmd = io_request->scmd;
8400                if (scmd) {
8401                        set_host_byte(scmd, DID_NO_CONNECT);
8402                } else {
8403                        io_request->status = -ENXIO;
8404                        io_request->error_info =
8405                                &pqi_ctrl_offline_raid_error_info;
8406                }
8407
8408                io_request->io_complete_callback(io_request,
8409                        io_request->context);
8410        }
8411}
8412
8413static void pqi_take_ctrl_offline_deferred(struct pqi_ctrl_info *ctrl_info)
8414{
8415        pqi_perform_lockup_action();
8416        pqi_stop_heartbeat_timer(ctrl_info);
8417        pqi_free_interrupts(ctrl_info);
8418        pqi_cancel_rescan_worker(ctrl_info);
8419        pqi_cancel_update_time_worker(ctrl_info);
8420        pqi_ctrl_wait_until_quiesced(ctrl_info);
8421        pqi_fail_all_outstanding_requests(ctrl_info);
8422        pqi_ctrl_unblock_requests(ctrl_info);
8423}
8424
8425static void pqi_ctrl_offline_worker(struct work_struct *work)
8426{
8427        struct pqi_ctrl_info *ctrl_info;
8428
8429        ctrl_info = container_of(work, struct pqi_ctrl_info, ctrl_offline_work);
8430        pqi_take_ctrl_offline_deferred(ctrl_info);
8431}
8432
8433static void pqi_take_ctrl_offline(struct pqi_ctrl_info *ctrl_info)
8434{
8435        if (!ctrl_info->controller_online)
8436                return;
8437
8438        ctrl_info->controller_online = false;
8439        ctrl_info->pqi_mode_enabled = false;
8440        pqi_ctrl_block_requests(ctrl_info);
8441        if (!pqi_disable_ctrl_shutdown)
8442                sis_shutdown_ctrl(ctrl_info);
8443        pci_disable_device(ctrl_info->pci_dev);
8444        dev_err(&ctrl_info->pci_dev->dev, "controller offline\n");
8445        schedule_work(&ctrl_info->ctrl_offline_work);
8446}
8447
8448static void pqi_print_ctrl_info(struct pci_dev *pci_dev,
8449        const struct pci_device_id *id)
8450{
8451        char *ctrl_description;
8452
8453        if (id->driver_data)
8454                ctrl_description = (char *)id->driver_data;
8455        else
8456                ctrl_description = "Microchip Smart Family Controller";
8457
8458        dev_info(&pci_dev->dev, "%s found\n", ctrl_description);
8459}
8460
8461static int pqi_pci_probe(struct pci_dev *pci_dev,
8462        const struct pci_device_id *id)
8463{
8464        int rc;
8465        int node, cp_node;
8466        struct pqi_ctrl_info *ctrl_info;
8467
8468        pqi_print_ctrl_info(pci_dev, id);
8469
8470        if (pqi_disable_device_id_wildcards &&
8471                id->subvendor == PCI_ANY_ID &&
8472                id->subdevice == PCI_ANY_ID) {
8473                dev_warn(&pci_dev->dev,
8474                        "controller not probed because device ID wildcards are disabled\n");
8475                return -ENODEV;
8476        }
8477
8478        if (id->subvendor == PCI_ANY_ID || id->subdevice == PCI_ANY_ID)
8479                dev_warn(&pci_dev->dev,
8480                        "controller device ID matched using wildcards\n");
8481
8482        node = dev_to_node(&pci_dev->dev);
8483        if (node == NUMA_NO_NODE) {
8484                cp_node = cpu_to_node(0);
8485                if (cp_node == NUMA_NO_NODE)
8486                        cp_node = 0;
8487                set_dev_node(&pci_dev->dev, cp_node);
8488        }
8489
8490        ctrl_info = pqi_alloc_ctrl_info(node);
8491        if (!ctrl_info) {
8492                dev_err(&pci_dev->dev,
8493                        "failed to allocate controller info block\n");
8494                return -ENOMEM;
8495        }
8496
8497        ctrl_info->pci_dev = pci_dev;
8498
8499        rc = pqi_pci_init(ctrl_info);
8500        if (rc)
8501                goto error;
8502
8503        rc = pqi_ctrl_init(ctrl_info);
8504        if (rc)
8505                goto error;
8506
8507        return 0;
8508
8509error:
8510        pqi_remove_ctrl(ctrl_info);
8511
8512        return rc;
8513}
8514
8515static void pqi_pci_remove(struct pci_dev *pci_dev)
8516{
8517        struct pqi_ctrl_info *ctrl_info;
8518
8519        ctrl_info = pci_get_drvdata(pci_dev);
8520        if (!ctrl_info)
8521                return;
8522
8523        pqi_remove_ctrl(ctrl_info);
8524}
8525
8526static void pqi_crash_if_pending_command(struct pqi_ctrl_info *ctrl_info)
8527{
8528        unsigned int i;
8529        struct pqi_io_request *io_request;
8530        struct scsi_cmnd *scmd;
8531
8532        for (i = 0; i < ctrl_info->max_io_slots; i++) {
8533                io_request = &ctrl_info->io_request_pool[i];
8534                if (atomic_read(&io_request->refcount) == 0)
8535                        continue;
8536                scmd = io_request->scmd;
8537                WARN_ON(scmd != NULL); /* IO command from SML */
8538                WARN_ON(scmd == NULL); /* Non-IO cmd or driver initiated*/
8539        }
8540}
8541
8542static void pqi_shutdown(struct pci_dev *pci_dev)
8543{
8544        int rc;
8545        struct pqi_ctrl_info *ctrl_info;
8546
8547        ctrl_info = pci_get_drvdata(pci_dev);
8548        if (!ctrl_info) {
8549                dev_err(&pci_dev->dev,
8550                        "cache could not be flushed\n");
8551                return;
8552        }
8553
8554        pqi_wait_until_ofa_finished(ctrl_info);
8555
8556        pqi_scsi_block_requests(ctrl_info);
8557        pqi_ctrl_block_device_reset(ctrl_info);
8558        pqi_ctrl_block_requests(ctrl_info);
8559        pqi_ctrl_wait_until_quiesced(ctrl_info);
8560
8561        /*
8562         * Write all data in the controller's battery-backed cache to
8563         * storage.
8564         */
8565        rc = pqi_flush_cache(ctrl_info, SHUTDOWN);
8566        if (rc)
8567                dev_err(&pci_dev->dev,
8568                        "unable to flush controller cache\n");
8569
8570        pqi_crash_if_pending_command(ctrl_info);
8571        pqi_reset(ctrl_info);
8572}
8573
8574static void pqi_process_lockup_action_param(void)
8575{
8576        unsigned int i;
8577
8578        if (!pqi_lockup_action_param)
8579                return;
8580
8581        for (i = 0; i < ARRAY_SIZE(pqi_lockup_actions); i++) {
8582                if (strcmp(pqi_lockup_action_param,
8583                        pqi_lockup_actions[i].name) == 0) {
8584                        pqi_lockup_action = pqi_lockup_actions[i].action;
8585                        return;
8586                }
8587        }
8588
8589        pr_warn("%s: invalid lockup action setting \"%s\" - supported settings: none, reboot, panic\n",
8590                DRIVER_NAME_SHORT, pqi_lockup_action_param);
8591}
8592
8593static void pqi_process_module_params(void)
8594{
8595        pqi_process_lockup_action_param();
8596}
8597
8598static __maybe_unused int pqi_suspend(struct pci_dev *pci_dev, pm_message_t state)
8599{
8600        struct pqi_ctrl_info *ctrl_info;
8601
8602        ctrl_info = pci_get_drvdata(pci_dev);
8603
8604        pqi_wait_until_ofa_finished(ctrl_info);
8605
8606        pqi_ctrl_block_scan(ctrl_info);
8607        pqi_scsi_block_requests(ctrl_info);
8608        pqi_ctrl_block_device_reset(ctrl_info);
8609        pqi_ctrl_block_requests(ctrl_info);
8610        pqi_ctrl_wait_until_quiesced(ctrl_info);
8611        pqi_flush_cache(ctrl_info, SUSPEND);
8612        pqi_stop_heartbeat_timer(ctrl_info);
8613
8614        pqi_crash_if_pending_command(ctrl_info);
8615
8616        if (state.event == PM_EVENT_FREEZE)
8617                return 0;
8618
8619        pci_save_state(pci_dev);
8620        pci_set_power_state(pci_dev, pci_choose_state(pci_dev, state));
8621
8622        ctrl_info->controller_online = false;
8623        ctrl_info->pqi_mode_enabled = false;
8624
8625        return 0;
8626}
8627
8628static __maybe_unused int pqi_resume(struct pci_dev *pci_dev)
8629{
8630        int rc;
8631        struct pqi_ctrl_info *ctrl_info;
8632
8633        ctrl_info = pci_get_drvdata(pci_dev);
8634
8635        if (pci_dev->current_state != PCI_D0) {
8636                ctrl_info->max_hw_queue_index = 0;
8637                pqi_free_interrupts(ctrl_info);
8638                pqi_change_irq_mode(ctrl_info, IRQ_MODE_INTX);
8639                rc = request_irq(pci_irq_vector(pci_dev, 0), pqi_irq_handler,
8640                        IRQF_SHARED, DRIVER_NAME_SHORT,
8641                        &ctrl_info->queue_groups[0]);
8642                if (rc) {
8643                        dev_err(&ctrl_info->pci_dev->dev,
8644                                "irq %u init failed with error %d\n",
8645                                pci_dev->irq, rc);
8646                        return rc;
8647                }
8648                pqi_ctrl_unblock_device_reset(ctrl_info);
8649                pqi_ctrl_unblock_requests(ctrl_info);
8650                pqi_scsi_unblock_requests(ctrl_info);
8651                pqi_ctrl_unblock_scan(ctrl_info);
8652                return 0;
8653        }
8654
8655        pci_set_power_state(pci_dev, PCI_D0);
8656        pci_restore_state(pci_dev);
8657
8658        pqi_ctrl_unblock_device_reset(ctrl_info);
8659        pqi_ctrl_unblock_requests(ctrl_info);
8660        pqi_scsi_unblock_requests(ctrl_info);
8661        pqi_ctrl_unblock_scan(ctrl_info);
8662
8663        return pqi_ctrl_init_resume(ctrl_info);
8664}
8665
8666/* Define the PCI IDs for the controllers that we support. */
8667static const struct pci_device_id pqi_pci_id_table[] = {
8668        {
8669                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8670                               0x105b, 0x1211)
8671        },
8672        {
8673                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8674                               0x105b, 0x1321)
8675        },
8676        {
8677                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8678                               0x152d, 0x8a22)
8679        },
8680        {
8681                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8682                               0x152d, 0x8a23)
8683        },
8684        {
8685                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8686                               0x152d, 0x8a24)
8687        },
8688        {
8689                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8690                               0x152d, 0x8a36)
8691        },
8692        {
8693                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8694                               0x152d, 0x8a37)
8695        },
8696        {
8697                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8698                               0x193d, 0x8460)
8699        },
8700        {
8701                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8702                               0x193d, 0x1104)
8703        },
8704        {
8705                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8706                               0x193d, 0x1105)
8707        },
8708        {
8709                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8710                               0x193d, 0x1106)
8711        },
8712        {
8713                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8714                               0x193d, 0x1107)
8715        },
8716        {
8717                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8718                               0x193d, 0x1108)
8719        },
8720        {
8721                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8722                               0x193d, 0x1109)
8723        },
8724        {
8725                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8726                               0x193d, 0x8460)
8727        },
8728        {
8729                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8730                               0x193d, 0x8461)
8731        },
8732        {
8733                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8734                               0x193d, 0xc460)
8735        },
8736        {
8737                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8738                               0x193d, 0xc461)
8739        },
8740        {
8741                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8742                               0x193d, 0xf460)
8743        },
8744        {
8745                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8746                               0x193d, 0xf461)
8747        },
8748        {
8749                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8750                               0x1bd4, 0x0045)
8751        },
8752        {
8753                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8754                               0x1bd4, 0x0046)
8755        },
8756        {
8757                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8758                               0x1bd4, 0x0047)
8759        },
8760        {
8761                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8762                               0x1bd4, 0x0048)
8763        },
8764        {
8765                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8766                               0x1bd4, 0x004a)
8767        },
8768        {
8769                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8770                               0x1bd4, 0x004b)
8771        },
8772        {
8773                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8774                               0x1bd4, 0x004c)
8775        },
8776        {
8777                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8778                               0x1bd4, 0x004f)
8779        },
8780        {
8781                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8782                               0x1bd4, 0x0051)
8783        },
8784        {
8785                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8786                               0x1bd4, 0x0052)
8787        },
8788        {
8789                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8790                               0x1bd4, 0x0053)
8791        },
8792        {
8793                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8794                               0x1bd4, 0x0054)
8795        },
8796        {
8797                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8798                               0x19e5, 0xd227)
8799        },
8800        {
8801                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8802                               0x19e5, 0xd228)
8803        },
8804        {
8805                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8806                               0x19e5, 0xd229)
8807        },
8808        {
8809                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8810                               0x19e5, 0xd22a)
8811        },
8812        {
8813                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8814                               0x19e5, 0xd22b)
8815        },
8816        {
8817                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8818                               0x19e5, 0xd22c)
8819        },
8820        {
8821                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8822                               PCI_VENDOR_ID_ADAPTEC2, 0x0110)
8823        },
8824        {
8825                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8826                               PCI_VENDOR_ID_ADAPTEC2, 0x0608)
8827        },
8828        {
8829                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8830                               PCI_VENDOR_ID_ADAPTEC2, 0x0800)
8831        },
8832        {
8833                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8834                               PCI_VENDOR_ID_ADAPTEC2, 0x0801)
8835        },
8836        {
8837                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8838                               PCI_VENDOR_ID_ADAPTEC2, 0x0802)
8839        },
8840        {
8841                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8842                               PCI_VENDOR_ID_ADAPTEC2, 0x0803)
8843        },
8844        {
8845                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8846                               PCI_VENDOR_ID_ADAPTEC2, 0x0804)
8847        },
8848        {
8849                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8850                               PCI_VENDOR_ID_ADAPTEC2, 0x0805)
8851        },
8852        {
8853                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8854                               PCI_VENDOR_ID_ADAPTEC2, 0x0806)
8855        },
8856        {
8857                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8858                               PCI_VENDOR_ID_ADAPTEC2, 0x0807)
8859        },
8860        {
8861                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8862                               PCI_VENDOR_ID_ADAPTEC2, 0x0808)
8863        },
8864        {
8865                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8866                               PCI_VENDOR_ID_ADAPTEC2, 0x0809)
8867        },
8868        {
8869                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8870                               PCI_VENDOR_ID_ADAPTEC2, 0x080a)
8871        },
8872        {
8873                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8874                               PCI_VENDOR_ID_ADAPTEC2, 0x0900)
8875        },
8876        {
8877                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8878                               PCI_VENDOR_ID_ADAPTEC2, 0x0901)
8879        },
8880        {
8881                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8882                               PCI_VENDOR_ID_ADAPTEC2, 0x0902)
8883        },
8884        {
8885                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8886                               PCI_VENDOR_ID_ADAPTEC2, 0x0903)
8887        },
8888        {
8889                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8890                               PCI_VENDOR_ID_ADAPTEC2, 0x0904)
8891        },
8892        {
8893                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8894                               PCI_VENDOR_ID_ADAPTEC2, 0x0905)
8895        },
8896        {
8897                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8898                               PCI_VENDOR_ID_ADAPTEC2, 0x0906)
8899        },
8900        {
8901                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8902                               PCI_VENDOR_ID_ADAPTEC2, 0x0907)
8903        },
8904        {
8905                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8906                               PCI_VENDOR_ID_ADAPTEC2, 0x0908)
8907        },
8908        {
8909                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8910                               PCI_VENDOR_ID_ADAPTEC2, 0x090a)
8911        },
8912        {
8913                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8914                               PCI_VENDOR_ID_ADAPTEC2, 0x1200)
8915        },
8916        {
8917                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8918                               PCI_VENDOR_ID_ADAPTEC2, 0x1201)
8919        },
8920        {
8921                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8922                               PCI_VENDOR_ID_ADAPTEC2, 0x1202)
8923        },
8924        {
8925                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8926                               PCI_VENDOR_ID_ADAPTEC2, 0x1280)
8927        },
8928        {
8929                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8930                               PCI_VENDOR_ID_ADAPTEC2, 0x1281)
8931        },
8932        {
8933                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8934                               PCI_VENDOR_ID_ADAPTEC2, 0x1282)
8935        },
8936        {
8937                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8938                               PCI_VENDOR_ID_ADAPTEC2, 0x1300)
8939        },
8940        {
8941                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8942                               PCI_VENDOR_ID_ADAPTEC2, 0x1301)
8943        },
8944        {
8945                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8946                               PCI_VENDOR_ID_ADAPTEC2, 0x1302)
8947        },
8948        {
8949                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8950                               PCI_VENDOR_ID_ADAPTEC2, 0x1303)
8951        },
8952        {
8953                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8954                               PCI_VENDOR_ID_ADAPTEC2, 0x1380)
8955        },
8956        {
8957                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8958                               PCI_VENDOR_ID_ADAPTEC2, 0x1400)
8959        },
8960        {
8961                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8962                               PCI_VENDOR_ID_ADAPTEC2, 0x1402)
8963        },
8964        {
8965                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8966                               PCI_VENDOR_ID_ADAPTEC2, 0x1410)
8967        },
8968        {
8969                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8970                               PCI_VENDOR_ID_ADAPTEC2, 0x1411)
8971        },
8972        {
8973                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8974                               PCI_VENDOR_ID_ADAPTEC2, 0x1412)
8975        },
8976        {
8977                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8978                               PCI_VENDOR_ID_ADAPTEC2, 0x1420)
8979        },
8980        {
8981                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8982                               PCI_VENDOR_ID_ADAPTEC2, 0x1430)
8983        },
8984        {
8985                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8986                               PCI_VENDOR_ID_ADAPTEC2, 0x1440)
8987        },
8988        {
8989                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8990                               PCI_VENDOR_ID_ADAPTEC2, 0x1441)
8991        },
8992        {
8993                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8994                               PCI_VENDOR_ID_ADAPTEC2, 0x1450)
8995        },
8996        {
8997                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
8998                               PCI_VENDOR_ID_ADAPTEC2, 0x1452)
8999        },
9000        {
9001                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9002                               PCI_VENDOR_ID_ADAPTEC2, 0x1460)
9003        },
9004        {
9005                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9006                               PCI_VENDOR_ID_ADAPTEC2, 0x1461)
9007        },
9008        {
9009                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9010                               PCI_VENDOR_ID_ADAPTEC2, 0x1462)
9011        },
9012        {
9013                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9014                               PCI_VENDOR_ID_ADAPTEC2, 0x1470)
9015        },
9016        {
9017                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9018                               PCI_VENDOR_ID_ADAPTEC2, 0x1471)
9019        },
9020        {
9021                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9022                               PCI_VENDOR_ID_ADAPTEC2, 0x1472)
9023        },
9024        {
9025                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9026                               PCI_VENDOR_ID_ADAPTEC2, 0x1480)
9027        },
9028        {
9029                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9030                               PCI_VENDOR_ID_ADAPTEC2, 0x1490)
9031        },
9032        {
9033                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9034                               PCI_VENDOR_ID_ADAPTEC2, 0x1491)
9035        },
9036        {
9037                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9038                               PCI_VENDOR_ID_ADAPTEC2, 0x14a0)
9039        },
9040        {
9041                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9042                               PCI_VENDOR_ID_ADAPTEC2, 0x14a1)
9043        },
9044        {
9045                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9046                               PCI_VENDOR_ID_ADAPTEC2, 0x14b0)
9047        },
9048        {
9049                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9050                               PCI_VENDOR_ID_ADAPTEC2, 0x14b1)
9051        },
9052        {
9053                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9054                               PCI_VENDOR_ID_ADAPTEC2, 0x14c0)
9055        },
9056        {
9057                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9058                               PCI_VENDOR_ID_ADAPTEC2, 0x14c1)
9059        },
9060        {
9061                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9062                               PCI_VENDOR_ID_ADAPTEC2, 0x14d0)
9063        },
9064        {
9065                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9066                               PCI_VENDOR_ID_ADAPTEC2, 0x14e0)
9067        },
9068        {
9069                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9070                               PCI_VENDOR_ID_ADAPTEC2, 0x14f0)
9071        },
9072        {
9073                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9074                               PCI_VENDOR_ID_ADVANTECH, 0x8312)
9075        },
9076        {
9077                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9078                               PCI_VENDOR_ID_DELL, 0x1fe0)
9079        },
9080        {
9081                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9082                               PCI_VENDOR_ID_HP, 0x0600)
9083        },
9084        {
9085                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9086                               PCI_VENDOR_ID_HP, 0x0601)
9087        },
9088        {
9089                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9090                               PCI_VENDOR_ID_HP, 0x0602)
9091        },
9092        {
9093                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9094                               PCI_VENDOR_ID_HP, 0x0603)
9095        },
9096        {
9097                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9098                               PCI_VENDOR_ID_HP, 0x0609)
9099        },
9100        {
9101                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9102                               PCI_VENDOR_ID_HP, 0x0650)
9103        },
9104        {
9105                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9106                               PCI_VENDOR_ID_HP, 0x0651)
9107        },
9108        {
9109                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9110                               PCI_VENDOR_ID_HP, 0x0652)
9111        },
9112        {
9113                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9114                               PCI_VENDOR_ID_HP, 0x0653)
9115        },
9116        {
9117                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9118                               PCI_VENDOR_ID_HP, 0x0654)
9119        },
9120        {
9121                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9122                               PCI_VENDOR_ID_HP, 0x0655)
9123        },
9124        {
9125                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9126                               PCI_VENDOR_ID_HP, 0x0700)
9127        },
9128        {
9129                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9130                               PCI_VENDOR_ID_HP, 0x0701)
9131        },
9132        {
9133                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9134                               PCI_VENDOR_ID_HP, 0x1001)
9135        },
9136        {
9137                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9138                               PCI_VENDOR_ID_HP, 0x1002)
9139        },
9140        {
9141                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9142                               PCI_VENDOR_ID_HP, 0x1100)
9143        },
9144        {
9145                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9146                               PCI_VENDOR_ID_HP, 0x1101)
9147        },
9148        {
9149                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9150                               0x1590, 0x0294)
9151        },
9152        {
9153                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9154                               0x1590, 0x02db)
9155        },
9156        {
9157                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9158                               0x1590, 0x02dc)
9159        },
9160        {
9161                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9162                               0x1590, 0x032e)
9163        },
9164        {
9165                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9166                               0x1d8d, 0x0800)
9167        },
9168        {
9169                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9170                               0x1d8d, 0x0908)
9171        },
9172        {
9173                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9174                               0x1d8d, 0x0806)
9175        },
9176        {
9177                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9178                               0x1d8d, 0x0916)
9179        },
9180        {
9181                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9182                               PCI_VENDOR_ID_GIGABYTE, 0x1000)
9183        },
9184        {
9185                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9186                               0x1dfc, 0x3161)
9187        },
9188        {
9189                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9190                               0x1cf2, 0x5445)
9191        },
9192        {
9193                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9194                               0x1cf2, 0x5446)
9195        },
9196        {
9197                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9198                               0x1cf2, 0x5447)
9199        },
9200        {
9201                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9202                               0x1cf2, 0x0b27)
9203        },
9204        {
9205                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9206                               0x1cf2, 0x0b29)
9207        },
9208        {
9209                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9210                               0x1cf2, 0x0b45)
9211        },
9212        {
9213                PCI_DEVICE_SUB(PCI_VENDOR_ID_ADAPTEC2, 0x028f,
9214                               PCI_ANY_ID, PCI_ANY_ID)
9215        },
9216        { 0 }
9217};
9218
9219MODULE_DEVICE_TABLE(pci, pqi_pci_id_table);
9220
9221static struct pci_driver pqi_pci_driver = {
9222        .name = DRIVER_NAME_SHORT,
9223        .id_table = pqi_pci_id_table,
9224        .probe = pqi_pci_probe,
9225        .remove = pqi_pci_remove,
9226        .shutdown = pqi_shutdown,
9227#if defined(CONFIG_PM)
9228        .suspend = pqi_suspend,
9229        .resume = pqi_resume,
9230#endif
9231};
9232
9233static int __init pqi_init(void)
9234{
9235        int rc;
9236
9237        pr_info(DRIVER_NAME "\n");
9238
9239        pqi_sas_transport_template = sas_attach_transport(&pqi_sas_transport_functions);
9240        if (!pqi_sas_transport_template)
9241                return -ENODEV;
9242
9243        pqi_process_module_params();
9244
9245        rc = pci_register_driver(&pqi_pci_driver);
9246        if (rc)
9247                sas_release_transport(pqi_sas_transport_template);
9248
9249        return rc;
9250}
9251
9252static void __exit pqi_cleanup(void)
9253{
9254        pci_unregister_driver(&pqi_pci_driver);
9255        sas_release_transport(pqi_sas_transport_template);
9256}
9257
9258module_init(pqi_init);
9259module_exit(pqi_cleanup);
9260
9261static void __attribute__((unused)) verify_structures(void)
9262{
9263        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9264                sis_host_to_ctrl_doorbell) != 0x20);
9265        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9266                sis_interrupt_mask) != 0x34);
9267        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9268                sis_ctrl_to_host_doorbell) != 0x9c);
9269        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9270                sis_ctrl_to_host_doorbell_clear) != 0xa0);
9271        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9272                sis_driver_scratch) != 0xb0);
9273        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9274                sis_product_identifier) != 0xb4);
9275        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9276                sis_firmware_status) != 0xbc);
9277        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9278                sis_mailbox) != 0x1000);
9279        BUILD_BUG_ON(offsetof(struct pqi_ctrl_registers,
9280                pqi_registers) != 0x4000);
9281
9282        BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9283                iu_type) != 0x0);
9284        BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9285                iu_length) != 0x2);
9286        BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9287                response_queue_id) != 0x4);
9288        BUILD_BUG_ON(offsetof(struct pqi_iu_header,
9289                driver_flags) != 0x6);
9290        BUILD_BUG_ON(sizeof(struct pqi_iu_header) != 0x8);
9291
9292        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9293                status) != 0x0);
9294        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9295                service_response) != 0x1);
9296        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9297                data_present) != 0x2);
9298        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9299                reserved) != 0x3);
9300        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9301                residual_count) != 0x4);
9302        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9303                data_length) != 0x8);
9304        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9305                reserved1) != 0xa);
9306        BUILD_BUG_ON(offsetof(struct pqi_aio_error_info,
9307                data) != 0xc);
9308        BUILD_BUG_ON(sizeof(struct pqi_aio_error_info) != 0x10c);
9309
9310        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9311                data_in_result) != 0x0);
9312        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9313                data_out_result) != 0x1);
9314        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9315                reserved) != 0x2);
9316        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9317                status) != 0x5);
9318        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9319                status_qualifier) != 0x6);
9320        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9321                sense_data_length) != 0x8);
9322        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9323                response_data_length) != 0xa);
9324        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9325                data_in_transferred) != 0xc);
9326        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9327                data_out_transferred) != 0x10);
9328        BUILD_BUG_ON(offsetof(struct pqi_raid_error_info,
9329                data) != 0x14);
9330        BUILD_BUG_ON(sizeof(struct pqi_raid_error_info) != 0x114);
9331
9332        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9333                signature) != 0x0);
9334        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9335                function_and_status_code) != 0x8);
9336        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9337                max_admin_iq_elements) != 0x10);
9338        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9339                max_admin_oq_elements) != 0x11);
9340        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9341                admin_iq_element_length) != 0x12);
9342        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9343                admin_oq_element_length) != 0x13);
9344        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9345                max_reset_timeout) != 0x14);
9346        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9347                legacy_intx_status) != 0x18);
9348        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9349                legacy_intx_mask_set) != 0x1c);
9350        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9351                legacy_intx_mask_clear) != 0x20);
9352        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9353                device_status) != 0x40);
9354        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9355                admin_iq_pi_offset) != 0x48);
9356        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9357                admin_oq_ci_offset) != 0x50);
9358        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9359                admin_iq_element_array_addr) != 0x58);
9360        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9361                admin_oq_element_array_addr) != 0x60);
9362        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9363                admin_iq_ci_addr) != 0x68);
9364        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9365                admin_oq_pi_addr) != 0x70);
9366        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9367                admin_iq_num_elements) != 0x78);
9368        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9369                admin_oq_num_elements) != 0x79);
9370        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9371                admin_queue_int_msg_num) != 0x7a);
9372        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9373                device_error) != 0x80);
9374        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9375                error_details) != 0x88);
9376        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9377                device_reset) != 0x90);
9378        BUILD_BUG_ON(offsetof(struct pqi_device_registers,
9379                power_action) != 0x94);
9380        BUILD_BUG_ON(sizeof(struct pqi_device_registers) != 0x100);
9381
9382        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9383                header.iu_type) != 0);
9384        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9385                header.iu_length) != 2);
9386        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9387                header.driver_flags) != 6);
9388        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9389                request_id) != 8);
9390        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9391                function_code) != 10);
9392        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9393                data.report_device_capability.buffer_length) != 44);
9394        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9395                data.report_device_capability.sg_descriptor) != 48);
9396        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9397                data.create_operational_iq.queue_id) != 12);
9398        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9399                data.create_operational_iq.element_array_addr) != 16);
9400        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9401                data.create_operational_iq.ci_addr) != 24);
9402        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9403                data.create_operational_iq.num_elements) != 32);
9404        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9405                data.create_operational_iq.element_length) != 34);
9406        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9407                data.create_operational_iq.queue_protocol) != 36);
9408        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9409                data.create_operational_oq.queue_id) != 12);
9410        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9411                data.create_operational_oq.element_array_addr) != 16);
9412        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9413                data.create_operational_oq.pi_addr) != 24);
9414        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9415                data.create_operational_oq.num_elements) != 32);
9416        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9417                data.create_operational_oq.element_length) != 34);
9418        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9419                data.create_operational_oq.queue_protocol) != 36);
9420        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9421                data.create_operational_oq.int_msg_num) != 40);
9422        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9423                data.create_operational_oq.coalescing_count) != 42);
9424        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9425                data.create_operational_oq.min_coalescing_time) != 44);
9426        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9427                data.create_operational_oq.max_coalescing_time) != 48);
9428        BUILD_BUG_ON(offsetof(struct pqi_general_admin_request,
9429                data.delete_operational_queue.queue_id) != 12);
9430        BUILD_BUG_ON(sizeof(struct pqi_general_admin_request) != 64);
9431        BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9432                data.create_operational_iq) != 64 - 11);
9433        BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9434                data.create_operational_oq) != 64 - 11);
9435        BUILD_BUG_ON(sizeof_field(struct pqi_general_admin_request,
9436                data.delete_operational_queue) != 64 - 11);
9437
9438        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9439                header.iu_type) != 0);
9440        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9441                header.iu_length) != 2);
9442        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9443                header.driver_flags) != 6);
9444        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9445                request_id) != 8);
9446        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9447                function_code) != 10);
9448        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9449                status) != 11);
9450        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9451                data.create_operational_iq.status_descriptor) != 12);
9452        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9453                data.create_operational_iq.iq_pi_offset) != 16);
9454        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9455                data.create_operational_oq.status_descriptor) != 12);
9456        BUILD_BUG_ON(offsetof(struct pqi_general_admin_response,
9457                data.create_operational_oq.oq_ci_offset) != 16);
9458        BUILD_BUG_ON(sizeof(struct pqi_general_admin_response) != 64);
9459
9460        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9461                header.iu_type) != 0);
9462        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9463                header.iu_length) != 2);
9464        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9465                header.response_queue_id) != 4);
9466        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9467                header.driver_flags) != 6);
9468        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9469                request_id) != 8);
9470        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9471                nexus_id) != 10);
9472        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9473                buffer_length) != 12);
9474        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9475                lun_number) != 16);
9476        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9477                protocol_specific) != 24);
9478        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9479                error_index) != 27);
9480        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9481                cdb) != 32);
9482        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9483                timeout) != 60);
9484        BUILD_BUG_ON(offsetof(struct pqi_raid_path_request,
9485                sg_descriptors) != 64);
9486        BUILD_BUG_ON(sizeof(struct pqi_raid_path_request) !=
9487                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
9488
9489        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9490                header.iu_type) != 0);
9491        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9492                header.iu_length) != 2);
9493        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9494                header.response_queue_id) != 4);
9495        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9496                header.driver_flags) != 6);
9497        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9498                request_id) != 8);
9499        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9500                nexus_id) != 12);
9501        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9502                buffer_length) != 16);
9503        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9504                data_encryption_key_index) != 22);
9505        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9506                encrypt_tweak_lower) != 24);
9507        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9508                encrypt_tweak_upper) != 28);
9509        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9510                cdb) != 32);
9511        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9512                error_index) != 48);
9513        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9514                num_sg_descriptors) != 50);
9515        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9516                cdb_length) != 51);
9517        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9518                lun_number) != 52);
9519        BUILD_BUG_ON(offsetof(struct pqi_aio_path_request,
9520                sg_descriptors) != 64);
9521        BUILD_BUG_ON(sizeof(struct pqi_aio_path_request) !=
9522                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
9523
9524        BUILD_BUG_ON(offsetof(struct pqi_io_response,
9525                header.iu_type) != 0);
9526        BUILD_BUG_ON(offsetof(struct pqi_io_response,
9527                header.iu_length) != 2);
9528        BUILD_BUG_ON(offsetof(struct pqi_io_response,
9529                request_id) != 8);
9530        BUILD_BUG_ON(offsetof(struct pqi_io_response,
9531                error_index) != 10);
9532
9533        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9534                header.iu_type) != 0);
9535        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9536                header.iu_length) != 2);
9537        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9538                header.response_queue_id) != 4);
9539        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9540                request_id) != 8);
9541        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9542                data.report_event_configuration.buffer_length) != 12);
9543        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9544                data.report_event_configuration.sg_descriptors) != 16);
9545        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9546                data.set_event_configuration.global_event_oq_id) != 10);
9547        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9548                data.set_event_configuration.buffer_length) != 12);
9549        BUILD_BUG_ON(offsetof(struct pqi_general_management_request,
9550                data.set_event_configuration.sg_descriptors) != 16);
9551
9552        BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
9553                max_inbound_iu_length) != 6);
9554        BUILD_BUG_ON(offsetof(struct pqi_iu_layer_descriptor,
9555                max_outbound_iu_length) != 14);
9556        BUILD_BUG_ON(sizeof(struct pqi_iu_layer_descriptor) != 16);
9557
9558        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9559                data_length) != 0);
9560        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9561                iq_arbitration_priority_support_bitmask) != 8);
9562        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9563                maximum_aw_a) != 9);
9564        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9565                maximum_aw_b) != 10);
9566        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9567                maximum_aw_c) != 11);
9568        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9569                max_inbound_queues) != 16);
9570        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9571                max_elements_per_iq) != 18);
9572        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9573                max_iq_element_length) != 24);
9574        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9575                min_iq_element_length) != 26);
9576        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9577                max_outbound_queues) != 30);
9578        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9579                max_elements_per_oq) != 32);
9580        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9581                intr_coalescing_time_granularity) != 34);
9582        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9583                max_oq_element_length) != 36);
9584        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9585                min_oq_element_length) != 38);
9586        BUILD_BUG_ON(offsetof(struct pqi_device_capability,
9587                iu_layer_descriptors) != 64);
9588        BUILD_BUG_ON(sizeof(struct pqi_device_capability) != 576);
9589
9590        BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
9591                event_type) != 0);
9592        BUILD_BUG_ON(offsetof(struct pqi_event_descriptor,
9593                oq_id) != 2);
9594        BUILD_BUG_ON(sizeof(struct pqi_event_descriptor) != 4);
9595
9596        BUILD_BUG_ON(offsetof(struct pqi_event_config,
9597                num_event_descriptors) != 2);
9598        BUILD_BUG_ON(offsetof(struct pqi_event_config,
9599                descriptors) != 4);
9600
9601        BUILD_BUG_ON(PQI_NUM_SUPPORTED_EVENTS !=
9602                ARRAY_SIZE(pqi_supported_event_types));
9603
9604        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9605                header.iu_type) != 0);
9606        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9607                header.iu_length) != 2);
9608        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9609                event_type) != 8);
9610        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9611                event_id) != 10);
9612        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9613                additional_event_id) != 12);
9614        BUILD_BUG_ON(offsetof(struct pqi_event_response,
9615                data) != 16);
9616        BUILD_BUG_ON(sizeof(struct pqi_event_response) != 32);
9617
9618        BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9619                header.iu_type) != 0);
9620        BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9621                header.iu_length) != 2);
9622        BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9623                event_type) != 8);
9624        BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9625                event_id) != 10);
9626        BUILD_BUG_ON(offsetof(struct pqi_event_acknowledge_request,
9627                additional_event_id) != 12);
9628        BUILD_BUG_ON(sizeof(struct pqi_event_acknowledge_request) != 16);
9629
9630        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9631                header.iu_type) != 0);
9632        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9633                header.iu_length) != 2);
9634        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9635                request_id) != 8);
9636        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9637                nexus_id) != 10);
9638        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9639                timeout) != 14);
9640        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9641                lun_number) != 16);
9642        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9643                protocol_specific) != 24);
9644        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9645                outbound_queue_id_to_manage) != 26);
9646        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9647                request_id_to_manage) != 28);
9648        BUILD_BUG_ON(offsetof(struct pqi_task_management_request,
9649                task_management_function) != 30);
9650        BUILD_BUG_ON(sizeof(struct pqi_task_management_request) != 32);
9651
9652        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9653                header.iu_type) != 0);
9654        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9655                header.iu_length) != 2);
9656        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9657                request_id) != 8);
9658        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9659                nexus_id) != 10);
9660        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9661                additional_response_info) != 12);
9662        BUILD_BUG_ON(offsetof(struct pqi_task_management_response,
9663                response_code) != 15);
9664        BUILD_BUG_ON(sizeof(struct pqi_task_management_response) != 16);
9665
9666        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9667                configured_logical_drive_count) != 0);
9668        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9669                configuration_signature) != 1);
9670        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9671                firmware_version_short) != 5);
9672        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9673                extended_logical_unit_count) != 154);
9674        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9675                firmware_build_number) != 190);
9676        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9677                vendor_id) != 200);
9678        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9679                product_id) != 208);
9680        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9681                extra_controller_flags) != 286);
9682        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9683                controller_mode) != 292);
9684        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9685                spare_part_number) != 293);
9686        BUILD_BUG_ON(offsetof(struct bmic_identify_controller,
9687                firmware_version_long) != 325);
9688
9689        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9690                phys_bay_in_box) != 115);
9691        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9692                device_type) != 120);
9693        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9694                redundant_path_present_map) != 1736);
9695        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9696                active_path_number) != 1738);
9697        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9698                alternate_paths_phys_connector) != 1739);
9699        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9700                alternate_paths_phys_box_on_port) != 1755);
9701        BUILD_BUG_ON(offsetof(struct bmic_identify_physical_device,
9702                current_queue_depth_limit) != 1796);
9703        BUILD_BUG_ON(sizeof(struct bmic_identify_physical_device) != 2560);
9704
9705        BUILD_BUG_ON(sizeof(struct bmic_sense_feature_buffer_header) != 4);
9706        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9707                page_code) != 0);
9708        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9709                subpage_code) != 1);
9710        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_buffer_header,
9711                buffer_length) != 2);
9712
9713        BUILD_BUG_ON(sizeof(struct bmic_sense_feature_page_header) != 4);
9714        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9715                page_code) != 0);
9716        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9717                subpage_code) != 1);
9718        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_page_header,
9719                page_length) != 2);
9720
9721        BUILD_BUG_ON(sizeof(struct bmic_sense_feature_io_page_aio_subpage)
9722                != 18);
9723        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9724                header) != 0);
9725        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9726                firmware_read_support) != 4);
9727        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9728                driver_read_support) != 5);
9729        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9730                firmware_write_support) != 6);
9731        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9732                driver_write_support) != 7);
9733        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9734                max_transfer_encrypted_sas_sata) != 8);
9735        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9736                max_transfer_encrypted_nvme) != 10);
9737        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9738                max_write_raid_5_6) != 12);
9739        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9740                max_write_raid_1_10_2drive) != 14);
9741        BUILD_BUG_ON(offsetof(struct bmic_sense_feature_io_page_aio_subpage,
9742                max_write_raid_1_10_3drive) != 16);
9743
9744        BUILD_BUG_ON(PQI_ADMIN_IQ_NUM_ELEMENTS > 255);
9745        BUILD_BUG_ON(PQI_ADMIN_OQ_NUM_ELEMENTS > 255);
9746        BUILD_BUG_ON(PQI_ADMIN_IQ_ELEMENT_LENGTH %
9747                PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9748        BUILD_BUG_ON(PQI_ADMIN_OQ_ELEMENT_LENGTH %
9749                PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9750        BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH > 1048560);
9751        BUILD_BUG_ON(PQI_OPERATIONAL_IQ_ELEMENT_LENGTH %
9752                PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9753        BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH > 1048560);
9754        BUILD_BUG_ON(PQI_OPERATIONAL_OQ_ELEMENT_LENGTH %
9755                PQI_QUEUE_ELEMENT_LENGTH_ALIGNMENT != 0);
9756
9757        BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >= PQI_MAX_OUTSTANDING_REQUESTS);
9758        BUILD_BUG_ON(PQI_RESERVED_IO_SLOTS >=
9759                PQI_MAX_OUTSTANDING_REQUESTS_KDUMP);
9760}
9761