linux/drivers/block/cciss.c
<<
>>
Prefs
   1/*
   2 *    Disk Array driver for HP Smart Array controllers.
   3 *    (C) Copyright 2000, 2007 Hewlett-Packard Development Company, L.P.
   4 *
   5 *    This program is free software; you can redistribute it and/or modify
   6 *    it under the terms of the GNU General Public License as published by
   7 *    the Free Software Foundation; version 2 of the License.
   8 *
   9 *    This program is distributed in the hope that it will be useful,
  10 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
  11 *    MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12 *    General Public License for more details.
  13 *
  14 *    You should have received a copy of the GNU General Public License
  15 *    along with this program; if not, write to the Free Software
  16 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
  17 *    02111-1307, USA.
  18 *
  19 *    Questions/Comments/Bugfixes to iss_storagedev@hp.com
  20 *
  21 */
  22
  23#include <linux/module.h>
  24#include <linux/interrupt.h>
  25#include <linux/types.h>
  26#include <linux/pci.h>
  27#include <linux/kernel.h>
  28#include <linux/slab.h>
  29#include <linux/delay.h>
  30#include <linux/major.h>
  31#include <linux/fs.h>
  32#include <linux/bio.h>
  33#include <linux/blkpg.h>
  34#include <linux/timer.h>
  35#include <linux/proc_fs.h>
  36#include <linux/seq_file.h>
  37#include <linux/init.h>
  38#include <linux/hdreg.h>
  39#include <linux/spinlock.h>
  40#include <linux/compat.h>
  41#include <linux/blktrace_api.h>
  42#include <asm/uaccess.h>
  43#include <asm/io.h>
  44
  45#include <linux/dma-mapping.h>
  46#include <linux/blkdev.h>
  47#include <linux/genhd.h>
  48#include <linux/completion.h>
  49#include <scsi/scsi.h>
  50#include <scsi/sg.h>
  51#include <scsi/scsi_ioctl.h>
  52#include <linux/cdrom.h>
  53#include <linux/scatterlist.h>
  54
  55#define CCISS_DRIVER_VERSION(maj,min,submin) ((maj<<16)|(min<<8)|(submin))
  56#define DRIVER_NAME "HP CISS Driver (v 3.6.20)"
  57#define DRIVER_VERSION CCISS_DRIVER_VERSION(3, 6, 20)
  58
  59/* Embedded module documentation macros - see modules.h */
  60MODULE_AUTHOR("Hewlett-Packard Company");
  61MODULE_DESCRIPTION("Driver for HP Smart Array Controllers");
  62MODULE_SUPPORTED_DEVICE("HP SA5i SA5i+ SA532 SA5300 SA5312 SA641 SA642 SA6400"
  63                        " SA6i P600 P800 P400 P400i E200 E200i E500 P700m"
  64                        " Smart Array G2 Series SAS/SATA Controllers");
  65MODULE_VERSION("3.6.20");
  66MODULE_LICENSE("GPL");
  67
  68#include "cciss_cmd.h"
  69#include "cciss.h"
  70#include <linux/cciss_ioctl.h>
  71
  72/* define the PCI info for the cards we can control */
  73static const struct pci_device_id cciss_pci_device_id[] = {
  74        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISS,  0x0E11, 0x4070},
  75        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4080},
  76        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4082},
  77        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSB, 0x0E11, 0x4083},
  78        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x4091},
  79        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409A},
  80        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409B},
  81        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409C},
  82        {PCI_VENDOR_ID_COMPAQ, PCI_DEVICE_ID_COMPAQ_CISSC, 0x0E11, 0x409D},
  83        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSA,     0x103C, 0x3225},
  84        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3223},
  85        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3234},
  86        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3235},
  87        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3211},
  88        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3212},
  89        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3213},
  90        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3214},
  91        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSD,     0x103C, 0x3215},
  92        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x3237},
  93        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSC,     0x103C, 0x323D},
  94        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3241},
  95        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3243},
  96        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3245},
  97        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3247},
  98        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x3249},
  99        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324A},
 100        {PCI_VENDOR_ID_HP,     PCI_DEVICE_ID_HP_CISSE,     0x103C, 0x324B},
 101        {PCI_VENDOR_ID_HP,     PCI_ANY_ID,      PCI_ANY_ID, PCI_ANY_ID,
 102                PCI_CLASS_STORAGE_RAID << 8, 0xffff << 8, 0},
 103        {0,}
 104};
 105
 106MODULE_DEVICE_TABLE(pci, cciss_pci_device_id);
 107
 108/*  board_id = Subsystem Device ID & Vendor ID
 109 *  product = Marketing Name for the board
 110 *  access = Address of the struct of function pointers
 111 */
 112static struct board_type products[] = {
 113        {0x40700E11, "Smart Array 5300", &SA5_access},
 114        {0x40800E11, "Smart Array 5i", &SA5B_access},
 115        {0x40820E11, "Smart Array 532", &SA5B_access},
 116        {0x40830E11, "Smart Array 5312", &SA5B_access},
 117        {0x409A0E11, "Smart Array 641", &SA5_access},
 118        {0x409B0E11, "Smart Array 642", &SA5_access},
 119        {0x409C0E11, "Smart Array 6400", &SA5_access},
 120        {0x409D0E11, "Smart Array 6400 EM", &SA5_access},
 121        {0x40910E11, "Smart Array 6i", &SA5_access},
 122        {0x3225103C, "Smart Array P600", &SA5_access},
 123        {0x3223103C, "Smart Array P800", &SA5_access},
 124        {0x3234103C, "Smart Array P400", &SA5_access},
 125        {0x3235103C, "Smart Array P400i", &SA5_access},
 126        {0x3211103C, "Smart Array E200i", &SA5_access},
 127        {0x3212103C, "Smart Array E200", &SA5_access},
 128        {0x3213103C, "Smart Array E200i", &SA5_access},
 129        {0x3214103C, "Smart Array E200i", &SA5_access},
 130        {0x3215103C, "Smart Array E200i", &SA5_access},
 131        {0x3237103C, "Smart Array E500", &SA5_access},
 132        {0x323D103C, "Smart Array P700m", &SA5_access},
 133        {0x3241103C, "Smart Array P212", &SA5_access},
 134        {0x3243103C, "Smart Array P410", &SA5_access},
 135        {0x3245103C, "Smart Array P410i", &SA5_access},
 136        {0x3247103C, "Smart Array P411", &SA5_access},
 137        {0x3249103C, "Smart Array P812", &SA5_access},
 138        {0x324A103C, "Smart Array P712m", &SA5_access},
 139        {0x324B103C, "Smart Array P711m", &SA5_access},
 140        {0xFFFF103C, "Unknown Smart Array", &SA5_access},
 141};
 142
 143/* How long to wait (in milliseconds) for board to go into simple mode */
 144#define MAX_CONFIG_WAIT 30000
 145#define MAX_IOCTL_CONFIG_WAIT 1000
 146
 147/*define how many times we will try a command because of bus resets */
 148#define MAX_CMD_RETRIES 3
 149
 150#define MAX_CTLR        32
 151
 152/* Originally cciss driver only supports 8 major numbers */
 153#define MAX_CTLR_ORIG   8
 154
 155static ctlr_info_t *hba[MAX_CTLR];
 156
 157static void do_cciss_request(struct request_queue *q);
 158static irqreturn_t do_cciss_intr(int irq, void *dev_id);
 159static int cciss_open(struct inode *inode, struct file *filep);
 160static int cciss_release(struct inode *inode, struct file *filep);
 161static int cciss_ioctl(struct inode *inode, struct file *filep,
 162                       unsigned int cmd, unsigned long arg);
 163static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo);
 164
 165static int cciss_revalidate(struct gendisk *disk);
 166static int rebuild_lun_table(ctlr_info_t *h, int first_time);
 167static int deregister_disk(struct gendisk *disk, drive_info_struct *drv,
 168                           int clear_all);
 169
 170static void cciss_read_capacity(int ctlr, int logvol, int withirq,
 171                        sector_t *total_size, unsigned int *block_size);
 172static void cciss_read_capacity_16(int ctlr, int logvol, int withirq,
 173                        sector_t *total_size, unsigned int *block_size);
 174static void cciss_geometry_inquiry(int ctlr, int logvol,
 175                        int withirq, sector_t total_size,
 176                        unsigned int block_size, InquiryData_struct *inq_buff,
 177                                   drive_info_struct *drv);
 178static void __devinit cciss_interrupt_mode(ctlr_info_t *, struct pci_dev *,
 179                                           __u32);
 180static void start_io(ctlr_info_t *h);
 181static int sendcmd(__u8 cmd, int ctlr, void *buff, size_t size,
 182                   unsigned int use_unit_num, unsigned int log_unit,
 183                   __u8 page_code, unsigned char *scsi3addr, int cmd_type);
 184static int sendcmd_withirq(__u8 cmd, int ctlr, void *buff, size_t size,
 185                           unsigned int use_unit_num, unsigned int log_unit,
 186                           __u8 page_code, int cmd_type);
 187
 188static void fail_all_cmds(unsigned long ctlr);
 189
 190#ifdef CONFIG_PROC_FS
 191static void cciss_procinit(int i);
 192#else
 193static void cciss_procinit(int i)
 194{
 195}
 196#endif                          /* CONFIG_PROC_FS */
 197
 198#ifdef CONFIG_COMPAT
 199static long cciss_compat_ioctl(struct file *f, unsigned cmd, unsigned long arg);
 200#endif
 201
 202static struct block_device_operations cciss_fops = {
 203        .owner = THIS_MODULE,
 204        .open = cciss_open,
 205        .release = cciss_release,
 206        .ioctl = cciss_ioctl,
 207        .getgeo = cciss_getgeo,
 208#ifdef CONFIG_COMPAT
 209        .compat_ioctl = cciss_compat_ioctl,
 210#endif
 211        .revalidate_disk = cciss_revalidate,
 212};
 213
 214/*
 215 * Enqueuing and dequeuing functions for cmdlists.
 216 */
 217static inline void addQ(CommandList_struct **Qptr, CommandList_struct *c)
 218{
 219        if (*Qptr == NULL) {
 220                *Qptr = c;
 221                c->next = c->prev = c;
 222        } else {
 223                c->prev = (*Qptr)->prev;
 224                c->next = (*Qptr);
 225                (*Qptr)->prev->next = c;
 226                (*Qptr)->prev = c;
 227        }
 228}
 229
 230static inline CommandList_struct *removeQ(CommandList_struct **Qptr,
 231                                          CommandList_struct *c)
 232{
 233        if (c && c->next != c) {
 234                if (*Qptr == c)
 235                        *Qptr = c->next;
 236                c->prev->next = c->next;
 237                c->next->prev = c->prev;
 238        } else {
 239                *Qptr = NULL;
 240        }
 241        return c;
 242}
 243
 244#include "cciss_scsi.c"         /* For SCSI tape support */
 245
 246#define RAID_UNKNOWN 6
 247
 248#ifdef CONFIG_PROC_FS
 249
 250/*
 251 * Report information about this controller.
 252 */
 253#define ENG_GIG 1000000000
 254#define ENG_GIG_FACTOR (ENG_GIG/512)
 255#define ENGAGE_SCSI     "engage scsi"
 256static const char *raid_label[] = { "0", "4", "1(1+0)", "5", "5+1", "ADG",
 257        "UNKNOWN"
 258};
 259
 260static struct proc_dir_entry *proc_cciss;
 261
 262static void cciss_seq_show_header(struct seq_file *seq)
 263{
 264        ctlr_info_t *h = seq->private;
 265
 266        seq_printf(seq, "%s: HP %s Controller\n"
 267                "Board ID: 0x%08lx\n"
 268                "Firmware Version: %c%c%c%c\n"
 269                "IRQ: %d\n"
 270                "Logical drives: %d\n"
 271                "Current Q depth: %d\n"
 272                "Current # commands on controller: %d\n"
 273                "Max Q depth since init: %d\n"
 274                "Max # commands on controller since init: %d\n"
 275                "Max SG entries since init: %d\n",
 276                h->devname,
 277                h->product_name,
 278                (unsigned long)h->board_id,
 279                h->firm_ver[0], h->firm_ver[1], h->firm_ver[2],
 280                h->firm_ver[3], (unsigned int)h->intr[SIMPLE_MODE_INT],
 281                h->num_luns,
 282                h->Qdepth, h->commands_outstanding,
 283                h->maxQsinceinit, h->max_outstanding, h->maxSG);
 284
 285#ifdef CONFIG_CISS_SCSI_TAPE
 286        cciss_seq_tape_report(seq, h->ctlr);
 287#endif /* CONFIG_CISS_SCSI_TAPE */
 288}
 289
 290static void *cciss_seq_start(struct seq_file *seq, loff_t *pos)
 291{
 292        ctlr_info_t *h = seq->private;
 293        unsigned ctlr = h->ctlr;
 294        unsigned long flags;
 295
 296        /* prevent displaying bogus info during configuration
 297         * or deconfiguration of a logical volume
 298         */
 299        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
 300        if (h->busy_configuring) {
 301                spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
 302                return ERR_PTR(-EBUSY);
 303        }
 304        h->busy_configuring = 1;
 305        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
 306
 307        if (*pos == 0)
 308                cciss_seq_show_header(seq);
 309
 310        return pos;
 311}
 312
 313static int cciss_seq_show(struct seq_file *seq, void *v)
 314{
 315        sector_t vol_sz, vol_sz_frac;
 316        ctlr_info_t *h = seq->private;
 317        unsigned ctlr = h->ctlr;
 318        loff_t *pos = v;
 319        drive_info_struct *drv = &h->drv[*pos];
 320
 321        if (*pos > h->highest_lun)
 322                return 0;
 323
 324        if (drv->heads == 0)
 325                return 0;
 326
 327        vol_sz = drv->nr_blocks;
 328        vol_sz_frac = sector_div(vol_sz, ENG_GIG_FACTOR);
 329        vol_sz_frac *= 100;
 330        sector_div(vol_sz_frac, ENG_GIG_FACTOR);
 331
 332        if (drv->raid_level > 5)
 333                drv->raid_level = RAID_UNKNOWN;
 334        seq_printf(seq, "cciss/c%dd%d:"
 335                        "\t%4u.%02uGB\tRAID %s\n",
 336                        ctlr, (int) *pos, (int)vol_sz, (int)vol_sz_frac,
 337                        raid_label[drv->raid_level]);
 338        return 0;
 339}
 340
 341static void *cciss_seq_next(struct seq_file *seq, void *v, loff_t *pos)
 342{
 343        ctlr_info_t *h = seq->private;
 344
 345        if (*pos > h->highest_lun)
 346                return NULL;
 347        *pos += 1;
 348
 349        return pos;
 350}
 351
 352static void cciss_seq_stop(struct seq_file *seq, void *v)
 353{
 354        ctlr_info_t *h = seq->private;
 355
 356        /* Only reset h->busy_configuring if we succeeded in setting
 357         * it during cciss_seq_start. */
 358        if (v == ERR_PTR(-EBUSY))
 359                return;
 360
 361        h->busy_configuring = 0;
 362}
 363
 364static struct seq_operations cciss_seq_ops = {
 365        .start = cciss_seq_start,
 366        .show  = cciss_seq_show,
 367        .next  = cciss_seq_next,
 368        .stop  = cciss_seq_stop,
 369};
 370
 371static int cciss_seq_open(struct inode *inode, struct file *file)
 372{
 373        int ret = seq_open(file, &cciss_seq_ops);
 374        struct seq_file *seq = file->private_data;
 375
 376        if (!ret)
 377                seq->private = PDE(inode)->data;
 378
 379        return ret;
 380}
 381
 382static ssize_t
 383cciss_proc_write(struct file *file, const char __user *buf,
 384                 size_t length, loff_t *ppos)
 385{
 386        int err;
 387        char *buffer;
 388
 389#ifndef CONFIG_CISS_SCSI_TAPE
 390        return -EINVAL;
 391#endif
 392
 393        if (!buf || length > PAGE_SIZE - 1)
 394                return -EINVAL;
 395
 396        buffer = (char *)__get_free_page(GFP_KERNEL);
 397        if (!buffer)
 398                return -ENOMEM;
 399
 400        err = -EFAULT;
 401        if (copy_from_user(buffer, buf, length))
 402                goto out;
 403        buffer[length] = '\0';
 404
 405#ifdef CONFIG_CISS_SCSI_TAPE
 406        if (strncmp(ENGAGE_SCSI, buffer, sizeof ENGAGE_SCSI - 1) == 0) {
 407                struct seq_file *seq = file->private_data;
 408                ctlr_info_t *h = seq->private;
 409                int rc;
 410
 411                rc = cciss_engage_scsi(h->ctlr);
 412                if (rc != 0)
 413                        err = -rc;
 414                else
 415                        err = length;
 416        } else
 417#endif /* CONFIG_CISS_SCSI_TAPE */
 418                err = -EINVAL;
 419        /* might be nice to have "disengage" too, but it's not
 420           safely possible. (only 1 module use count, lock issues.) */
 421
 422out:
 423        free_page((unsigned long)buffer);
 424        return err;
 425}
 426
 427static struct file_operations cciss_proc_fops = {
 428        .owner   = THIS_MODULE,
 429        .open    = cciss_seq_open,
 430        .read    = seq_read,
 431        .llseek  = seq_lseek,
 432        .release = seq_release,
 433        .write   = cciss_proc_write,
 434};
 435
 436static void __devinit cciss_procinit(int i)
 437{
 438        struct proc_dir_entry *pde;
 439
 440        if (proc_cciss == NULL)
 441                proc_cciss = proc_mkdir("driver/cciss", NULL);
 442        if (!proc_cciss)
 443                return;
 444        pde = proc_create_data(hba[i]->devname, S_IWUSR | S_IRUSR | S_IRGRP |
 445                                        S_IROTH, proc_cciss,
 446                                        &cciss_proc_fops, hba[i]);
 447}
 448#endif                          /* CONFIG_PROC_FS */
 449
 450/*
 451 * For operations that cannot sleep, a command block is allocated at init,
 452 * and managed by cmd_alloc() and cmd_free() using a simple bitmap to track
 453 * which ones are free or in use.  For operations that can wait for kmalloc
 454 * to possible sleep, this routine can be called with get_from_pool set to 0.
 455 * cmd_free() MUST be called with a got_from_pool set to 0 if cmd_alloc was.
 456 */
 457static CommandList_struct *cmd_alloc(ctlr_info_t *h, int get_from_pool)
 458{
 459        CommandList_struct *c;
 460        int i;
 461        u64bit temp64;
 462        dma_addr_t cmd_dma_handle, err_dma_handle;
 463
 464        if (!get_from_pool) {
 465                c = (CommandList_struct *) pci_alloc_consistent(h->pdev,
 466                        sizeof(CommandList_struct), &cmd_dma_handle);
 467                if (c == NULL)
 468                        return NULL;
 469                memset(c, 0, sizeof(CommandList_struct));
 470
 471                c->cmdindex = -1;
 472
 473                c->err_info = (ErrorInfo_struct *)
 474                    pci_alloc_consistent(h->pdev, sizeof(ErrorInfo_struct),
 475                            &err_dma_handle);
 476
 477                if (c->err_info == NULL) {
 478                        pci_free_consistent(h->pdev,
 479                                sizeof(CommandList_struct), c, cmd_dma_handle);
 480                        return NULL;
 481                }
 482                memset(c->err_info, 0, sizeof(ErrorInfo_struct));
 483        } else {                /* get it out of the controllers pool */
 484
 485                do {
 486                        i = find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds);
 487                        if (i == h->nr_cmds)
 488                                return NULL;
 489                } while (test_and_set_bit
 490                         (i & (BITS_PER_LONG - 1),
 491                          h->cmd_pool_bits + (i / BITS_PER_LONG)) != 0);
 492#ifdef CCISS_DEBUG
 493                printk(KERN_DEBUG "cciss: using command buffer %d\n", i);
 494#endif
 495                c = h->cmd_pool + i;
 496                memset(c, 0, sizeof(CommandList_struct));
 497                cmd_dma_handle = h->cmd_pool_dhandle
 498                    + i * sizeof(CommandList_struct);
 499                c->err_info = h->errinfo_pool + i;
 500                memset(c->err_info, 0, sizeof(ErrorInfo_struct));
 501                err_dma_handle = h->errinfo_pool_dhandle
 502                    + i * sizeof(ErrorInfo_struct);
 503                h->nr_allocs++;
 504
 505                c->cmdindex = i;
 506        }
 507
 508        c->busaddr = (__u32) cmd_dma_handle;
 509        temp64.val = (__u64) err_dma_handle;
 510        c->ErrDesc.Addr.lower = temp64.val32.lower;
 511        c->ErrDesc.Addr.upper = temp64.val32.upper;
 512        c->ErrDesc.Len = sizeof(ErrorInfo_struct);
 513
 514        c->ctlr = h->ctlr;
 515        return c;
 516}
 517
 518/*
 519 * Frees a command block that was previously allocated with cmd_alloc().
 520 */
 521static void cmd_free(ctlr_info_t *h, CommandList_struct *c, int got_from_pool)
 522{
 523        int i;
 524        u64bit temp64;
 525
 526        if (!got_from_pool) {
 527                temp64.val32.lower = c->ErrDesc.Addr.lower;
 528                temp64.val32.upper = c->ErrDesc.Addr.upper;
 529                pci_free_consistent(h->pdev, sizeof(ErrorInfo_struct),
 530                                    c->err_info, (dma_addr_t) temp64.val);
 531                pci_free_consistent(h->pdev, sizeof(CommandList_struct),
 532                                    c, (dma_addr_t) c->busaddr);
 533        } else {
 534                i = c - h->cmd_pool;
 535                clear_bit(i & (BITS_PER_LONG - 1),
 536                          h->cmd_pool_bits + (i / BITS_PER_LONG));
 537                h->nr_frees++;
 538        }
 539}
 540
 541static inline ctlr_info_t *get_host(struct gendisk *disk)
 542{
 543        return disk->queue->queuedata;
 544}
 545
 546static inline drive_info_struct *get_drv(struct gendisk *disk)
 547{
 548        return disk->private_data;
 549}
 550
 551/*
 552 * Open.  Make sure the device is really there.
 553 */
 554static int cciss_open(struct inode *inode, struct file *filep)
 555{
 556        ctlr_info_t *host = get_host(inode->i_bdev->bd_disk);
 557        drive_info_struct *drv = get_drv(inode->i_bdev->bd_disk);
 558
 559#ifdef CCISS_DEBUG
 560        printk(KERN_DEBUG "cciss_open %s\n", inode->i_bdev->bd_disk->disk_name);
 561#endif                          /* CCISS_DEBUG */
 562
 563        if (host->busy_initializing || drv->busy_configuring)
 564                return -EBUSY;
 565        /*
 566         * Root is allowed to open raw volume zero even if it's not configured
 567         * so array config can still work. Root is also allowed to open any
 568         * volume that has a LUN ID, so it can issue IOCTL to reread the
 569         * disk information.  I don't think I really like this
 570         * but I'm already using way to many device nodes to claim another one
 571         * for "raw controller".
 572         */
 573        if (drv->heads == 0) {
 574                if (iminor(inode) != 0) {       /* not node 0? */
 575                        /* if not node 0 make sure it is a partition = 0 */
 576                        if (iminor(inode) & 0x0f) {
 577                                return -ENXIO;
 578                                /* if it is, make sure we have a LUN ID */
 579                        } else if (drv->LunID == 0) {
 580                                return -ENXIO;
 581                        }
 582                }
 583                if (!capable(CAP_SYS_ADMIN))
 584                        return -EPERM;
 585        }
 586        drv->usage_count++;
 587        host->usage_count++;
 588        return 0;
 589}
 590
 591/*
 592 * Close.  Sync first.
 593 */
 594static int cciss_release(struct inode *inode, struct file *filep)
 595{
 596        ctlr_info_t *host = get_host(inode->i_bdev->bd_disk);
 597        drive_info_struct *drv = get_drv(inode->i_bdev->bd_disk);
 598
 599#ifdef CCISS_DEBUG
 600        printk(KERN_DEBUG "cciss_release %s\n",
 601               inode->i_bdev->bd_disk->disk_name);
 602#endif                          /* CCISS_DEBUG */
 603
 604        drv->usage_count--;
 605        host->usage_count--;
 606        return 0;
 607}
 608
 609#ifdef CONFIG_COMPAT
 610
 611static int do_ioctl(struct file *f, unsigned cmd, unsigned long arg)
 612{
 613        int ret;
 614        lock_kernel();
 615        ret = cciss_ioctl(f->f_path.dentry->d_inode, f, cmd, arg);
 616        unlock_kernel();
 617        return ret;
 618}
 619
 620static int cciss_ioctl32_passthru(struct file *f, unsigned cmd,
 621                                  unsigned long arg);
 622static int cciss_ioctl32_big_passthru(struct file *f, unsigned cmd,
 623                                      unsigned long arg);
 624
 625static long cciss_compat_ioctl(struct file *f, unsigned cmd, unsigned long arg)
 626{
 627        switch (cmd) {
 628        case CCISS_GETPCIINFO:
 629        case CCISS_GETINTINFO:
 630        case CCISS_SETINTINFO:
 631        case CCISS_GETNODENAME:
 632        case CCISS_SETNODENAME:
 633        case CCISS_GETHEARTBEAT:
 634        case CCISS_GETBUSTYPES:
 635        case CCISS_GETFIRMVER:
 636        case CCISS_GETDRIVVER:
 637        case CCISS_REVALIDVOLS:
 638        case CCISS_DEREGDISK:
 639        case CCISS_REGNEWDISK:
 640        case CCISS_REGNEWD:
 641        case CCISS_RESCANDISK:
 642        case CCISS_GETLUNINFO:
 643                return do_ioctl(f, cmd, arg);
 644
 645        case CCISS_PASSTHRU32:
 646                return cciss_ioctl32_passthru(f, cmd, arg);
 647        case CCISS_BIG_PASSTHRU32:
 648                return cciss_ioctl32_big_passthru(f, cmd, arg);
 649
 650        default:
 651                return -ENOIOCTLCMD;
 652        }
 653}
 654
 655static int cciss_ioctl32_passthru(struct file *f, unsigned cmd,
 656                                  unsigned long arg)
 657{
 658        IOCTL32_Command_struct __user *arg32 =
 659            (IOCTL32_Command_struct __user *) arg;
 660        IOCTL_Command_struct arg64;
 661        IOCTL_Command_struct __user *p = compat_alloc_user_space(sizeof(arg64));
 662        int err;
 663        u32 cp;
 664
 665        err = 0;
 666        err |=
 667            copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
 668                           sizeof(arg64.LUN_info));
 669        err |=
 670            copy_from_user(&arg64.Request, &arg32->Request,
 671                           sizeof(arg64.Request));
 672        err |=
 673            copy_from_user(&arg64.error_info, &arg32->error_info,
 674                           sizeof(arg64.error_info));
 675        err |= get_user(arg64.buf_size, &arg32->buf_size);
 676        err |= get_user(cp, &arg32->buf);
 677        arg64.buf = compat_ptr(cp);
 678        err |= copy_to_user(p, &arg64, sizeof(arg64));
 679
 680        if (err)
 681                return -EFAULT;
 682
 683        err = do_ioctl(f, CCISS_PASSTHRU, (unsigned long)p);
 684        if (err)
 685                return err;
 686        err |=
 687            copy_in_user(&arg32->error_info, &p->error_info,
 688                         sizeof(arg32->error_info));
 689        if (err)
 690                return -EFAULT;
 691        return err;
 692}
 693
 694static int cciss_ioctl32_big_passthru(struct file *file, unsigned cmd,
 695                                      unsigned long arg)
 696{
 697        BIG_IOCTL32_Command_struct __user *arg32 =
 698            (BIG_IOCTL32_Command_struct __user *) arg;
 699        BIG_IOCTL_Command_struct arg64;
 700        BIG_IOCTL_Command_struct __user *p =
 701            compat_alloc_user_space(sizeof(arg64));
 702        int err;
 703        u32 cp;
 704
 705        err = 0;
 706        err |=
 707            copy_from_user(&arg64.LUN_info, &arg32->LUN_info,
 708                           sizeof(arg64.LUN_info));
 709        err |=
 710            copy_from_user(&arg64.Request, &arg32->Request,
 711                           sizeof(arg64.Request));
 712        err |=
 713            copy_from_user(&arg64.error_info, &arg32->error_info,
 714                           sizeof(arg64.error_info));
 715        err |= get_user(arg64.buf_size, &arg32->buf_size);
 716        err |= get_user(arg64.malloc_size, &arg32->malloc_size);
 717        err |= get_user(cp, &arg32->buf);
 718        arg64.buf = compat_ptr(cp);
 719        err |= copy_to_user(p, &arg64, sizeof(arg64));
 720
 721        if (err)
 722                return -EFAULT;
 723
 724        err = do_ioctl(file, CCISS_BIG_PASSTHRU, (unsigned long)p);
 725        if (err)
 726                return err;
 727        err |=
 728            copy_in_user(&arg32->error_info, &p->error_info,
 729                         sizeof(arg32->error_info));
 730        if (err)
 731                return -EFAULT;
 732        return err;
 733}
 734#endif
 735
 736static int cciss_getgeo(struct block_device *bdev, struct hd_geometry *geo)
 737{
 738        drive_info_struct *drv = get_drv(bdev->bd_disk);
 739
 740        if (!drv->cylinders)
 741                return -ENXIO;
 742
 743        geo->heads = drv->heads;
 744        geo->sectors = drv->sectors;
 745        geo->cylinders = drv->cylinders;
 746        return 0;
 747}
 748
 749/*
 750 * ioctl
 751 */
 752static int cciss_ioctl(struct inode *inode, struct file *filep,
 753                       unsigned int cmd, unsigned long arg)
 754{
 755        struct block_device *bdev = inode->i_bdev;
 756        struct gendisk *disk = bdev->bd_disk;
 757        ctlr_info_t *host = get_host(disk);
 758        drive_info_struct *drv = get_drv(disk);
 759        int ctlr = host->ctlr;
 760        void __user *argp = (void __user *)arg;
 761
 762#ifdef CCISS_DEBUG
 763        printk(KERN_DEBUG "cciss_ioctl: Called with cmd=%x %lx\n", cmd, arg);
 764#endif                          /* CCISS_DEBUG */
 765
 766        switch (cmd) {
 767        case CCISS_GETPCIINFO:
 768                {
 769                        cciss_pci_info_struct pciinfo;
 770
 771                        if (!arg)
 772                                return -EINVAL;
 773                        pciinfo.domain = pci_domain_nr(host->pdev->bus);
 774                        pciinfo.bus = host->pdev->bus->number;
 775                        pciinfo.dev_fn = host->pdev->devfn;
 776                        pciinfo.board_id = host->board_id;
 777                        if (copy_to_user
 778                            (argp, &pciinfo, sizeof(cciss_pci_info_struct)))
 779                                return -EFAULT;
 780                        return 0;
 781                }
 782        case CCISS_GETINTINFO:
 783                {
 784                        cciss_coalint_struct intinfo;
 785                        if (!arg)
 786                                return -EINVAL;
 787                        intinfo.delay =
 788                            readl(&host->cfgtable->HostWrite.CoalIntDelay);
 789                        intinfo.count =
 790                            readl(&host->cfgtable->HostWrite.CoalIntCount);
 791                        if (copy_to_user
 792                            (argp, &intinfo, sizeof(cciss_coalint_struct)))
 793                                return -EFAULT;
 794                        return 0;
 795                }
 796        case CCISS_SETINTINFO:
 797                {
 798                        cciss_coalint_struct intinfo;
 799                        unsigned long flags;
 800                        int i;
 801
 802                        if (!arg)
 803                                return -EINVAL;
 804                        if (!capable(CAP_SYS_ADMIN))
 805                                return -EPERM;
 806                        if (copy_from_user
 807                            (&intinfo, argp, sizeof(cciss_coalint_struct)))
 808                                return -EFAULT;
 809                        if ((intinfo.delay == 0) && (intinfo.count == 0))
 810                        {
 811//                      printk("cciss_ioctl: delay and count cannot be 0\n");
 812                                return -EINVAL;
 813                        }
 814                        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
 815                        /* Update the field, and then ring the doorbell */
 816                        writel(intinfo.delay,
 817                               &(host->cfgtable->HostWrite.CoalIntDelay));
 818                        writel(intinfo.count,
 819                               &(host->cfgtable->HostWrite.CoalIntCount));
 820                        writel(CFGTBL_ChangeReq, host->vaddr + SA5_DOORBELL);
 821
 822                        for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
 823                                if (!(readl(host->vaddr + SA5_DOORBELL)
 824                                      & CFGTBL_ChangeReq))
 825                                        break;
 826                                /* delay and try again */
 827                                udelay(1000);
 828                        }
 829                        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
 830                        if (i >= MAX_IOCTL_CONFIG_WAIT)
 831                                return -EAGAIN;
 832                        return 0;
 833                }
 834        case CCISS_GETNODENAME:
 835                {
 836                        NodeName_type NodeName;
 837                        int i;
 838
 839                        if (!arg)
 840                                return -EINVAL;
 841                        for (i = 0; i < 16; i++)
 842                                NodeName[i] =
 843                                    readb(&host->cfgtable->ServerName[i]);
 844                        if (copy_to_user(argp, NodeName, sizeof(NodeName_type)))
 845                                return -EFAULT;
 846                        return 0;
 847                }
 848        case CCISS_SETNODENAME:
 849                {
 850                        NodeName_type NodeName;
 851                        unsigned long flags;
 852                        int i;
 853
 854                        if (!arg)
 855                                return -EINVAL;
 856                        if (!capable(CAP_SYS_ADMIN))
 857                                return -EPERM;
 858
 859                        if (copy_from_user
 860                            (NodeName, argp, sizeof(NodeName_type)))
 861                                return -EFAULT;
 862
 863                        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
 864
 865                        /* Update the field, and then ring the doorbell */
 866                        for (i = 0; i < 16; i++)
 867                                writeb(NodeName[i],
 868                                       &host->cfgtable->ServerName[i]);
 869
 870                        writel(CFGTBL_ChangeReq, host->vaddr + SA5_DOORBELL);
 871
 872                        for (i = 0; i < MAX_IOCTL_CONFIG_WAIT; i++) {
 873                                if (!(readl(host->vaddr + SA5_DOORBELL)
 874                                      & CFGTBL_ChangeReq))
 875                                        break;
 876                                /* delay and try again */
 877                                udelay(1000);
 878                        }
 879                        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
 880                        if (i >= MAX_IOCTL_CONFIG_WAIT)
 881                                return -EAGAIN;
 882                        return 0;
 883                }
 884
 885        case CCISS_GETHEARTBEAT:
 886                {
 887                        Heartbeat_type heartbeat;
 888
 889                        if (!arg)
 890                                return -EINVAL;
 891                        heartbeat = readl(&host->cfgtable->HeartBeat);
 892                        if (copy_to_user
 893                            (argp, &heartbeat, sizeof(Heartbeat_type)))
 894                                return -EFAULT;
 895                        return 0;
 896                }
 897        case CCISS_GETBUSTYPES:
 898                {
 899                        BusTypes_type BusTypes;
 900
 901                        if (!arg)
 902                                return -EINVAL;
 903                        BusTypes = readl(&host->cfgtable->BusTypes);
 904                        if (copy_to_user
 905                            (argp, &BusTypes, sizeof(BusTypes_type)))
 906                                return -EFAULT;
 907                        return 0;
 908                }
 909        case CCISS_GETFIRMVER:
 910                {
 911                        FirmwareVer_type firmware;
 912
 913                        if (!arg)
 914                                return -EINVAL;
 915                        memcpy(firmware, host->firm_ver, 4);
 916
 917                        if (copy_to_user
 918                            (argp, firmware, sizeof(FirmwareVer_type)))
 919                                return -EFAULT;
 920                        return 0;
 921                }
 922        case CCISS_GETDRIVVER:
 923                {
 924                        DriverVer_type DriverVer = DRIVER_VERSION;
 925
 926                        if (!arg)
 927                                return -EINVAL;
 928
 929                        if (copy_to_user
 930                            (argp, &DriverVer, sizeof(DriverVer_type)))
 931                                return -EFAULT;
 932                        return 0;
 933                }
 934
 935        case CCISS_DEREGDISK:
 936        case CCISS_REGNEWD:
 937        case CCISS_REVALIDVOLS:
 938                return rebuild_lun_table(host, 0);
 939
 940        case CCISS_GETLUNINFO:{
 941                        LogvolInfo_struct luninfo;
 942
 943                        luninfo.LunID = drv->LunID;
 944                        luninfo.num_opens = drv->usage_count;
 945                        luninfo.num_parts = 0;
 946                        if (copy_to_user(argp, &luninfo,
 947                                         sizeof(LogvolInfo_struct)))
 948                                return -EFAULT;
 949                        return 0;
 950                }
 951        case CCISS_PASSTHRU:
 952                {
 953                        IOCTL_Command_struct iocommand;
 954                        CommandList_struct *c;
 955                        char *buff = NULL;
 956                        u64bit temp64;
 957                        unsigned long flags;
 958                        DECLARE_COMPLETION_ONSTACK(wait);
 959
 960                        if (!arg)
 961                                return -EINVAL;
 962
 963                        if (!capable(CAP_SYS_RAWIO))
 964                                return -EPERM;
 965
 966                        if (copy_from_user
 967                            (&iocommand, argp, sizeof(IOCTL_Command_struct)))
 968                                return -EFAULT;
 969                        if ((iocommand.buf_size < 1) &&
 970                            (iocommand.Request.Type.Direction != XFER_NONE)) {
 971                                return -EINVAL;
 972                        }
 973#if 0                           /* 'buf_size' member is 16-bits, and always smaller than kmalloc limit */
 974                        /* Check kmalloc limits */
 975                        if (iocommand.buf_size > 128000)
 976                                return -EINVAL;
 977#endif
 978                        if (iocommand.buf_size > 0) {
 979                                buff = kmalloc(iocommand.buf_size, GFP_KERNEL);
 980                                if (buff == NULL)
 981                                        return -EFAULT;
 982                        }
 983                        if (iocommand.Request.Type.Direction == XFER_WRITE) {
 984                                /* Copy the data into the buffer we created */
 985                                if (copy_from_user
 986                                    (buff, iocommand.buf, iocommand.buf_size)) {
 987                                        kfree(buff);
 988                                        return -EFAULT;
 989                                }
 990                        } else {
 991                                memset(buff, 0, iocommand.buf_size);
 992                        }
 993                        if ((c = cmd_alloc(host, 0)) == NULL) {
 994                                kfree(buff);
 995                                return -ENOMEM;
 996                        }
 997                        // Fill in the command type
 998                        c->cmd_type = CMD_IOCTL_PEND;
 999                        // Fill in Command Header
1000                        c->Header.ReplyQueue = 0;       // unused in simple mode
1001                        if (iocommand.buf_size > 0)     // buffer to fill
1002                        {
1003                                c->Header.SGList = 1;
1004                                c->Header.SGTotal = 1;
1005                        } else  // no buffers to fill
1006                        {
1007                                c->Header.SGList = 0;
1008                                c->Header.SGTotal = 0;
1009                        }
1010                        c->Header.LUN = iocommand.LUN_info;
1011                        c->Header.Tag.lower = c->busaddr;       // use the kernel address the cmd block for tag
1012
1013                        // Fill in Request block
1014                        c->Request = iocommand.Request;
1015
1016                        // Fill in the scatter gather information
1017                        if (iocommand.buf_size > 0) {
1018                                temp64.val = pci_map_single(host->pdev, buff,
1019                                        iocommand.buf_size,
1020                                        PCI_DMA_BIDIRECTIONAL);
1021                                c->SG[0].Addr.lower = temp64.val32.lower;
1022                                c->SG[0].Addr.upper = temp64.val32.upper;
1023                                c->SG[0].Len = iocommand.buf_size;
1024                                c->SG[0].Ext = 0;       // we are not chaining
1025                        }
1026                        c->waiting = &wait;
1027
1028                        /* Put the request on the tail of the request queue */
1029                        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1030                        addQ(&host->reqQ, c);
1031                        host->Qdepth++;
1032                        start_io(host);
1033                        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1034
1035                        wait_for_completion(&wait);
1036
1037                        /* unlock the buffers from DMA */
1038                        temp64.val32.lower = c->SG[0].Addr.lower;
1039                        temp64.val32.upper = c->SG[0].Addr.upper;
1040                        pci_unmap_single(host->pdev, (dma_addr_t) temp64.val,
1041                                         iocommand.buf_size,
1042                                         PCI_DMA_BIDIRECTIONAL);
1043
1044                        /* Copy the error information out */
1045                        iocommand.error_info = *(c->err_info);
1046                        if (copy_to_user
1047                            (argp, &iocommand, sizeof(IOCTL_Command_struct))) {
1048                                kfree(buff);
1049                                cmd_free(host, c, 0);
1050                                return -EFAULT;
1051                        }
1052
1053                        if (iocommand.Request.Type.Direction == XFER_READ) {
1054                                /* Copy the data out of the buffer we created */
1055                                if (copy_to_user
1056                                    (iocommand.buf, buff, iocommand.buf_size)) {
1057                                        kfree(buff);
1058                                        cmd_free(host, c, 0);
1059                                        return -EFAULT;
1060                                }
1061                        }
1062                        kfree(buff);
1063                        cmd_free(host, c, 0);
1064                        return 0;
1065                }
1066        case CCISS_BIG_PASSTHRU:{
1067                        BIG_IOCTL_Command_struct *ioc;
1068                        CommandList_struct *c;
1069                        unsigned char **buff = NULL;
1070                        int *buff_size = NULL;
1071                        u64bit temp64;
1072                        unsigned long flags;
1073                        BYTE sg_used = 0;
1074                        int status = 0;
1075                        int i;
1076                        DECLARE_COMPLETION_ONSTACK(wait);
1077                        __u32 left;
1078                        __u32 sz;
1079                        BYTE __user *data_ptr;
1080
1081                        if (!arg)
1082                                return -EINVAL;
1083                        if (!capable(CAP_SYS_RAWIO))
1084                                return -EPERM;
1085                        ioc = (BIG_IOCTL_Command_struct *)
1086                            kmalloc(sizeof(*ioc), GFP_KERNEL);
1087                        if (!ioc) {
1088                                status = -ENOMEM;
1089                                goto cleanup1;
1090                        }
1091                        if (copy_from_user(ioc, argp, sizeof(*ioc))) {
1092                                status = -EFAULT;
1093                                goto cleanup1;
1094                        }
1095                        if ((ioc->buf_size < 1) &&
1096                            (ioc->Request.Type.Direction != XFER_NONE)) {
1097                                status = -EINVAL;
1098                                goto cleanup1;
1099                        }
1100                        /* Check kmalloc limits  using all SGs */
1101                        if (ioc->malloc_size > MAX_KMALLOC_SIZE) {
1102                                status = -EINVAL;
1103                                goto cleanup1;
1104                        }
1105                        if (ioc->buf_size > ioc->malloc_size * MAXSGENTRIES) {
1106                                status = -EINVAL;
1107                                goto cleanup1;
1108                        }
1109                        buff =
1110                            kzalloc(MAXSGENTRIES * sizeof(char *), GFP_KERNEL);
1111                        if (!buff) {
1112                                status = -ENOMEM;
1113                                goto cleanup1;
1114                        }
1115                        buff_size = kmalloc(MAXSGENTRIES * sizeof(int),
1116                                                   GFP_KERNEL);
1117                        if (!buff_size) {
1118                                status = -ENOMEM;
1119                                goto cleanup1;
1120                        }
1121                        left = ioc->buf_size;
1122                        data_ptr = ioc->buf;
1123                        while (left) {
1124                                sz = (left >
1125                                      ioc->malloc_size) ? ioc->
1126                                    malloc_size : left;
1127                                buff_size[sg_used] = sz;
1128                                buff[sg_used] = kmalloc(sz, GFP_KERNEL);
1129                                if (buff[sg_used] == NULL) {
1130                                        status = -ENOMEM;
1131                                        goto cleanup1;
1132                                }
1133                                if (ioc->Request.Type.Direction == XFER_WRITE) {
1134                                        if (copy_from_user
1135                                            (buff[sg_used], data_ptr, sz)) {
1136                                                status = -EFAULT;
1137                                                goto cleanup1;
1138                                        }
1139                                } else {
1140                                        memset(buff[sg_used], 0, sz);
1141                                }
1142                                left -= sz;
1143                                data_ptr += sz;
1144                                sg_used++;
1145                        }
1146                        if ((c = cmd_alloc(host, 0)) == NULL) {
1147                                status = -ENOMEM;
1148                                goto cleanup1;
1149                        }
1150                        c->cmd_type = CMD_IOCTL_PEND;
1151                        c->Header.ReplyQueue = 0;
1152
1153                        if (ioc->buf_size > 0) {
1154                                c->Header.SGList = sg_used;
1155                                c->Header.SGTotal = sg_used;
1156                        } else {
1157                                c->Header.SGList = 0;
1158                                c->Header.SGTotal = 0;
1159                        }
1160                        c->Header.LUN = ioc->LUN_info;
1161                        c->Header.Tag.lower = c->busaddr;
1162
1163                        c->Request = ioc->Request;
1164                        if (ioc->buf_size > 0) {
1165                                int i;
1166                                for (i = 0; i < sg_used; i++) {
1167                                        temp64.val =
1168                                            pci_map_single(host->pdev, buff[i],
1169                                                    buff_size[i],
1170                                                    PCI_DMA_BIDIRECTIONAL);
1171                                        c->SG[i].Addr.lower =
1172                                            temp64.val32.lower;
1173                                        c->SG[i].Addr.upper =
1174                                            temp64.val32.upper;
1175                                        c->SG[i].Len = buff_size[i];
1176                                        c->SG[i].Ext = 0;       /* we are not chaining */
1177                                }
1178                        }
1179                        c->waiting = &wait;
1180                        /* Put the request on the tail of the request queue */
1181                        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
1182                        addQ(&host->reqQ, c);
1183                        host->Qdepth++;
1184                        start_io(host);
1185                        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
1186                        wait_for_completion(&wait);
1187                        /* unlock the buffers from DMA */
1188                        for (i = 0; i < sg_used; i++) {
1189                                temp64.val32.lower = c->SG[i].Addr.lower;
1190                                temp64.val32.upper = c->SG[i].Addr.upper;
1191                                pci_unmap_single(host->pdev,
1192                                        (dma_addr_t) temp64.val, buff_size[i],
1193                                        PCI_DMA_BIDIRECTIONAL);
1194                        }
1195                        /* Copy the error information out */
1196                        ioc->error_info = *(c->err_info);
1197                        if (copy_to_user(argp, ioc, sizeof(*ioc))) {
1198                                cmd_free(host, c, 0);
1199                                status = -EFAULT;
1200                                goto cleanup1;
1201                        }
1202                        if (ioc->Request.Type.Direction == XFER_READ) {
1203                                /* Copy the data out of the buffer we created */
1204                                BYTE __user *ptr = ioc->buf;
1205                                for (i = 0; i < sg_used; i++) {
1206                                        if (copy_to_user
1207                                            (ptr, buff[i], buff_size[i])) {
1208                                                cmd_free(host, c, 0);
1209                                                status = -EFAULT;
1210                                                goto cleanup1;
1211                                        }
1212                                        ptr += buff_size[i];
1213                                }
1214                        }
1215                        cmd_free(host, c, 0);
1216                        status = 0;
1217                      cleanup1:
1218                        if (buff) {
1219                                for (i = 0; i < sg_used; i++)
1220                                        kfree(buff[i]);
1221                                kfree(buff);
1222                        }
1223                        kfree(buff_size);
1224                        kfree(ioc);
1225                        return status;
1226                }
1227
1228        /* scsi_cmd_blk_ioctl handles these, below, though some are not */
1229        /* very meaningful for cciss.  SG_IO is the main one people want. */
1230
1231        case SG_GET_VERSION_NUM:
1232        case SG_SET_TIMEOUT:
1233        case SG_GET_TIMEOUT:
1234        case SG_GET_RESERVED_SIZE:
1235        case SG_SET_RESERVED_SIZE:
1236        case SG_EMULATED_HOST:
1237        case SG_IO:
1238        case SCSI_IOCTL_SEND_COMMAND:
1239                return scsi_cmd_blk_ioctl(filep, bdev, cmd, argp);
1240
1241        /* scsi_cmd_blk_ioctl would normally handle these, below, but */
1242        /* they aren't a good fit for cciss, as CD-ROMs are */
1243        /* not supported, and we don't have any bus/target/lun */
1244        /* which we present to the kernel. */
1245
1246        case CDROM_SEND_PACKET:
1247        case CDROMCLOSETRAY:
1248        case CDROMEJECT:
1249        case SCSI_IOCTL_GET_IDLUN:
1250        case SCSI_IOCTL_GET_BUS_NUMBER:
1251        default:
1252                return -ENOTTY;
1253        }
1254}
1255
1256static void cciss_check_queues(ctlr_info_t *h)
1257{
1258        int start_queue = h->next_to_run;
1259        int i;
1260
1261        /* check to see if we have maxed out the number of commands that can
1262         * be placed on the queue.  If so then exit.  We do this check here
1263         * in case the interrupt we serviced was from an ioctl and did not
1264         * free any new commands.
1265         */
1266        if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds)
1267                return;
1268
1269        /* We have room on the queue for more commands.  Now we need to queue
1270         * them up.  We will also keep track of the next queue to run so
1271         * that every queue gets a chance to be started first.
1272         */
1273        for (i = 0; i < h->highest_lun + 1; i++) {
1274                int curr_queue = (start_queue + i) % (h->highest_lun + 1);
1275                /* make sure the disk has been added and the drive is real
1276                 * because this can be called from the middle of init_one.
1277                 */
1278                if (!(h->drv[curr_queue].queue) || !(h->drv[curr_queue].heads))
1279                        continue;
1280                blk_start_queue(h->gendisk[curr_queue]->queue);
1281
1282                /* check to see if we have maxed out the number of commands
1283                 * that can be placed on the queue.
1284                 */
1285                if ((find_first_zero_bit(h->cmd_pool_bits, h->nr_cmds)) == h->nr_cmds) {
1286                        if (curr_queue == start_queue) {
1287                                h->next_to_run =
1288                                    (start_queue + 1) % (h->highest_lun + 1);
1289                                break;
1290                        } else {
1291                                h->next_to_run = curr_queue;
1292                                break;
1293                        }
1294                }
1295        }
1296}
1297
1298static void cciss_softirq_done(struct request *rq)
1299{
1300        CommandList_struct *cmd = rq->completion_data;
1301        ctlr_info_t *h = hba[cmd->ctlr];
1302        unsigned long flags;
1303        u64bit temp64;
1304        int i, ddir;
1305
1306        if (cmd->Request.Type.Direction == XFER_READ)
1307                ddir = PCI_DMA_FROMDEVICE;
1308        else
1309                ddir = PCI_DMA_TODEVICE;
1310
1311        /* command did not need to be retried */
1312        /* unmap the DMA mapping for all the scatter gather elements */
1313        for (i = 0; i < cmd->Header.SGList; i++) {
1314                temp64.val32.lower = cmd->SG[i].Addr.lower;
1315                temp64.val32.upper = cmd->SG[i].Addr.upper;
1316                pci_unmap_page(h->pdev, temp64.val, cmd->SG[i].Len, ddir);
1317        }
1318
1319#ifdef CCISS_DEBUG
1320        printk("Done with %p\n", rq);
1321#endif                          /* CCISS_DEBUG */
1322
1323        if (blk_end_request(rq, (rq->errors == 0) ? 0 : -EIO, blk_rq_bytes(rq)))
1324                BUG();
1325
1326        spin_lock_irqsave(&h->lock, flags);
1327        cmd_free(h, cmd, 1);
1328        cciss_check_queues(h);
1329        spin_unlock_irqrestore(&h->lock, flags);
1330}
1331
1332/* This function gets the serial number of a logical drive via
1333 * inquiry page 0x83.  Serial no. is 16 bytes.  If the serial
1334 * number cannot be had, for whatever reason, 16 bytes of 0xff
1335 * are returned instead.
1336 */
1337static void cciss_get_serial_no(int ctlr, int logvol, int withirq,
1338                                unsigned char *serial_no, int buflen)
1339{
1340#define PAGE_83_INQ_BYTES 64
1341        int rc;
1342        unsigned char *buf;
1343
1344        if (buflen > 16)
1345                buflen = 16;
1346        memset(serial_no, 0xff, buflen);
1347        buf = kzalloc(PAGE_83_INQ_BYTES, GFP_KERNEL);
1348        if (!buf)
1349                return;
1350        memset(serial_no, 0, buflen);
1351        if (withirq)
1352                rc = sendcmd_withirq(CISS_INQUIRY, ctlr, buf,
1353                        PAGE_83_INQ_BYTES, 1, logvol, 0x83, TYPE_CMD);
1354        else
1355                rc = sendcmd(CISS_INQUIRY, ctlr, buf,
1356                        PAGE_83_INQ_BYTES, 1, logvol, 0x83, NULL, TYPE_CMD);
1357        if (rc == IO_OK)
1358                memcpy(serial_no, &buf[8], buflen);
1359        kfree(buf);
1360        return;
1361}
1362
1363static void cciss_add_disk(ctlr_info_t *h, struct gendisk *disk,
1364                                int drv_index)
1365{
1366        disk->queue = blk_init_queue(do_cciss_request, &h->lock);
1367        sprintf(disk->disk_name, "cciss/c%dd%d", h->ctlr, drv_index);
1368        disk->major = h->major;
1369        disk->first_minor = drv_index << NWD_SHIFT;
1370        disk->fops = &cciss_fops;
1371        disk->private_data = &h->drv[drv_index];
1372        disk->driverfs_dev = &h->pdev->dev;
1373
1374        /* Set up queue information */
1375        blk_queue_bounce_limit(disk->queue, h->pdev->dma_mask);
1376
1377        /* This is a hardware imposed limit. */
1378        blk_queue_max_hw_segments(disk->queue, MAXSGENTRIES);
1379
1380        /* This is a limit in the driver and could be eliminated. */
1381        blk_queue_max_phys_segments(disk->queue, MAXSGENTRIES);
1382
1383        blk_queue_max_sectors(disk->queue, h->cciss_max_sectors);
1384
1385        blk_queue_softirq_done(disk->queue, cciss_softirq_done);
1386
1387        disk->queue->queuedata = h;
1388
1389        blk_queue_hardsect_size(disk->queue,
1390                                h->drv[drv_index].block_size);
1391
1392        /* Make sure all queue data is written out before */
1393        /* setting h->drv[drv_index].queue, as setting this */
1394        /* allows the interrupt handler to start the queue */
1395        wmb();
1396        h->drv[drv_index].queue = disk->queue;
1397        add_disk(disk);
1398}
1399
1400/* This function will check the usage_count of the drive to be updated/added.
1401 * If the usage_count is zero and it is a heretofore unknown drive, or,
1402 * the drive's capacity, geometry, or serial number has changed,
1403 * then the drive information will be updated and the disk will be
1404 * re-registered with the kernel.  If these conditions don't hold,
1405 * then it will be left alone for the next reboot.  The exception to this
1406 * is disk 0 which will always be left registered with the kernel since it
1407 * is also the controller node.  Any changes to disk 0 will show up on
1408 * the next reboot.
1409 */
1410static void cciss_update_drive_info(int ctlr, int drv_index, int first_time)
1411{
1412        ctlr_info_t *h = hba[ctlr];
1413        struct gendisk *disk;
1414        InquiryData_struct *inq_buff = NULL;
1415        unsigned int block_size;
1416        sector_t total_size;
1417        unsigned long flags = 0;
1418        int ret = 0;
1419        drive_info_struct *drvinfo;
1420        int was_only_controller_node;
1421
1422        /* Get information about the disk and modify the driver structure */
1423        inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
1424        drvinfo = kmalloc(sizeof(*drvinfo), GFP_KERNEL);
1425        if (inq_buff == NULL || drvinfo == NULL)
1426                goto mem_msg;
1427
1428        /* See if we're trying to update the "controller node"
1429         * this will happen the when the first logical drive gets
1430         * created by ACU.
1431         */
1432        was_only_controller_node = (drv_index == 0 &&
1433                                h->drv[0].raid_level == -1);
1434
1435        /* testing to see if 16-byte CDBs are already being used */
1436        if (h->cciss_read == CCISS_READ_16) {
1437                cciss_read_capacity_16(h->ctlr, drv_index, 1,
1438                        &total_size, &block_size);
1439
1440        } else {
1441                cciss_read_capacity(ctlr, drv_index, 1,
1442                                    &total_size, &block_size);
1443
1444                /* if read_capacity returns all F's this volume is >2TB */
1445                /* in size so we switch to 16-byte CDB's for all */
1446                /* read/write ops */
1447                if (total_size == 0xFFFFFFFFULL) {
1448                        cciss_read_capacity_16(ctlr, drv_index, 1,
1449                        &total_size, &block_size);
1450                        h->cciss_read = CCISS_READ_16;
1451                        h->cciss_write = CCISS_WRITE_16;
1452                } else {
1453                        h->cciss_read = CCISS_READ_10;
1454                        h->cciss_write = CCISS_WRITE_10;
1455                }
1456        }
1457
1458        cciss_geometry_inquiry(ctlr, drv_index, 1, total_size, block_size,
1459                               inq_buff, drvinfo);
1460        drvinfo->block_size = block_size;
1461        drvinfo->nr_blocks = total_size + 1;
1462
1463        cciss_get_serial_no(ctlr, drv_index, 1, drvinfo->serial_no,
1464                        sizeof(drvinfo->serial_no));
1465
1466        /* Is it the same disk we already know, and nothing's changed? */
1467        if (h->drv[drv_index].raid_level != -1 &&
1468                ((memcmp(drvinfo->serial_no,
1469                                h->drv[drv_index].serial_no, 16) == 0) &&
1470                drvinfo->block_size == h->drv[drv_index].block_size &&
1471                drvinfo->nr_blocks == h->drv[drv_index].nr_blocks &&
1472                drvinfo->heads == h->drv[drv_index].heads &&
1473                drvinfo->sectors == h->drv[drv_index].sectors &&
1474                drvinfo->cylinders == h->drv[drv_index].cylinders))
1475                        /* The disk is unchanged, nothing to update */
1476                        goto freeret;
1477
1478        /* If we get here it's not the same disk, or something's changed,
1479         * so we need to * deregister it, and re-register it, if it's not
1480         * in use.
1481         * If the disk already exists then deregister it before proceeding
1482         * (unless it's the first disk (for the controller node).
1483         */
1484        if (h->drv[drv_index].raid_level != -1 && drv_index != 0) {
1485                printk(KERN_WARNING "disk %d has changed.\n", drv_index);
1486                spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
1487                h->drv[drv_index].busy_configuring = 1;
1488                spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
1489
1490                /* deregister_disk sets h->drv[drv_index].queue = NULL
1491                 * which keeps the interrupt handler from starting
1492                 * the queue.
1493                 */
1494                ret = deregister_disk(h->gendisk[drv_index],
1495                                      &h->drv[drv_index], 0);
1496                h->drv[drv_index].busy_configuring = 0;
1497        }
1498
1499        /* If the disk is in use return */
1500        if (ret)
1501                goto freeret;
1502
1503        /* Save the new information from cciss_geometry_inquiry
1504         * and serial number inquiry.
1505         */
1506        h->drv[drv_index].block_size = drvinfo->block_size;
1507        h->drv[drv_index].nr_blocks = drvinfo->nr_blocks;
1508        h->drv[drv_index].heads = drvinfo->heads;
1509        h->drv[drv_index].sectors = drvinfo->sectors;
1510        h->drv[drv_index].cylinders = drvinfo->cylinders;
1511        h->drv[drv_index].raid_level = drvinfo->raid_level;
1512        memcpy(h->drv[drv_index].serial_no, drvinfo->serial_no, 16);
1513
1514        ++h->num_luns;
1515        disk = h->gendisk[drv_index];
1516        set_capacity(disk, h->drv[drv_index].nr_blocks);
1517
1518        /* If it's not disk 0 (drv_index != 0)
1519         * or if it was disk 0, but there was previously
1520         * no actual corresponding configured logical drive
1521         * (raid_leve == -1) then we want to update the
1522         * logical drive's information.
1523         */
1524        if (drv_index || first_time)
1525                cciss_add_disk(h, disk, drv_index);
1526
1527freeret:
1528        kfree(inq_buff);
1529        kfree(drvinfo);
1530        return;
1531mem_msg:
1532        printk(KERN_ERR "cciss: out of memory\n");
1533        goto freeret;
1534}
1535
1536/* This function will find the first index of the controllers drive array
1537 * that has a -1 for the raid_level and will return that index.  This is
1538 * where new drives will be added.  If the index to be returned is greater
1539 * than the highest_lun index for the controller then highest_lun is set
1540 * to this new index.  If there are no available indexes then -1 is returned.
1541 * "controller_node" is used to know if this is a real logical drive, or just
1542 * the controller node, which determines if this counts towards highest_lun.
1543 */
1544static int cciss_find_free_drive_index(int ctlr, int controller_node)
1545{
1546        int i;
1547
1548        for (i = 0; i < CISS_MAX_LUN; i++) {
1549                if (hba[ctlr]->drv[i].raid_level == -1) {
1550                        if (i > hba[ctlr]->highest_lun)
1551                                if (!controller_node)
1552                                        hba[ctlr]->highest_lun = i;
1553                        return i;
1554                }
1555        }
1556        return -1;
1557}
1558
1559/* cciss_add_gendisk finds a free hba[]->drv structure
1560 * and allocates a gendisk if needed, and sets the lunid
1561 * in the drvinfo structure.   It returns the index into
1562 * the ->drv[] array, or -1 if none are free.
1563 * is_controller_node indicates whether highest_lun should
1564 * count this disk, or if it's only being added to provide
1565 * a means to talk to the controller in case no logical
1566 * drives have yet been configured.
1567 */
1568static int cciss_add_gendisk(ctlr_info_t *h, __u32 lunid, int controller_node)
1569{
1570        int drv_index;
1571
1572        drv_index = cciss_find_free_drive_index(h->ctlr, controller_node);
1573        if (drv_index == -1)
1574                return -1;
1575        /*Check if the gendisk needs to be allocated */
1576        if (!h->gendisk[drv_index]) {
1577                h->gendisk[drv_index] =
1578                        alloc_disk(1 << NWD_SHIFT);
1579                if (!h->gendisk[drv_index]) {
1580                        printk(KERN_ERR "cciss%d: could not "
1581                                "allocate a new disk %d\n",
1582                                h->ctlr, drv_index);
1583                        return -1;
1584                }
1585        }
1586        h->drv[drv_index].LunID = lunid;
1587
1588        /* Don't need to mark this busy because nobody */
1589        /* else knows about this disk yet to contend */
1590        /* for access to it. */
1591        h->drv[drv_index].busy_configuring = 0;
1592        wmb();
1593        return drv_index;
1594}
1595
1596/* This is for the special case of a controller which
1597 * has no logical drives.  In this case, we still need
1598 * to register a disk so the controller can be accessed
1599 * by the Array Config Utility.
1600 */
1601static void cciss_add_controller_node(ctlr_info_t *h)
1602{
1603        struct gendisk *disk;
1604        int drv_index;
1605
1606        if (h->gendisk[0] != NULL) /* already did this? Then bail. */
1607                return;
1608
1609        drv_index = cciss_add_gendisk(h, 0, 1);
1610        if (drv_index == -1) {
1611                printk(KERN_WARNING "cciss%d: could not "
1612                        "add disk 0.\n", h->ctlr);
1613                return;
1614        }
1615        h->drv[drv_index].block_size = 512;
1616        h->drv[drv_index].nr_blocks = 0;
1617        h->drv[drv_index].heads = 0;
1618        h->drv[drv_index].sectors = 0;
1619        h->drv[drv_index].cylinders = 0;
1620        h->drv[drv_index].raid_level = -1;
1621        memset(h->drv[drv_index].serial_no, 0, 16);
1622        disk = h->gendisk[drv_index];
1623        cciss_add_disk(h, disk, drv_index);
1624}
1625
1626/* This function will add and remove logical drives from the Logical
1627 * drive array of the controller and maintain persistency of ordering
1628 * so that mount points are preserved until the next reboot.  This allows
1629 * for the removal of logical drives in the middle of the drive array
1630 * without a re-ordering of those drives.
1631 * INPUT
1632 * h            = The controller to perform the operations on
1633 */
1634static int rebuild_lun_table(ctlr_info_t *h, int first_time)
1635{
1636        int ctlr = h->ctlr;
1637        int num_luns;
1638        ReportLunData_struct *ld_buff = NULL;
1639        int return_code;
1640        int listlength = 0;
1641        int i;
1642        int drv_found;
1643        int drv_index = 0;
1644        __u32 lunid = 0;
1645        unsigned long flags;
1646
1647        if (!capable(CAP_SYS_RAWIO))
1648                return -EPERM;
1649
1650        /* Set busy_configuring flag for this operation */
1651        spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
1652        if (h->busy_configuring) {
1653                spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
1654                return -EBUSY;
1655        }
1656        h->busy_configuring = 1;
1657        spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
1658
1659        ld_buff = kzalloc(sizeof(ReportLunData_struct), GFP_KERNEL);
1660        if (ld_buff == NULL)
1661                goto mem_msg;
1662
1663        return_code = sendcmd_withirq(CISS_REPORT_LOG, ctlr, ld_buff,
1664                                      sizeof(ReportLunData_struct), 0,
1665                                      0, 0, TYPE_CMD);
1666
1667        if (return_code == IO_OK)
1668                listlength = be32_to_cpu(*(__be32 *) ld_buff->LUNListLength);
1669        else {  /* reading number of logical volumes failed */
1670                printk(KERN_WARNING "cciss: report logical volume"
1671                       " command failed\n");
1672                listlength = 0;
1673                goto freeret;
1674        }
1675
1676        num_luns = listlength / 8;      /* 8 bytes per entry */
1677        if (num_luns > CISS_MAX_LUN) {
1678                num_luns = CISS_MAX_LUN;
1679                printk(KERN_WARNING "cciss: more luns configured"
1680                       " on controller than can be handled by"
1681                       " this driver.\n");
1682        }
1683
1684        if (num_luns == 0)
1685                cciss_add_controller_node(h);
1686
1687        /* Compare controller drive array to driver's drive array
1688         * to see if any drives are missing on the controller due
1689         * to action of Array Config Utility (user deletes drive)
1690         * and deregister logical drives which have disappeared.
1691         */
1692        for (i = 0; i <= h->highest_lun; i++) {
1693                int j;
1694                drv_found = 0;
1695
1696                /* skip holes in the array from already deleted drives */
1697                if (h->drv[i].raid_level == -1)
1698                        continue;
1699
1700                for (j = 0; j < num_luns; j++) {
1701                        memcpy(&lunid, &ld_buff->LUN[j][0], 4);
1702                        lunid = le32_to_cpu(lunid);
1703                        if (h->drv[i].LunID == lunid) {
1704                                drv_found = 1;
1705                                break;
1706                        }
1707                }
1708                if (!drv_found) {
1709                        /* Deregister it from the OS, it's gone. */
1710                        spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
1711                        h->drv[i].busy_configuring = 1;
1712                        spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
1713                        return_code = deregister_disk(h->gendisk[i],
1714                                &h->drv[i], 1);
1715                        h->drv[i].busy_configuring = 0;
1716                }
1717        }
1718
1719        /* Compare controller drive array to driver's drive array.
1720         * Check for updates in the drive information and any new drives
1721         * on the controller due to ACU adding logical drives, or changing
1722         * a logical drive's size, etc.  Reregister any new/changed drives
1723         */
1724        for (i = 0; i < num_luns; i++) {
1725                int j;
1726
1727                drv_found = 0;
1728
1729                memcpy(&lunid, &ld_buff->LUN[i][0], 4);
1730                lunid = le32_to_cpu(lunid);
1731
1732                /* Find if the LUN is already in the drive array
1733                 * of the driver.  If so then update its info
1734                 * if not in use.  If it does not exist then find
1735                 * the first free index and add it.
1736                 */
1737                for (j = 0; j <= h->highest_lun; j++) {
1738                        if (h->drv[j].raid_level != -1 &&
1739                                h->drv[j].LunID == lunid) {
1740                                drv_index = j;
1741                                drv_found = 1;
1742                                break;
1743                        }
1744                }
1745
1746                /* check if the drive was found already in the array */
1747                if (!drv_found) {
1748                        drv_index = cciss_add_gendisk(h, lunid, 0);
1749                        if (drv_index == -1)
1750                                goto freeret;
1751                }
1752                cciss_update_drive_info(ctlr, drv_index, first_time);
1753        }               /* end for */
1754
1755freeret:
1756        kfree(ld_buff);
1757        h->busy_configuring = 0;
1758        /* We return -1 here to tell the ACU that we have registered/updated
1759         * all of the drives that we can and to keep it from calling us
1760         * additional times.
1761         */
1762        return -1;
1763mem_msg:
1764        printk(KERN_ERR "cciss: out of memory\n");
1765        h->busy_configuring = 0;
1766        goto freeret;
1767}
1768
1769/* This function will deregister the disk and it's queue from the
1770 * kernel.  It must be called with the controller lock held and the
1771 * drv structures busy_configuring flag set.  It's parameters are:
1772 *
1773 * disk = This is the disk to be deregistered
1774 * drv  = This is the drive_info_struct associated with the disk to be
1775 *        deregistered.  It contains information about the disk used
1776 *        by the driver.
1777 * clear_all = This flag determines whether or not the disk information
1778 *             is going to be completely cleared out and the highest_lun
1779 *             reset.  Sometimes we want to clear out information about
1780 *             the disk in preparation for re-adding it.  In this case
1781 *             the highest_lun should be left unchanged and the LunID
1782 *             should not be cleared.
1783*/
1784static int deregister_disk(struct gendisk *disk, drive_info_struct *drv,
1785                           int clear_all)
1786{
1787        int i;
1788        ctlr_info_t *h = get_host(disk);
1789
1790        if (!capable(CAP_SYS_RAWIO))
1791                return -EPERM;
1792
1793        /* make sure logical volume is NOT is use */
1794        if (clear_all || (h->gendisk[0] == disk)) {
1795                if (drv->usage_count > 1)
1796                        return -EBUSY;
1797        } else if (drv->usage_count > 0)
1798                return -EBUSY;
1799
1800        /* invalidate the devices and deregister the disk.  If it is disk
1801         * zero do not deregister it but just zero out it's values.  This
1802         * allows us to delete disk zero but keep the controller registered.
1803         */
1804        if (h->gendisk[0] != disk) {
1805                struct request_queue *q = disk->queue;
1806                if (disk->flags & GENHD_FL_UP)
1807                        del_gendisk(disk);
1808                if (q) {
1809                        blk_cleanup_queue(q);
1810                        /* Set drv->queue to NULL so that we do not try
1811                         * to call blk_start_queue on this queue in the
1812                         * interrupt handler
1813                         */
1814                        drv->queue = NULL;
1815                }
1816                /* If clear_all is set then we are deleting the logical
1817                 * drive, not just refreshing its info.  For drives
1818                 * other than disk 0 we will call put_disk.  We do not
1819                 * do this for disk 0 as we need it to be able to
1820                 * configure the controller.
1821                 */
1822                if (clear_all){
1823                        /* This isn't pretty, but we need to find the
1824                         * disk in our array and NULL our the pointer.
1825                         * This is so that we will call alloc_disk if
1826                         * this index is used again later.
1827                         */
1828                        for (i=0; i < CISS_MAX_LUN; i++){
1829                                if (h->gendisk[i] == disk) {
1830                                        h->gendisk[i] = NULL;
1831                                        break;
1832                                }
1833                        }
1834                        put_disk(disk);
1835                }
1836        } else {
1837                set_capacity(disk, 0);
1838        }
1839
1840        --h->num_luns;
1841        /* zero out the disk size info */
1842        drv->nr_blocks = 0;
1843        drv->block_size = 0;
1844        drv->heads = 0;
1845        drv->sectors = 0;
1846        drv->cylinders = 0;
1847        drv->raid_level = -1;   /* This can be used as a flag variable to
1848                                 * indicate that this element of the drive
1849                                 * array is free.
1850                                 */
1851
1852        if (clear_all) {
1853                /* check to see if it was the last disk */
1854                if (drv == h->drv + h->highest_lun) {
1855                        /* if so, find the new hightest lun */
1856                        int i, newhighest = -1;
1857                        for (i = 0; i <= h->highest_lun; i++) {
1858                                /* if the disk has size > 0, it is available */
1859                                if (h->drv[i].heads)
1860                                        newhighest = i;
1861                        }
1862                        h->highest_lun = newhighest;
1863                }
1864
1865                drv->LunID = 0;
1866        }
1867        return 0;
1868}
1869
1870static int fill_cmd(CommandList_struct *c, __u8 cmd, int ctlr, void *buff, size_t size, unsigned int use_unit_num,      /* 0: address the controller,
1871                                                                                                                           1: address logical volume log_unit,
1872                                                                                                                           2: periph device address is scsi3addr */
1873                    unsigned int log_unit, __u8 page_code,
1874                    unsigned char *scsi3addr, int cmd_type)
1875{
1876        ctlr_info_t *h = hba[ctlr];
1877        u64bit buff_dma_handle;
1878        int status = IO_OK;
1879
1880        c->cmd_type = CMD_IOCTL_PEND;
1881        c->Header.ReplyQueue = 0;
1882        if (buff != NULL) {
1883                c->Header.SGList = 1;
1884                c->Header.SGTotal = 1;
1885        } else {
1886                c->Header.SGList = 0;
1887                c->Header.SGTotal = 0;
1888        }
1889        c->Header.Tag.lower = c->busaddr;
1890
1891        c->Request.Type.Type = cmd_type;
1892        if (cmd_type == TYPE_CMD) {
1893                switch (cmd) {
1894                case CISS_INQUIRY:
1895                        /* If the logical unit number is 0 then, this is going
1896                           to controller so It's a physical command
1897                           mode = 0 target = 0.  So we have nothing to write.
1898                           otherwise, if use_unit_num == 1,
1899                           mode = 1(volume set addressing) target = LUNID
1900                           otherwise, if use_unit_num == 2,
1901                           mode = 0(periph dev addr) target = scsi3addr */
1902                        if (use_unit_num == 1) {
1903                                c->Header.LUN.LogDev.VolId =
1904                                    h->drv[log_unit].LunID;
1905                                c->Header.LUN.LogDev.Mode = 1;
1906                        } else if (use_unit_num == 2) {
1907                                memcpy(c->Header.LUN.LunAddrBytes, scsi3addr,
1908                                       8);
1909                                c->Header.LUN.LogDev.Mode = 0;
1910                        }
1911                        /* are we trying to read a vital product page */
1912                        if (page_code != 0) {
1913                                c->Request.CDB[1] = 0x01;
1914                                c->Request.CDB[2] = page_code;
1915                        }
1916                        c->Request.CDBLen = 6;
1917                        c->Request.Type.Attribute = ATTR_SIMPLE;
1918                        c->Request.Type.Direction = XFER_READ;
1919                        c->Request.Timeout = 0;
1920                        c->Request.CDB[0] = CISS_INQUIRY;
1921                        c->Request.CDB[4] = size & 0xFF;
1922                        break;
1923                case CISS_REPORT_LOG:
1924                case CISS_REPORT_PHYS:
1925                        /* Talking to controller so It's a physical command
1926                           mode = 00 target = 0.  Nothing to write.
1927                         */
1928                        c->Request.CDBLen = 12;
1929                        c->Request.Type.Attribute = ATTR_SIMPLE;
1930                        c->Request.Type.Direction = XFER_READ;
1931                        c->Request.Timeout = 0;
1932                        c->Request.CDB[0] = cmd;
1933                        c->Request.CDB[6] = (size >> 24) & 0xFF;        //MSB
1934                        c->Request.CDB[7] = (size >> 16) & 0xFF;
1935                        c->Request.CDB[8] = (size >> 8) & 0xFF;
1936                        c->Request.CDB[9] = size & 0xFF;
1937                        break;
1938
1939                case CCISS_READ_CAPACITY:
1940                        c->Header.LUN.LogDev.VolId = h->drv[log_unit].LunID;
1941                        c->Header.LUN.LogDev.Mode = 1;
1942                        c->Request.CDBLen = 10;
1943                        c->Request.Type.Attribute = ATTR_SIMPLE;
1944                        c->Request.Type.Direction = XFER_READ;
1945                        c->Request.Timeout = 0;
1946                        c->Request.CDB[0] = cmd;
1947                        break;
1948                case CCISS_READ_CAPACITY_16:
1949                        c->Header.LUN.LogDev.VolId = h->drv[log_unit].LunID;
1950                        c->Header.LUN.LogDev.Mode = 1;
1951                        c->Request.CDBLen = 16;
1952                        c->Request.Type.Attribute = ATTR_SIMPLE;
1953                        c->Request.Type.Direction = XFER_READ;
1954                        c->Request.Timeout = 0;
1955                        c->Request.CDB[0] = cmd;
1956                        c->Request.CDB[1] = 0x10;
1957                        c->Request.CDB[10] = (size >> 24) & 0xFF;
1958                        c->Request.CDB[11] = (size >> 16) & 0xFF;
1959                        c->Request.CDB[12] = (size >> 8) & 0xFF;
1960                        c->Request.CDB[13] = size & 0xFF;
1961                        c->Request.Timeout = 0;
1962                        c->Request.CDB[0] = cmd;
1963                        break;
1964                case CCISS_CACHE_FLUSH:
1965                        c->Request.CDBLen = 12;
1966                        c->Request.Type.Attribute = ATTR_SIMPLE;
1967                        c->Request.Type.Direction = XFER_WRITE;
1968                        c->Request.Timeout = 0;
1969                        c->Request.CDB[0] = BMIC_WRITE;
1970                        c->Request.CDB[6] = BMIC_CACHE_FLUSH;
1971                        break;
1972                default:
1973                        printk(KERN_WARNING
1974                               "cciss%d:  Unknown Command 0x%c\n", ctlr, cmd);
1975                        return IO_ERROR;
1976                }
1977        } else if (cmd_type == TYPE_MSG) {
1978                switch (cmd) {
1979                case 0: /* ABORT message */
1980                        c->Request.CDBLen = 12;
1981                        c->Request.Type.Attribute = ATTR_SIMPLE;
1982                        c->Request.Type.Direction = XFER_WRITE;
1983                        c->Request.Timeout = 0;
1984                        c->Request.CDB[0] = cmd;        /* abort */
1985                        c->Request.CDB[1] = 0;  /* abort a command */
1986                        /* buff contains the tag of the command to abort */
1987                        memcpy(&c->Request.CDB[4], buff, 8);
1988                        break;
1989                case 1: /* RESET message */
1990                        c->Request.CDBLen = 12;
1991                        c->Request.Type.Attribute = ATTR_SIMPLE;
1992                        c->Request.Type.Direction = XFER_WRITE;
1993                        c->Request.Timeout = 0;
1994                        memset(&c->Request.CDB[0], 0, sizeof(c->Request.CDB));
1995                        c->Request.CDB[0] = cmd;        /* reset */
1996                        c->Request.CDB[1] = 0x04;       /* reset a LUN */
1997                        break;
1998                case 3: /* No-Op message */
1999                        c->Request.CDBLen = 1;
2000                        c->Request.Type.Attribute = ATTR_SIMPLE;
2001                        c->Request.Type.Direction = XFER_WRITE;
2002                        c->Request.Timeout = 0;
2003                        c->Request.CDB[0] = cmd;
2004                        break;
2005                default:
2006                        printk(KERN_WARNING
2007                               "cciss%d: unknown message type %d\n", ctlr, cmd);
2008                        return IO_ERROR;
2009                }
2010        } else {
2011                printk(KERN_WARNING
2012                       "cciss%d: unknown command type %d\n", ctlr, cmd_type);
2013                return IO_ERROR;
2014        }
2015        /* Fill in the scatter gather information */
2016        if (size > 0) {
2017                buff_dma_handle.val = (__u64) pci_map_single(h->pdev,
2018                                                             buff, size,
2019                                                             PCI_DMA_BIDIRECTIONAL);
2020                c->SG[0].Addr.lower = buff_dma_handle.val32.lower;
2021                c->SG[0].Addr.upper = buff_dma_handle.val32.upper;
2022                c->SG[0].Len = size;
2023                c->SG[0].Ext = 0;       /* we are not chaining */
2024        }
2025        return status;
2026}
2027
2028static int sendcmd_withirq(__u8 cmd,
2029                           int ctlr,
2030                           void *buff,
2031                           size_t size,
2032                           unsigned int use_unit_num,
2033                           unsigned int log_unit, __u8 page_code, int cmd_type)
2034{
2035        ctlr_info_t *h = hba[ctlr];
2036        CommandList_struct *c;
2037        u64bit buff_dma_handle;
2038        unsigned long flags;
2039        int return_status;
2040        DECLARE_COMPLETION_ONSTACK(wait);
2041
2042        if ((c = cmd_alloc(h, 0)) == NULL)
2043                return -ENOMEM;
2044        return_status = fill_cmd(c, cmd, ctlr, buff, size, use_unit_num,
2045                                 log_unit, page_code, NULL, cmd_type);
2046        if (return_status != IO_OK) {
2047                cmd_free(h, c, 0);
2048                return return_status;
2049        }
2050      resend_cmd2:
2051        c->waiting = &wait;
2052
2053        /* Put the request on the tail of the queue and send it */
2054        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
2055        addQ(&h->reqQ, c);
2056        h->Qdepth++;
2057        start_io(h);
2058        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
2059
2060        wait_for_completion(&wait);
2061
2062        if (c->err_info->CommandStatus != 0) {  /* an error has occurred */
2063                switch (c->err_info->CommandStatus) {
2064                case CMD_TARGET_STATUS:
2065                        printk(KERN_WARNING "cciss: cmd %p has "
2066                               " completed with errors\n", c);
2067                        if (c->err_info->ScsiStatus) {
2068                                printk(KERN_WARNING "cciss: cmd %p "
2069                                       "has SCSI Status = %x\n",
2070                                       c, c->err_info->ScsiStatus);
2071                        }
2072
2073                        break;
2074                case CMD_DATA_UNDERRUN:
2075                case CMD_DATA_OVERRUN:
2076                        /* expected for inquire and report lun commands */
2077                        break;
2078                case CMD_INVALID:
2079                        printk(KERN_WARNING "cciss: Cmd %p is "
2080                               "reported invalid\n", c);
2081                        return_status = IO_ERROR;
2082                        break;
2083                case CMD_PROTOCOL_ERR:
2084                        printk(KERN_WARNING "cciss: cmd %p has "
2085                               "protocol error \n", c);
2086                        return_status = IO_ERROR;
2087                        break;
2088                case CMD_HARDWARE_ERR:
2089                        printk(KERN_WARNING "cciss: cmd %p had "
2090                               " hardware error\n", c);
2091                        return_status = IO_ERROR;
2092                        break;
2093                case CMD_CONNECTION_LOST:
2094                        printk(KERN_WARNING "cciss: cmd %p had "
2095                               "connection lost\n", c);
2096                        return_status = IO_ERROR;
2097                        break;
2098                case CMD_ABORTED:
2099                        printk(KERN_WARNING "cciss: cmd %p was "
2100                               "aborted\n", c);
2101                        return_status = IO_ERROR;
2102                        break;
2103                case CMD_ABORT_FAILED:
2104                        printk(KERN_WARNING "cciss: cmd %p reports "
2105                               "abort failed\n", c);
2106                        return_status = IO_ERROR;
2107                        break;
2108                case CMD_UNSOLICITED_ABORT:
2109                        printk(KERN_WARNING
2110                               "cciss%d: unsolicited abort %p\n", ctlr, c);
2111                        if (c->retry_count < MAX_CMD_RETRIES) {
2112                                printk(KERN_WARNING
2113                                       "cciss%d: retrying %p\n", ctlr, c);
2114                                c->retry_count++;
2115                                /* erase the old error information */
2116                                memset(c->err_info, 0,
2117                                       sizeof(ErrorInfo_struct));
2118                                return_status = IO_OK;
2119                                INIT_COMPLETION(wait);
2120                                goto resend_cmd2;
2121                        }
2122                        return_status = IO_ERROR;
2123                        break;
2124                default:
2125                        printk(KERN_WARNING "cciss: cmd %p returned "
2126                               "unknown status %x\n", c,
2127                               c->err_info->CommandStatus);
2128                        return_status = IO_ERROR;
2129                }
2130        }
2131        /* unlock the buffers from DMA */
2132        buff_dma_handle.val32.lower = c->SG[0].Addr.lower;
2133        buff_dma_handle.val32.upper = c->SG[0].Addr.upper;
2134        pci_unmap_single(h->pdev, (dma_addr_t) buff_dma_handle.val,
2135                         c->SG[0].Len, PCI_DMA_BIDIRECTIONAL);
2136        cmd_free(h, c, 0);
2137        return return_status;
2138}
2139
2140static void cciss_geometry_inquiry(int ctlr, int logvol,
2141                                   int withirq, sector_t total_size,
2142                                   unsigned int block_size,
2143                                   InquiryData_struct *inq_buff,
2144                                   drive_info_struct *drv)
2145{
2146        int return_code;
2147        unsigned long t;
2148
2149        memset(inq_buff, 0, sizeof(InquiryData_struct));
2150        if (withirq)
2151                return_code = sendcmd_withirq(CISS_INQUIRY, ctlr,
2152                                              inq_buff, sizeof(*inq_buff), 1,
2153                                              logvol, 0xC1, TYPE_CMD);
2154        else
2155                return_code = sendcmd(CISS_INQUIRY, ctlr, inq_buff,
2156                                      sizeof(*inq_buff), 1, logvol, 0xC1, NULL,
2157                                      TYPE_CMD);
2158        if (return_code == IO_OK) {
2159                if (inq_buff->data_byte[8] == 0xFF) {
2160                        printk(KERN_WARNING
2161                               "cciss: reading geometry failed, volume "
2162                               "does not support reading geometry\n");
2163                        drv->heads = 255;
2164                        drv->sectors = 32;      // Sectors per track
2165                        drv->cylinders = total_size + 1;
2166                        drv->raid_level = RAID_UNKNOWN;
2167                } else {
2168                        drv->heads = inq_buff->data_byte[6];
2169                        drv->sectors = inq_buff->data_byte[7];
2170                        drv->cylinders = (inq_buff->data_byte[4] & 0xff) << 8;
2171                        drv->cylinders += inq_buff->data_byte[5];
2172                        drv->raid_level = inq_buff->data_byte[8];
2173                }
2174                drv->block_size = block_size;
2175                drv->nr_blocks = total_size + 1;
2176                t = drv->heads * drv->sectors;
2177                if (t > 1) {
2178                        sector_t real_size = total_size + 1;
2179                        unsigned long rem = sector_div(real_size, t);
2180                        if (rem)
2181                                real_size++;
2182                        drv->cylinders = real_size;
2183                }
2184        } else {                /* Get geometry failed */
2185                printk(KERN_WARNING "cciss: reading geometry failed\n");
2186        }
2187        printk(KERN_INFO "      heads=%d, sectors=%d, cylinders=%d\n\n",
2188               drv->heads, drv->sectors, drv->cylinders);
2189}
2190
2191static void
2192cciss_read_capacity(int ctlr, int logvol, int withirq, sector_t *total_size,
2193                    unsigned int *block_size)
2194{
2195        ReadCapdata_struct *buf;
2196        int return_code;
2197
2198        buf = kzalloc(sizeof(ReadCapdata_struct), GFP_KERNEL);
2199        if (!buf) {
2200                printk(KERN_WARNING "cciss: out of memory\n");
2201                return;
2202        }
2203
2204        if (withirq)
2205                return_code = sendcmd_withirq(CCISS_READ_CAPACITY,
2206                                ctlr, buf, sizeof(ReadCapdata_struct),
2207                                        1, logvol, 0, TYPE_CMD);
2208        else
2209                return_code = sendcmd(CCISS_READ_CAPACITY,
2210                                ctlr, buf, sizeof(ReadCapdata_struct),
2211                                        1, logvol, 0, NULL, TYPE_CMD);
2212        if (return_code == IO_OK) {
2213                *total_size = be32_to_cpu(*(__be32 *) buf->total_size);
2214                *block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2215        } else {                /* read capacity command failed */
2216                printk(KERN_WARNING "cciss: read capacity failed\n");
2217                *total_size = 0;
2218                *block_size = BLOCK_SIZE;
2219        }
2220        if (*total_size != 0)
2221                printk(KERN_INFO "      blocks= %llu block_size= %d\n",
2222                (unsigned long long)*total_size+1, *block_size);
2223        kfree(buf);
2224}
2225
2226static void
2227cciss_read_capacity_16(int ctlr, int logvol, int withirq, sector_t *total_size,                                 unsigned int *block_size)
2228{
2229        ReadCapdata_struct_16 *buf;
2230        int return_code;
2231
2232        buf = kzalloc(sizeof(ReadCapdata_struct_16), GFP_KERNEL);
2233        if (!buf) {
2234                printk(KERN_WARNING "cciss: out of memory\n");
2235                return;
2236        }
2237
2238        if (withirq) {
2239                return_code = sendcmd_withirq(CCISS_READ_CAPACITY_16,
2240                        ctlr, buf, sizeof(ReadCapdata_struct_16),
2241                                1, logvol, 0, TYPE_CMD);
2242        }
2243        else {
2244                return_code = sendcmd(CCISS_READ_CAPACITY_16,
2245                        ctlr, buf, sizeof(ReadCapdata_struct_16),
2246                                1, logvol, 0, NULL, TYPE_CMD);
2247        }
2248        if (return_code == IO_OK) {
2249                *total_size = be64_to_cpu(*(__be64 *) buf->total_size);
2250                *block_size = be32_to_cpu(*(__be32 *) buf->block_size);
2251        } else {                /* read capacity command failed */
2252                printk(KERN_WARNING "cciss: read capacity failed\n");
2253                *total_size = 0;
2254                *block_size = BLOCK_SIZE;
2255        }
2256        printk(KERN_INFO "      blocks= %llu block_size= %d\n",
2257               (unsigned long long)*total_size+1, *block_size);
2258        kfree(buf);
2259}
2260
2261static int cciss_revalidate(struct gendisk *disk)
2262{
2263        ctlr_info_t *h = get_host(disk);
2264        drive_info_struct *drv = get_drv(disk);
2265        int logvol;
2266        int FOUND = 0;
2267        unsigned int block_size;
2268        sector_t total_size;
2269        InquiryData_struct *inq_buff = NULL;
2270
2271        for (logvol = 0; logvol < CISS_MAX_LUN; logvol++) {
2272                if (h->drv[logvol].LunID == drv->LunID) {
2273                        FOUND = 1;
2274                        break;
2275                }
2276        }
2277
2278        if (!FOUND)
2279                return 1;
2280
2281        inq_buff = kmalloc(sizeof(InquiryData_struct), GFP_KERNEL);
2282        if (inq_buff == NULL) {
2283                printk(KERN_WARNING "cciss: out of memory\n");
2284                return 1;
2285        }
2286        if (h->cciss_read == CCISS_READ_10) {
2287                cciss_read_capacity(h->ctlr, logvol, 1,
2288                                        &total_size, &block_size);
2289        } else {
2290                cciss_read_capacity_16(h->ctlr, logvol, 1,
2291                                        &total_size, &block_size);
2292        }
2293        cciss_geometry_inquiry(h->ctlr, logvol, 1, total_size, block_size,
2294                               inq_buff, drv);
2295
2296        blk_queue_hardsect_size(drv->queue, drv->block_size);
2297        set_capacity(disk, drv->nr_blocks);
2298
2299        kfree(inq_buff);
2300        return 0;
2301}
2302
2303/*
2304 *   Wait polling for a command to complete.
2305 *   The memory mapped FIFO is polled for the completion.
2306 *   Used only at init time, interrupts from the HBA are disabled.
2307 */
2308static unsigned long pollcomplete(int ctlr)
2309{
2310        unsigned long done;
2311        int i;
2312
2313        /* Wait (up to 20 seconds) for a command to complete */
2314
2315        for (i = 20 * HZ; i > 0; i--) {
2316                done = hba[ctlr]->access.command_completed(hba[ctlr]);
2317                if (done == FIFO_EMPTY)
2318                        schedule_timeout_uninterruptible(1);
2319                else
2320                        return done;
2321        }
2322        /* Invalid address to tell caller we ran out of time */
2323        return 1;
2324}
2325
2326static int add_sendcmd_reject(__u8 cmd, int ctlr, unsigned long complete)
2327{
2328        /* We get in here if sendcmd() is polling for completions
2329           and gets some command back that it wasn't expecting --
2330           something other than that which it just sent down.
2331           Ordinarily, that shouldn't happen, but it can happen when
2332           the scsi tape stuff gets into error handling mode, and
2333           starts using sendcmd() to try to abort commands and
2334           reset tape drives.  In that case, sendcmd may pick up
2335           completions of commands that were sent to logical drives
2336           through the block i/o system, or cciss ioctls completing, etc.
2337           In that case, we need to save those completions for later
2338           processing by the interrupt handler.
2339         */
2340
2341#ifdef CONFIG_CISS_SCSI_TAPE
2342        struct sendcmd_reject_list *srl = &hba[ctlr]->scsi_rejects;
2343
2344        /* If it's not the scsi tape stuff doing error handling, (abort */
2345        /* or reset) then we don't expect anything weird. */
2346        if (cmd != CCISS_RESET_MSG && cmd != CCISS_ABORT_MSG) {
2347#endif
2348                printk(KERN_WARNING "cciss cciss%d: SendCmd "
2349                       "Invalid command list address returned! (%lx)\n",
2350                       ctlr, complete);
2351                /* not much we can do. */
2352#ifdef CONFIG_CISS_SCSI_TAPE
2353                return 1;
2354        }
2355
2356        /* We've sent down an abort or reset, but something else
2357           has completed */
2358        if (srl->ncompletions >= (hba[ctlr]->nr_cmds + 2)) {
2359                /* Uh oh.  No room to save it for later... */
2360                printk(KERN_WARNING "cciss%d: Sendcmd: Invalid command addr, "
2361                       "reject list overflow, command lost!\n", ctlr);
2362                return 1;
2363        }
2364        /* Save it for later */
2365        srl->complete[srl->ncompletions] = complete;
2366        srl->ncompletions++;
2367#endif
2368        return 0;
2369}
2370
2371/*
2372 * Send a command to the controller, and wait for it to complete.
2373 * Only used at init time.
2374 */
2375static int sendcmd(__u8 cmd, int ctlr, void *buff, size_t size, unsigned int use_unit_num,      /* 0: address the controller,
2376                                                                                                   1: address logical volume log_unit,
2377                                                                                                   2: periph device address is scsi3addr */
2378                   unsigned int log_unit,
2379                   __u8 page_code, unsigned char *scsi3addr, int cmd_type)
2380{
2381        CommandList_struct *c;
2382        int i;
2383        unsigned long complete;
2384        ctlr_info_t *info_p = hba[ctlr];
2385        u64bit buff_dma_handle;
2386        int status, done = 0;
2387
2388        if ((c = cmd_alloc(info_p, 1)) == NULL) {
2389                printk(KERN_WARNING "cciss: unable to get memory");
2390                return IO_ERROR;
2391        }
2392        status = fill_cmd(c, cmd, ctlr, buff, size, use_unit_num,
2393                          log_unit, page_code, scsi3addr, cmd_type);
2394        if (status != IO_OK) {
2395                cmd_free(info_p, c, 1);
2396                return status;
2397        }
2398      resend_cmd1:
2399        /*
2400         * Disable interrupt
2401         */
2402#ifdef CCISS_DEBUG
2403        printk(KERN_DEBUG "cciss: turning intr off\n");
2404#endif                          /* CCISS_DEBUG */
2405        info_p->access.set_intr_mask(info_p, CCISS_INTR_OFF);
2406
2407        /* Make sure there is room in the command FIFO */
2408        /* Actually it should be completely empty at this time */
2409        /* unless we are in here doing error handling for the scsi */
2410        /* tape side of the driver. */
2411        for (i = 200000; i > 0; i--) {
2412                /* if fifo isn't full go */
2413                if (!(info_p->access.fifo_full(info_p))) {
2414
2415                        break;
2416                }
2417                udelay(10);
2418                printk(KERN_WARNING "cciss cciss%d: SendCmd FIFO full,"
2419                       " waiting!\n", ctlr);
2420        }
2421        /*
2422         * Send the cmd
2423         */
2424        info_p->access.submit_command(info_p, c);
2425        done = 0;
2426        do {
2427                complete = pollcomplete(ctlr);
2428
2429#ifdef CCISS_DEBUG
2430                printk(KERN_DEBUG "cciss: command completed\n");
2431#endif                          /* CCISS_DEBUG */
2432
2433                if (complete == 1) {
2434                        printk(KERN_WARNING
2435                               "cciss cciss%d: SendCmd Timeout out, "
2436                               "No command list address returned!\n", ctlr);
2437                        status = IO_ERROR;
2438                        done = 1;
2439                        break;
2440                }
2441
2442                /* This will need to change for direct lookup completions */
2443                if ((complete & CISS_ERROR_BIT)
2444                    && (complete & ~CISS_ERROR_BIT) == c->busaddr) {
2445                        /* if data overrun or underun on Report command
2446                           ignore it
2447                         */
2448                        if (((c->Request.CDB[0] == CISS_REPORT_LOG) ||
2449                             (c->Request.CDB[0] == CISS_REPORT_PHYS) ||
2450                             (c->Request.CDB[0] == CISS_INQUIRY)) &&
2451                            ((c->err_info->CommandStatus ==
2452                              CMD_DATA_OVERRUN) ||
2453                             (c->err_info->CommandStatus == CMD_DATA_UNDERRUN)
2454                            )) {
2455                                complete = c->busaddr;
2456                        } else {
2457                                if (c->err_info->CommandStatus ==
2458                                    CMD_UNSOLICITED_ABORT) {
2459                                        printk(KERN_WARNING "cciss%d: "
2460                                               "unsolicited abort %p\n",
2461                                               ctlr, c);
2462                                        if (c->retry_count < MAX_CMD_RETRIES) {
2463                                                printk(KERN_WARNING
2464                                                       "cciss%d: retrying %p\n",
2465                                                       ctlr, c);
2466                                                c->retry_count++;
2467                                                /* erase the old error */
2468                                                /* information */
2469                                                memset(c->err_info, 0,
2470                                                       sizeof
2471                                                       (ErrorInfo_struct));
2472                                                goto resend_cmd1;
2473                                        } else {
2474                                                printk(KERN_WARNING
2475                                                       "cciss%d: retried %p too "
2476                                                       "many times\n", ctlr, c);
2477                                                status = IO_ERROR;
2478                                                goto cleanup1;
2479                                        }
2480                                } else if (c->err_info->CommandStatus ==
2481                                           CMD_UNABORTABLE) {
2482                                        printk(KERN_WARNING
2483                                               "cciss%d: command could not be aborted.\n",
2484                                               ctlr);
2485                                        status = IO_ERROR;
2486                                        goto cleanup1;
2487                                }
2488                                printk(KERN_WARNING "ciss ciss%d: sendcmd"
2489                                       " Error %x \n", ctlr,
2490                                       c->err_info->CommandStatus);
2491                                printk(KERN_WARNING "ciss ciss%d: sendcmd"
2492                                       " offensive info\n"
2493                                       "  size %x\n   num %x   value %x\n",
2494                                       ctlr,
2495                                       c->err_info->MoreErrInfo.Invalid_Cmd.
2496                                       offense_size,
2497                                       c->err_info->MoreErrInfo.Invalid_Cmd.
2498                                       offense_num,
2499                                       c->err_info->MoreErrInfo.Invalid_Cmd.
2500                                       offense_value);
2501                                status = IO_ERROR;
2502                                goto cleanup1;
2503                        }
2504                }
2505                /* This will need changing for direct lookup completions */
2506                if (complete != c->busaddr) {
2507                        if (add_sendcmd_reject(cmd, ctlr, complete) != 0) {
2508                                BUG();  /* we are pretty much hosed if we get here. */
2509                        }
2510                        continue;
2511                } else
2512                        done = 1;
2513        } while (!done);
2514
2515      cleanup1:
2516        /* unlock the data buffer from DMA */
2517        buff_dma_handle.val32.lower = c->SG[0].Addr.lower;
2518        buff_dma_handle.val32.upper = c->SG[0].Addr.upper;
2519        pci_unmap_single(info_p->pdev, (dma_addr_t) buff_dma_handle.val,
2520                         c->SG[0].Len, PCI_DMA_BIDIRECTIONAL);
2521#ifdef CONFIG_CISS_SCSI_TAPE
2522        /* if we saved some commands for later, process them now. */
2523        if (info_p->scsi_rejects.ncompletions > 0)
2524                do_cciss_intr(0, info_p);
2525#endif
2526        cmd_free(info_p, c, 1);
2527        return status;
2528}
2529
2530/*
2531 * Map (physical) PCI mem into (virtual) kernel space
2532 */
2533static void __iomem *remap_pci_mem(ulong base, ulong size)
2534{
2535        ulong page_base = ((ulong) base) & PAGE_MASK;
2536        ulong page_offs = ((ulong) base) - page_base;
2537        void __iomem *page_remapped = ioremap(page_base, page_offs + size);
2538
2539        return page_remapped ? (page_remapped + page_offs) : NULL;
2540}
2541
2542/*
2543 * Takes jobs of the Q and sends them to the hardware, then puts it on
2544 * the Q to wait for completion.
2545 */
2546static void start_io(ctlr_info_t *h)
2547{
2548        CommandList_struct *c;
2549
2550        while ((c = h->reqQ) != NULL) {
2551                /* can't do anything if fifo is full */
2552                if ((h->access.fifo_full(h))) {
2553                        printk(KERN_WARNING "cciss: fifo full\n");
2554                        break;
2555                }
2556
2557                /* Get the first entry from the Request Q */
2558                removeQ(&(h->reqQ), c);
2559                h->Qdepth--;
2560
2561                /* Tell the controller execute command */
2562                h->access.submit_command(h, c);
2563
2564                /* Put job onto the completed Q */
2565                addQ(&(h->cmpQ), c);
2566        }
2567}
2568
2569/* Assumes that CCISS_LOCK(h->ctlr) is held. */
2570/* Zeros out the error record and then resends the command back */
2571/* to the controller */
2572static inline void resend_cciss_cmd(ctlr_info_t *h, CommandList_struct *c)
2573{
2574        /* erase the old error information */
2575        memset(c->err_info, 0, sizeof(ErrorInfo_struct));
2576
2577        /* add it to software queue and then send it to the controller */
2578        addQ(&(h->reqQ), c);
2579        h->Qdepth++;
2580        if (h->Qdepth > h->maxQsinceinit)
2581                h->maxQsinceinit = h->Qdepth;
2582
2583        start_io(h);
2584}
2585
2586static inline unsigned int make_status_bytes(unsigned int scsi_status_byte,
2587        unsigned int msg_byte, unsigned int host_byte,
2588        unsigned int driver_byte)
2589{
2590        /* inverse of macros in scsi.h */
2591        return (scsi_status_byte & 0xff) |
2592                ((msg_byte & 0xff) << 8) |
2593                ((host_byte & 0xff) << 16) |
2594                ((driver_byte & 0xff) << 24);
2595}
2596
2597static inline int evaluate_target_status(CommandList_struct *cmd)
2598{
2599        unsigned char sense_key;
2600        unsigned char status_byte, msg_byte, host_byte, driver_byte;
2601        int error_value;
2602
2603        /* If we get in here, it means we got "target status", that is, scsi status */
2604        status_byte = cmd->err_info->ScsiStatus;
2605        driver_byte = DRIVER_OK;
2606        msg_byte = cmd->err_info->CommandStatus; /* correct?  seems too device specific */
2607
2608        if (blk_pc_request(cmd->rq))
2609                host_byte = DID_PASSTHROUGH;
2610        else
2611                host_byte = DID_OK;
2612
2613        error_value = make_status_bytes(status_byte, msg_byte,
2614                host_byte, driver_byte);
2615
2616        if (cmd->err_info->ScsiStatus != SAM_STAT_CHECK_CONDITION) {
2617                if (!blk_pc_request(cmd->rq))
2618                        printk(KERN_WARNING "cciss: cmd %p "
2619                               "has SCSI Status 0x%x\n",
2620                               cmd, cmd->err_info->ScsiStatus);
2621                return error_value;
2622        }
2623
2624        /* check the sense key */
2625        sense_key = 0xf & cmd->err_info->SenseInfo[2];
2626        /* no status or recovered error */
2627        if (((sense_key == 0x0) || (sense_key == 0x1)) && !blk_pc_request(cmd->rq))
2628                error_value = 0;
2629
2630        if (!blk_pc_request(cmd->rq)) { /* Not SG_IO or similar? */
2631                if (error_value != 0)
2632                        printk(KERN_WARNING "cciss: cmd %p has CHECK CONDITION"
2633                               " sense key = 0x%x\n", cmd, sense_key);
2634                return error_value;
2635        }
2636
2637        /* SG_IO or similar, copy sense data back */
2638        if (cmd->rq->sense) {
2639                if (cmd->rq->sense_len > cmd->err_info->SenseLen)
2640                        cmd->rq->sense_len = cmd->err_info->SenseLen;
2641                memcpy(cmd->rq->sense, cmd->err_info->SenseInfo,
2642                        cmd->rq->sense_len);
2643        } else
2644                cmd->rq->sense_len = 0;
2645
2646        return error_value;
2647}
2648
2649/* checks the status of the job and calls complete buffers to mark all
2650 * buffers for the completed job. Note that this function does not need
2651 * to hold the hba/queue lock.
2652 */
2653static inline void complete_command(ctlr_info_t *h, CommandList_struct *cmd,
2654                                    int timeout)
2655{
2656        int retry_cmd = 0;
2657        struct request *rq = cmd->rq;
2658
2659        rq->errors = 0;
2660
2661        if (timeout)
2662                rq->errors = make_status_bytes(0, 0, 0, DRIVER_TIMEOUT);
2663
2664        if (cmd->err_info->CommandStatus == 0)  /* no error has occurred */
2665                goto after_error_processing;
2666
2667        switch (cmd->err_info->CommandStatus) {
2668        case CMD_TARGET_STATUS:
2669                rq->errors = evaluate_target_status(cmd);
2670                break;
2671        case CMD_DATA_UNDERRUN:
2672                if (blk_fs_request(cmd->rq)) {
2673                        printk(KERN_WARNING "cciss: cmd %p has"
2674                               " completed with data underrun "
2675                               "reported\n", cmd);
2676                        cmd->rq->data_len = cmd->err_info->ResidualCnt;
2677                }
2678                break;
2679        case CMD_DATA_OVERRUN:
2680                if (blk_fs_request(cmd->rq))
2681                        printk(KERN_WARNING "cciss: cmd %p has"
2682                               " completed with data overrun "
2683                               "reported\n", cmd);
2684                break;
2685        case CMD_INVALID:
2686                printk(KERN_WARNING "cciss: cmd %p is "
2687                       "reported invalid\n", cmd);
2688                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2689                        cmd->err_info->CommandStatus, DRIVER_OK,
2690                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2691                break;
2692        case CMD_PROTOCOL_ERR:
2693                printk(KERN_WARNING "cciss: cmd %p has "
2694                       "protocol error \n", cmd);
2695                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2696                        cmd->err_info->CommandStatus, DRIVER_OK,
2697                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2698                break;
2699        case CMD_HARDWARE_ERR:
2700                printk(KERN_WARNING "cciss: cmd %p had "
2701                       " hardware error\n", cmd);
2702                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2703                        cmd->err_info->CommandStatus, DRIVER_OK,
2704                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2705                break;
2706        case CMD_CONNECTION_LOST:
2707                printk(KERN_WARNING "cciss: cmd %p had "
2708                       "connection lost\n", cmd);
2709                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2710                        cmd->err_info->CommandStatus, DRIVER_OK,
2711                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2712                break;
2713        case CMD_ABORTED:
2714                printk(KERN_WARNING "cciss: cmd %p was "
2715                       "aborted\n", cmd);
2716                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2717                        cmd->err_info->CommandStatus, DRIVER_OK,
2718                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ABORT);
2719                break;
2720        case CMD_ABORT_FAILED:
2721                printk(KERN_WARNING "cciss: cmd %p reports "
2722                       "abort failed\n", cmd);
2723                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2724                        cmd->err_info->CommandStatus, DRIVER_OK,
2725                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2726                break;
2727        case CMD_UNSOLICITED_ABORT:
2728                printk(KERN_WARNING "cciss%d: unsolicited "
2729                       "abort %p\n", h->ctlr, cmd);
2730                if (cmd->retry_count < MAX_CMD_RETRIES) {
2731                        retry_cmd = 1;
2732                        printk(KERN_WARNING
2733                               "cciss%d: retrying %p\n", h->ctlr, cmd);
2734                        cmd->retry_count++;
2735                } else
2736                        printk(KERN_WARNING
2737                               "cciss%d: %p retried too "
2738                               "many times\n", h->ctlr, cmd);
2739                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2740                        cmd->err_info->CommandStatus, DRIVER_OK,
2741                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ABORT);
2742                break;
2743        case CMD_TIMEOUT:
2744                printk(KERN_WARNING "cciss: cmd %p timedout\n", cmd);
2745                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2746                        cmd->err_info->CommandStatus, DRIVER_OK,
2747                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2748                break;
2749        default:
2750                printk(KERN_WARNING "cciss: cmd %p returned "
2751                       "unknown status %x\n", cmd,
2752                       cmd->err_info->CommandStatus);
2753                rq->errors = make_status_bytes(SAM_STAT_GOOD,
2754                        cmd->err_info->CommandStatus, DRIVER_OK,
2755                        blk_pc_request(cmd->rq) ? DID_PASSTHROUGH : DID_ERROR);
2756        }
2757
2758after_error_processing:
2759
2760        /* We need to return this command */
2761        if (retry_cmd) {
2762                resend_cciss_cmd(h, cmd);
2763                return;
2764        }
2765        cmd->rq->completion_data = cmd;
2766        blk_complete_request(cmd->rq);
2767}
2768
2769/*
2770 * Get a request and submit it to the controller.
2771 */
2772static void do_cciss_request(struct request_queue *q)
2773{
2774        ctlr_info_t *h = q->queuedata;
2775        CommandList_struct *c;
2776        sector_t start_blk;
2777        int seg;
2778        struct request *creq;
2779        u64bit temp64;
2780        struct scatterlist tmp_sg[MAXSGENTRIES];
2781        drive_info_struct *drv;
2782        int i, dir;
2783
2784        /* We call start_io here in case there is a command waiting on the
2785         * queue that has not been sent.
2786         */
2787        if (blk_queue_plugged(q))
2788                goto startio;
2789
2790      queue:
2791        creq = elv_next_request(q);
2792        if (!creq)
2793                goto startio;
2794
2795        BUG_ON(creq->nr_phys_segments > MAXSGENTRIES);
2796
2797        if ((c = cmd_alloc(h, 1)) == NULL)
2798                goto full;
2799
2800        blkdev_dequeue_request(creq);
2801
2802        spin_unlock_irq(q->queue_lock);
2803
2804        c->cmd_type = CMD_RWREQ;
2805        c->rq = creq;
2806
2807        /* fill in the request */
2808        drv = creq->rq_disk->private_data;
2809        c->Header.ReplyQueue = 0;       // unused in simple mode
2810        /* got command from pool, so use the command block index instead */
2811        /* for direct lookups. */
2812        /* The first 2 bits are reserved for controller error reporting. */
2813        c->Header.Tag.lower = (c->cmdindex << 3);
2814        c->Header.Tag.lower |= 0x04;    /* flag for direct lookup. */
2815        c->Header.LUN.LogDev.VolId = drv->LunID;
2816        c->Header.LUN.LogDev.Mode = 1;
2817        c->Request.CDBLen = 10; // 12 byte commands not in FW yet;
2818        c->Request.Type.Type = TYPE_CMD;        // It is a command.
2819        c->Request.Type.Attribute = ATTR_SIMPLE;
2820        c->Request.Type.Direction =
2821            (rq_data_dir(creq) == READ) ? XFER_READ : XFER_WRITE;
2822        c->Request.Timeout = 0; // Don't time out
2823        c->Request.CDB[0] =
2824            (rq_data_dir(creq) == READ) ? h->cciss_read : h->cciss_write;
2825        start_blk = creq->sector;
2826#ifdef CCISS_DEBUG
2827        printk(KERN_DEBUG "ciss: sector =%d nr_sectors=%d\n", (int)creq->sector,
2828               (int)creq->nr_sectors);
2829#endif                          /* CCISS_DEBUG */
2830
2831        sg_init_table(tmp_sg, MAXSGENTRIES);
2832        seg = blk_rq_map_sg(q, creq, tmp_sg);
2833
2834        /* get the DMA records for the setup */
2835        if (c->Request.Type.Direction == XFER_READ)
2836                dir = PCI_DMA_FROMDEVICE;
2837        else
2838                dir = PCI_DMA_TODEVICE;
2839
2840        for (i = 0; i < seg; i++) {
2841                c->SG[i].Len = tmp_sg[i].length;
2842                temp64.val = (__u64) pci_map_page(h->pdev, sg_page(&tmp_sg[i]),
2843                                                  tmp_sg[i].offset,
2844                                                  tmp_sg[i].length, dir);
2845                c->SG[i].Addr.lower = temp64.val32.lower;
2846                c->SG[i].Addr.upper = temp64.val32.upper;
2847                c->SG[i].Ext = 0;       // we are not chaining
2848        }
2849        /* track how many SG entries we are using */
2850        if (seg > h->maxSG)
2851                h->maxSG = seg;
2852
2853#ifdef CCISS_DEBUG
2854        printk(KERN_DEBUG "cciss: Submitting %d sectors in %d segments\n",
2855               creq->nr_sectors, seg);
2856#endif                          /* CCISS_DEBUG */
2857
2858        c->Header.SGList = c->Header.SGTotal = seg;
2859        if (likely(blk_fs_request(creq))) {
2860                if(h->cciss_read == CCISS_READ_10) {
2861                        c->Request.CDB[1] = 0;
2862                        c->Request.CDB[2] = (start_blk >> 24) & 0xff;   //MSB
2863                        c->Request.CDB[3] = (start_blk >> 16) & 0xff;
2864                        c->Request.CDB[4] = (start_blk >> 8) & 0xff;
2865                        c->Request.CDB[5] = start_blk & 0xff;
2866                        c->Request.CDB[6] = 0;  // (sect >> 24) & 0xff; MSB
2867                        c->Request.CDB[7] = (creq->nr_sectors >> 8) & 0xff;
2868                        c->Request.CDB[8] = creq->nr_sectors & 0xff;
2869                        c->Request.CDB[9] = c->Request.CDB[11] = c->Request.CDB[12] = 0;
2870                } else {
2871                        u32 upper32 = upper_32_bits(start_blk);
2872
2873                        c->Request.CDBLen = 16;
2874                        c->Request.CDB[1]= 0;
2875                        c->Request.CDB[2]= (upper32 >> 24) & 0xff;      //MSB
2876                        c->Request.CDB[3]= (upper32 >> 16) & 0xff;
2877                        c->Request.CDB[4]= (upper32 >>  8) & 0xff;
2878                        c->Request.CDB[5]= upper32 & 0xff;
2879                        c->Request.CDB[6]= (start_blk >> 24) & 0xff;
2880                        c->Request.CDB[7]= (start_blk >> 16) & 0xff;
2881                        c->Request.CDB[8]= (start_blk >>  8) & 0xff;
2882                        c->Request.CDB[9]= start_blk & 0xff;
2883                        c->Request.CDB[10]= (creq->nr_sectors >>  24) & 0xff;
2884                        c->Request.CDB[11]= (creq->nr_sectors >>  16) & 0xff;
2885                        c->Request.CDB[12]= (creq->nr_sectors >>  8) & 0xff;
2886                        c->Request.CDB[13]= creq->nr_sectors & 0xff;
2887                        c->Request.CDB[14] = c->Request.CDB[15] = 0;
2888                }
2889        } else if (blk_pc_request(creq)) {
2890                c->Request.CDBLen = creq->cmd_len;
2891                memcpy(c->Request.CDB, creq->cmd, BLK_MAX_CDB);
2892        } else {
2893                printk(KERN_WARNING "cciss%d: bad request type %d\n", h->ctlr, creq->cmd_type);
2894                BUG();
2895        }
2896
2897        spin_lock_irq(q->queue_lock);
2898
2899        addQ(&(h->reqQ), c);
2900        h->Qdepth++;
2901        if (h->Qdepth > h->maxQsinceinit)
2902                h->maxQsinceinit = h->Qdepth;
2903
2904        goto queue;
2905full:
2906        blk_stop_queue(q);
2907startio:
2908        /* We will already have the driver lock here so not need
2909         * to lock it.
2910         */
2911        start_io(h);
2912}
2913
2914static inline unsigned long get_next_completion(ctlr_info_t *h)
2915{
2916#ifdef CONFIG_CISS_SCSI_TAPE
2917        /* Any rejects from sendcmd() lying around? Process them first */
2918        if (h->scsi_rejects.ncompletions == 0)
2919                return h->access.command_completed(h);
2920        else {
2921                struct sendcmd_reject_list *srl;
2922                int n;
2923                srl = &h->scsi_rejects;
2924                n = --srl->ncompletions;
2925                /* printk("cciss%d: processing saved reject\n", h->ctlr); */
2926                printk("p");
2927                return srl->complete[n];
2928        }
2929#else
2930        return h->access.command_completed(h);
2931#endif
2932}
2933
2934static inline int interrupt_pending(ctlr_info_t *h)
2935{
2936#ifdef CONFIG_CISS_SCSI_TAPE
2937        return (h->access.intr_pending(h)
2938                || (h->scsi_rejects.ncompletions > 0));
2939#else
2940        return h->access.intr_pending(h);
2941#endif
2942}
2943
2944static inline long interrupt_not_for_us(ctlr_info_t *h)
2945{
2946#ifdef CONFIG_CISS_SCSI_TAPE
2947        return (((h->access.intr_pending(h) == 0) ||
2948                 (h->interrupts_enabled == 0))
2949                && (h->scsi_rejects.ncompletions == 0));
2950#else
2951        return (((h->access.intr_pending(h) == 0) ||
2952                 (h->interrupts_enabled == 0)));
2953#endif
2954}
2955
2956static irqreturn_t do_cciss_intr(int irq, void *dev_id)
2957{
2958        ctlr_info_t *h = dev_id;
2959        CommandList_struct *c;
2960        unsigned long flags;
2961        __u32 a, a1, a2;
2962
2963        if (interrupt_not_for_us(h))
2964                return IRQ_NONE;
2965        /*
2966         * If there are completed commands in the completion queue,
2967         * we had better do something about it.
2968         */
2969        spin_lock_irqsave(CCISS_LOCK(h->ctlr), flags);
2970        while (interrupt_pending(h)) {
2971                while ((a = get_next_completion(h)) != FIFO_EMPTY) {
2972                        a1 = a;
2973                        if ((a & 0x04)) {
2974                                a2 = (a >> 3);
2975                                if (a2 >= h->nr_cmds) {
2976                                        printk(KERN_WARNING
2977                                               "cciss: controller cciss%d failed, stopping.\n",
2978                                               h->ctlr);
2979                                        fail_all_cmds(h->ctlr);
2980                                        return IRQ_HANDLED;
2981                                }
2982
2983                                c = h->cmd_pool + a2;
2984                                a = c->busaddr;
2985
2986                        } else {
2987                                a &= ~3;
2988                                if ((c = h->cmpQ) == NULL) {
2989                                        printk(KERN_WARNING
2990                                               "cciss: Completion of %08x ignored\n",
2991                                               a1);
2992                                        continue;
2993                                }
2994                                while (c->busaddr != a) {
2995                                        c = c->next;
2996                                        if (c == h->cmpQ)
2997                                                break;
2998                                }
2999                        }
3000                        /*
3001                         * If we've found the command, take it off the
3002                         * completion Q and free it
3003                         */
3004                        if (c->busaddr == a) {
3005                                removeQ(&h->cmpQ, c);
3006                                if (c->cmd_type == CMD_RWREQ) {
3007                                        complete_command(h, c, 0);
3008                                } else if (c->cmd_type == CMD_IOCTL_PEND) {
3009                                        complete(c->waiting);
3010                                }
3011#                               ifdef CONFIG_CISS_SCSI_TAPE
3012                                else if (c->cmd_type == CMD_SCSI)
3013                                        complete_scsi_command(c, 0, a1);
3014#                               endif
3015                                continue;
3016                        }
3017                }
3018        }
3019
3020        spin_unlock_irqrestore(CCISS_LOCK(h->ctlr), flags);
3021        return IRQ_HANDLED;
3022}
3023
3024/*
3025 *  We cannot read the structure directly, for portability we must use
3026 *   the io functions.
3027 *   This is for debug only.
3028 */
3029#ifdef CCISS_DEBUG
3030static void print_cfg_table(CfgTable_struct *tb)
3031{
3032        int i;
3033        char temp_name[17];
3034
3035        printk("Controller Configuration information\n");
3036        printk("------------------------------------\n");
3037        for (i = 0; i < 4; i++)
3038                temp_name[i] = readb(&(tb->Signature[i]));
3039        temp_name[4] = '\0';
3040        printk("   Signature = %s\n", temp_name);
3041        printk("   Spec Number = %d\n", readl(&(tb->SpecValence)));
3042        printk("   Transport methods supported = 0x%x\n",
3043               readl(&(tb->TransportSupport)));
3044        printk("   Transport methods active = 0x%x\n",
3045               readl(&(tb->TransportActive)));
3046        printk("   Requested transport Method = 0x%x\n",
3047               readl(&(tb->HostWrite.TransportRequest)));
3048        printk("   Coalesce Interrupt Delay = 0x%x\n",
3049               readl(&(tb->HostWrite.CoalIntDelay)));
3050        printk("   Coalesce Interrupt Count = 0x%x\n",
3051               readl(&(tb->HostWrite.CoalIntCount)));
3052        printk("   Max outstanding commands = 0x%d\n",
3053               readl(&(tb->CmdsOutMax)));
3054        printk("   Bus Types = 0x%x\n", readl(&(tb->BusTypes)));
3055        for (i = 0; i < 16; i++)
3056                temp_name[i] = readb(&(tb->ServerName[i]));
3057        temp_name[16] = '\0';
3058        printk("   Server Name = %s\n", temp_name);
3059        printk("   Heartbeat Counter = 0x%x\n\n\n", readl(&(tb->HeartBeat)));
3060}
3061#endif                          /* CCISS_DEBUG */
3062
3063static int find_PCI_BAR_index(struct pci_dev *pdev, unsigned long pci_bar_addr)
3064{
3065        int i, offset, mem_type, bar_type;
3066        if (pci_bar_addr == PCI_BASE_ADDRESS_0) /* looking for BAR zero? */
3067                return 0;
3068        offset = 0;
3069        for (i = 0; i < DEVICE_COUNT_RESOURCE; i++) {
3070                bar_type = pci_resource_flags(pdev, i) & PCI_BASE_ADDRESS_SPACE;
3071                if (bar_type == PCI_BASE_ADDRESS_SPACE_IO)
3072                        offset += 4;
3073                else {
3074                        mem_type = pci_resource_flags(pdev, i) &
3075                            PCI_BASE_ADDRESS_MEM_TYPE_MASK;
3076                        switch (mem_type) {
3077                        case PCI_BASE_ADDRESS_MEM_TYPE_32:
3078                        case PCI_BASE_ADDRESS_MEM_TYPE_1M:
3079                                offset += 4;    /* 32 bit */
3080                                break;
3081                        case PCI_BASE_ADDRESS_MEM_TYPE_64:
3082                                offset += 8;
3083                                break;
3084                        default:        /* reserved in PCI 2.2 */
3085                                printk(KERN_WARNING
3086                                       "Base address is invalid\n");
3087                                return -1;
3088                                break;
3089                        }
3090                }
3091                if (offset == pci_bar_addr - PCI_BASE_ADDRESS_0)
3092                        return i + 1;
3093        }
3094        return -1;
3095}
3096
3097/* If MSI/MSI-X is supported by the kernel we will try to enable it on
3098 * controllers that are capable. If not, we use IO-APIC mode.
3099 */
3100
3101static void __devinit cciss_interrupt_mode(ctlr_info_t *c,
3102                                           struct pci_dev *pdev, __u32 board_id)
3103{
3104#ifdef CONFIG_PCI_MSI
3105        int err;
3106        struct msix_entry cciss_msix_entries[4] = { {0, 0}, {0, 1},
3107        {0, 2}, {0, 3}
3108        };
3109
3110        /* Some boards advertise MSI but don't really support it */
3111        if ((board_id == 0x40700E11) ||
3112            (board_id == 0x40800E11) ||
3113            (board_id == 0x40820E11) || (board_id == 0x40830E11))
3114                goto default_int_mode;
3115
3116        if (pci_find_capability(pdev, PCI_CAP_ID_MSIX)) {
3117                err = pci_enable_msix(pdev, cciss_msix_entries, 4);
3118                if (!err) {
3119                        c->intr[0] = cciss_msix_entries[0].vector;
3120                        c->intr[1] = cciss_msix_entries[1].vector;
3121                        c->intr[2] = cciss_msix_entries[2].vector;
3122                        c->intr[3] = cciss_msix_entries[3].vector;
3123                        c->msix_vector = 1;
3124                        return;
3125                }
3126                if (err > 0) {
3127                        printk(KERN_WARNING "cciss: only %d MSI-X vectors "
3128                               "available\n", err);
3129                        goto default_int_mode;
3130                } else {
3131                        printk(KERN_WARNING "cciss: MSI-X init failed %d\n",
3132                               err);
3133                        goto default_int_mode;
3134                }
3135        }
3136        if (pci_find_capability(pdev, PCI_CAP_ID_MSI)) {
3137                if (!pci_enable_msi(pdev)) {
3138                        c->msi_vector = 1;
3139                } else {
3140                        printk(KERN_WARNING "cciss: MSI init failed\n");
3141                }
3142        }
3143default_int_mode:
3144#endif                          /* CONFIG_PCI_MSI */
3145        /* if we get here we're going to use the default interrupt mode */
3146        c->intr[SIMPLE_MODE_INT] = pdev->irq;
3147        return;
3148}
3149
3150static int __devinit cciss_pci_init(ctlr_info_t *c, struct pci_dev *pdev)
3151{
3152        ushort subsystem_vendor_id, subsystem_device_id, command;
3153        __u32 board_id, scratchpad = 0;
3154        __u64 cfg_offset;
3155        __u32 cfg_base_addr;
3156        __u64 cfg_base_addr_index;
3157        int i, err;
3158
3159        /* check to see if controller has been disabled */
3160        /* BEFORE trying to enable it */
3161        (void)pci_read_config_word(pdev, PCI_COMMAND, &command);
3162        if (!(command & 0x02)) {
3163                printk(KERN_WARNING
3164                       "cciss: controller appears to be disabled\n");
3165                return -ENODEV;
3166        }
3167
3168        err = pci_enable_device(pdev);
3169        if (err) {
3170                printk(KERN_ERR "cciss: Unable to Enable PCI device\n");
3171                return err;
3172        }
3173
3174        err = pci_request_regions(pdev, "cciss");
3175        if (err) {
3176                printk(KERN_ERR "cciss: Cannot obtain PCI resources, "
3177                       "aborting\n");
3178                return err;
3179        }
3180
3181        subsystem_vendor_id = pdev->subsystem_vendor;
3182        subsystem_device_id = pdev->subsystem_device;
3183        board_id = (((__u32) (subsystem_device_id << 16) & 0xffff0000) |
3184                    subsystem_vendor_id);
3185
3186#ifdef CCISS_DEBUG
3187        printk("command = %x\n", command);
3188        printk("irq = %x\n", pdev->irq);
3189        printk("board_id = %x\n", board_id);
3190#endif                          /* CCISS_DEBUG */
3191
3192/* If the kernel supports MSI/MSI-X we will try to enable that functionality,
3193 * else we use the IO-APIC interrupt assigned to us by system ROM.
3194 */
3195        cciss_interrupt_mode(c, pdev, board_id);
3196
3197        /*
3198         * Memory base addr is first addr , the second points to the config
3199         *   table
3200         */
3201
3202        c->paddr = pci_resource_start(pdev, 0); /* addressing mode bits already removed */
3203#ifdef CCISS_DEBUG
3204        printk("address 0 = %x\n", c->paddr);
3205#endif                          /* CCISS_DEBUG */
3206        c->vaddr = remap_pci_mem(c->paddr, 0x250);
3207
3208        /* Wait for the board to become ready.  (PCI hotplug needs this.)
3209         * We poll for up to 120 secs, once per 100ms. */
3210        for (i = 0; i < 1200; i++) {
3211                scratchpad = readl(c->vaddr + SA5_SCRATCHPAD_OFFSET);
3212                if (scratchpad == CCISS_FIRMWARE_READY)
3213                        break;
3214                set_current_state(TASK_INTERRUPTIBLE);
3215                schedule_timeout(HZ / 10);      /* wait 100ms */
3216        }
3217        if (scratchpad != CCISS_FIRMWARE_READY) {
3218                printk(KERN_WARNING "cciss: Board not ready.  Timed out.\n");
3219                err = -ENODEV;
3220                goto err_out_free_res;
3221        }
3222
3223        /* get the address index number */
3224        cfg_base_addr = readl(c->vaddr + SA5_CTCFG_OFFSET);
3225        cfg_base_addr &= (__u32) 0x0000ffff;
3226#ifdef CCISS_DEBUG
3227        printk("cfg base address = %x\n", cfg_base_addr);
3228#endif                          /* CCISS_DEBUG */
3229        cfg_base_addr_index = find_PCI_BAR_index(pdev, cfg_base_addr);
3230#ifdef CCISS_DEBUG
3231        printk("cfg base address index = %x\n", cfg_base_addr_index);
3232#endif                          /* CCISS_DEBUG */
3233        if (cfg_base_addr_index == -1) {
3234                printk(KERN_WARNING "cciss: Cannot find cfg_base_addr_index\n");
3235                err = -ENODEV;
3236                goto err_out_free_res;
3237        }
3238
3239        cfg_offset = readl(c->vaddr + SA5_CTMEM_OFFSET);
3240#ifdef CCISS_DEBUG
3241        printk("cfg offset = %x\n", cfg_offset);
3242#endif                          /* CCISS_DEBUG */
3243        c->cfgtable = remap_pci_mem(pci_resource_start(pdev,
3244                                                       cfg_base_addr_index) +
3245                                    cfg_offset, sizeof(CfgTable_struct));
3246        c->board_id = board_id;
3247
3248#ifdef CCISS_DEBUG
3249        print_cfg_table(c->cfgtable);
3250#endif                          /* CCISS_DEBUG */
3251
3252        /* Some controllers support Zero Memory Raid (ZMR).
3253         * When configured in ZMR mode the number of supported
3254         * commands drops to 64. So instead of just setting an
3255         * arbitrary value we make the driver a little smarter.
3256         * We read the config table to tell us how many commands
3257         * are supported on the controller then subtract 4 to
3258         * leave a little room for ioctl calls.
3259         */
3260        c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
3261        for (i = 0; i < ARRAY_SIZE(products); i++) {
3262                if (board_id == products[i].board_id) {
3263                        c->product_name = products[i].product_name;
3264                        c->access = *(products[i].access);
3265                        c->nr_cmds = c->max_commands - 4;
3266                        break;
3267                }
3268        }
3269        if ((readb(&c->cfgtable->Signature[0]) != 'C') ||
3270            (readb(&c->cfgtable->Signature[1]) != 'I') ||
3271            (readb(&c->cfgtable->Signature[2]) != 'S') ||
3272            (readb(&c->cfgtable->Signature[3]) != 'S')) {
3273                printk("Does not appear to be a valid CISS config table\n");
3274                err = -ENODEV;
3275                goto err_out_free_res;
3276        }
3277        /* We didn't find the controller in our list. We know the
3278         * signature is valid. If it's an HP device let's try to
3279         * bind to the device and fire it up. Otherwise we bail.
3280         */
3281        if (i == ARRAY_SIZE(products)) {
3282                if (subsystem_vendor_id == PCI_VENDOR_ID_HP) {
3283                        c->product_name = products[i-1].product_name;
3284                        c->access = *(products[i-1].access);
3285                        c->nr_cmds = c->max_commands - 4;
3286                        printk(KERN_WARNING "cciss: This is an unknown "
3287                                "Smart Array controller.\n"
3288                                "cciss: Please update to the latest driver "
3289                                "available from www.hp.com.\n");
3290                } else {
3291                        printk(KERN_WARNING "cciss: Sorry, I don't know how"
3292                                " to access the Smart Array controller %08lx\n"
3293                                        , (unsigned long)board_id);
3294                        err = -ENODEV;
3295                        goto err_out_free_res;
3296                }
3297        }
3298#ifdef CONFIG_X86
3299        {
3300                /* Need to enable prefetch in the SCSI core for 6400 in x86 */
3301                __u32 prefetch;
3302                prefetch = readl(&(c->cfgtable->SCSI_Prefetch));
3303                prefetch |= 0x100;
3304                writel(prefetch, &(c->cfgtable->SCSI_Prefetch));
3305        }
3306#endif
3307
3308        /* Disabling DMA prefetch and refetch for the P600.
3309         * An ASIC bug may result in accesses to invalid memory addresses.
3310         * We've disabled prefetch for some time now. Testing with XEN
3311         * kernels revealed a bug in the refetch if dom0 resides on a P600.
3312         */
3313        if(board_id == 0x3225103C) {
3314                __u32 dma_prefetch;
3315                __u32 dma_refetch;
3316                dma_prefetch = readl(c->vaddr + I2O_DMA1_CFG);
3317                dma_prefetch |= 0x8000;
3318                writel(dma_prefetch, c->vaddr + I2O_DMA1_CFG);
3319                pci_read_config_dword(pdev, PCI_COMMAND_PARITY, &dma_refetch);
3320                dma_refetch |= 0x1;
3321                pci_write_config_dword(pdev, PCI_COMMAND_PARITY, dma_refetch);
3322        }
3323
3324#ifdef CCISS_DEBUG
3325        printk("Trying to put board into Simple mode\n");
3326#endif                          /* CCISS_DEBUG */
3327        c->max_commands = readl(&(c->cfgtable->CmdsOutMax));
3328        /* Update the field, and then ring the doorbell */
3329        writel(CFGTBL_Trans_Simple, &(c->cfgtable->HostWrite.TransportRequest));
3330        writel(CFGTBL_ChangeReq, c->vaddr + SA5_DOORBELL);
3331
3332        /* under certain very rare conditions, this can take awhile.
3333         * (e.g.: hot replace a failed 144GB drive in a RAID 5 set right
3334         * as we enter this code.) */
3335        for (i = 0; i < MAX_CONFIG_WAIT; i++) {
3336                if (!(readl(c->vaddr + SA5_DOORBELL) & CFGTBL_ChangeReq))
3337                        break;
3338                /* delay and try again */
3339                set_current_state(TASK_INTERRUPTIBLE);
3340                schedule_timeout(10);
3341        }
3342
3343#ifdef CCISS_DEBUG
3344        printk(KERN_DEBUG "I counter got to %d %x\n", i,
3345               readl(c->vaddr + SA5_DOORBELL));
3346#endif                          /* CCISS_DEBUG */
3347#ifdef CCISS_DEBUG
3348        print_cfg_table(c->cfgtable);
3349#endif                          /* CCISS_DEBUG */
3350
3351        if (!(readl(&(c->cfgtable->TransportActive)) & CFGTBL_Trans_Simple)) {
3352                printk(KERN_WARNING "cciss: unable to get board into"
3353                       " simple mode\n");
3354                err = -ENODEV;
3355                goto err_out_free_res;
3356        }
3357        return 0;
3358
3359err_out_free_res:
3360        /*
3361         * Deliberately omit pci_disable_device(): it does something nasty to
3362         * Smart Array controllers that pci_enable_device does not undo
3363         */
3364        pci_release_regions(pdev);
3365        return err;
3366}
3367
3368/* Function to find the first free pointer into our hba[] array
3369 * Returns -1 if no free entries are left.
3370 */
3371static int alloc_cciss_hba(void)
3372{
3373        int i;
3374
3375        for (i = 0; i < MAX_CTLR; i++) {
3376                if (!hba[i]) {
3377                        ctlr_info_t *p;
3378
3379                        p = kzalloc(sizeof(ctlr_info_t), GFP_KERNEL);
3380                        if (!p)
3381                                goto Enomem;
3382                        hba[i] = p;
3383                        return i;
3384                }
3385        }
3386        printk(KERN_WARNING "cciss: This driver supports a maximum"
3387               " of %d controllers.\n", MAX_CTLR);
3388        return -1;
3389Enomem:
3390        printk(KERN_ERR "cciss: out of memory.\n");
3391        return -1;
3392}
3393
3394static void free_hba(int i)
3395{
3396        ctlr_info_t *p = hba[i];
3397        int n;
3398
3399        hba[i] = NULL;
3400        for (n = 0; n < CISS_MAX_LUN; n++)
3401                put_disk(p->gendisk[n]);
3402        kfree(p);
3403}
3404
3405/*
3406 *  This is it.  Find all the controllers and register them.  I really hate
3407 *  stealing all these major device numbers.
3408 *  returns the number of block devices registered.
3409 */
3410static int __devinit cciss_init_one(struct pci_dev *pdev,
3411                                    const struct pci_device_id *ent)
3412{
3413        int i;
3414        int j = 0;
3415        int rc;
3416        int dac, return_code;
3417        InquiryData_struct *inq_buff = NULL;
3418
3419        i = alloc_cciss_hba();
3420        if (i < 0)
3421                return -1;
3422
3423        hba[i]->busy_initializing = 1;
3424
3425        if (cciss_pci_init(hba[i], pdev) != 0)
3426                goto clean1;
3427
3428        sprintf(hba[i]->devname, "cciss%d", i);
3429        hba[i]->ctlr = i;
3430        hba[i]->pdev = pdev;
3431
3432        /* configure PCI DMA stuff */
3433        if (!pci_set_dma_mask(pdev, DMA_64BIT_MASK))
3434                dac = 1;
3435        else if (!pci_set_dma_mask(pdev, DMA_32BIT_MASK))
3436                dac = 0;
3437        else {
3438                printk(KERN_ERR "cciss: no suitable DMA available\n");
3439                goto clean1;
3440        }
3441
3442        /*
3443         * register with the major number, or get a dynamic major number
3444         * by passing 0 as argument.  This is done for greater than
3445         * 8 controller support.
3446         */
3447        if (i < MAX_CTLR_ORIG)
3448                hba[i]->major = COMPAQ_CISS_MAJOR + i;
3449        rc = register_blkdev(hba[i]->major, hba[i]->devname);
3450        if (rc == -EBUSY || rc == -EINVAL) {
3451                printk(KERN_ERR
3452                       "cciss:  Unable to get major number %d for %s "
3453                       "on hba %d\n", hba[i]->major, hba[i]->devname, i);
3454                goto clean1;
3455        } else {
3456                if (i >= MAX_CTLR_ORIG)
3457                        hba[i]->major = rc;
3458        }
3459
3460        /* make sure the board interrupts are off */
3461        hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_OFF);
3462        if (request_irq(hba[i]->intr[SIMPLE_MODE_INT], do_cciss_intr,
3463                        IRQF_DISABLED | IRQF_SHARED, hba[i]->devname, hba[i])) {
3464                printk(KERN_ERR "cciss: Unable to get irq %d for %s\n",
3465                       hba[i]->intr[SIMPLE_MODE_INT], hba[i]->devname);
3466                goto clean2;
3467        }
3468
3469        printk(KERN_INFO "%s: <0x%x> at PCI %s IRQ %d%s using DAC\n",
3470               hba[i]->devname, pdev->device, pci_name(pdev),
3471               hba[i]->intr[SIMPLE_MODE_INT], dac ? "" : " not");
3472
3473        hba[i]->cmd_pool_bits =
3474            kmalloc(((hba[i]->nr_cmds + BITS_PER_LONG -
3475                      1) / BITS_PER_LONG) * sizeof(unsigned long), GFP_KERNEL);
3476        hba[i]->cmd_pool = (CommandList_struct *)
3477            pci_alloc_consistent(hba[i]->pdev,
3478                    hba[i]->nr_cmds * sizeof(CommandList_struct),
3479                    &(hba[i]->cmd_pool_dhandle));
3480        hba[i]->errinfo_pool = (ErrorInfo_struct *)
3481            pci_alloc_consistent(hba[i]->pdev,
3482                    hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
3483                    &(hba[i]->errinfo_pool_dhandle));
3484        if ((hba[i]->cmd_pool_bits == NULL)
3485            || (hba[i]->cmd_pool == NULL)
3486            || (hba[i]->errinfo_pool == NULL)) {
3487                printk(KERN_ERR "cciss: out of memory");
3488                goto clean4;
3489        }
3490#ifdef CONFIG_CISS_SCSI_TAPE
3491        hba[i]->scsi_rejects.complete =
3492            kmalloc(sizeof(hba[i]->scsi_rejects.complete[0]) *
3493                    (hba[i]->nr_cmds + 5), GFP_KERNEL);
3494        if (hba[i]->scsi_rejects.complete == NULL) {
3495                printk(KERN_ERR "cciss: out of memory");
3496                goto clean4;
3497        }
3498#endif
3499        spin_lock_init(&hba[i]->lock);
3500
3501        /* Initialize the pdev driver private data.
3502           have it point to hba[i].  */
3503        pci_set_drvdata(pdev, hba[i]);
3504        /* command and error info recs zeroed out before
3505           they are used */
3506        memset(hba[i]->cmd_pool_bits, 0,
3507               ((hba[i]->nr_cmds + BITS_PER_LONG -
3508                 1) / BITS_PER_LONG) * sizeof(unsigned long));
3509
3510        hba[i]->num_luns = 0;
3511        hba[i]->highest_lun = -1;
3512        for (j = 0; j < CISS_MAX_LUN; j++) {
3513                hba[i]->drv[j].raid_level = -1;
3514                hba[i]->drv[j].queue = NULL;
3515                hba[i]->gendisk[j] = NULL;
3516        }
3517
3518        cciss_scsi_setup(i);
3519
3520        /* Turn the interrupts on so we can service requests */
3521        hba[i]->access.set_intr_mask(hba[i], CCISS_INTR_ON);
3522
3523        /* Get the firmware version */
3524        inq_buff = kzalloc(sizeof(InquiryData_struct), GFP_KERNEL);
3525        if (inq_buff == NULL) {
3526                printk(KERN_ERR "cciss: out of memory\n");
3527                goto clean4;
3528        }
3529
3530        return_code = sendcmd_withirq(CISS_INQUIRY, i, inq_buff,
3531                sizeof(InquiryData_struct), 0, 0 , 0, TYPE_CMD);
3532        if (return_code == IO_OK) {
3533                hba[i]->firm_ver[0] = inq_buff->data_byte[32];
3534                hba[i]->firm_ver[1] = inq_buff->data_byte[33];
3535                hba[i]->firm_ver[2] = inq_buff->data_byte[34];
3536                hba[i]->firm_ver[3] = inq_buff->data_byte[35];
3537        } else {         /* send command failed */
3538                printk(KERN_WARNING "cciss: unable to determine firmware"
3539                        " version of controller\n");
3540        }
3541
3542        cciss_procinit(i);
3543
3544        hba[i]->cciss_max_sectors = 2048;
3545
3546        hba[i]->busy_initializing = 0;
3547
3548        rebuild_lun_table(hba[i], 1);
3549        return 1;
3550
3551clean4:
3552        kfree(inq_buff);
3553#ifdef CONFIG_CISS_SCSI_TAPE
3554        kfree(hba[i]->scsi_rejects.complete);
3555#endif
3556        kfree(hba[i]->cmd_pool_bits);
3557        if (hba[i]->cmd_pool)
3558                pci_free_consistent(hba[i]->pdev,
3559                                    hba[i]->nr_cmds * sizeof(CommandList_struct),
3560                                    hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
3561        if (hba[i]->errinfo_pool)
3562                pci_free_consistent(hba[i]->pdev,
3563                                    hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
3564                                    hba[i]->errinfo_pool,
3565                                    hba[i]->errinfo_pool_dhandle);
3566        free_irq(hba[i]->intr[SIMPLE_MODE_INT], hba[i]);
3567clean2:
3568        unregister_blkdev(hba[i]->major, hba[i]->devname);
3569clean1:
3570        hba[i]->busy_initializing = 0;
3571        /* cleanup any queues that may have been initialized */
3572        for (j=0; j <= hba[i]->highest_lun; j++){
3573                drive_info_struct *drv = &(hba[i]->drv[j]);
3574                if (drv->queue)
3575                        blk_cleanup_queue(drv->queue);
3576        }
3577        /*
3578         * Deliberately omit pci_disable_device(): it does something nasty to
3579         * Smart Array controllers that pci_enable_device does not undo
3580         */
3581        pci_release_regions(pdev);
3582        pci_set_drvdata(pdev, NULL);
3583        free_hba(i);
3584        return -1;
3585}
3586
3587static void cciss_shutdown(struct pci_dev *pdev)
3588{
3589        ctlr_info_t *tmp_ptr;
3590        int i;
3591        char flush_buf[4];
3592        int return_code;
3593
3594        tmp_ptr = pci_get_drvdata(pdev);
3595        if (tmp_ptr == NULL)
3596                return;
3597        i = tmp_ptr->ctlr;
3598        if (hba[i] == NULL)
3599                return;
3600
3601        /* Turn board interrupts off  and send the flush cache command */
3602        /* sendcmd will turn off interrupt, and send the flush...
3603         * To write all data in the battery backed cache to disks */
3604        memset(flush_buf, 0, 4);
3605        return_code = sendcmd(CCISS_CACHE_FLUSH, i, flush_buf, 4, 0, 0, 0, NULL,
3606                              TYPE_CMD);
3607        if (return_code == IO_OK) {
3608                printk(KERN_INFO "Completed flushing cache on controller %d\n", i);
3609        } else {
3610                printk(KERN_WARNING "Error flushing cache on controller %d\n", i);
3611        }
3612        free_irq(hba[i]->intr[2], hba[i]);
3613}
3614
3615static void __devexit cciss_remove_one(struct pci_dev *pdev)
3616{
3617        ctlr_info_t *tmp_ptr;
3618        int i, j;
3619
3620        if (pci_get_drvdata(pdev) == NULL) {
3621                printk(KERN_ERR "cciss: Unable to remove device \n");
3622                return;
3623        }
3624        tmp_ptr = pci_get_drvdata(pdev);
3625        i = tmp_ptr->ctlr;
3626        if (hba[i] == NULL) {
3627                printk(KERN_ERR "cciss: device appears to "
3628                       "already be removed \n");
3629                return;
3630        }
3631
3632        remove_proc_entry(hba[i]->devname, proc_cciss);
3633        unregister_blkdev(hba[i]->major, hba[i]->devname);
3634
3635        /* remove it from the disk list */
3636        for (j = 0; j < CISS_MAX_LUN; j++) {
3637                struct gendisk *disk = hba[i]->gendisk[j];
3638                if (disk) {
3639                        struct request_queue *q = disk->queue;
3640
3641                        if (disk->flags & GENHD_FL_UP)
3642                                del_gendisk(disk);
3643                        if (q)
3644                                blk_cleanup_queue(q);
3645                }
3646        }
3647
3648#ifdef CONFIG_CISS_SCSI_TAPE
3649        cciss_unregister_scsi(i);       /* unhook from SCSI subsystem */
3650#endif
3651
3652        cciss_shutdown(pdev);
3653
3654#ifdef CONFIG_PCI_MSI
3655        if (hba[i]->msix_vector)
3656                pci_disable_msix(hba[i]->pdev);
3657        else if (hba[i]->msi_vector)
3658                pci_disable_msi(hba[i]->pdev);
3659#endif                          /* CONFIG_PCI_MSI */
3660
3661        iounmap(hba[i]->vaddr);
3662
3663        pci_free_consistent(hba[i]->pdev, hba[i]->nr_cmds * sizeof(CommandList_struct),
3664                            hba[i]->cmd_pool, hba[i]->cmd_pool_dhandle);
3665        pci_free_consistent(hba[i]->pdev, hba[i]->nr_cmds * sizeof(ErrorInfo_struct),
3666                            hba[i]->errinfo_pool, hba[i]->errinfo_pool_dhandle);
3667        kfree(hba[i]->cmd_pool_bits);
3668#ifdef CONFIG_CISS_SCSI_TAPE
3669        kfree(hba[i]->scsi_rejects.complete);
3670#endif
3671        /*
3672         * Deliberately omit pci_disable_device(): it does something nasty to
3673         * Smart Array controllers that pci_enable_device does not undo
3674         */
3675        pci_release_regions(pdev);
3676        pci_set_drvdata(pdev, NULL);
3677        free_hba(i);
3678}
3679
3680static struct pci_driver cciss_pci_driver = {
3681        .name = "cciss",
3682        .probe = cciss_init_one,
3683        .remove = __devexit_p(cciss_remove_one),
3684        .id_table = cciss_pci_device_id,        /* id_table */
3685        .shutdown = cciss_shutdown,
3686};
3687
3688/*
3689 *  This is it.  Register the PCI driver information for the cards we control
3690 *  the OS will call our registered routines when it finds one of our cards.
3691 */
3692static int __init cciss_init(void)
3693{
3694        printk(KERN_INFO DRIVER_NAME "\n");
3695
3696        /* Register for our PCI devices */
3697        return pci_register_driver(&cciss_pci_driver);
3698}
3699
3700static void __exit cciss_cleanup(void)
3701{
3702        int i;
3703
3704        pci_unregister_driver(&cciss_pci_driver);
3705        /* double check that all controller entrys have been removed */
3706        for (i = 0; i < MAX_CTLR; i++) {
3707                if (hba[i] != NULL) {
3708                        printk(KERN_WARNING "cciss: had to remove"
3709                               " controller %d\n", i);
3710                        cciss_remove_one(hba[i]->pdev);
3711                }
3712        }
3713        remove_proc_entry("driver/cciss", NULL);
3714}
3715
3716static void fail_all_cmds(unsigned long ctlr)
3717{
3718        /* If we get here, the board is apparently dead. */
3719        ctlr_info_t *h = hba[ctlr];
3720        CommandList_struct *c;
3721        unsigned long flags;
3722
3723        printk(KERN_WARNING "cciss%d: controller not responding.\n", h->ctlr);
3724        h->alive = 0;           /* the controller apparently died... */
3725
3726        spin_lock_irqsave(CCISS_LOCK(ctlr), flags);
3727
3728        pci_disable_device(h->pdev);    /* Make sure it is really dead. */
3729
3730        /* move everything off the request queue onto the completed queue */
3731        while ((c = h->reqQ) != NULL) {
3732                removeQ(&(h->reqQ), c);
3733                h->Qdepth--;
3734                addQ(&(h->cmpQ), c);
3735        }
3736
3737        /* Now, fail everything on the completed queue with a HW error */
3738        while ((c = h->cmpQ) != NULL) {
3739                removeQ(&h->cmpQ, c);
3740                c->err_info->CommandStatus = CMD_HARDWARE_ERR;
3741                if (c->cmd_type == CMD_RWREQ) {
3742                        complete_command(h, c, 0);
3743                } else if (c->cmd_type == CMD_IOCTL_PEND)
3744                        complete(c->waiting);
3745#ifdef CONFIG_CISS_SCSI_TAPE
3746                else if (c->cmd_type == CMD_SCSI)
3747                        complete_scsi_command(c, 0, 0);
3748#endif
3749        }
3750        spin_unlock_irqrestore(CCISS_LOCK(ctlr), flags);
3751        return;
3752}
3753
3754module_init(cciss_init);
3755module_exit(cciss_cleanup);
3756