linux/drivers/scsi/smartpqi/smartpqi_init.c
<<
>>
Prefs
   1// SPDX-License-Identifier: GPL-2.0
   2/*
   3 *    driver for Microsemi PQI-based storage controllers
   4 *    Copyright (c) 2019-2020 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.8-045"
  37#define DRIVER_MAJOR            2
  38#define DRIVER_MINOR            1
  39#define DRIVER_RELEASE          8
  40#define DRIVER_REVISION         45
  41
  42#define DRIVER_NAME             "Microsemi PQI 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("Microsemi");
  52MODULE_DESCRIPTION("Driver for Microsemi 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                        goto error;
1326                }
1327        }
1328
1329        rc = pqi_validate_raid_map(ctrl_info, device, raid_map);
1330        if (rc)
1331                goto error;
1332
1333        device->raid_map = raid_map;
1334
1335        return 0;
1336
1337error:
1338        kfree(raid_map);
1339
1340        return rc;
1341}
1342
1343static void pqi_set_max_transfer_encrypted(struct pqi_ctrl_info *ctrl_info,
1344        struct pqi_scsi_dev *device)
1345{
1346        if (!ctrl_info->lv_drive_type_mix_valid) {
1347                device->max_transfer_encrypted = ~0;
1348                return;
1349        }
1350
1351        switch (LV_GET_DRIVE_TYPE_MIX(device->scsi3addr)) {
1352        case LV_DRIVE_TYPE_MIX_SAS_HDD_ONLY:
1353        case LV_DRIVE_TYPE_MIX_SATA_HDD_ONLY:
1354        case LV_DRIVE_TYPE_MIX_SAS_OR_SATA_SSD_ONLY:
1355        case LV_DRIVE_TYPE_MIX_SAS_SSD_ONLY:
1356        case LV_DRIVE_TYPE_MIX_SATA_SSD_ONLY:
1357        case LV_DRIVE_TYPE_MIX_SAS_ONLY:
1358        case LV_DRIVE_TYPE_MIX_SATA_ONLY:
1359                device->max_transfer_encrypted =
1360                        ctrl_info->max_transfer_encrypted_sas_sata;
1361                break;
1362        case LV_DRIVE_TYPE_MIX_NVME_ONLY:
1363                device->max_transfer_encrypted =
1364                        ctrl_info->max_transfer_encrypted_nvme;
1365                break;
1366        case LV_DRIVE_TYPE_MIX_UNKNOWN:
1367        case LV_DRIVE_TYPE_MIX_NO_RESTRICTION:
1368        default:
1369                device->max_transfer_encrypted =
1370                        min(ctrl_info->max_transfer_encrypted_sas_sata,
1371                                ctrl_info->max_transfer_encrypted_nvme);
1372                break;
1373        }
1374}
1375
1376static void pqi_get_raid_bypass_status(struct pqi_ctrl_info *ctrl_info,
1377        struct pqi_scsi_dev *device)
1378{
1379        int rc;
1380        u8 *buffer;
1381        u8 bypass_status;
1382
1383        buffer = kmalloc(64, GFP_KERNEL);
1384        if (!buffer)
1385                return;
1386
1387        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1388                VPD_PAGE | CISS_VPD_LV_BYPASS_STATUS, buffer, 64);
1389        if (rc)
1390                goto out;
1391
1392#define RAID_BYPASS_STATUS              4
1393#define RAID_BYPASS_CONFIGURED          0x1
1394#define RAID_BYPASS_ENABLED             0x2
1395
1396        bypass_status = buffer[RAID_BYPASS_STATUS];
1397        device->raid_bypass_configured =
1398                (bypass_status & RAID_BYPASS_CONFIGURED) != 0;
1399        if (device->raid_bypass_configured &&
1400                (bypass_status & RAID_BYPASS_ENABLED) &&
1401                pqi_get_raid_map(ctrl_info, device) == 0) {
1402                device->raid_bypass_enabled = true;
1403                if (get_unaligned_le16(&device->raid_map->flags) &
1404                        RAID_MAP_ENCRYPTION_ENABLED)
1405                        pqi_set_max_transfer_encrypted(ctrl_info, device);
1406        }
1407
1408out:
1409        kfree(buffer);
1410}
1411
1412/*
1413 * Use vendor-specific VPD to determine online/offline status of a volume.
1414 */
1415
1416static void pqi_get_volume_status(struct pqi_ctrl_info *ctrl_info,
1417        struct pqi_scsi_dev *device)
1418{
1419        int rc;
1420        size_t page_length;
1421        u8 volume_status = CISS_LV_STATUS_UNAVAILABLE;
1422        bool volume_offline = true;
1423        u32 volume_flags;
1424        struct ciss_vpd_logical_volume_status *vpd;
1425
1426        vpd = kmalloc(sizeof(*vpd), GFP_KERNEL);
1427        if (!vpd)
1428                goto no_buffer;
1429
1430        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr,
1431                VPD_PAGE | CISS_VPD_LV_STATUS, vpd, sizeof(*vpd));
1432        if (rc)
1433                goto out;
1434
1435        if (vpd->page_code != CISS_VPD_LV_STATUS)
1436                goto out;
1437
1438        page_length = offsetof(struct ciss_vpd_logical_volume_status,
1439                volume_status) + vpd->page_length;
1440        if (page_length < sizeof(*vpd))
1441                goto out;
1442
1443        volume_status = vpd->volume_status;
1444        volume_flags = get_unaligned_be32(&vpd->flags);
1445        volume_offline = (volume_flags & CISS_LV_FLAGS_NO_HOST_IO) != 0;
1446
1447out:
1448        kfree(vpd);
1449no_buffer:
1450        device->volume_status = volume_status;
1451        device->volume_offline = volume_offline;
1452}
1453
1454#define PQI_DEVICE_PHY_MAP_SUPPORTED    0x10
1455
1456static int pqi_get_physical_device_info(struct pqi_ctrl_info *ctrl_info,
1457        struct pqi_scsi_dev *device,
1458        struct bmic_identify_physical_device *id_phys)
1459{
1460        int rc;
1461
1462        memset(id_phys, 0, sizeof(*id_phys));
1463
1464        rc = pqi_identify_physical_device(ctrl_info, device,
1465                id_phys, sizeof(*id_phys));
1466        if (rc) {
1467                device->queue_depth = PQI_PHYSICAL_DISK_DEFAULT_MAX_QUEUE_DEPTH;
1468                return rc;
1469        }
1470
1471        scsi_sanitize_inquiry_string(&id_phys->model[0], 8);
1472        scsi_sanitize_inquiry_string(&id_phys->model[8], 16);
1473
1474        memcpy(device->vendor, &id_phys->model[0], sizeof(device->vendor));
1475        memcpy(device->model, &id_phys->model[8], sizeof(device->model));
1476
1477        device->box_index = id_phys->box_index;
1478        device->phys_box_on_bus = id_phys->phys_box_on_bus;
1479        device->phy_connected_dev_type = id_phys->phy_connected_dev_type[0];
1480        device->queue_depth =
1481                get_unaligned_le16(&id_phys->current_queue_depth_limit);
1482        device->active_path_index = id_phys->active_path_number;
1483        device->path_map = id_phys->redundant_path_present_map;
1484        memcpy(&device->box,
1485                &id_phys->alternate_paths_phys_box_on_port,
1486                sizeof(device->box));
1487        memcpy(&device->phys_connector,
1488                &id_phys->alternate_paths_phys_connector,
1489                sizeof(device->phys_connector));
1490        device->bay = id_phys->phys_bay_in_box;
1491
1492        memcpy(&device->page_83_identifier, &id_phys->page_83_identifier,
1493                sizeof(device->page_83_identifier));
1494
1495        if ((id_phys->even_more_flags & PQI_DEVICE_PHY_MAP_SUPPORTED) &&
1496                id_phys->phy_count)
1497                device->phy_id =
1498                        id_phys->phy_to_phy_map[device->active_path_index];
1499        else
1500                device->phy_id = 0xFF;
1501
1502        return 0;
1503}
1504
1505static int pqi_get_logical_device_info(struct pqi_ctrl_info *ctrl_info,
1506        struct pqi_scsi_dev *device)
1507{
1508        int rc;
1509        u8 *buffer;
1510
1511        buffer = kmalloc(64, GFP_KERNEL);
1512        if (!buffer)
1513                return -ENOMEM;
1514
1515        /* Send an inquiry to the device to see what it is. */
1516        rc = pqi_scsi_inquiry(ctrl_info, device->scsi3addr, 0, buffer, 64);
1517        if (rc)
1518                goto out;
1519
1520        scsi_sanitize_inquiry_string(&buffer[8], 8);
1521        scsi_sanitize_inquiry_string(&buffer[16], 16);
1522
1523        device->devtype = buffer[0] & 0x1f;
1524        memcpy(device->vendor, &buffer[8], sizeof(device->vendor));
1525        memcpy(device->model, &buffer[16], sizeof(device->model));
1526
1527        if (device->devtype == TYPE_DISK) {
1528                if (device->is_external_raid_device) {
1529                        device->raid_level = SA_RAID_UNKNOWN;
1530                        device->volume_status = CISS_LV_OK;
1531                        device->volume_offline = false;
1532                } else {
1533                        pqi_get_raid_level(ctrl_info, device);
1534                        pqi_get_raid_bypass_status(ctrl_info, device);
1535                        pqi_get_volume_status(ctrl_info, device);
1536                }
1537        }
1538
1539out:
1540        kfree(buffer);
1541
1542        return rc;
1543}
1544
1545static int pqi_get_device_info(struct pqi_ctrl_info *ctrl_info,
1546        struct pqi_scsi_dev *device,
1547        struct bmic_identify_physical_device *id_phys)
1548{
1549        int rc;
1550
1551        if (device->is_expander_smp_device)
1552                return 0;
1553
1554        if (pqi_is_logical_device(device))
1555                rc = pqi_get_logical_device_info(ctrl_info, device);
1556        else
1557                rc = pqi_get_physical_device_info(ctrl_info, device, id_phys);
1558
1559        return rc;
1560}
1561
1562static void pqi_show_volume_status(struct pqi_ctrl_info *ctrl_info,
1563        struct pqi_scsi_dev *device)
1564{
1565        char *status;
1566        static const char unknown_state_str[] =
1567                "Volume is in an unknown state (%u)";
1568        char unknown_state_buffer[sizeof(unknown_state_str) + 10];
1569
1570        switch (device->volume_status) {
1571        case CISS_LV_OK:
1572                status = "Volume online";
1573                break;
1574        case CISS_LV_FAILED:
1575                status = "Volume failed";
1576                break;
1577        case CISS_LV_NOT_CONFIGURED:
1578                status = "Volume not configured";
1579                break;
1580        case CISS_LV_DEGRADED:
1581                status = "Volume degraded";
1582                break;
1583        case CISS_LV_READY_FOR_RECOVERY:
1584                status = "Volume ready for recovery operation";
1585                break;
1586        case CISS_LV_UNDERGOING_RECOVERY:
1587                status = "Volume undergoing recovery";
1588                break;
1589        case CISS_LV_WRONG_PHYSICAL_DRIVE_REPLACED:
1590                status = "Wrong physical drive was replaced";
1591                break;
1592        case CISS_LV_PHYSICAL_DRIVE_CONNECTION_PROBLEM:
1593                status = "A physical drive not properly connected";
1594                break;
1595        case CISS_LV_HARDWARE_OVERHEATING:
1596                status = "Hardware is overheating";
1597                break;
1598        case CISS_LV_HARDWARE_HAS_OVERHEATED:
1599                status = "Hardware has overheated";
1600                break;
1601        case CISS_LV_UNDERGOING_EXPANSION:
1602                status = "Volume undergoing expansion";
1603                break;
1604        case CISS_LV_NOT_AVAILABLE:
1605                status = "Volume waiting for transforming volume";
1606                break;
1607        case CISS_LV_QUEUED_FOR_EXPANSION:
1608                status = "Volume queued for expansion";
1609                break;
1610        case CISS_LV_DISABLED_SCSI_ID_CONFLICT:
1611                status = "Volume disabled due to SCSI ID conflict";
1612                break;
1613        case CISS_LV_EJECTED:
1614                status = "Volume has been ejected";
1615                break;
1616        case CISS_LV_UNDERGOING_ERASE:
1617                status = "Volume undergoing background erase";
1618                break;
1619        case CISS_LV_READY_FOR_PREDICTIVE_SPARE_REBUILD:
1620                status = "Volume ready for predictive spare rebuild";
1621                break;
1622        case CISS_LV_UNDERGOING_RPI:
1623                status = "Volume undergoing rapid parity initialization";
1624                break;
1625        case CISS_LV_PENDING_RPI:
1626                status = "Volume queued for rapid parity initialization";
1627                break;
1628        case CISS_LV_ENCRYPTED_NO_KEY:
1629                status = "Encrypted volume inaccessible - key not present";
1630                break;
1631        case CISS_LV_UNDERGOING_ENCRYPTION:
1632                status = "Volume undergoing encryption process";
1633                break;
1634        case CISS_LV_UNDERGOING_ENCRYPTION_REKEYING:
1635                status = "Volume undergoing encryption re-keying process";
1636                break;
1637        case CISS_LV_ENCRYPTED_IN_NON_ENCRYPTED_CONTROLLER:
1638                status = "Volume encrypted but encryption is disabled";
1639                break;
1640        case CISS_LV_PENDING_ENCRYPTION:
1641                status = "Volume pending migration to encrypted state";
1642                break;
1643        case CISS_LV_PENDING_ENCRYPTION_REKEYING:
1644                status = "Volume pending encryption rekeying";
1645                break;
1646        case CISS_LV_NOT_SUPPORTED:
1647                status = "Volume not supported on this controller";
1648                break;
1649        case CISS_LV_STATUS_UNAVAILABLE:
1650                status = "Volume status not available";
1651                break;
1652        default:
1653                snprintf(unknown_state_buffer, sizeof(unknown_state_buffer),
1654                        unknown_state_str, device->volume_status);
1655                status = unknown_state_buffer;
1656                break;
1657        }
1658
1659        dev_info(&ctrl_info->pci_dev->dev,
1660                "scsi %d:%d:%d:%d %s\n",
1661                ctrl_info->scsi_host->host_no,
1662                device->bus, device->target, device->lun, status);
1663}
1664
1665static void pqi_rescan_worker(struct work_struct *work)
1666{
1667        struct pqi_ctrl_info *ctrl_info;
1668
1669        ctrl_info = container_of(to_delayed_work(work), struct pqi_ctrl_info,
1670                rescan_work);
1671
1672        pqi_scan_scsi_devices(ctrl_info);
1673}
1674
1675static int pqi_add_device(struct pqi_ctrl_info *ctrl_info,
1676        struct pqi_scsi_dev *device)
1677{
1678        int rc;
1679
1680        if (pqi_is_logical_device(device))
1681                rc = scsi_add_device(ctrl_info->scsi_host, device->bus,
1682                        device->target, device->lun);
1683        else
1684                rc = pqi_add_sas_device(ctrl_info->sas_host, device);
1685
1686        return rc;
1687}
1688
1689#define PQI_REMOVE_DEVICE_PENDING_IO_TIMEOUT_MSECS      (20 * 1000)
1690
1691static inline void pqi_remove_device(struct pqi_ctrl_info *ctrl_info, struct pqi_scsi_dev *device)
1692{
1693        int rc;
1694
1695        pqi_device_remove_start(device);
1696
1697        rc = pqi_device_wait_for_pending_io(ctrl_info, device,
1698                PQI_REMOVE_DEVICE_PENDING_IO_TIMEOUT_MSECS);
1699        if (rc)
1700                dev_err(&ctrl_info->pci_dev->dev,
1701                        "scsi %d:%d:%d:%d removing device with %d outstanding command(s)\n",
1702                        ctrl_info->scsi_host->host_no, device->bus,
1703                        device->target, device->lun,
1704                        atomic_read(&device->scsi_cmds_outstanding));
1705
1706        if (pqi_is_logical_device(device))
1707                scsi_remove_device(device->sdev);
1708        else
1709                pqi_remove_sas_device(device);
1710}
1711
1712/* Assumes the SCSI device list lock is held. */
1713
1714static struct pqi_scsi_dev *pqi_find_scsi_dev(struct pqi_ctrl_info *ctrl_info,
1715        int bus, int target, int lun)
1716{
1717        struct pqi_scsi_dev *device;
1718
1719        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1720                if (device->bus == bus && device->target == target && device->lun == lun)
1721                        return device;
1722
1723        return NULL;
1724}
1725
1726static inline bool pqi_device_equal(struct pqi_scsi_dev *dev1, struct pqi_scsi_dev *dev2)
1727{
1728        if (dev1->is_physical_device != dev2->is_physical_device)
1729                return false;
1730
1731        if (dev1->is_physical_device)
1732                return dev1->wwid == dev2->wwid;
1733
1734        return memcmp(dev1->volume_id, dev2->volume_id, sizeof(dev1->volume_id)) == 0;
1735}
1736
1737enum pqi_find_result {
1738        DEVICE_NOT_FOUND,
1739        DEVICE_CHANGED,
1740        DEVICE_SAME,
1741};
1742
1743static enum pqi_find_result pqi_scsi_find_entry(struct pqi_ctrl_info *ctrl_info,
1744        struct pqi_scsi_dev *device_to_find, struct pqi_scsi_dev **matching_device)
1745{
1746        struct pqi_scsi_dev *device;
1747
1748        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
1749                if (pqi_scsi3addr_equal(device_to_find->scsi3addr, device->scsi3addr)) {
1750                        *matching_device = device;
1751                        if (pqi_device_equal(device_to_find, device)) {
1752                                if (device_to_find->volume_offline)
1753                                        return DEVICE_CHANGED;
1754                                return DEVICE_SAME;
1755                        }
1756                        return DEVICE_CHANGED;
1757                }
1758        }
1759
1760        return DEVICE_NOT_FOUND;
1761}
1762
1763static inline const char *pqi_device_type(struct pqi_scsi_dev *device)
1764{
1765        if (device->is_expander_smp_device)
1766                return "Enclosure SMP    ";
1767
1768        return scsi_device_type(device->devtype);
1769}
1770
1771#define PQI_DEV_INFO_BUFFER_LENGTH      128
1772
1773static void pqi_dev_info(struct pqi_ctrl_info *ctrl_info,
1774        char *action, struct pqi_scsi_dev *device)
1775{
1776        ssize_t count;
1777        char buffer[PQI_DEV_INFO_BUFFER_LENGTH];
1778
1779        count = scnprintf(buffer, PQI_DEV_INFO_BUFFER_LENGTH,
1780                "%d:%d:", ctrl_info->scsi_host->host_no, device->bus);
1781
1782        if (device->target_lun_valid)
1783                count += scnprintf(buffer + count,
1784                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1785                        "%d:%d",
1786                        device->target,
1787                        device->lun);
1788        else
1789                count += scnprintf(buffer + count,
1790                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1791                        "-:-");
1792
1793        if (pqi_is_logical_device(device))
1794                count += scnprintf(buffer + count,
1795                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1796                        " %08x%08x",
1797                        *((u32 *)&device->scsi3addr),
1798                        *((u32 *)&device->scsi3addr[4]));
1799        else
1800                count += scnprintf(buffer + count,
1801                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1802                        " %016llx", device->sas_address);
1803
1804        count += scnprintf(buffer + count, PQI_DEV_INFO_BUFFER_LENGTH - count,
1805                " %s %.8s %.16s ",
1806                pqi_device_type(device),
1807                device->vendor,
1808                device->model);
1809
1810        if (pqi_is_logical_device(device)) {
1811                if (device->devtype == TYPE_DISK)
1812                        count += scnprintf(buffer + count,
1813                                PQI_DEV_INFO_BUFFER_LENGTH - count,
1814                                "SSDSmartPathCap%c En%c %-12s",
1815                                device->raid_bypass_configured ? '+' : '-',
1816                                device->raid_bypass_enabled ? '+' : '-',
1817                                pqi_raid_level_to_string(device->raid_level));
1818        } else {
1819                count += scnprintf(buffer + count,
1820                        PQI_DEV_INFO_BUFFER_LENGTH - count,
1821                        "AIO%c", device->aio_enabled ? '+' : '-');
1822                if (device->devtype == TYPE_DISK ||
1823                        device->devtype == TYPE_ZBC)
1824                        count += scnprintf(buffer + count,
1825                                PQI_DEV_INFO_BUFFER_LENGTH - count,
1826                                " qd=%-6d", device->queue_depth);
1827        }
1828
1829        dev_info(&ctrl_info->pci_dev->dev, "%s %s\n", action, buffer);
1830}
1831
1832/* Assumes the SCSI device list lock is held. */
1833
1834static void pqi_scsi_update_device(struct pqi_scsi_dev *existing_device,
1835        struct pqi_scsi_dev *new_device)
1836{
1837        existing_device->device_type = new_device->device_type;
1838        existing_device->bus = new_device->bus;
1839        if (new_device->target_lun_valid) {
1840                existing_device->target = new_device->target;
1841                existing_device->lun = new_device->lun;
1842                existing_device->target_lun_valid = true;
1843        }
1844
1845        if ((existing_device->volume_status == CISS_LV_QUEUED_FOR_EXPANSION ||
1846                existing_device->volume_status == CISS_LV_UNDERGOING_EXPANSION) &&
1847                new_device->volume_status == CISS_LV_OK)
1848                existing_device->rescan = true;
1849
1850        /* By definition, the scsi3addr and wwid fields are already the same. */
1851
1852        existing_device->is_physical_device = new_device->is_physical_device;
1853        existing_device->is_external_raid_device =
1854                new_device->is_external_raid_device;
1855        existing_device->is_expander_smp_device =
1856                new_device->is_expander_smp_device;
1857        existing_device->aio_enabled = new_device->aio_enabled;
1858        memcpy(existing_device->vendor, new_device->vendor,
1859                sizeof(existing_device->vendor));
1860        memcpy(existing_device->model, new_device->model,
1861                sizeof(existing_device->model));
1862        existing_device->sas_address = new_device->sas_address;
1863        existing_device->raid_level = new_device->raid_level;
1864        existing_device->queue_depth = new_device->queue_depth;
1865        existing_device->aio_handle = new_device->aio_handle;
1866        existing_device->volume_status = new_device->volume_status;
1867        existing_device->active_path_index = new_device->active_path_index;
1868        existing_device->phy_id = new_device->phy_id;
1869        existing_device->path_map = new_device->path_map;
1870        existing_device->bay = new_device->bay;
1871        existing_device->box_index = new_device->box_index;
1872        existing_device->phys_box_on_bus = new_device->phys_box_on_bus;
1873        existing_device->phy_connected_dev_type = new_device->phy_connected_dev_type;
1874        memcpy(existing_device->box, new_device->box,
1875                sizeof(existing_device->box));
1876        memcpy(existing_device->phys_connector, new_device->phys_connector,
1877                sizeof(existing_device->phys_connector));
1878        existing_device->next_bypass_group = 0;
1879        kfree(existing_device->raid_map);
1880        existing_device->raid_map = new_device->raid_map;
1881        existing_device->raid_bypass_configured =
1882                new_device->raid_bypass_configured;
1883        existing_device->raid_bypass_enabled =
1884                new_device->raid_bypass_enabled;
1885        existing_device->device_offline = false;
1886
1887        /* To prevent this from being freed later. */
1888        new_device->raid_map = NULL;
1889}
1890
1891static inline void pqi_free_device(struct pqi_scsi_dev *device)
1892{
1893        if (device) {
1894                kfree(device->raid_map);
1895                kfree(device);
1896        }
1897}
1898
1899/*
1900 * Called when exposing a new device to the OS fails in order to re-adjust
1901 * our internal SCSI device list to match the SCSI ML's view.
1902 */
1903
1904static inline void pqi_fixup_botched_add(struct pqi_ctrl_info *ctrl_info,
1905        struct pqi_scsi_dev *device)
1906{
1907        unsigned long flags;
1908
1909        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1910        list_del(&device->scsi_device_list_entry);
1911        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
1912
1913        /* Allow the device structure to be freed later. */
1914        device->keep_device = false;
1915}
1916
1917static inline bool pqi_is_device_added(struct pqi_scsi_dev *device)
1918{
1919        if (device->is_expander_smp_device)
1920                return device->sas_port != NULL;
1921
1922        return device->sdev != NULL;
1923}
1924
1925static void pqi_update_device_list(struct pqi_ctrl_info *ctrl_info,
1926        struct pqi_scsi_dev *new_device_list[], unsigned int num_new_devices)
1927{
1928        int rc;
1929        unsigned int i;
1930        unsigned long flags;
1931        enum pqi_find_result find_result;
1932        struct pqi_scsi_dev *device;
1933        struct pqi_scsi_dev *next;
1934        struct pqi_scsi_dev *matching_device;
1935        LIST_HEAD(add_list);
1936        LIST_HEAD(delete_list);
1937
1938        /*
1939         * The idea here is to do as little work as possible while holding the
1940         * spinlock.  That's why we go to great pains to defer anything other
1941         * than updating the internal device list until after we release the
1942         * spinlock.
1943         */
1944
1945        spin_lock_irqsave(&ctrl_info->scsi_device_list_lock, flags);
1946
1947        /* Assume that all devices in the existing list have gone away. */
1948        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry)
1949                device->device_gone = true;
1950
1951        for (i = 0; i < num_new_devices; i++) {
1952                device = new_device_list[i];
1953
1954                find_result = pqi_scsi_find_entry(ctrl_info, device,
1955                        &matching_device);
1956
1957                switch (find_result) {
1958                case DEVICE_SAME:
1959                        /*
1960                         * The newly found device is already in the existing
1961                         * device list.
1962                         */
1963                        device->new_device = false;
1964                        matching_device->device_gone = false;
1965                        pqi_scsi_update_device(matching_device, device);
1966                        break;
1967                case DEVICE_NOT_FOUND:
1968                        /*
1969                         * The newly found device is NOT in the existing device
1970                         * list.
1971                         */
1972                        device->new_device = true;
1973                        break;
1974                case DEVICE_CHANGED:
1975                        /*
1976                         * The original device has gone away and we need to add
1977                         * the new device.
1978                         */
1979                        device->new_device = true;
1980                        break;
1981                }
1982        }
1983
1984        /* Process all devices that have gone away. */
1985        list_for_each_entry_safe(device, next, &ctrl_info->scsi_device_list,
1986                scsi_device_list_entry) {
1987                if (device->device_gone) {
1988                        list_del_init(&device->scsi_device_list_entry);
1989                        list_add_tail(&device->delete_list_entry, &delete_list);
1990                }
1991        }
1992
1993        /* Process all new devices. */
1994        for (i = 0; i < num_new_devices; i++) {
1995                device = new_device_list[i];
1996                if (!device->new_device)
1997                        continue;
1998                if (device->volume_offline)
1999                        continue;
2000                list_add_tail(&device->scsi_device_list_entry,
2001                        &ctrl_info->scsi_device_list);
2002                list_add_tail(&device->add_list_entry, &add_list);
2003                /* To prevent this device structure from being freed later. */
2004                device->keep_device = true;
2005        }
2006
2007        spin_unlock_irqrestore(&ctrl_info->scsi_device_list_lock, flags);
2008
2009        /*
2010         * If OFA is in progress and there are devices that need to be deleted,
2011         * allow any pending reset operations to continue and unblock any SCSI
2012         * requests before removal.
2013         */
2014        if (pqi_ofa_in_progress(ctrl_info)) {
2015                list_for_each_entry_safe(device, next, &delete_list, delete_list_entry)
2016                        if (pqi_is_device_added(device))
2017                                pqi_device_remove_start(device);
2018                pqi_ctrl_unblock_device_reset(ctrl_info);
2019                pqi_scsi_unblock_requests(ctrl_info);
2020        }
2021
2022        /* Remove all devices that have gone away. */
2023        list_for_each_entry_safe(device, next, &delete_list, delete_list_entry) {
2024                if (device->volume_offline) {
2025                        pqi_dev_info(ctrl_info, "offline", device);
2026                        pqi_show_volume_status(ctrl_info, device);
2027                }
2028                list_del(&device->delete_list_entry);
2029                if (pqi_is_device_added(device)) {
2030                        pqi_remove_device(ctrl_info, device);
2031                } else {
2032                        if (!device->volume_offline)
2033                                pqi_dev_info(ctrl_info, "removed", device);
2034                        pqi_free_device(device);
2035                }
2036        }
2037
2038        /*
2039         * Notify the SCSI ML if the queue depth of any existing device has
2040         * changed.
2041         */
2042        list_for_each_entry(device, &ctrl_info->scsi_device_list, scsi_device_list_entry) {
2043                if (device->sdev && device->queue_depth != device->advertised_queue_depth) {
2044                        device->advertised_queue_depth = device->queue_depth;
2045                        scsi_change_queue_depth(device->sdev, device->advertised_queue_depth);
2046                        if (device->rescan) {
2047                                scsi_rescan_device(&device->sdev->sdev_gendev);
2048                                device->rescan = false;
2049                        }
2050                }
2051        }
2052
2053        /* Expose any new devices. */
2054        list_for_each_entry_safe(device, next, &add_list, add_list_entry) {
2055                if (!pqi_is_device_added(device)) {
2056                        rc = pqi_add_device(ctrl_info, device);
2057                        if (rc == 0) {
2058                                pqi_dev_info(ctrl_info, "added", device);
2059                        } else {
2060                                dev_warn(&ctrl_info->pci_dev->dev,
2061                                        "scsi %d:%d:%d:%d addition failed, device not added\n",
2062                                        ctrl_info->scsi_host->host_no,
2063                                        device->bus, device->target,
2064                                        device->lun);
2065                                pqi_fixup_botched_add(ctrl_info, device);
2066                        }
2067                }
2068        }
2069}
2070
2071static inline bool pqi_is_supported_device(struct pqi_scsi_dev *device)
2072{
2073        /*
2074         * Only support the HBA controller itself as a RAID
2075         * controller.  If it's a RAID controller other than
2076         * the HBA itself (an external RAID controller, for
2077         * example), we don't support it.
2078         */
2079        if (device->device_type == SA_DEVICE_TYPE_CONTROLLER &&
2080                !pqi_is_hba_lunid(device->scsi3addr))
2081                        return false;
2082
2083        return true;
2084}
2085
2086static inline bool pqi_skip_device(u8 *scsi3addr)
2087{
2088        /* Ignore all masked devices. */
2089        if (MASKED_DEVICE(scsi3addr))
2090                return true;
2091
2092        return false;
2093}
2094
2095static inline void pqi_mask_device(u8 *scsi3addr)
2096{
2097        scsi3addr[3] |= 0xc0;
2098}
2099
2100static inline bool pqi_is_device_with_sas_address(struct pqi_scsi_dev *device)
2101{
2102        switch (device->device_type) {
2103        case SA_DEVICE_TYPE_SAS:
2104        case SA_DEVICE_TYPE_EXPANDER_SMP:
2105        case SA_DEVICE_TYPE_SES:
2106                return true;
2107        }
2108
2109        return false;
2110}
2111
2112static inline bool pqi_expose_device(struct pqi_scsi_dev *device)
2113{
2114        return !device->is_physical_device || !pqi_skip_device(device->scsi3addr);
2115}
2116
2117static inline void pqi_set_physical_device_wwid(struct pqi_ctrl_info *ctrl_info,
2118        struct pqi_scsi_dev *device, struct report_phys_lun_extended_entry *phys_lun_ext_entry)
2119{
2120        if (ctrl_info->unique_wwid_in_report_phys_lun_supported ||
2121                pqi_is_device_with_sas_address(device))
2122                device->wwid = phys_lun_ext_entry->wwid;
2123        else
2124                device->wwid = cpu_to_be64(get_unaligned_be64(&device->page_83_identifier));
2125}
2126
2127static int pqi_update_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2128{
2129        int i;
2130        int rc;
2131        LIST_HEAD(new_device_list_head);
2132        struct report_phys_lun_extended *physdev_list = NULL;
2133        struct report_log_lun_extended *logdev_list = NULL;
2134        struct report_phys_lun_extended_entry *phys_lun_ext_entry;
2135        struct report_log_lun_extended_entry *log_lun_ext_entry;
2136        struct bmic_identify_physical_device *id_phys = NULL;
2137        u32 num_physicals;
2138        u32 num_logicals;
2139        struct pqi_scsi_dev **new_device_list = NULL;
2140        struct pqi_scsi_dev *device;
2141        struct pqi_scsi_dev *next;
2142        unsigned int num_new_devices;
2143        unsigned int num_valid_devices;
2144        bool is_physical_device;
2145        u8 *scsi3addr;
2146        unsigned int physical_index;
2147        unsigned int logical_index;
2148        static char *out_of_memory_msg =
2149                "failed to allocate memory, device discovery stopped";
2150
2151        rc = pqi_get_device_lists(ctrl_info, &physdev_list, &logdev_list);
2152        if (rc)
2153                goto out;
2154
2155        if (physdev_list)
2156                num_physicals =
2157                        get_unaligned_be32(&physdev_list->header.list_length)
2158                                / sizeof(physdev_list->lun_entries[0]);
2159        else
2160                num_physicals = 0;
2161
2162        if (logdev_list)
2163                num_logicals =
2164                        get_unaligned_be32(&logdev_list->header.list_length)
2165                                / sizeof(logdev_list->lun_entries[0]);
2166        else
2167                num_logicals = 0;
2168
2169        if (num_physicals) {
2170                /*
2171                 * We need this buffer for calls to pqi_get_physical_disk_info()
2172                 * below.  We allocate it here instead of inside
2173                 * pqi_get_physical_disk_info() because it's a fairly large
2174                 * buffer.
2175                 */
2176                id_phys = kmalloc(sizeof(*id_phys), GFP_KERNEL);
2177                if (!id_phys) {
2178                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2179                                out_of_memory_msg);
2180                        rc = -ENOMEM;
2181                        goto out;
2182                }
2183
2184                if (pqi_hide_vsep) {
2185                        for (i = num_physicals - 1; i >= 0; i--) {
2186                                phys_lun_ext_entry =
2187                                                &physdev_list->lun_entries[i];
2188                                if (CISS_GET_DRIVE_NUMBER(phys_lun_ext_entry->lunid) == PQI_VSEP_CISS_BTL) {
2189                                        pqi_mask_device(phys_lun_ext_entry->lunid);
2190                                        break;
2191                                }
2192                        }
2193                }
2194        }
2195
2196        if (num_logicals &&
2197                (logdev_list->header.flags & CISS_REPORT_LOG_FLAG_DRIVE_TYPE_MIX))
2198                ctrl_info->lv_drive_type_mix_valid = true;
2199
2200        num_new_devices = num_physicals + num_logicals;
2201
2202        new_device_list = kmalloc_array(num_new_devices,
2203                                        sizeof(*new_device_list),
2204                                        GFP_KERNEL);
2205        if (!new_device_list) {
2206                dev_warn(&ctrl_info->pci_dev->dev, "%s\n", out_of_memory_msg);
2207                rc = -ENOMEM;
2208                goto out;
2209        }
2210
2211        for (i = 0; i < num_new_devices; i++) {
2212                device = kzalloc(sizeof(*device), GFP_KERNEL);
2213                if (!device) {
2214                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2215                                out_of_memory_msg);
2216                        rc = -ENOMEM;
2217                        goto out;
2218                }
2219                list_add_tail(&device->new_device_list_entry,
2220                        &new_device_list_head);
2221        }
2222
2223        device = NULL;
2224        num_valid_devices = 0;
2225        physical_index = 0;
2226        logical_index = 0;
2227
2228        for (i = 0; i < num_new_devices; i++) {
2229
2230                if ((!pqi_expose_ld_first && i < num_physicals) ||
2231                        (pqi_expose_ld_first && i >= num_logicals)) {
2232                        is_physical_device = true;
2233                        phys_lun_ext_entry =
2234                                &physdev_list->lun_entries[physical_index++];
2235                        log_lun_ext_entry = NULL;
2236                        scsi3addr = phys_lun_ext_entry->lunid;
2237                } else {
2238                        is_physical_device = false;
2239                        phys_lun_ext_entry = NULL;
2240                        log_lun_ext_entry =
2241                                &logdev_list->lun_entries[logical_index++];
2242                        scsi3addr = log_lun_ext_entry->lunid;
2243                }
2244
2245                if (is_physical_device && pqi_skip_device(scsi3addr))
2246                        continue;
2247
2248                if (device)
2249                        device = list_next_entry(device, new_device_list_entry);
2250                else
2251                        device = list_first_entry(&new_device_list_head,
2252                                struct pqi_scsi_dev, new_device_list_entry);
2253
2254                memcpy(device->scsi3addr, scsi3addr, sizeof(device->scsi3addr));
2255                device->is_physical_device = is_physical_device;
2256                if (is_physical_device) {
2257                        device->device_type = phys_lun_ext_entry->device_type;
2258                        if (device->device_type == SA_DEVICE_TYPE_EXPANDER_SMP)
2259                                device->is_expander_smp_device = true;
2260                } else {
2261                        device->is_external_raid_device =
2262                                pqi_is_external_raid_addr(scsi3addr);
2263                }
2264
2265                if (!pqi_is_supported_device(device))
2266                        continue;
2267
2268                /* Gather information about the device. */
2269                rc = pqi_get_device_info(ctrl_info, device, id_phys);
2270                if (rc == -ENOMEM) {
2271                        dev_warn(&ctrl_info->pci_dev->dev, "%s\n",
2272                                out_of_memory_msg);
2273                        goto out;
2274                }
2275                if (rc) {
2276                        if (device->is_physical_device)
2277                                dev_warn(&ctrl_info->pci_dev->dev,
2278                                        "obtaining device info failed, skipping physical device %016llx\n",
2279                                        get_unaligned_be64(&phys_lun_ext_entry->wwid));
2280                        else
2281                                dev_warn(&ctrl_info->pci_dev->dev,
2282                                        "obtaining device info failed, skipping logical device %08x%08x\n",
2283                                        *((u32 *)&device->scsi3addr),
2284                                        *((u32 *)&device->scsi3addr[4]));
2285                        rc = 0;
2286                        continue;
2287                }
2288
2289                pqi_assign_bus_target_lun(device);
2290
2291                if (device->is_physical_device) {
2292                        pqi_set_physical_device_wwid(ctrl_info, device, phys_lun_ext_entry);
2293                        if ((phys_lun_ext_entry->device_flags &
2294                                CISS_REPORT_PHYS_DEV_FLAG_AIO_ENABLED) &&
2295                                phys_lun_ext_entry->aio_handle) {
2296                                        device->aio_enabled = true;
2297                                        device->aio_handle =
2298                                                phys_lun_ext_entry->aio_handle;
2299                        }
2300                } else {
2301                        memcpy(device->volume_id, log_lun_ext_entry->volume_id,
2302                                sizeof(device->volume_id));
2303                }
2304
2305                if (pqi_is_device_with_sas_address(device))
2306                        device->sas_address = get_unaligned_be64(&device->wwid);
2307
2308                new_device_list[num_valid_devices++] = device;
2309        }
2310
2311        pqi_update_device_list(ctrl_info, new_device_list, num_valid_devices);
2312
2313out:
2314        list_for_each_entry_safe(device, next, &new_device_list_head,
2315                new_device_list_entry) {
2316                if (device->keep_device)
2317                        continue;
2318                list_del(&device->new_device_list_entry);
2319                pqi_free_device(device);
2320        }
2321
2322        kfree(new_device_list);
2323        kfree(physdev_list);
2324        kfree(logdev_list);
2325        kfree(id_phys);
2326
2327        return rc;
2328}
2329
2330static int pqi_scan_scsi_devices(struct pqi_ctrl_info *ctrl_info)
2331{
2332        int rc;
2333        int mutex_acquired;
2334
2335        if (pqi_ctrl_offline(ctrl_info))
2336                return -ENXIO;
2337
2338        mutex_acquired = mutex_trylock(&ctrl_info->scan_mutex);
2339
2340        if (!mutex_acquired) {
2341                if (pqi_ctrl_scan_blocked(ctrl_info))
2342                        return -EBUSY;
2343                pqi_schedule_rescan_worker_delayed(ctrl_info);
2344                return -EINPROGRESS;
2345        }
2346
2347        rc = pqi_update_scsi_devices(ctrl_info);
2348        if (rc && !pqi_ctrl_scan_blocked(ctrl_info))
2349                pqi_schedule_rescan_worker_delayed(ctrl_info);
2350
2351        mutex_unlock(&ctrl_info->scan_mutex);
2352
2353        return rc;
2354}
2355
2356static void pqi_scan_start(struct Scsi_Host *shost)
2357{
2358        struct pqi_ctrl_info *ctrl_info;
2359
2360        ctrl_info = shost_to_hba(shost);
2361
2362        pqi_scan_scsi_devices(ctrl_info);
2363}
2364
2365/* Returns TRUE if scan is finished. */
2366
2367static int pqi_scan_finished(struct Scsi_Host *shost,
2368        unsigned long elapsed_time)
2369{
2370        struct pqi_ctrl_info *ctrl_info;
2371
2372        ctrl_info = shost_priv(shost);
2373
2374        return !mutex_is_locked(&ctrl_info->scan_mutex);
2375}
2376
2377static inline void pqi_set_encryption_info(struct pqi_encryption_info *encryption_info,
2378        struct raid_map *raid_map, u64 first_block)
2379{
2380        u32 volume_blk_size;
2381
2382        /*
2383         * Set the encryption tweak values based on logical block address.
2384         * If the block size is 512, the tweak value is equal to the LBA.
2385         * For other block sizes, tweak value is (LBA * block size) / 512.
2386         */
2387        volume_blk_size = get_unaligned_le32(&raid_map->volume_blk_size);
2388        if (volume_blk_size != 512)
2389                first_block = (first_block * volume_blk_size) / 512;
2390
2391        encryption_info->data_encryption_key_index =
2392                get_unaligned_le16(&raid_map->data_encryption_key_index);
2393        encryption_info->encrypt_tweak_lower = lower_32_bits(first_block);
2394        encryption_info->encrypt_tweak_upper = upper_32_bits(first_block);
2395}
2396
2397/*
2398 * Attempt to perform RAID bypass mapping for a logical volume I/O.
2399 */
2400
2401static bool pqi_aio_raid_level_supported(struct pqi_ctrl_info *ctrl_info,
2402        struct pqi_scsi_dev_raid_map_data *rmd)
2403{
2404        bool is_supported = true;
2405
2406        switch (rmd->raid_level) {
2407        case SA_RAID_0:
2408                break;
2409        case SA_RAID_1:
2410                if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2411                        rmd->data_length > ctrl_info->max_write_raid_1_10_2drive))
2412                        is_supported = false;
2413                break;
2414        case SA_RAID_TRIPLE:
2415                if (rmd->is_write && (!ctrl_info->enable_r1_writes ||
2416                        rmd->data_length > ctrl_info->max_write_raid_1_10_3drive))
2417                        is_supported = false;
2418                break;
2419        case SA_RAID_5:
2420                if (rmd->is_write && (!ctrl_info->enable_r5_writes ||
2421                        rmd->data_length > ctrl_info->max_write_raid_5_6))
2422                        is_supported = false;
2423                break;
2424        case SA_RAID_6:
2425                if (rmd->is_write && (!ctrl_info->enable_r6_writes ||
2426                        rmd->data_length > ctrl_info->max_write_raid_5_6))
2427                        is_supported = false;
2428                break;
2429        default:
2430                is_supported = false;
2431                break;
2432        }
2433
2434        return is_supported;
2435}
2436
2437#define PQI_RAID_BYPASS_INELIGIBLE      1
2438
2439static int pqi_get_aio_lba_and_block_count(struct scsi_cmnd *scmd,
2440        struct pqi_scsi_dev_raid_map_data *rmd)
2441{
2442        /* Check for valid opcode, get LBA and block count. */
2443        switch (scmd->cmnd[0]) {
2444        case WRITE_6:
2445                rmd->is_write = true;
2446                fallthrough;
2447        case READ_6:
2448                rmd->first_block = (u64)(((scmd->cmnd[1] & 0x1f) << 16) |
2449                        (scmd->cmnd[2] << 8) | scmd->cmnd[3]);
2450                rmd->block_cnt = (u32)scmd->cmnd[4];
2451                if (rmd->block_cnt == 0)
2452                        rmd->block_cnt = 256;
2453                break;
2454        case WRITE_10:
2455                rmd->is_write = true;
2456                fallthrough;
2457        case READ_10:
2458                rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2459                rmd->block_cnt = (u32)get_unaligned_be16(&scmd->cmnd[7]);
2460                break;
2461        case WRITE_12:
2462                rmd->is_write = true;
2463                fallthrough;
2464        case READ_12:
2465                rmd->first_block = (u64)get_unaligned_be32(&scmd->cmnd[2]);
2466                rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[6]);
2467                break;
2468        case WRITE_16:
2469                rmd->is_write = true;
2470                fallthrough;
2471        case READ_16:
2472                rmd->first_block = get_unaligned_be64(&scmd->cmnd[2]);
2473                rmd->block_cnt = get_unaligned_be32(&scmd->cmnd[10]);
2474                break;
2475        default:
2476                /* Process via normal I/O path. */
2477                return PQI_RAID_BYPASS_INELIGIBLE;
2478        }
2479
2480        put_unaligned_le32(scsi_bufflen(scmd), &rmd->data_length);
2481
2482        return 0;
2483}
2484
2485static int pci_get_aio_common_raid_map_values(struct pqi_ctrl_info *ctrl_info,
2486        struct pqi_scsi_dev_raid_map_data *rmd, struct raid_map *raid_map)
2487{
2488#if BITS_PER_LONG == 32
2489        u64 tmpdiv;
2490#endif
2491
2492        rmd->last_block = rmd->first_block + rmd->block_cnt - 1;
2493
2494        /* Check for invalid block or wraparound. */
2495        if (rmd->last_block >=
2496                get_unaligned_le64(&raid_map->volume_blk_cnt) ||
2497                rmd->last_block < rmd->first_block)
2498                return PQI_RAID_BYPASS_INELIGIBLE;
2499
2500        rmd->data_disks_per_row =
2501                get_unaligned_le16(&raid_map->data_disks_per_row);
2502        rmd->strip_size = get_unaligned_le16(&raid_map->strip_size);
2503        rmd->layout_map_count = get_unaligned_le16(&raid_map->layout_map_count);
2504
2505        /* Calculate stripe information for the request. */
2506        rmd->blocks_per_row = rmd->data_disks_per_row * rmd->strip_size;
2507        if (rmd->blocks_per_row == 0) /* Used as a divisor in many calculations */
2508                return PQI_RAID_BYPASS_INELIGIBLE;
2509#if BITS_PER_LONG == 32
2510        tmpdiv = rmd->first_block;
2511        do_div(tmpdiv, rmd->blocks_per_row);
2512        rmd->first_row = tmpdiv;
2513        tmpdiv = rmd->last_block;
2514        do_div(tmpdiv, rmd->blocks_per_row);
2515        rmd->last_row = tmpdiv;
2516        rmd->first_row_offset = (u32)(rmd->first_block - (rmd->first_row * rmd->blocks_per_row));
2517        rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row * rmd->blocks_per_row));
2518        tmpdiv = rmd->first_row_offset;
2519        do_div(tmpdiv, rmd->strip_size);
2520        rmd->first_column = tmpdiv;
2521        tmpdiv = rmd->last_row_offset;
2522        do_div(tmpdiv, rmd->strip_size);
2523        rmd->last_column = tmpdiv;
2524#else
2525        rmd->first_row = rmd->first_block / rmd->blocks_per_row;
2526        rmd->last_row = rmd->last_block / rmd->blocks_per_row;
2527        rmd->first_row_offset = (u32)(rmd->first_block -
2528                (rmd->first_row * rmd->blocks_per_row));
2529        rmd->last_row_offset = (u32)(rmd->last_block - (rmd->last_row *
2530                rmd->blocks_per_row));
2531        rmd->first_column = rmd->first_row_offset / rmd->strip_size;
2532        rmd->last_column = rmd->last_row_offset / rmd->strip_size;
2533#endif
2534
2535        /* If this isn't a single row/column then give to the controller. */
2536        if (rmd->first_row != rmd->last_row ||
2537                rmd->first_column != rmd->last_column)
2538                return PQI_RAID_BYPASS_INELIGIBLE;
2539
2540        /* Proceeding with driver mapping. */
2541        rmd->total_disks_per_row = rmd->data_disks_per_row +
2542                get_unaligned_le16(&raid_map->metadata_disks_per_row);
2543        rmd->map_row = ((u32)(rmd->first_row >>
2544                raid_map->parity_rotation_shift)) %
2545                get_unaligned_le16(&raid_map->row_cnt);
2546        rmd->map_index = (rmd->map_row * rmd->total_disks_per_row) +
2547                rmd->first_column;
2548
2549        return 0;
2550}
2551
2552static int pqi_calc_aio_r5_or_r6(struct pqi_scsi_dev_raid_map_data *rmd,
2553        struct raid_map *raid_map)
2554{
2555#if BITS_PER_LONG == 32
2556        u64 tmpdiv;
2557#endif
2558
2559        if (rmd->blocks_per_row == 0) /* Used as a divisor in many calculations */
2560                return PQI_RAID_BYPASS_INELIGIBLE;
2561
2562        /* RAID 50/60 */
2563        /* Verify first and last block are in same RAID group. */
2564        rmd->stripesize = rmd->blocks_per_row * rmd->layout_map_count;
2565#if BITS_PER_LONG == 32
2566        tmpdiv = rmd->first_block;
2567        rmd->first_group = do_div(tmpdiv, rmd->stripesize);
2568        tmpdiv = rmd->first_group;
2569        do_div(tmpdiv, rmd->blocks_per_row);
2570        rmd->first_group = tmpdiv;
2571        tmpdiv = rmd->last_block;
2572        rmd->last_group = do_div(tmpdiv, rmd->stripesize);
2573        tmpdiv = rmd->last_group;
2574        do_div(tmpdiv, rmd->blocks_per_row);
2575        rmd->last_group = tmpdiv;
2576#else
2577        rmd->first_group = (rmd->first_block % rmd->stripesize) / rmd->blocks_per_row;
2578        rmd->last_group = (rmd->last_block % rmd->stripesize) / rmd->blocks_per_row;
2579#endif
2580        if (rmd->first_group != rmd->last_group)
2581                return PQI_RAID_BYPASS_INELIGIBLE;
2582
2583        /* Verify request is in a single row of RAID 5/6. */
2584#if BITS_PER_LONG == 32
2585        tmpdiv = rmd->first_block;
2586        do_div(tmpdiv, rmd->stripesize);
2587        rmd->first_row = tmpdiv;
2588        rmd->r5or6_first_row = tmpdiv;
2589        tmpdiv = rmd->last_block;
2590        do_div(tmpdiv, rmd->stripesize);
2591        rmd->r5or6_last_row = tmpdiv;
2592#else
2593        rmd->first_row = rmd->r5or6_first_row =
2594                rmd->first_block / rmd->stripesize;
2595        rmd->r5or6_last_row = rmd->last_block / rmd->stripesize;
2596#endif
2597        if (rmd->r5or6_first_row != rmd->r5or6_last_row)
2598                return PQI_RAID_BYPASS_INELIGIBLE;
2599
2600        /* Verify request is in a single column. */
2601#if BITS_PER_LONG == 32
2602        tmpdiv = rmd->first_block;
2603        rmd->first_row_offset = do_div(tmpdiv, rmd->stripesize);
2604        tmpdiv = rmd->first_row_offset;
2605        rmd->first_row_offset = (u32)do_div(tmpdiv, rmd->blocks_per_row);
2606        rmd->r5or6_first_row_offset = rmd->first_row_offset;
2607        tmpdiv = rmd->last_block;
2608        rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->stripesize);
2609        tmpdiv = rmd->r5or6_last_row_offset;
2610        rmd->r5or6_last_row_offset = do_div(tmpdiv, rmd->blocks_per_row);
2611        tmpdiv = rmd->r5or6_first_row_offset;
2612        do_div(tmpdiv, rmd->strip_size);
2613        rmd->first_column = rmd->r5or6_first_column = tmpdiv;
2614        tmpdiv = rmd->r5or6_last_row_offset;
2615        do_div(tmpdiv, rmd->strip_size);
2616        rmd->r5or6_last_column = tmpdiv;
2617#else
2618        rmd->first_row_offset = rmd->r5or6_first_row_offset =
2619                (u32)((rmd->first_block % rmd->stripesize) %
2620                rmd->blocks_per_row);
2621
2622        rmd->r5or6_last_row_offset =
2623                (u32)((rmd->last_block % rmd->stripesize) %
2624                rmd->blocks_per_row);
2625
2626        rmd->first_column =
2627                rmd->r5or6_first_row_offset / rmd->strip_size;
2628        rmd->r5or6_first_column = rmd->first_column;
2629        rmd->r5or6_last_column = rmd->r5or6_last_row_offset / rmd->strip_size;
2630#endif
2631        if (rmd->r5or6_first_column != rmd->r5or6_last_column)
2632                return PQI_RAID_BYPASS_INELIGIBLE;
2633
2634        /* Request is eligible. */
2635        rmd->map_row =
2636                ((u32)(rmd->first_row >> raid_map->parity_rotation_shift)) %
2637                get_unaligned_le16(&raid_map->row_cnt);
2638
2639        rmd->map_index = (rmd->first_group *
2640                (get_unaligned_le16(&raid_map->row_cnt) *
2641                rmd->total_disks_per_row)) +
2642                (rmd->map_row * rmd->total_disks_per_row) + rmd->first_column;
2643
2644        if (rmd->is_write) {
2645                u32 index;
2646
2647                /*
2648                 * p_parity_it_nexus and q_parity_it_nexus are pointers to the
2649                 * parity entries inside the device's raid_map.
2650                 *
2651                 * A device's RAID map is bounded by: number of RAID disks squared.
2652                 *
2653                 * The devices RAID map size is checked during device
2654                 * initialization.
2655                 */
2656                index = DIV_ROUND_UP(rmd->map_index + 1, rmd->total_disks_per_row);
2657                index *= rmd->total_disks_per_row;
2658                index -= get_unaligned_le16(&raid_map->metadata_disks_per_row);
2659
2660                rmd->p_parity_it_nexus = raid_map->disk_data[index].aio_handle;
2661                if (rmd->raid_level == SA_RAID_6) {
2662                        rmd->q_parity_it_nexus = raid_map->disk_data[index + 1].aio_handle;
2663                        rmd->xor_mult = raid_map->disk_data[rmd->map_index].xor_mult[1];
2664                }
2665#if BITS_PER_LONG == 32
2666                tmpdiv = rmd->first_block;
2667                do_div(tmpdiv, rmd->blocks_per_row);
2668                rmd->row = tmpdiv;
2669#else
2670                rmd->row = rmd->first_block / rmd->blocks_per_row;
2671#endif
2672        }
2673
2674        return 0;
2675}
2676
2677static void pqi_set_aio_cdb(struct pqi_scsi_dev_raid_map_data *rmd)
2678{
2679        /* Build the new CDB for the physical disk I/O. */
2680        if (rmd->disk_block > 0xffffffff) {
2681                rmd->cdb[0] = rmd->is_write ? WRITE_16 : READ_16;
2682                rmd->cdb[1] = 0;
2683                put_unaligned_be64(rmd->disk_block, &rmd->cdb[2]);
2684                put_unaligned_be32(rmd->disk_block_cnt, &rmd->cdb[10]);
2685                rmd->cdb[14] = 0;
2686                rmd->cdb[15] = 0;
2687                rmd->cdb_length = 16;
2688        } else {
2689                rmd->cdb[0] = rmd->is_write ? WRITE_10 : READ_10;
2690                rmd->cdb[1] = 0;
2691                put_unaligned_be32((u32)rmd->disk_block, &rmd->cdb[2]);
2692                rmd->cdb[6] = 0;
2693                put_unaligned_be16((u16)rmd->disk_block_cnt, &rmd->cdb[7]);
2694                rmd->cdb[9] = 0;
2695                rmd->cdb_length = 10;
2696        }
2697}
2698
2699static void pqi_calc_aio_r1_nexus(struct raid_map *raid_map,
2700        struct pqi_scsi_dev_raid_map_data *rmd)
2701{
2702        u32 index;
2703        u32 group;
2704
2705        group = rmd->map_index / rmd->data_disks_per_row;
2706
2707        index = rmd->map_index - (group * rmd->data_disks_per_row);
2708        rmd->it_nexus[0] = raid_map->disk_data[index].aio_handle;
2709        index += rmd->data_disks_per_row;
2710        rmd->it_nexus[1] = raid_map->disk_data[index].aio_handle;
2711        if (rmd->layout_map_count > 2) {
2712                index += rmd->data_disks_per_row;
2713                rmd->it_nexus[2] = raid_map->disk_data[index].aio_handle;
2714        }
2715
2716        rmd->num_it_nexus_entries = rmd->layout_map_count;
2717}
2718
2719static int pqi_raid_bypass_submit_scsi_cmd(struct pqi_ctrl_info *ctrl_info,
2720        struct pqi_scsi_dev *device, struct scsi_cmnd *scmd,
2721        struct pqi_queue_group *queue_group)
2722{
2723        int rc;
2724        struct raid_map *raid_map;
2725        u32 group;
2726        u32 next_bypass_group;
2727        struct pqi_encryption_info *encryption_info_ptr;
2728        struct pqi_encryption_info encryption_info;
2729        struct pqi_scsi_dev_raid_map_data rmd = { 0 };
2730
2731        rc = pqi_get_aio_lba_and_block_count(scmd, &rmd);
2732        if (rc)
2733                return PQI_RAID_BYPASS_INELIGIBLE;
2734
2735        rmd.raid_level = device->raid_level;
2736
2737        if (!pqi_aio_raid_level_supported(ctrl_info, &rmd))
2738                return PQI_RAID_BYPASS_INELIGIBLE;
2739
2740        if (unlikely(rmd.block_cnt == 0))
2741                return PQI_RAID_BYPASS_INELIGIBLE;
2742
2743        raid_map = device->raid_map;
2744
2745        rc = pci_get_aio_common_raid_map_values(ctrl_info, &rmd, raid_map);
2746        if (rc)
2747                return PQI_RAID_BYPASS_INELIGIBLE;
2748
2749        if (device->raid_level == SA_RAID_1 ||
2750                device->raid_level == SA_RAID_TRIPLE) {
2751                if (rmd.is_write) {
2752                        pqi_calc_aio_r1_nexus(raid_map, &rmd);
2753                } else {
2754                        group = device->next_bypass_group;
2755                        next_bypass_group = group + 1;
2756                        if (next_bypass_group >= rmd.layout_map_count)
2757                                next_bypass_group = 0;
2758                        device->next_bypass_group = next_bypass_group;
2759                        rmd.map_index += group * rmd.data_disks_per_row;
2760                }
2761        } else if ((device->raid_level == SA_RAID_5 ||
2762                device->raid_level == SA_RAID_6) &&
2763                (rmd.layout_map_count > 1 || rmd.is_write)) {
2764                rc = pqi_calc_aio_r5_or_r6(&rmd, raid_map);
2765                if (rc)
2766                        return PQI_RAID_BYPASS_INELIGIBLE;
2767        }
2768
2769        if (unlikely(rmd.map_index >= RAID_MAP_MAX_ENTRIES))
2770                return PQI_RAID_BYPASS_INELIGIBLE;
2771
2772        rmd.aio_handle = raid_map->disk_data[rmd.map_index].aio_handle;
2773        rmd.disk_block = get_unaligned_le64(&raid_map->disk_starting_blk) +
2774                rmd.first_row * rmd.strip_size +
2775                (rmd.first_row_offset - rmd.first_column * rmd.strip_size);
2776        rmd.disk_block_cnt = rmd.block_cnt;
2777
2778        /* Handle differing logical/physical block sizes. */
2779        if (raid_map->phys_blk_shift) {
2780                rmd.disk_block <<= raid_map->phys_blk_shift;
2781                rmd.disk_block_cnt <<= raid_map->phys_blk_shift;
2782        }
2783
2784        if (unlikely(rmd.disk_block_cnt > 0xffff))
2785                return PQI_RAID_BYPASS_INELIGIBLE;
2786
2787        pqi_set_aio_cdb(&rmd);
2788
2789        if (get_unaligned_le16(&raid_map->flags) & RAID_MAP_ENCRYPTION_ENABLED) {
2790                if (rmd.data_length > device->max_transfer_encrypted)
2791                        return PQI_RAID_BYPASS_INELIGIBLE;
2792                pqi_set_encryption_info(&encryption_info, raid_map, rmd.first_block);
2793                encryption_info_ptr = &encryption_info;
2794        } else {
2795                encryption_info_ptr = NULL;
2796        }
2797
2798        if (rmd.is_write) {
2799                switch (device->raid_level) {
2800                case SA_RAID_1:
2801                case SA_RAID_TRIPLE:
2802                        return pqi_aio_submit_r1_write_io(ctrl_info, scmd, queue_group,
2803                                encryption_info_ptr, device, &rmd);
2804                case SA_RAID_5:
2805                case SA_RAID_6:
2806                        return pqi_aio_submit_r56_write_io(ctrl_info, scmd, queue_group,
2807                                encryption_info_ptr, device, &rmd);
2808                }
2809        }
2810
2811        return pqi_aio_submit_io(ctrl_info, scmd, rmd.aio_handle,
2812                rmd.cdb, rmd.cdb_length, queue_group,
2813                encryption_info_ptr, true);
2814}
2815
2816#define PQI_STATUS_IDLE         0x0
2817
2818#define PQI_CREATE_ADMIN_QUEUE_PAIR     1
2819#define PQI_DELETE_ADMIN_QUEUE_PAIR     2
2820
2821#define PQI_DEVICE_STATE_POWER_ON_AND_RESET             0x0
2822#define PQI_DEVICE_STATE_STATUS_AVAILABLE               0x1
2823#define PQI_DEVICE_STATE_ALL_REGISTERS_READY            0x2
2824#define PQI_DEVICE_STATE_ADMIN_QUEUE_PAIR_READY         0x3
2825#define PQI_DEVICE_STATE_ERROR                          0x4
2826
2827#define PQI_MODE_READY_TIMEOUT_SECS             30
2828#define PQI_MODE_READY_POLL_INTERVAL_MSECS      1
2829
2830static int pqi_wait_for_pqi_mode_ready(struct pqi_ctrl_info *ctrl_info)
2831{
2832        struct pqi_device_registers __iomem *pqi_registers;
2833        unsigned long timeout;
2834        u64 signature;
2835        u8 status;
2836
2837        pqi_registers = ctrl_info->pqi_registers;
2838        timeout = (PQI_MODE_READY_TIMEOUT_SECS * PQI_HZ) + jiffies;
2839
2840        while (1) {
2841                signature = readq(&pqi_registers->signature);
2842                if (memcmp(&signature, PQI_DEVICE_SIGNATURE,
2843                        sizeof(signature)) == 0)
2844                        break;
2845                if (time_after(jiffies, timeout)) {
2846                        dev_err(&ctrl_info->pci_dev->dev,
2847                                "timed out waiting for PQI signature\n");
2848                        return -ETIMEDOUT;
2849                }
2850                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2851        }
2852
2853        while (1) {
2854                status = readb(&pqi_registers->function_and_status_code);
2855                if (status == PQI_STATUS_IDLE)
2856                        break;
2857                if (time_after(jiffies, timeout)) {
2858                        dev_err(&ctrl_info->pci_dev->dev,
2859                                "timed out waiting for PQI IDLE\n");
2860                        return -ETIMEDOUT;
2861                }
2862                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2863        }
2864
2865        while (1) {
2866                if (readl(&pqi_registers->device_status) ==
2867                        PQI_DEVICE_STATE_ALL_REGISTERS_READY)
2868                        break;
2869                if (time_after(jiffies, timeout)) {
2870                        dev_err(&ctrl_info->pci_dev->dev,
2871                                "timed out waiting for PQI all registers ready\n");
2872                        return -ETIMEDOUT;
2873                }
2874                msleep(PQI_MODE_READY_POLL_INTERVAL_MSECS);
2875        }
2876
2877        return 0;
2878}
2879
2880static inline void pqi_aio_path_disabled(struct pqi_io_request *io_request)
2881{
2882        struct pqi_scsi_dev *device;
2883
2884        device = io_request->scmd->device->hostdata;
2885        device->raid_bypass_enabled = false;
2886        device->aio_enabled = false;
2887}
2888
2889static inline void pqi_take_device_offline(struct scsi_device *sdev, char *path)
2890{
2891        struct pqi_ctrl_info *ctrl_info;
2892        struct pqi_scsi_dev *device;
2893
2894        device = sdev->hostdata;
2895        if (device->device_offline)
2896                return;
2897
2898        device->device_offline = true;
2899        ctrl_info = shost_to_hba(sdev->host);
2900        pqi_schedule_rescan_worker(ctrl_info);
2901        dev_err(&ctrl_info->pci_dev->dev, "re-scanning %s scsi %d:%d:%d:%d\n",
2902                path, ctrl_info->scsi_host->host_no, device->bus,
2903                device->target, device->lun);
2904}
2905
2906static void pqi_process_raid_io_error(struct pqi_io_request *io_request)
2907{
2908        u8 scsi_status;
2909        u8 host_byte;
2910        struct scsi_cmnd *scmd;
2911        struct pqi_raid_error_info *error_info;
2912        size_t sense_data_length;
2913        int residual_count;
2914        int xfer_count;
2915        struct scsi_sense_hdr sshdr;
2916
2917        scmd = io_request->scmd;
2918        if (!scmd)
2919                return;
2920
2921        error_info = io_request->error_info;
2922        scsi_status = error_info->status;
2923        host_byte = DID_OK;
2924
2925        switch (error_info->data_out_result) {
2926        case PQI_DATA_IN_OUT_GOOD:
2927                break;
2928        case PQI_DATA_IN_OUT_UNDERFLOW:
2929                xfer_count =
2930                        get_unaligned_le32(&error_info->data_out_transferred);
2931                residual_count = scsi_bufflen(scmd) - xfer_count;
2932                scsi_set_resid(scmd, residual_count);
2933                if (xfer_count < scmd->underflow)
2934                        host_byte = DID_SOFT_ERROR;
2935                break;
2936        case PQI_DATA_IN_OUT_UNSOLICITED_ABORT:
2937        case PQI_DATA_IN_OUT_ABORTED:
2938                host_byte = DID_ABORT;
2939                break;
2940        case PQI_DATA_IN_OUT_TIMEOUT:
2941                host_byte = DID_TIME_OUT;
2942                break;
2943        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW:
2944        case PQI_DATA_IN_OUT_PROTOCOL_ERROR:
2945        case PQI_DATA_IN_OUT_BUFFER_ERROR:
2946        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_DESCRIPTOR_AREA:
2947        case PQI_DATA_IN_OUT_BUFFER_OVERFLOW_BRIDGE:
2948        case PQI_DATA_IN_OUT_ERROR:
2949        case PQI_DATA_IN_OUT_HARDWARE_ERROR:
2950        case PQI_DATA_IN_OUT_PCIE_FABRIC_ERROR:
2951        case PQI_DATA_IN_OUT_PCIE_COMPLETION_TIMEOUT:
2952        case PQI_DATA_IN_OUT_PCIE_COMPLETER_ABORT_RECEIVED:
2953        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST_RECEIVED:
2954        case PQI_DATA_IN_OUT_PCIE_ECRC_CHECK_FAILED:
2955        case PQI_DATA_IN_OUT_PCIE_UNSUPPORTED_REQUEST:
2956        case PQI_DATA_IN_OUT_PCIE_ACS_VIOLATION:
2957        case PQI_DATA_IN_OUT_PCIE_TLP_PREFIX_BLOCKED:
2958        case PQI_DATA_IN_OUT_PCIE_POISONED_MEMORY_READ:
2959        default:
2960                host_byte = DID_ERROR;
2961                break;
2962        }
2963
2964        sense_data_length = get_unaligned_le16(&error_info->sense_data_length);
2965        if (sense_data_length == 0)
2966                sense_data_length =
2967                        get_unaligned_le16(&error_info->response_data_length);
2968        if (sense_data_length) {
2969                if (sense_data_length > sizeof(error_info->data))
2970                        sense_data_length = sizeof(error_info->data);
2971
2972                if (scsi_status == SAM_STAT_CHECK_CONDITION &&
2973                        scsi_normalize_sense(error_info->data,
2974                                sense_data_length, &sshdr) &&
2975                                sshdr.sense_key == HARDWARE_ERROR &&
2976                                sshdr.asc == 0x3e) {
2977                        struct pqi_ctrl_info *ctrl_info = shost_to_hba(scmd->device->host);
2978                        struct pqi_scsi_dev *device = scmd->device->hostdata;
2979
2980                        switch (sshdr.ascq) {
2981                        case 0x1: /* LOGICAL UNIT FAILURE */
2982                                if (printk_ratelimit())
2983                                        scmd_printk(KERN_ERR, scmd, "received 'logical unit failure' from controller for scsi %d:%d:%d:%d\n",
2984                                                ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2985                                pqi_take_device_offline(scmd->device, "RAID");
2986                                host_byte = DID_NO_CONNECT;
2987                                break;
2988
2989                        default: /* See http://www.t10.org/lists/asc-num.htm#ASC_3E */
2990                                if (printk_ratelimit())
2991                                        scmd_printk(KERN_ERR, scmd, "received unhandled error %d from controller for scsi %d:%d:%d:%d\n",
2992                                                sshdr.ascq, ctrl_info->scsi_host->host_no, device->bus, device->target, device->lun);
2993                                break;
2994                        }
2995                }
2996
2997                if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
2998                        sense_data_length = SCSI_SENSE_BUFFERSIZE;
2999                memcpy(scmd->sense_buffer, error_info->data,
3000                        sense_data_length);
3001        }
3002
3003        scmd->result = scsi_status;
3004        set_host_byte(scmd, host_byte);
3005}
3006
3007static void pqi_process_aio_io_error(struct pqi_io_request *io_request)
3008{
3009        u8 scsi_status;
3010        u8 host_byte;
3011        struct scsi_cmnd *scmd;
3012        struct pqi_aio_error_info *error_info;
3013        size_t sense_data_length;
3014        int residual_count;
3015        int xfer_count;
3016        bool device_offline;
3017
3018        scmd = io_request->scmd;
3019        error_info = io_request->error_info;
3020        host_byte = DID_OK;
3021        sense_data_length = 0;
3022        device_offline = false;
3023
3024        switch (error_info->service_response) {
3025        case PQI_AIO_SERV_RESPONSE_COMPLETE:
3026                scsi_status = error_info->status;
3027                break;
3028        case PQI_AIO_SERV_RESPONSE_FAILURE:
3029                switch (error_info->status) {
3030                case PQI_AIO_STATUS_IO_ABORTED:
3031                        scsi_status = SAM_STAT_TASK_ABORTED;
3032                        break;
3033                case PQI_AIO_STATUS_UNDERRUN:
3034                        scsi_status = SAM_STAT_GOOD;
3035                        residual_count = get_unaligned_le32(
3036                                                &error_info->residual_count);
3037                        scsi_set_resid(scmd, residual_count);
3038                        xfer_count = scsi_bufflen(scmd) - residual_count;
3039                        if (xfer_count < scmd->underflow)
3040                                host_byte = DID_SOFT_ERROR;
3041                        break;
3042                case PQI_AIO_STATUS_OVERRUN:
3043                        scsi_status = SAM_STAT_GOOD;
3044                        break;
3045                case PQI_AIO_STATUS_AIO_PATH_DISABLED:
3046                        pqi_aio_path_disabled(io_request);
3047                        scsi_status = SAM_STAT_GOOD;
3048                        io_request->status = -EAGAIN;
3049                        break;
3050                case PQI_AIO_STATUS_NO_PATH_TO_DEVICE:
3051                case PQI_AIO_STATUS_INVALID_DEVICE:
3052                        if (!io_request->raid_bypass) {
3053                                device_offline = true;
3054                                pqi_take_device_offline(scmd->device, "AIO");
3055                                host_byte = DID_NO_CONNECT;
3056                        }
3057                        scsi_status = SAM_STAT_CHECK_CONDITION;
3058                        break;
3059                case PQI_AIO_STATUS_IO_ERROR:
3060                default:
3061                        scsi_status = SAM_STAT_CHECK_CONDITION;
3062                        break;
3063                }
3064                break;
3065        case PQI_AIO_SERV_RESPONSE_TMF_COMPLETE:
3066        case PQI_AIO_SERV_RESPONSE_TMF_SUCCEEDED:
3067                scsi_status = SAM_STAT_GOOD;
3068                break;
3069        case PQI_AIO_SERV_RESPONSE_TMF_REJECTED:
3070        case PQI_AIO_SERV_RESPONSE_TMF_INCORRECT_LUN:
3071        default:
3072                scsi_status = SAM_STAT_CHECK_CONDITION;
3073                break;
3074        }
3075
3076        if (error_info->data_present) {
3077                sense_data_length =
3078                        get_unaligned_le16(&error_info->data_length);
3079                if (sense_data_length) {
3080                        if (sense_data_length > sizeof(error_info->data))
3081                                sense_data_length = sizeof(error_info->data);
3082                        if (sense_data_length > SCSI_SENSE_BUFFERSIZE)
3083                                sense_data_length = SCSI_SENSE_BUFFERSIZE;
3084                        memcpy(scmd->sense_buffer, error_info->data,
3085                                sense_data_length);
3086                }
3087        }
3088
3089        if (device_offline && sense_data_length == 0)
3090                scsi_build_sense(scmd, 0, HARDWARE_ERROR, 0x3e, 0x1);
3091
3092        scmd->result = scsi_status;
3093        set_host_byte(scmd, host_byte);
3094}
3095
3096static void pqi_process_io_error(unsigned int iu_type,
3097        struct pqi_io_request *io_request)
3098{
3099        switch (iu_type) {
3100        case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3101                pqi_process_raid_io_error(io_request);
3102                break;
3103        case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3104                pqi_process_aio_io_error(io_request);
3105                break;
3106        }
3107}
3108
3109static int pqi_interpret_task_management_response(struct pqi_ctrl_info *ctrl_info,
3110        struct pqi_task_management_response *response)
3111{
3112        int rc;
3113
3114        switch (response->response_code) {
3115        case SOP_TMF_COMPLETE:
3116        case SOP_TMF_FUNCTION_SUCCEEDED:
3117                rc = 0;
3118                break;
3119        case SOP_TMF_REJECTED:
3120                rc = -EAGAIN;
3121                break;
3122        default:
3123                rc = -EIO;
3124                break;
3125        }
3126
3127        if (rc)
3128                dev_err(&ctrl_info->pci_dev->dev,
3129                        "Task Management Function error: %d (response code: %u)\n", rc, response->response_code);
3130
3131        return rc;
3132}
3133
3134static inline void pqi_invalid_response(struct pqi_ctrl_info *ctrl_info)
3135{
3136        pqi_take_ctrl_offline(ctrl_info);
3137}
3138
3139static int pqi_process_io_intr(struct pqi_ctrl_info *ctrl_info, struct pqi_queue_group *queue_group)
3140{
3141        int num_responses;
3142        pqi_index_t oq_pi;
3143        pqi_index_t oq_ci;
3144        struct pqi_io_request *io_request;
3145        struct pqi_io_response *response;
3146        u16 request_id;
3147
3148        num_responses = 0;
3149        oq_ci = queue_group->oq_ci_copy;
3150
3151        while (1) {
3152                oq_pi = readl(queue_group->oq_pi);
3153                if (oq_pi >= ctrl_info->num_elements_per_oq) {
3154                        pqi_invalid_response(ctrl_info);
3155                        dev_err(&ctrl_info->pci_dev->dev,
3156                                "I/O interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3157                                oq_pi, ctrl_info->num_elements_per_oq - 1, oq_ci);
3158                        return -1;
3159                }
3160                if (oq_pi == oq_ci)
3161                        break;
3162
3163                num_responses++;
3164                response = queue_group->oq_element_array +
3165                        (oq_ci * PQI_OPERATIONAL_OQ_ELEMENT_LENGTH);
3166
3167                request_id = get_unaligned_le16(&response->request_id);
3168                if (request_id >= ctrl_info->max_io_slots) {
3169                        pqi_invalid_response(ctrl_info);
3170                        dev_err(&ctrl_info->pci_dev->dev,
3171                                "request ID in response (%u) out of range (0-%u): producer index: %u  consumer index: %u\n",
3172                                request_id, ctrl_info->max_io_slots - 1, oq_pi, oq_ci);
3173                        return -1;
3174                }
3175
3176                io_request = &ctrl_info->io_request_pool[request_id];
3177                if (atomic_read(&io_request->refcount) == 0) {
3178                        pqi_invalid_response(ctrl_info);
3179                        dev_err(&ctrl_info->pci_dev->dev,
3180                                "request ID in response (%u) does not match an outstanding I/O request: producer index: %u  consumer index: %u\n",
3181                                request_id, oq_pi, oq_ci);
3182                        return -1;
3183                }
3184
3185                switch (response->header.iu_type) {
3186                case PQI_RESPONSE_IU_RAID_PATH_IO_SUCCESS:
3187                case PQI_RESPONSE_IU_AIO_PATH_IO_SUCCESS:
3188                        if (io_request->scmd)
3189                                io_request->scmd->result = 0;
3190                        fallthrough;
3191                case PQI_RESPONSE_IU_GENERAL_MANAGEMENT:
3192                        break;
3193                case PQI_RESPONSE_IU_VENDOR_GENERAL:
3194                        io_request->status =
3195                                get_unaligned_le16(
3196                                &((struct pqi_vendor_general_response *)response)->status);
3197                        break;
3198                case PQI_RESPONSE_IU_TASK_MANAGEMENT:
3199                        io_request->status = pqi_interpret_task_management_response(ctrl_info,
3200                                (void *)response);
3201                        break;
3202                case PQI_RESPONSE_IU_AIO_PATH_DISABLED:
3203                        pqi_aio_path_disabled(io_request);
3204                        io_request->status = -EAGAIN;
3205                        break;
3206                case PQI_RESPONSE_IU_RAID_PATH_IO_ERROR:
3207                case PQI_RESPONSE_IU_AIO_PATH_IO_ERROR:
3208                        io_request->error_info = ctrl_info->error_buffer +
3209                                (get_unaligned_le16(&response->error_index) *
3210                                PQI_ERROR_BUFFER_ELEMENT_LENGTH);
3211                        pqi_process_io_error(response->header.iu_type, io_request);
3212                        break;
3213                default:
3214                        pqi_invalid_response(ctrl_info);
3215                        dev_err(&ctrl_info->pci_dev->dev,
3216                                "unexpected IU type: 0x%x: producer index: %u  consumer index: %u\n",
3217                                response->header.iu_type, oq_pi, oq_ci);
3218                        return -1;
3219                }
3220
3221                io_request->io_complete_callback(io_request, io_request->context);
3222
3223                /*
3224                 * Note that the I/O request structure CANNOT BE TOUCHED after
3225                 * returning from the I/O completion callback!
3226                 */
3227                oq_ci = (oq_ci + 1) % ctrl_info->num_elements_per_oq;
3228        }
3229
3230        if (num_responses) {
3231                queue_group->oq_ci_copy = oq_ci;
3232                writel(oq_ci, queue_group->oq_ci);
3233        }
3234
3235        return num_responses;
3236}
3237
3238static inline unsigned int pqi_num_elements_free(unsigned int pi,
3239        unsigned int ci, unsigned int elements_in_queue)
3240{
3241        unsigned int num_elements_used;
3242
3243        if (pi >= ci)
3244                num_elements_used = pi - ci;
3245        else
3246                num_elements_used = elements_in_queue - ci + pi;
3247
3248        return elements_in_queue - num_elements_used - 1;
3249}
3250
3251static void pqi_send_event_ack(struct pqi_ctrl_info *ctrl_info,
3252        struct pqi_event_acknowledge_request *iu, size_t iu_length)
3253{
3254        pqi_index_t iq_pi;
3255        pqi_index_t iq_ci;
3256        unsigned long flags;
3257        void *next_element;
3258        struct pqi_queue_group *queue_group;
3259
3260        queue_group = &ctrl_info->queue_groups[PQI_DEFAULT_QUEUE_GROUP];
3261        put_unaligned_le16(queue_group->oq_id, &iu->header.response_queue_id);
3262
3263        while (1) {
3264                spin_lock_irqsave(&queue_group->submit_lock[RAID_PATH], flags);
3265
3266                iq_pi = queue_group->iq_pi_copy[RAID_PATH];
3267                iq_ci = readl(queue_group->iq_ci[RAID_PATH]);
3268
3269                if (pqi_num_elements_free(iq_pi, iq_ci,
3270                        ctrl_info->num_elements_per_iq))
3271                        break;
3272
3273                spin_unlock_irqrestore(
3274                        &queue_group->submit_lock[RAID_PATH], flags);
3275
3276                if (pqi_ctrl_offline(ctrl_info))
3277                        return;
3278        }
3279
3280        next_element = queue_group->iq_element_array[RAID_PATH] +
3281                (iq_pi * PQI_OPERATIONAL_IQ_ELEMENT_LENGTH);
3282
3283        memcpy(next_element, iu, iu_length);
3284
3285        iq_pi = (iq_pi + 1) % ctrl_info->num_elements_per_iq;
3286        queue_group->iq_pi_copy[RAID_PATH] = iq_pi;
3287
3288        /*
3289         * This write notifies the controller that an IU is available to be
3290         * processed.
3291         */
3292        writel(iq_pi, queue_group->iq_pi[RAID_PATH]);
3293
3294        spin_unlock_irqrestore(&queue_group->submit_lock[RAID_PATH], flags);
3295}
3296
3297static void pqi_acknowledge_event(struct pqi_ctrl_info *ctrl_info,
3298        struct pqi_event *event)
3299{
3300        struct pqi_event_acknowledge_request request;
3301
3302        memset(&request, 0, sizeof(request));
3303
3304        request.header.iu_type = PQI_REQUEST_IU_ACKNOWLEDGE_VENDOR_EVENT;
3305        put_unaligned_le16(sizeof(request) - PQI_REQUEST_HEADER_LENGTH,
3306                &request.header.iu_length);
3307        request.event_type = event->event_type;
3308        put_unaligned_le16(event->event_id, &request.event_id);
3309        put_unaligned_le32(event->additional_event_id, &request.additional_event_id);
3310
3311        pqi_send_event_ack(ctrl_info, &request, sizeof(request));
3312}
3313
3314#define PQI_SOFT_RESET_STATUS_TIMEOUT_SECS              30
3315#define PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS        1
3316
3317static enum pqi_soft_reset_status pqi_poll_for_soft_reset_status(
3318        struct pqi_ctrl_info *ctrl_info)
3319{
3320        u8 status;
3321        unsigned long timeout;
3322
3323        timeout = (PQI_SOFT_RESET_STATUS_TIMEOUT_SECS * PQI_HZ) + jiffies;
3324
3325        while (1) {
3326                status = pqi_read_soft_reset_status(ctrl_info);
3327                if (status & PQI_SOFT_RESET_INITIATE)
3328                        return RESET_INITIATE_DRIVER;
3329
3330                if (status & PQI_SOFT_RESET_ABORT)
3331                        return RESET_ABORT;
3332
3333                if (!sis_is_firmware_running(ctrl_info))
3334                        return RESET_NORESPONSE;
3335
3336                if (time_after(jiffies, timeout)) {
3337                        dev_warn(&ctrl_info->pci_dev->dev,
3338                                "timed out waiting for soft reset status\n");
3339                        return RESET_TIMEDOUT;
3340                }
3341
3342                ssleep(PQI_SOFT_RESET_STATUS_POLL_INTERVAL_SECS);
3343        }
3344}
3345
3346static void pqi_process_soft_reset(struct pqi_ctrl_info *ctrl_info)
3347{
3348        int rc;
3349        unsigned int delay_secs;
3350        enum pqi_soft_reset_status reset_status;
3351
3352        if (ctrl_info->soft_reset_handshake_supported)
3353                reset_status = pqi_poll_for_soft_reset_status(ctrl_info);
3354        else
3355                reset_status = RESET_INITIATE_FIRMWARE;
3356
3357        delay_secs = PQI_POST_RESET_DELAY_SECS;
3358
3359        switch (reset_status) {
3360        case RESET_TIMEDOUT:
3361                delay_secs = PQI_POST_OFA_RESET_DELAY_UPON_TIMEOUT_SECS;
3362                fallthrough;
3363        case RESET_INITIATE_DRIVER:
3364                dev_info(&ctrl_info->pci_dev->dev,
3365                                "Online Firmware Activation: resetting controller\n");
3366                sis_soft_reset(ctrl_info);
3367                fallthrough;
3368        case RESET_INITIATE_FIRMWARE:
3369                ctrl_info->pqi_mode_enabled = false;
3370                pqi_save_ctrl_mode(ctrl_info, SIS_MODE);
3371                rc = pqi_ofa_ctrl_restart(ctrl_info, delay_secs);
3372                pqi_ofa_free_host_buffer(ctrl_info);
3373                pqi_ctrl_ofa_done(ctrl_info);
3374                dev_info(&ctrl_info->pci_dev->dev,
3375                                "Online Firmware Activation: %s\n",
3376                                rc == 0 ? "SUCCESS" : "FAILED");
3377                break;
3378        case RESET_ABORT:
3379                dev_info(&ctrl_info->pci_dev->dev,
3380                                "Online Firmware Activation ABORTED\n");
3381                if (ctrl_info->soft_reset_handshake_supported)
3382                        pqi_clear_soft_reset_status(ctrl_info);
3383                pqi_ofa_free_host_buffer(ctrl_info);
3384                pqi_ctrl_ofa_done(ctrl_info);
3385                pqi_ofa_ctrl_unquiesce(ctrl_info);
3386                break;
3387        case RESET_NORESPONSE:
3388                fallthrough;
3389        default:
3390                dev_err(&ctrl_info->pci_dev->dev,
3391                        "unexpected Online Firmware Activation reset status: 0x%x\n",
3392                        reset_status);
3393                pqi_ofa_free_host_buffer(ctrl_info);
3394                pqi_ctrl_ofa_done(ctrl_info);
3395                pqi_ofa_ctrl_unquiesce(ctrl_info);
3396                pqi_take_ctrl_offline(ctrl_info);
3397                break;
3398        }
3399}
3400
3401static void pqi_ofa_memory_alloc_worker(struct work_struct *work)
3402{
3403        struct pqi_ctrl_info *ctrl_info;
3404
3405        ctrl_info = container_of(work, struct pqi_ctrl_info, ofa_memory_alloc_work);
3406
3407        pqi_ctrl_ofa_start(ctrl_info);
3408        pqi_ofa_setup_host_buffer(ctrl_info);
3409        pqi_ofa_host_memory_update(ctrl_info);
3410}
3411
3412static void pqi_ofa_quiesce_worker(struct work_struct *work)
3413{
3414        struct pqi_ctrl_info *ctrl_info;
3415        struct pqi_event *event;
3416
3417        ctrl_info = container_of(work, struct pqi_ctrl_info, ofa_quiesce_work);
3418
3419        event = &ctrl_info->events[pqi_event_type_to_event_index(PQI_EVENT_TYPE_OFA)];
3420
3421        pqi_ofa_ctrl_quiesce(ctrl_info);
3422        pqi_acknowledge_event(ctrl_info, event);
3423        pqi_process_soft_reset(ctrl_info);
3424}
3425
3426static bool pqi_ofa_process_event(struct pqi_ctrl_info *ctrl_info,
3427        struct pqi_event *event)
3428{
3429        bool ack_event;
3430
3431        ack_event = true;
3432
3433        switch (event->event_id) {
3434        case PQI_EVENT_OFA_MEMORY_ALLOCATION:
3435                dev_info(&ctrl_info->pci_dev->dev,
3436                        "received Online Firmware Activation memory allocation request\n");
3437                schedule_work(&ctrl_info->ofa_memory_alloc_work);
3438                break;
3439        case PQI_EVENT_OFA_QUIESCE:
3440                dev_info(&ctrl_info->pci_dev->dev,
3441                        "received Online Firmware Activation quiesce request\n");
3442                schedule_work(&ctrl_info->ofa_quiesce_work);
3443                ack_event = false;
3444                break;
3445        case PQI_EVENT_OFA_CANCELED:
3446                dev_info(&ctrl_info->pci_dev->dev,
3447                        "received Online Firmware Activation cancel request: reason: %u\n",
3448                        ctrl_info->ofa_cancel_reason);
3449                pqi_ofa_free_host_buffer(ctrl_info);
3450                pqi_ctrl_ofa_done(ctrl_info);
3451                break;
3452        default:
3453                dev_err(&ctrl_info->pci_dev->dev,
3454                        "received unknown Online Firmware Activation request: event ID: %u\n",
3455                        event->event_id);
3456                break;
3457        }
3458
3459        return ack_event;
3460}
3461
3462static void pqi_event_worker(struct work_struct *work)
3463{
3464        unsigned int i;
3465        bool rescan_needed;
3466        struct pqi_ctrl_info *ctrl_info;
3467        struct pqi_event *event;
3468        bool ack_event;
3469
3470        ctrl_info = container_of(work, struct pqi_ctrl_info, event_work);
3471
3472        pqi_ctrl_busy(ctrl_info);
3473        pqi_wait_if_ctrl_blocked(ctrl_info);
3474        if (pqi_ctrl_offline(ctrl_info))
3475                goto out;
3476
3477        rescan_needed = false;
3478        event = ctrl_info->events;
3479        for (i = 0; i < PQI_NUM_SUPPORTED_EVENTS; i++) {
3480                if (event->pending) {
3481                        event->pending = false;
3482                        if (event->event_type == PQI_EVENT_TYPE_OFA) {
3483                                ack_event = pqi_ofa_process_event(ctrl_info, event);
3484                        } else {
3485                                ack_event = true;
3486                                rescan_needed = true;
3487                        }
3488                        if (ack_event)
3489                                pqi_acknowledge_event(ctrl_info, event);
3490                }
3491                event++;
3492        }
3493
3494        if (rescan_needed)
3495                pqi_schedule_rescan_worker_delayed(ctrl_info);
3496
3497out:
3498        pqi_ctrl_unbusy(ctrl_info);
3499}
3500
3501#define PQI_HEARTBEAT_TIMER_INTERVAL    (10 * PQI_HZ)
3502
3503static void pqi_heartbeat_timer_handler(struct timer_list *t)
3504{
3505        int num_interrupts;
3506        u32 heartbeat_count;
3507        struct pqi_ctrl_info *ctrl_info = from_timer(ctrl_info, t, heartbeat_timer);
3508
3509        pqi_check_ctrl_health(ctrl_info);
3510        if (pqi_ctrl_offline(ctrl_info))
3511                return;
3512
3513        num_interrupts = atomic_read(&ctrl_info->num_interrupts);
3514        heartbeat_count = pqi_read_heartbeat_counter(ctrl_info);
3515
3516        if (num_interrupts == ctrl_info->previous_num_interrupts) {
3517                if (heartbeat_count == ctrl_info->previous_heartbeat_count) {
3518                        dev_err(&ctrl_info->pci_dev->dev,
3519                                "no heartbeat detected - last heartbeat count: %u\n",
3520                                heartbeat_count);
3521                        pqi_take_ctrl_offline(ctrl_info);
3522                        return;
3523                }
3524        } else {
3525                ctrl_info->previous_num_interrupts = num_interrupts;
3526        }
3527
3528        ctrl_info->previous_heartbeat_count = heartbeat_count;
3529        mod_timer(&ctrl_info->heartbeat_timer,
3530                jiffies + PQI_HEARTBEAT_TIMER_INTERVAL);
3531}
3532
3533static void pqi_start_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3534{
3535        if (!ctrl_info->heartbeat_counter)
3536                return;
3537
3538        ctrl_info->previous_num_interrupts =
3539                atomic_read(&ctrl_info->num_interrupts);
3540        ctrl_info->previous_heartbeat_count =
3541                pqi_read_heartbeat_counter(ctrl_info);
3542
3543        ctrl_info->heartbeat_timer.expires =
3544                jiffies + PQI_HEARTBEAT_TIMER_INTERVAL;
3545        add_timer(&ctrl_info->heartbeat_timer);
3546}
3547
3548static inline void pqi_stop_heartbeat_timer(struct pqi_ctrl_info *ctrl_info)
3549{
3550        del_timer_sync(&ctrl_info->heartbeat_timer);
3551}
3552
3553static void pqi_ofa_capture_event_payload(struct pqi_ctrl_info *ctrl_info,
3554        struct pqi_event *event, struct pqi_event_response *response)
3555{
3556        switch (event->event_id) {
3557        case PQI_EVENT_OFA_MEMORY_ALLOCATION:
3558                ctrl_info->ofa_bytes_requested =
3559                        get_unaligned_le32(&response->data.ofa_memory_allocation.bytes_requested);
3560                break;
3561        case PQI_EVENT_OFA_CANCELED:
3562                ctrl_info->ofa_cancel_reason =
3563                        get_unaligned_le16(&response->data.ofa_cancelled.reason);
3564                break;
3565        }
3566}
3567
3568static int pqi_process_event_intr(struct pqi_ctrl_info *ctrl_info)
3569{
3570        int num_events;
3571        pqi_index_t oq_pi;
3572        pqi_index_t oq_ci;
3573        struct pqi_event_queue *event_queue;
3574        struct pqi_event_response *response;
3575        struct pqi_event *event;
3576        int event_index;
3577
3578        event_queue = &ctrl_info->event_queue;
3579        num_events = 0;
3580        oq_ci = event_queue->oq_ci_copy;
3581
3582        while (1) {
3583                oq_pi = readl(event_queue->oq_pi);
3584                if (oq_pi >= PQI_NUM_EVENT_QUEUE_ELEMENTS) {
3585                        pqi_invalid_response(ctrl_info);
3586                        dev_err(&ctrl_info->pci_dev->dev,
3587                                "event interrupt: producer index (%u) out of range (0-%u): consumer index: %u\n",
3588                                oq_pi, PQI_NUM_EVENT_QUEUE_ELEMENTS - 1, oq_ci);
3589                        return -1;
3590                }
3591
3592                if (oq_pi == oq_ci)
3593                        break;
3594
3595                num_events++;
3596                response = event_queue->oq_element_array + (oq_ci * PQI_EVENT_OQ_ELEMENT_LENGTH);
3597
3598                event_index = pqi_event_type_to_event_index(response->event_type);
3599
3600                if (event_index >= 0 && response->request_acknowledge) {
3601                        event = &ctrl_info->events[event_index];
3602                        event->pending = true;
3603                        event->event_type = response->event_type;
3604                        event->event_id = get_unaligned_le16(&response->event_id);
3605                        event->additional_event_id =
3606                                get_unaligned_le32(&response->additional_event_id);
3607                        if (event->event_type == PQI_EVENT_TYPE_OFA)
3608                                pqi_ofa_capture_event_payload(ctrl_info, event, response);
3609                }
3610
3611                oq_ci = (oq_ci + 1) % PQI_NUM_EVENT_QUEUE_ELEMENTS;
3612        }
3613
3614        if (num_events) {
3615                event_queue->oq_ci_copy = oq_ci;
3616                writel(oq_ci, event_queue->oq_ci);
3617                schedule_work(&ctrl_info->event_work);
3618        }
3619
3620        return num_events;
3621}
3622
3623#define PQI_LEGACY_INTX_MASK    0x1
3624
3625static inline void pqi_configure_legacy_intx(struct pqi_ctrl_info *ctrl_info, bool enable_intx)
3626{
3627        u32 intx_mask;
3628        struct pqi_device_registers __iomem *pqi_registers;
3629        volatile void __iomem *register_addr;
3630
3631        pqi_registers = ctrl_info->pqi_registers;
3632
3633        if (enable_intx)
3634                register_addr = &pqi_registers->legacy_intx_mask_clear;
3635        else
3636                register_addr = &pqi_registers->legacy_intx_mask_set;
3637
3638        intx_mask = readl(register_addr);
3639        intx_mask |= PQI_LEGACY_INTX_MASK;
3640        writel(intx_mask, register_addr);
3641}
3642
3643static void pqi_change_irq_mode(struct pqi_ctrl_info *ctrl_info,
3644        enum pqi_irq_mode new_mode)
3645{
3646        switch (ctrl_info->irq_mode) {
3647        case IRQ_MODE_MSIX:
3648                switch (new_mode) {
3649                case IRQ_MODE_MSIX:
3650                        break;
3651                case IRQ_MODE_INTX:
3652                        pqi_configure_legacy_intx(ctrl_info, true);
3653                        sis_enable_intx(ctrl_info);
3654                        break;
3655                case IRQ_MODE_NONE:
3656                        break;
3657                }
3658                break;
3659        case IRQ_MODE_INTX:
3660                switch (new_mode) {
3661                case IRQ_MODE_MSIX:
3662                        pqi_configure_legacy_intx(ctrl_info, false);
3663                        sis_enable_msix(ctrl_info);
3664                        break;
3665                case IRQ_MODE_INTX:
3666                        break;
3667                case IRQ_MODE_NONE:
3668                        pqi_configure_legacy_intx(ctrl_info, false);
3669                        break;
3670                }
3671                break;
3672        case IRQ_MODE_NONE:
3673                switch (new_mode) {
3674                case IRQ_MODE_MSIX:
3675                        sis_enable_msix(ctrl_info);
3676                        break;
3677                case IRQ_MODE_INTX:
3678                        pqi_configure_legacy_intx(ctrl_info, true);
3679                        sis_enable_intx(ctrl_info);
3680                        break;
3681                case IRQ_MODE_NONE:
3682                        break;
3683                }
3684                break;
3685        }
3686
3687        ctrl_info->irq_mode = new_mode;
3688}
3689
3690#define PQI_LEGACY_INTX_PENDING         0x1
3691
3692static inline bool pqi_is_valid_irq(struct pqi_ctrl_info *ctrl_info)
3693{
3694        bool valid_irq;
3695        u32 intx_status;
3696
3697        switch (ctrl_info->irq_mode) {
3698        case IRQ_MODE_MSIX:
3699                valid_irq = true;
3700                break;
3701        case IRQ_MODE_INTX:
3702                intx_status = readl(&ctrl_info->pqi_registers->legacy_intx_status);
3703                if (intx_status & PQI_LEGACY_INTX_PENDING)
3704                        valid_irq = true;
3705                else
3706                        valid_irq = false;
3707                break;
3708        case IRQ_MODE_NONE:
3709        default:
3710                valid_irq = false;
3711                break;
3712        }
3713
3714        return valid_irq;
3715}
3716
3717static irqreturn_t pqi_irq_handler(int irq, void *data)
3718{
3719        struct pqi_ctrl_info *ctrl_info;
3720        struct pqi_queue_group *queue_group;
3721        int num_io_responses_handled;
3722        int num_events_handled;
3723
3724        queue_group = data;
3725        ctrl_info = queue_group->ctrl_info;
3726
3727        if (!pqi_is_valid_irq(ctrl_info))
3728                return IRQ_NONE;
3729
3730        num_io_responses_handled = pqi_process_io_intr(ctrl_info, queue_group);
3731        if (num_io_responses_handled < 0)
3732                goto out;
3733
3734        if (irq == ctrl_info->event_irq) {
3735                num_events_handled = pqi_process_event_intr(ctrl_info);
3736                if (num_events_handled < 0)
3737                        goto out;
3738        } else {
3739                num_events_handled = 0;
3740        }
3741
3742        if (num_io_responses_handled + num_events_handled > 0)
3743                atomic_inc(&ctrl_info->num_interrupts);
3744
3745        pqi_start_io(ctrl_info, queue_group, RAID_PATH, NULL);
3746        pqi_start_io(ctrl_info, queue_group, AIO_PATH, NULL);
3747
3748out:
3749        return IRQ_HANDLED;
3750}
3751
3752static int pqi_request_irqs(struct pqi_ctrl_info *ctrl_info)
3753{
3754        struct pci_dev *pci_dev = ctrl_info->pci_dev;
3755        int i;
3756        int rc;
3757
3758        ctrl_info->event_irq = pci_irq_vector(pci_dev, 0);
3759
3760        for (i = 0; i < ctrl_info->num_msix_vectors_enabled; i++) {
3761                rc = request_irq(pci_irq_vector(pci_dev, i), pqi_irq_handler, 0,
3762                        DRIVER_NAME_SHORT, &ctrl_info->queue_groups[i]);
3763                if (rc) {
3764                        dev_err(&pci_dev->dev,
3765                                "irq %u init failed with error %d\n",
3766                                pci_irq_vector(pci_dev, i), rc);
3767                        return rc;
3768                }
3769                ctrl_info->num_msix_vectors_initialized++;
3770        }
3771
3772        return 0;
3773}
3774
3775static void pqi_free_irqs(struct pqi_ctrl_info *ctrl_info)
3776{
3777        int i;
3778
3779        for (i = 0; i < ctrl_info->num_msix_vectors_initialized; i++)
3780                free_irq(pci_irq_vector(ctrl_info->pci_dev, i),
3781                        &ctrl_info->queue_groups[i]);
3782
3783        ctrl_info->num_msix_vectors_initialized = 0;
3784}
3785
3786static int pqi_enable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3787{
3788        int num_vectors_enabled;
3789
3790        num_vectors_enabled = pci_alloc_irq_vectors(ctrl_info->pci_dev,
3791                        PQI_MIN_MSIX_VECTORS, ctrl_info->num_queue_groups,
3792                        PCI_IRQ_MSIX | PCI_IRQ_AFFINITY);
3793        if (num_vectors_enabled < 0) {
3794                dev_err(&ctrl_info->pci_dev->dev,
3795                        "MSI-X init failed with error %d\n",
3796                        num_vectors_enabled);
3797                return num_vectors_enabled;
3798        }
3799
3800        ctrl_info->num_msix_vectors_enabled = num_vectors_enabled;
3801        ctrl_info->irq_mode = IRQ_MODE_MSIX;
3802        return 0;
3803}
3804
3805static void pqi_disable_msix_interrupts(struct pqi_ctrl_info *ctrl_info)
3806{
3807        if (ctrl_info->num_msix_vectors_enabled) {
3808                pci_free_irq_vectors(ctrl_info->pci_dev);
3809                ctrl_info->num_msix_vectors_enabled = 0;
3810        }
3811}
3812
3813static int pqi_alloc_operational_queues(struct pqi_ctrl_info *ctrl_info)
3814{
3815        unsigned int i;
3816        size_t alloc_length;
3817        size_t element_array_length_per_iq;
3818        size_t element_array_length_per_oq;
3819        void *element_array;
3820        void __iomem *next_queue_index;
3821        void *aligned_pointer;
3822        unsigned int num_inbound_queues;
3823        unsigned int num_outbound_queues;
3824        unsigned int num_queue_indexes;
3825        struct pqi_queue_group *queue_group;
3826
3827        element_array_length_per_iq =
3828                PQI_OPERATIONAL_IQ_ELEMENT_LENGTH *
3829                ctrl_info->num_elements_per_iq;
3830        element_array_length_per_oq =
3831                PQI_OPERATIONAL_OQ_ELEMENT_LENGTH *
3832                ctrl_info->num_elements_per_oq;
3833        num_inbound_queues = ctrl_info->num_queue_groups * 2;
3834        num_outbound_queues = ctrl_info->num_queue_groups;
3835        num_queue_indexes = (ctrl_info->num_queue_groups * 3) + 1;
3836
3837        aligned_pointer = NULL;
3838
3839        for (i = 0; i < num_inbound_queues; i++) {
3840                aligned_pointer = PTR_ALIGN(aligned_pointer,
3841                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3842                aligned_pointer += element_array_length_per_iq;
3843        }
3844
3845        for (i = 0; i < num_outbound_queues; i++) {
3846                aligned_pointer = PTR_ALIGN(aligned_pointer,
3847                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3848                aligned_pointer += element_array_length_per_oq;
3849        }
3850
3851        aligned_pointer = PTR_ALIGN(aligned_pointer,
3852                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3853        aligned_pointer += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3854                PQI_EVENT_OQ_ELEMENT_LENGTH;
3855
3856        for (i = 0; i < num_queue_indexes; i++) {
3857                aligned_pointer = PTR_ALIGN(aligned_pointer,
3858                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3859                aligned_pointer += sizeof(pqi_index_t);
3860        }
3861
3862        alloc_length = (size_t)aligned_pointer +
3863                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
3864
3865        alloc_length += PQI_EXTRA_SGL_MEMORY;
3866
3867        ctrl_info->queue_memory_base =
3868                dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
3869                                   &ctrl_info->queue_memory_base_dma_handle,
3870                                   GFP_KERNEL);
3871
3872        if (!ctrl_info->queue_memory_base)
3873                return -ENOMEM;
3874
3875        ctrl_info->queue_memory_length = alloc_length;
3876
3877        element_array = PTR_ALIGN(ctrl_info->queue_memory_base,
3878                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3879
3880        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3881                queue_group = &ctrl_info->queue_groups[i];
3882                queue_group->iq_element_array[RAID_PATH] = element_array;
3883                queue_group->iq_element_array_bus_addr[RAID_PATH] =
3884                        ctrl_info->queue_memory_base_dma_handle +
3885                                (element_array - ctrl_info->queue_memory_base);
3886                element_array += element_array_length_per_iq;
3887                element_array = PTR_ALIGN(element_array,
3888                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3889                queue_group->iq_element_array[AIO_PATH] = element_array;
3890                queue_group->iq_element_array_bus_addr[AIO_PATH] =
3891                        ctrl_info->queue_memory_base_dma_handle +
3892                        (element_array - ctrl_info->queue_memory_base);
3893                element_array += element_array_length_per_iq;
3894                element_array = PTR_ALIGN(element_array,
3895                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3896        }
3897
3898        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3899                queue_group = &ctrl_info->queue_groups[i];
3900                queue_group->oq_element_array = element_array;
3901                queue_group->oq_element_array_bus_addr =
3902                        ctrl_info->queue_memory_base_dma_handle +
3903                        (element_array - ctrl_info->queue_memory_base);
3904                element_array += element_array_length_per_oq;
3905                element_array = PTR_ALIGN(element_array,
3906                        PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
3907        }
3908
3909        ctrl_info->event_queue.oq_element_array = element_array;
3910        ctrl_info->event_queue.oq_element_array_bus_addr =
3911                ctrl_info->queue_memory_base_dma_handle +
3912                (element_array - ctrl_info->queue_memory_base);
3913        element_array += PQI_NUM_EVENT_QUEUE_ELEMENTS *
3914                PQI_EVENT_OQ_ELEMENT_LENGTH;
3915
3916        next_queue_index = (void __iomem *)PTR_ALIGN(element_array,
3917                PQI_OPERATIONAL_INDEX_ALIGNMENT);
3918
3919        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3920                queue_group = &ctrl_info->queue_groups[i];
3921                queue_group->iq_ci[RAID_PATH] = next_queue_index;
3922                queue_group->iq_ci_bus_addr[RAID_PATH] =
3923                        ctrl_info->queue_memory_base_dma_handle +
3924                        (next_queue_index -
3925                        (void __iomem *)ctrl_info->queue_memory_base);
3926                next_queue_index += sizeof(pqi_index_t);
3927                next_queue_index = PTR_ALIGN(next_queue_index,
3928                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3929                queue_group->iq_ci[AIO_PATH] = next_queue_index;
3930                queue_group->iq_ci_bus_addr[AIO_PATH] =
3931                        ctrl_info->queue_memory_base_dma_handle +
3932                        (next_queue_index -
3933                        (void __iomem *)ctrl_info->queue_memory_base);
3934                next_queue_index += sizeof(pqi_index_t);
3935                next_queue_index = PTR_ALIGN(next_queue_index,
3936                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3937                queue_group->oq_pi = next_queue_index;
3938                queue_group->oq_pi_bus_addr =
3939                        ctrl_info->queue_memory_base_dma_handle +
3940                        (next_queue_index -
3941                        (void __iomem *)ctrl_info->queue_memory_base);
3942                next_queue_index += sizeof(pqi_index_t);
3943                next_queue_index = PTR_ALIGN(next_queue_index,
3944                        PQI_OPERATIONAL_INDEX_ALIGNMENT);
3945        }
3946
3947        ctrl_info->event_queue.oq_pi = next_queue_index;
3948        ctrl_info->event_queue.oq_pi_bus_addr =
3949                ctrl_info->queue_memory_base_dma_handle +
3950                (next_queue_index -
3951                (void __iomem *)ctrl_info->queue_memory_base);
3952
3953        return 0;
3954}
3955
3956static void pqi_init_operational_queues(struct pqi_ctrl_info *ctrl_info)
3957{
3958        unsigned int i;
3959        u16 next_iq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3960        u16 next_oq_id = PQI_MIN_OPERATIONAL_QUEUE_ID;
3961
3962        /*
3963         * Initialize the backpointers to the controller structure in
3964         * each operational queue group structure.
3965         */
3966        for (i = 0; i < ctrl_info->num_queue_groups; i++)
3967                ctrl_info->queue_groups[i].ctrl_info = ctrl_info;
3968
3969        /*
3970         * Assign IDs to all operational queues.  Note that the IDs
3971         * assigned to operational IQs are independent of the IDs
3972         * assigned to operational OQs.
3973         */
3974        ctrl_info->event_queue.oq_id = next_oq_id++;
3975        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3976                ctrl_info->queue_groups[i].iq_id[RAID_PATH] = next_iq_id++;
3977                ctrl_info->queue_groups[i].iq_id[AIO_PATH] = next_iq_id++;
3978                ctrl_info->queue_groups[i].oq_id = next_oq_id++;
3979        }
3980
3981        /*
3982         * Assign MSI-X table entry indexes to all queues.  Note that the
3983         * interrupt for the event queue is shared with the first queue group.
3984         */
3985        ctrl_info->event_queue.int_msg_num = 0;
3986        for (i = 0; i < ctrl_info->num_queue_groups; i++)
3987                ctrl_info->queue_groups[i].int_msg_num = i;
3988
3989        for (i = 0; i < ctrl_info->num_queue_groups; i++) {
3990                spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[0]);
3991                spin_lock_init(&ctrl_info->queue_groups[i].submit_lock[1]);
3992                INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[0]);
3993                INIT_LIST_HEAD(&ctrl_info->queue_groups[i].request_list[1]);
3994        }
3995}
3996
3997static int pqi_alloc_admin_queues(struct pqi_ctrl_info *ctrl_info)
3998{
3999        size_t alloc_length;
4000        struct pqi_admin_queues_aligned *admin_queues_aligned;
4001        struct pqi_admin_queues *admin_queues;
4002
4003        alloc_length = sizeof(struct pqi_admin_queues_aligned) +
4004                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT;
4005
4006        ctrl_info->admin_queue_memory_base =
4007                dma_alloc_coherent(&ctrl_info->pci_dev->dev, alloc_length,
4008                                   &ctrl_info->admin_queue_memory_base_dma_handle,
4009                                   GFP_KERNEL);
4010
4011        if (!ctrl_info->admin_queue_memory_base)
4012                return -ENOMEM;
4013
4014        ctrl_info->admin_queue_memory_length = alloc_length;
4015
4016        admin_queues = &ctrl_info->admin_queues;
4017        admin_queues_aligned = PTR_ALIGN(ctrl_info->admin_queue_memory_base,
4018                PQI_QUEUE_ELEMENT_ARRAY_ALIGNMENT);
4019        admin_queues->iq_element_array =
4020                &admin_queues_aligned->iq_element_array;
4021        admin_queues->oq_element_array =
4022                &admin_queues_aligned->oq_element_array;
4023        admin_queues->iq_ci =
4024                (pqi_index_t __iomem *)&admin_queues_aligned->iq_ci;
4025        admin_queues->oq_pi =
4026                (pqi_index_t __iomem *)&admin_queues_aligned->oq_pi;
4027
4028        admin_queues->iq_element_array_bus_addr =
4029                ctrl_info->admin_queue_memory_base_dma_handle +
4030                (admin_queues->iq_element_array -
4031                ctrl_info->admin_queue_memory_base);
4032        admin_queues->oq_element_array_bus_addr =
4033                ctrl_info->admin_queue_memory_base_dma_handle +
4034                (admin_queues->oq_element_array -
4035                ctrl_info->admin_queue_memory_base);
4036        admin_queues->iq_ci_bus_addr =
4037                ctrl_info->admin_queue_memory_base_dma_handle +
4038                ((void __iomem *)admin_queues->iq_ci -
4039                (void __iomem *)ctrl_info->admin_queue_memory_base);
4040        admin_queues->oq_pi_bus_addr =
4041                ctrl_info->admin_queue_memory_base_dma_handle +
4042                ((void __iomem *)admin_queues->oq_pi -
4043                (void