linux/drivers/block/DAC960.c
<<
>>
Prefs
   1/*
   2
   3  Linux Driver for Mylex DAC960/AcceleRAID/eXtremeRAID PCI RAID Controllers
   4
   5  Copyright 1998-2001 by Leonard N. Zubkoff <lnz@dandelion.com>
   6  Portions Copyright 2002 by Mylex (An IBM Business Unit)
   7
   8  This program is free software; you may redistribute and/or modify it under
   9  the terms of the GNU General Public License Version 2 as published by the
  10  Free Software Foundation.
  11
  12  This program is distributed in the hope that it will be useful, but
  13  WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY
  14  or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  15  for complete details.
  16
  17*/
  18
  19
  20#define DAC960_DriverVersion                    "2.5.49"
  21#define DAC960_DriverDate                       "21 Aug 2007"
  22
  23
  24#include <linux/module.h>
  25#include <linux/types.h>
  26#include <linux/miscdevice.h>
  27#include <linux/blkdev.h>
  28#include <linux/bio.h>
  29#include <linux/completion.h>
  30#include <linux/delay.h>
  31#include <linux/genhd.h>
  32#include <linux/hdreg.h>
  33#include <linux/blkpg.h>
  34#include <linux/dma-mapping.h>
  35#include <linux/interrupt.h>
  36#include <linux/ioport.h>
  37#include <linux/mm.h>
  38#include <linux/slab.h>
  39#include <linux/smp_lock.h>
  40#include <linux/proc_fs.h>
  41#include <linux/seq_file.h>
  42#include <linux/reboot.h>
  43#include <linux/spinlock.h>
  44#include <linux/timer.h>
  45#include <linux/pci.h>
  46#include <linux/init.h>
  47#include <linux/jiffies.h>
  48#include <linux/random.h>
  49#include <linux/scatterlist.h>
  50#include <asm/io.h>
  51#include <asm/uaccess.h>
  52#include "DAC960.h"
  53
  54#define DAC960_GAM_MINOR        252
  55
  56
  57static DAC960_Controller_T *DAC960_Controllers[DAC960_MaxControllers];
  58static int DAC960_ControllerCount;
  59static struct proc_dir_entry *DAC960_ProcDirectoryEntry;
  60
  61static long disk_size(DAC960_Controller_T *p, int drive_nr)
  62{
  63        if (p->FirmwareType == DAC960_V1_Controller) {
  64                if (drive_nr >= p->LogicalDriveCount)
  65                        return 0;
  66                return p->V1.LogicalDriveInformation[drive_nr].
  67                        LogicalDriveSize;
  68        } else {
  69                DAC960_V2_LogicalDeviceInfo_T *i =
  70                        p->V2.LogicalDeviceInformation[drive_nr];
  71                if (i == NULL)
  72                        return 0;
  73                return i->ConfigurableDeviceSize;
  74        }
  75}
  76
  77static int DAC960_open(struct block_device *bdev, fmode_t mode)
  78{
  79        struct gendisk *disk = bdev->bd_disk;
  80        DAC960_Controller_T *p = disk->queue->queuedata;
  81        int drive_nr = (long)disk->private_data;
  82
  83        if (p->FirmwareType == DAC960_V1_Controller) {
  84                if (p->V1.LogicalDriveInformation[drive_nr].
  85                    LogicalDriveState == DAC960_V1_LogicalDrive_Offline)
  86                        return -ENXIO;
  87        } else {
  88                DAC960_V2_LogicalDeviceInfo_T *i =
  89                        p->V2.LogicalDeviceInformation[drive_nr];
  90                if (!i || i->LogicalDeviceState == DAC960_V2_LogicalDevice_Offline)
  91                        return -ENXIO;
  92        }
  93
  94        check_disk_change(bdev);
  95
  96        if (!get_capacity(p->disks[drive_nr]))
  97                return -ENXIO;
  98        return 0;
  99}
 100
 101static int DAC960_getgeo(struct block_device *bdev, struct hd_geometry *geo)
 102{
 103        struct gendisk *disk = bdev->bd_disk;
 104        DAC960_Controller_T *p = disk->queue->queuedata;
 105        int drive_nr = (long)disk->private_data;
 106
 107        if (p->FirmwareType == DAC960_V1_Controller) {
 108                geo->heads = p->V1.GeometryTranslationHeads;
 109                geo->sectors = p->V1.GeometryTranslationSectors;
 110                geo->cylinders = p->V1.LogicalDriveInformation[drive_nr].
 111                        LogicalDriveSize / (geo->heads * geo->sectors);
 112        } else {
 113                DAC960_V2_LogicalDeviceInfo_T *i =
 114                        p->V2.LogicalDeviceInformation[drive_nr];
 115                switch (i->DriveGeometry) {
 116                case DAC960_V2_Geometry_128_32:
 117                        geo->heads = 128;
 118                        geo->sectors = 32;
 119                        break;
 120                case DAC960_V2_Geometry_255_63:
 121                        geo->heads = 255;
 122                        geo->sectors = 63;
 123                        break;
 124                default:
 125                        DAC960_Error("Illegal Logical Device Geometry %d\n",
 126                                        p, i->DriveGeometry);
 127                        return -EINVAL;
 128                }
 129
 130                geo->cylinders = i->ConfigurableDeviceSize /
 131                        (geo->heads * geo->sectors);
 132        }
 133        
 134        return 0;
 135}
 136
 137static int DAC960_media_changed(struct gendisk *disk)
 138{
 139        DAC960_Controller_T *p = disk->queue->queuedata;
 140        int drive_nr = (long)disk->private_data;
 141
 142        if (!p->LogicalDriveInitiallyAccessible[drive_nr])
 143                return 1;
 144        return 0;
 145}
 146
 147static int DAC960_revalidate_disk(struct gendisk *disk)
 148{
 149        DAC960_Controller_T *p = disk->queue->queuedata;
 150        int unit = (long)disk->private_data;
 151
 152        set_capacity(disk, disk_size(p, unit));
 153        return 0;
 154}
 155
 156static const struct block_device_operations DAC960_BlockDeviceOperations = {
 157        .owner                  = THIS_MODULE,
 158        .open                   = DAC960_open,
 159        .getgeo                 = DAC960_getgeo,
 160        .media_changed          = DAC960_media_changed,
 161        .revalidate_disk        = DAC960_revalidate_disk,
 162};
 163
 164
 165/*
 166  DAC960_AnnounceDriver announces the Driver Version and Date, Author's Name,
 167  Copyright Notice, and Electronic Mail Address.
 168*/
 169
 170static void DAC960_AnnounceDriver(DAC960_Controller_T *Controller)
 171{
 172  DAC960_Announce("***** DAC960 RAID Driver Version "
 173                  DAC960_DriverVersion " of "
 174                  DAC960_DriverDate " *****\n", Controller);
 175  DAC960_Announce("Copyright 1998-2001 by Leonard N. Zubkoff "
 176                  "<lnz@dandelion.com>\n", Controller);
 177}
 178
 179
 180/*
 181  DAC960_Failure prints a standardized error message, and then returns false.
 182*/
 183
 184static bool DAC960_Failure(DAC960_Controller_T *Controller,
 185                              unsigned char *ErrorMessage)
 186{
 187  DAC960_Error("While configuring DAC960 PCI RAID Controller at\n",
 188               Controller);
 189  if (Controller->IO_Address == 0)
 190    DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
 191                 "PCI Address 0x%X\n", Controller,
 192                 Controller->Bus, Controller->Device,
 193                 Controller->Function, Controller->PCI_Address);
 194  else DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
 195                    "0x%X PCI Address 0x%X\n", Controller,
 196                    Controller->Bus, Controller->Device,
 197                    Controller->Function, Controller->IO_Address,
 198                    Controller->PCI_Address);
 199  DAC960_Error("%s FAILED - DETACHING\n", Controller, ErrorMessage);
 200  return false;
 201}
 202
 203/*
 204  init_dma_loaf() and slice_dma_loaf() are helper functions for
 205  aggregating the dma-mapped memory for a well-known collection of
 206  data structures that are of different lengths.
 207
 208  These routines don't guarantee any alignment.  The caller must
 209  include any space needed for alignment in the sizes of the structures
 210  that are passed in.
 211 */
 212
 213static bool init_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf,
 214                                                                 size_t len)
 215{
 216        void *cpu_addr;
 217        dma_addr_t dma_handle;
 218
 219        cpu_addr = pci_alloc_consistent(dev, len, &dma_handle);
 220        if (cpu_addr == NULL)
 221                return false;
 222        
 223        loaf->cpu_free = loaf->cpu_base = cpu_addr;
 224        loaf->dma_free =loaf->dma_base = dma_handle;
 225        loaf->length = len;
 226        memset(cpu_addr, 0, len);
 227        return true;
 228}
 229
 230static void *slice_dma_loaf(struct dma_loaf *loaf, size_t len,
 231                                        dma_addr_t *dma_handle)
 232{
 233        void *cpu_end = loaf->cpu_free + len;
 234        void *cpu_addr = loaf->cpu_free;
 235
 236        BUG_ON(cpu_end > loaf->cpu_base + loaf->length);
 237        *dma_handle = loaf->dma_free;
 238        loaf->cpu_free = cpu_end;
 239        loaf->dma_free += len;
 240        return cpu_addr;
 241}
 242
 243static void free_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf_handle)
 244{
 245        if (loaf_handle->cpu_base != NULL)
 246                pci_free_consistent(dev, loaf_handle->length,
 247                        loaf_handle->cpu_base, loaf_handle->dma_base);
 248}
 249
 250
 251/*
 252  DAC960_CreateAuxiliaryStructures allocates and initializes the auxiliary
 253  data structures for Controller.  It returns true on success and false on
 254  failure.
 255*/
 256
 257static bool DAC960_CreateAuxiliaryStructures(DAC960_Controller_T *Controller)
 258{
 259  int CommandAllocationLength, CommandAllocationGroupSize;
 260  int CommandsRemaining = 0, CommandIdentifier, CommandGroupByteCount;
 261  void *AllocationPointer = NULL;
 262  void *ScatterGatherCPU = NULL;
 263  dma_addr_t ScatterGatherDMA;
 264  struct pci_pool *ScatterGatherPool;
 265  void *RequestSenseCPU = NULL;
 266  dma_addr_t RequestSenseDMA;
 267  struct pci_pool *RequestSensePool = NULL;
 268
 269  if (Controller->FirmwareType == DAC960_V1_Controller)
 270    {
 271      CommandAllocationLength = offsetof(DAC960_Command_T, V1.EndMarker);
 272      CommandAllocationGroupSize = DAC960_V1_CommandAllocationGroupSize;
 273      ScatterGatherPool = pci_pool_create("DAC960_V1_ScatterGather",
 274                Controller->PCIDevice,
 275        DAC960_V1_ScatterGatherLimit * sizeof(DAC960_V1_ScatterGatherSegment_T),
 276        sizeof(DAC960_V1_ScatterGatherSegment_T), 0);
 277      if (ScatterGatherPool == NULL)
 278            return DAC960_Failure(Controller,
 279                        "AUXILIARY STRUCTURE CREATION (SG)");
 280      Controller->ScatterGatherPool = ScatterGatherPool;
 281    }
 282  else
 283    {
 284      CommandAllocationLength = offsetof(DAC960_Command_T, V2.EndMarker);
 285      CommandAllocationGroupSize = DAC960_V2_CommandAllocationGroupSize;
 286      ScatterGatherPool = pci_pool_create("DAC960_V2_ScatterGather",
 287                Controller->PCIDevice,
 288        DAC960_V2_ScatterGatherLimit * sizeof(DAC960_V2_ScatterGatherSegment_T),
 289        sizeof(DAC960_V2_ScatterGatherSegment_T), 0);
 290      if (ScatterGatherPool == NULL)
 291            return DAC960_Failure(Controller,
 292                        "AUXILIARY STRUCTURE CREATION (SG)");
 293      RequestSensePool = pci_pool_create("DAC960_V2_RequestSense",
 294                Controller->PCIDevice, sizeof(DAC960_SCSI_RequestSense_T),
 295                sizeof(int), 0);
 296      if (RequestSensePool == NULL) {
 297            pci_pool_destroy(ScatterGatherPool);
 298            return DAC960_Failure(Controller,
 299                        "AUXILIARY STRUCTURE CREATION (SG)");
 300      }
 301      Controller->ScatterGatherPool = ScatterGatherPool;
 302      Controller->V2.RequestSensePool = RequestSensePool;
 303    }
 304  Controller->CommandAllocationGroupSize = CommandAllocationGroupSize;
 305  Controller->FreeCommands = NULL;
 306  for (CommandIdentifier = 1;
 307       CommandIdentifier <= Controller->DriverQueueDepth;
 308       CommandIdentifier++)
 309    {
 310      DAC960_Command_T *Command;
 311      if (--CommandsRemaining <= 0)
 312        {
 313          CommandsRemaining =
 314                Controller->DriverQueueDepth - CommandIdentifier + 1;
 315          if (CommandsRemaining > CommandAllocationGroupSize)
 316                CommandsRemaining = CommandAllocationGroupSize;
 317          CommandGroupByteCount =
 318                CommandsRemaining * CommandAllocationLength;
 319          AllocationPointer = kzalloc(CommandGroupByteCount, GFP_ATOMIC);
 320          if (AllocationPointer == NULL)
 321                return DAC960_Failure(Controller,
 322                                        "AUXILIARY STRUCTURE CREATION");
 323         }
 324      Command = (DAC960_Command_T *) AllocationPointer;
 325      AllocationPointer += CommandAllocationLength;
 326      Command->CommandIdentifier = CommandIdentifier;
 327      Command->Controller = Controller;
 328      Command->Next = Controller->FreeCommands;
 329      Controller->FreeCommands = Command;
 330      Controller->Commands[CommandIdentifier-1] = Command;
 331      ScatterGatherCPU = pci_pool_alloc(ScatterGatherPool, GFP_ATOMIC,
 332                                                        &ScatterGatherDMA);
 333      if (ScatterGatherCPU == NULL)
 334          return DAC960_Failure(Controller, "AUXILIARY STRUCTURE CREATION");
 335
 336      if (RequestSensePool != NULL) {
 337          RequestSenseCPU = pci_pool_alloc(RequestSensePool, GFP_ATOMIC,
 338                                                &RequestSenseDMA);
 339          if (RequestSenseCPU == NULL) {
 340                pci_pool_free(ScatterGatherPool, ScatterGatherCPU,
 341                                ScatterGatherDMA);
 342                return DAC960_Failure(Controller,
 343                                        "AUXILIARY STRUCTURE CREATION");
 344          }
 345        }
 346     if (Controller->FirmwareType == DAC960_V1_Controller) {
 347        Command->cmd_sglist = Command->V1.ScatterList;
 348        Command->V1.ScatterGatherList =
 349                (DAC960_V1_ScatterGatherSegment_T *)ScatterGatherCPU;
 350        Command->V1.ScatterGatherListDMA = ScatterGatherDMA;
 351        sg_init_table(Command->cmd_sglist, DAC960_V1_ScatterGatherLimit);
 352      } else {
 353        Command->cmd_sglist = Command->V2.ScatterList;
 354        Command->V2.ScatterGatherList =
 355                (DAC960_V2_ScatterGatherSegment_T *)ScatterGatherCPU;
 356        Command->V2.ScatterGatherListDMA = ScatterGatherDMA;
 357        Command->V2.RequestSense =
 358                                (DAC960_SCSI_RequestSense_T *)RequestSenseCPU;
 359        Command->V2.RequestSenseDMA = RequestSenseDMA;
 360        sg_init_table(Command->cmd_sglist, DAC960_V2_ScatterGatherLimit);
 361      }
 362    }
 363  return true;
 364}
 365
 366
 367/*
 368  DAC960_DestroyAuxiliaryStructures deallocates the auxiliary data
 369  structures for Controller.
 370*/
 371
 372static void DAC960_DestroyAuxiliaryStructures(DAC960_Controller_T *Controller)
 373{
 374  int i;
 375  struct pci_pool *ScatterGatherPool = Controller->ScatterGatherPool;
 376  struct pci_pool *RequestSensePool = NULL;
 377  void *ScatterGatherCPU;
 378  dma_addr_t ScatterGatherDMA;
 379  void *RequestSenseCPU;
 380  dma_addr_t RequestSenseDMA;
 381  DAC960_Command_T *CommandGroup = NULL;
 382  
 383
 384  if (Controller->FirmwareType == DAC960_V2_Controller)
 385        RequestSensePool = Controller->V2.RequestSensePool;
 386
 387  Controller->FreeCommands = NULL;
 388  for (i = 0; i < Controller->DriverQueueDepth; i++)
 389    {
 390      DAC960_Command_T *Command = Controller->Commands[i];
 391
 392      if (Command == NULL)
 393          continue;
 394
 395      if (Controller->FirmwareType == DAC960_V1_Controller) {
 396          ScatterGatherCPU = (void *)Command->V1.ScatterGatherList;
 397          ScatterGatherDMA = Command->V1.ScatterGatherListDMA;
 398          RequestSenseCPU = NULL;
 399          RequestSenseDMA = (dma_addr_t)0;
 400      } else {
 401          ScatterGatherCPU = (void *)Command->V2.ScatterGatherList;
 402          ScatterGatherDMA = Command->V2.ScatterGatherListDMA;
 403          RequestSenseCPU = (void *)Command->V2.RequestSense;
 404          RequestSenseDMA = Command->V2.RequestSenseDMA;
 405      }
 406      if (ScatterGatherCPU != NULL)
 407          pci_pool_free(ScatterGatherPool, ScatterGatherCPU, ScatterGatherDMA);
 408      if (RequestSenseCPU != NULL)
 409          pci_pool_free(RequestSensePool, RequestSenseCPU, RequestSenseDMA);
 410
 411      if ((Command->CommandIdentifier
 412           % Controller->CommandAllocationGroupSize) == 1) {
 413           /*
 414            * We can't free the group of commands until all of the
 415            * request sense and scatter gather dma structures are free.
 416            * Remember the beginning of the group, but don't free it
 417            * until we've reached the beginning of the next group.
 418            */
 419           kfree(CommandGroup);
 420           CommandGroup = Command;
 421      }
 422      Controller->Commands[i] = NULL;
 423    }
 424  kfree(CommandGroup);
 425
 426  if (Controller->CombinedStatusBuffer != NULL)
 427    {
 428      kfree(Controller->CombinedStatusBuffer);
 429      Controller->CombinedStatusBuffer = NULL;
 430      Controller->CurrentStatusBuffer = NULL;
 431    }
 432
 433  if (ScatterGatherPool != NULL)
 434        pci_pool_destroy(ScatterGatherPool);
 435  if (Controller->FirmwareType == DAC960_V1_Controller)
 436        return;
 437
 438  if (RequestSensePool != NULL)
 439        pci_pool_destroy(RequestSensePool);
 440
 441  for (i = 0; i < DAC960_MaxLogicalDrives; i++) {
 442        kfree(Controller->V2.LogicalDeviceInformation[i]);
 443        Controller->V2.LogicalDeviceInformation[i] = NULL;
 444  }
 445
 446  for (i = 0; i < DAC960_V2_MaxPhysicalDevices; i++)
 447    {
 448      kfree(Controller->V2.PhysicalDeviceInformation[i]);
 449      Controller->V2.PhysicalDeviceInformation[i] = NULL;
 450      kfree(Controller->V2.InquiryUnitSerialNumber[i]);
 451      Controller->V2.InquiryUnitSerialNumber[i] = NULL;
 452    }
 453}
 454
 455
 456/*
 457  DAC960_V1_ClearCommand clears critical fields of Command for DAC960 V1
 458  Firmware Controllers.
 459*/
 460
 461static inline void DAC960_V1_ClearCommand(DAC960_Command_T *Command)
 462{
 463  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 464  memset(CommandMailbox, 0, sizeof(DAC960_V1_CommandMailbox_T));
 465  Command->V1.CommandStatus = 0;
 466}
 467
 468
 469/*
 470  DAC960_V2_ClearCommand clears critical fields of Command for DAC960 V2
 471  Firmware Controllers.
 472*/
 473
 474static inline void DAC960_V2_ClearCommand(DAC960_Command_T *Command)
 475{
 476  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 477  memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
 478  Command->V2.CommandStatus = 0;
 479}
 480
 481
 482/*
 483  DAC960_AllocateCommand allocates a Command structure from Controller's
 484  free list.  During driver initialization, a special initialization command
 485  has been placed on the free list to guarantee that command allocation can
 486  never fail.
 487*/
 488
 489static inline DAC960_Command_T *DAC960_AllocateCommand(DAC960_Controller_T
 490                                                       *Controller)
 491{
 492  DAC960_Command_T *Command = Controller->FreeCommands;
 493  if (Command == NULL) return NULL;
 494  Controller->FreeCommands = Command->Next;
 495  Command->Next = NULL;
 496  return Command;
 497}
 498
 499
 500/*
 501  DAC960_DeallocateCommand deallocates Command, returning it to Controller's
 502  free list.
 503*/
 504
 505static inline void DAC960_DeallocateCommand(DAC960_Command_T *Command)
 506{
 507  DAC960_Controller_T *Controller = Command->Controller;
 508
 509  Command->Request = NULL;
 510  Command->Next = Controller->FreeCommands;
 511  Controller->FreeCommands = Command;
 512}
 513
 514
 515/*
 516  DAC960_WaitForCommand waits for a wake_up on Controller's Command Wait Queue.
 517*/
 518
 519static void DAC960_WaitForCommand(DAC960_Controller_T *Controller)
 520{
 521  spin_unlock_irq(&Controller->queue_lock);
 522  __wait_event(Controller->CommandWaitQueue, Controller->FreeCommands);
 523  spin_lock_irq(&Controller->queue_lock);
 524}
 525
 526/*
 527  DAC960_GEM_QueueCommand queues Command for DAC960 GEM Series Controllers.
 528*/
 529
 530static void DAC960_GEM_QueueCommand(DAC960_Command_T *Command)
 531{
 532  DAC960_Controller_T *Controller = Command->Controller;
 533  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 534  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 535  DAC960_V2_CommandMailbox_T *NextCommandMailbox =
 536      Controller->V2.NextCommandMailbox;
 537
 538  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 539  DAC960_GEM_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 540
 541  if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
 542      Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
 543      DAC960_GEM_MemoryMailboxNewCommand(ControllerBaseAddress);
 544
 545  Controller->V2.PreviousCommandMailbox2 =
 546      Controller->V2.PreviousCommandMailbox1;
 547  Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
 548
 549  if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
 550      NextCommandMailbox = Controller->V2.FirstCommandMailbox;
 551
 552  Controller->V2.NextCommandMailbox = NextCommandMailbox;
 553}
 554
 555/*
 556  DAC960_BA_QueueCommand queues Command for DAC960 BA Series Controllers.
 557*/
 558
 559static void DAC960_BA_QueueCommand(DAC960_Command_T *Command)
 560{
 561  DAC960_Controller_T *Controller = Command->Controller;
 562  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 563  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 564  DAC960_V2_CommandMailbox_T *NextCommandMailbox =
 565    Controller->V2.NextCommandMailbox;
 566  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 567  DAC960_BA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 568  if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
 569      Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
 570    DAC960_BA_MemoryMailboxNewCommand(ControllerBaseAddress);
 571  Controller->V2.PreviousCommandMailbox2 =
 572    Controller->V2.PreviousCommandMailbox1;
 573  Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
 574  if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
 575    NextCommandMailbox = Controller->V2.FirstCommandMailbox;
 576  Controller->V2.NextCommandMailbox = NextCommandMailbox;
 577}
 578
 579
 580/*
 581  DAC960_LP_QueueCommand queues Command for DAC960 LP Series Controllers.
 582*/
 583
 584static void DAC960_LP_QueueCommand(DAC960_Command_T *Command)
 585{
 586  DAC960_Controller_T *Controller = Command->Controller;
 587  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 588  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 589  DAC960_V2_CommandMailbox_T *NextCommandMailbox =
 590    Controller->V2.NextCommandMailbox;
 591  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 592  DAC960_LP_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 593  if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
 594      Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
 595    DAC960_LP_MemoryMailboxNewCommand(ControllerBaseAddress);
 596  Controller->V2.PreviousCommandMailbox2 =
 597    Controller->V2.PreviousCommandMailbox1;
 598  Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
 599  if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
 600    NextCommandMailbox = Controller->V2.FirstCommandMailbox;
 601  Controller->V2.NextCommandMailbox = NextCommandMailbox;
 602}
 603
 604
 605/*
 606  DAC960_LA_QueueCommandDualMode queues Command for DAC960 LA Series
 607  Controllers with Dual Mode Firmware.
 608*/
 609
 610static void DAC960_LA_QueueCommandDualMode(DAC960_Command_T *Command)
 611{
 612  DAC960_Controller_T *Controller = Command->Controller;
 613  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 614  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 615  DAC960_V1_CommandMailbox_T *NextCommandMailbox =
 616    Controller->V1.NextCommandMailbox;
 617  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 618  DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 619  if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
 620      Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
 621    DAC960_LA_MemoryMailboxNewCommand(ControllerBaseAddress);
 622  Controller->V1.PreviousCommandMailbox2 =
 623    Controller->V1.PreviousCommandMailbox1;
 624  Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
 625  if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
 626    NextCommandMailbox = Controller->V1.FirstCommandMailbox;
 627  Controller->V1.NextCommandMailbox = NextCommandMailbox;
 628}
 629
 630
 631/*
 632  DAC960_LA_QueueCommandSingleMode queues Command for DAC960 LA Series
 633  Controllers with Single Mode Firmware.
 634*/
 635
 636static void DAC960_LA_QueueCommandSingleMode(DAC960_Command_T *Command)
 637{
 638  DAC960_Controller_T *Controller = Command->Controller;
 639  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 640  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 641  DAC960_V1_CommandMailbox_T *NextCommandMailbox =
 642    Controller->V1.NextCommandMailbox;
 643  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 644  DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 645  if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
 646      Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
 647    DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
 648  Controller->V1.PreviousCommandMailbox2 =
 649    Controller->V1.PreviousCommandMailbox1;
 650  Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
 651  if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
 652    NextCommandMailbox = Controller->V1.FirstCommandMailbox;
 653  Controller->V1.NextCommandMailbox = NextCommandMailbox;
 654}
 655
 656
 657/*
 658  DAC960_PG_QueueCommandDualMode queues Command for DAC960 PG Series
 659  Controllers with Dual Mode Firmware.
 660*/
 661
 662static void DAC960_PG_QueueCommandDualMode(DAC960_Command_T *Command)
 663{
 664  DAC960_Controller_T *Controller = Command->Controller;
 665  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 666  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 667  DAC960_V1_CommandMailbox_T *NextCommandMailbox =
 668    Controller->V1.NextCommandMailbox;
 669  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 670  DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 671  if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
 672      Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
 673    DAC960_PG_MemoryMailboxNewCommand(ControllerBaseAddress);
 674  Controller->V1.PreviousCommandMailbox2 =
 675    Controller->V1.PreviousCommandMailbox1;
 676  Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
 677  if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
 678    NextCommandMailbox = Controller->V1.FirstCommandMailbox;
 679  Controller->V1.NextCommandMailbox = NextCommandMailbox;
 680}
 681
 682
 683/*
 684  DAC960_PG_QueueCommandSingleMode queues Command for DAC960 PG Series
 685  Controllers with Single Mode Firmware.
 686*/
 687
 688static void DAC960_PG_QueueCommandSingleMode(DAC960_Command_T *Command)
 689{
 690  DAC960_Controller_T *Controller = Command->Controller;
 691  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 692  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 693  DAC960_V1_CommandMailbox_T *NextCommandMailbox =
 694    Controller->V1.NextCommandMailbox;
 695  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 696  DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
 697  if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
 698      Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
 699    DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
 700  Controller->V1.PreviousCommandMailbox2 =
 701    Controller->V1.PreviousCommandMailbox1;
 702  Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
 703  if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
 704    NextCommandMailbox = Controller->V1.FirstCommandMailbox;
 705  Controller->V1.NextCommandMailbox = NextCommandMailbox;
 706}
 707
 708
 709/*
 710  DAC960_PD_QueueCommand queues Command for DAC960 PD Series Controllers.
 711*/
 712
 713static void DAC960_PD_QueueCommand(DAC960_Command_T *Command)
 714{
 715  DAC960_Controller_T *Controller = Command->Controller;
 716  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 717  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 718  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 719  while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
 720    udelay(1);
 721  DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
 722  DAC960_PD_NewCommand(ControllerBaseAddress);
 723}
 724
 725
 726/*
 727  DAC960_P_QueueCommand queues Command for DAC960 P Series Controllers.
 728*/
 729
 730static void DAC960_P_QueueCommand(DAC960_Command_T *Command)
 731{
 732  DAC960_Controller_T *Controller = Command->Controller;
 733  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
 734  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 735  CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
 736  switch (CommandMailbox->Common.CommandOpcode)
 737    {
 738    case DAC960_V1_Enquiry:
 739      CommandMailbox->Common.CommandOpcode = DAC960_V1_Enquiry_Old;
 740      break;
 741    case DAC960_V1_GetDeviceState:
 742      CommandMailbox->Common.CommandOpcode = DAC960_V1_GetDeviceState_Old;
 743      break;
 744    case DAC960_V1_Read:
 745      CommandMailbox->Common.CommandOpcode = DAC960_V1_Read_Old;
 746      DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
 747      break;
 748    case DAC960_V1_Write:
 749      CommandMailbox->Common.CommandOpcode = DAC960_V1_Write_Old;
 750      DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
 751      break;
 752    case DAC960_V1_ReadWithScatterGather:
 753      CommandMailbox->Common.CommandOpcode =
 754        DAC960_V1_ReadWithScatterGather_Old;
 755      DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
 756      break;
 757    case DAC960_V1_WriteWithScatterGather:
 758      CommandMailbox->Common.CommandOpcode =
 759        DAC960_V1_WriteWithScatterGather_Old;
 760      DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
 761      break;
 762    default:
 763      break;
 764    }
 765  while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
 766    udelay(1);
 767  DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
 768  DAC960_PD_NewCommand(ControllerBaseAddress);
 769}
 770
 771
 772/*
 773  DAC960_ExecuteCommand executes Command and waits for completion.
 774*/
 775
 776static void DAC960_ExecuteCommand(DAC960_Command_T *Command)
 777{
 778  DAC960_Controller_T *Controller = Command->Controller;
 779  DECLARE_COMPLETION_ONSTACK(Completion);
 780  unsigned long flags;
 781  Command->Completion = &Completion;
 782
 783  spin_lock_irqsave(&Controller->queue_lock, flags);
 784  DAC960_QueueCommand(Command);
 785  spin_unlock_irqrestore(&Controller->queue_lock, flags);
 786 
 787  if (in_interrupt())
 788          return;
 789  wait_for_completion(&Completion);
 790}
 791
 792
 793/*
 794  DAC960_V1_ExecuteType3 executes a DAC960 V1 Firmware Controller Type 3
 795  Command and waits for completion.  It returns true on success and false
 796  on failure.
 797*/
 798
 799static bool DAC960_V1_ExecuteType3(DAC960_Controller_T *Controller,
 800                                      DAC960_V1_CommandOpcode_T CommandOpcode,
 801                                      dma_addr_t DataDMA)
 802{
 803  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 804  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 805  DAC960_V1_CommandStatus_T CommandStatus;
 806  DAC960_V1_ClearCommand(Command);
 807  Command->CommandType = DAC960_ImmediateCommand;
 808  CommandMailbox->Type3.CommandOpcode = CommandOpcode;
 809  CommandMailbox->Type3.BusAddress = DataDMA;
 810  DAC960_ExecuteCommand(Command);
 811  CommandStatus = Command->V1.CommandStatus;
 812  DAC960_DeallocateCommand(Command);
 813  return (CommandStatus == DAC960_V1_NormalCompletion);
 814}
 815
 816
 817/*
 818  DAC960_V1_ExecuteTypeB executes a DAC960 V1 Firmware Controller Type 3B
 819  Command and waits for completion.  It returns true on success and false
 820  on failure.
 821*/
 822
 823static bool DAC960_V1_ExecuteType3B(DAC960_Controller_T *Controller,
 824                                       DAC960_V1_CommandOpcode_T CommandOpcode,
 825                                       unsigned char CommandOpcode2,
 826                                       dma_addr_t DataDMA)
 827{
 828  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 829  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 830  DAC960_V1_CommandStatus_T CommandStatus;
 831  DAC960_V1_ClearCommand(Command);
 832  Command->CommandType = DAC960_ImmediateCommand;
 833  CommandMailbox->Type3B.CommandOpcode = CommandOpcode;
 834  CommandMailbox->Type3B.CommandOpcode2 = CommandOpcode2;
 835  CommandMailbox->Type3B.BusAddress = DataDMA;
 836  DAC960_ExecuteCommand(Command);
 837  CommandStatus = Command->V1.CommandStatus;
 838  DAC960_DeallocateCommand(Command);
 839  return (CommandStatus == DAC960_V1_NormalCompletion);
 840}
 841
 842
 843/*
 844  DAC960_V1_ExecuteType3D executes a DAC960 V1 Firmware Controller Type 3D
 845  Command and waits for completion.  It returns true on success and false
 846  on failure.
 847*/
 848
 849static bool DAC960_V1_ExecuteType3D(DAC960_Controller_T *Controller,
 850                                       DAC960_V1_CommandOpcode_T CommandOpcode,
 851                                       unsigned char Channel,
 852                                       unsigned char TargetID,
 853                                       dma_addr_t DataDMA)
 854{
 855  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 856  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
 857  DAC960_V1_CommandStatus_T CommandStatus;
 858  DAC960_V1_ClearCommand(Command);
 859  Command->CommandType = DAC960_ImmediateCommand;
 860  CommandMailbox->Type3D.CommandOpcode = CommandOpcode;
 861  CommandMailbox->Type3D.Channel = Channel;
 862  CommandMailbox->Type3D.TargetID = TargetID;
 863  CommandMailbox->Type3D.BusAddress = DataDMA;
 864  DAC960_ExecuteCommand(Command);
 865  CommandStatus = Command->V1.CommandStatus;
 866  DAC960_DeallocateCommand(Command);
 867  return (CommandStatus == DAC960_V1_NormalCompletion);
 868}
 869
 870
 871/*
 872  DAC960_V2_GeneralInfo executes a DAC960 V2 Firmware General Information
 873  Reading IOCTL Command and waits for completion.  It returns true on success
 874  and false on failure.
 875
 876  Return data in The controller's HealthStatusBuffer, which is dma-able memory
 877*/
 878
 879static bool DAC960_V2_GeneralInfo(DAC960_Controller_T *Controller)
 880{
 881  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 882  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 883  DAC960_V2_CommandStatus_T CommandStatus;
 884  DAC960_V2_ClearCommand(Command);
 885  Command->CommandType = DAC960_ImmediateCommand;
 886  CommandMailbox->Common.CommandOpcode = DAC960_V2_IOCTL;
 887  CommandMailbox->Common.CommandControlBits
 888                        .DataTransferControllerToHost = true;
 889  CommandMailbox->Common.CommandControlBits
 890                        .NoAutoRequestSense = true;
 891  CommandMailbox->Common.DataTransferSize = sizeof(DAC960_V2_HealthStatusBuffer_T);
 892  CommandMailbox->Common.IOCTL_Opcode = DAC960_V2_GetHealthStatus;
 893  CommandMailbox->Common.DataTransferMemoryAddress
 894                        .ScatterGatherSegments[0]
 895                        .SegmentDataPointer =
 896    Controller->V2.HealthStatusBufferDMA;
 897  CommandMailbox->Common.DataTransferMemoryAddress
 898                        .ScatterGatherSegments[0]
 899                        .SegmentByteCount =
 900    CommandMailbox->Common.DataTransferSize;
 901  DAC960_ExecuteCommand(Command);
 902  CommandStatus = Command->V2.CommandStatus;
 903  DAC960_DeallocateCommand(Command);
 904  return (CommandStatus == DAC960_V2_NormalCompletion);
 905}
 906
 907
 908/*
 909  DAC960_V2_ControllerInfo executes a DAC960 V2 Firmware Controller
 910  Information Reading IOCTL Command and waits for completion.  It returns
 911  true on success and false on failure.
 912
 913  Data is returned in the controller's V2.NewControllerInformation dma-able
 914  memory buffer.
 915*/
 916
 917static bool DAC960_V2_NewControllerInfo(DAC960_Controller_T *Controller)
 918{
 919  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 920  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 921  DAC960_V2_CommandStatus_T CommandStatus;
 922  DAC960_V2_ClearCommand(Command);
 923  Command->CommandType = DAC960_ImmediateCommand;
 924  CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
 925  CommandMailbox->ControllerInfo.CommandControlBits
 926                                .DataTransferControllerToHost = true;
 927  CommandMailbox->ControllerInfo.CommandControlBits
 928                                .NoAutoRequestSense = true;
 929  CommandMailbox->ControllerInfo.DataTransferSize = sizeof(DAC960_V2_ControllerInfo_T);
 930  CommandMailbox->ControllerInfo.ControllerNumber = 0;
 931  CommandMailbox->ControllerInfo.IOCTL_Opcode = DAC960_V2_GetControllerInfo;
 932  CommandMailbox->ControllerInfo.DataTransferMemoryAddress
 933                                .ScatterGatherSegments[0]
 934                                .SegmentDataPointer =
 935        Controller->V2.NewControllerInformationDMA;
 936  CommandMailbox->ControllerInfo.DataTransferMemoryAddress
 937                                .ScatterGatherSegments[0]
 938                                .SegmentByteCount =
 939    CommandMailbox->ControllerInfo.DataTransferSize;
 940  DAC960_ExecuteCommand(Command);
 941  CommandStatus = Command->V2.CommandStatus;
 942  DAC960_DeallocateCommand(Command);
 943  return (CommandStatus == DAC960_V2_NormalCompletion);
 944}
 945
 946
 947/*
 948  DAC960_V2_LogicalDeviceInfo executes a DAC960 V2 Firmware Controller Logical
 949  Device Information Reading IOCTL Command and waits for completion.  It
 950  returns true on success and false on failure.
 951
 952  Data is returned in the controller's V2.NewLogicalDeviceInformation
 953*/
 954
 955static bool DAC960_V2_NewLogicalDeviceInfo(DAC960_Controller_T *Controller,
 956                                           unsigned short LogicalDeviceNumber)
 957{
 958  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
 959  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
 960  DAC960_V2_CommandStatus_T CommandStatus;
 961
 962  DAC960_V2_ClearCommand(Command);
 963  Command->CommandType = DAC960_ImmediateCommand;
 964  CommandMailbox->LogicalDeviceInfo.CommandOpcode =
 965                                DAC960_V2_IOCTL;
 966  CommandMailbox->LogicalDeviceInfo.CommandControlBits
 967                                   .DataTransferControllerToHost = true;
 968  CommandMailbox->LogicalDeviceInfo.CommandControlBits
 969                                   .NoAutoRequestSense = true;
 970  CommandMailbox->LogicalDeviceInfo.DataTransferSize = 
 971                                sizeof(DAC960_V2_LogicalDeviceInfo_T);
 972  CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
 973    LogicalDeviceNumber;
 974  CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode = DAC960_V2_GetLogicalDeviceInfoValid;
 975  CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
 976                                   .ScatterGatherSegments[0]
 977                                   .SegmentDataPointer =
 978        Controller->V2.NewLogicalDeviceInformationDMA;
 979  CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
 980                                   .ScatterGatherSegments[0]
 981                                   .SegmentByteCount =
 982    CommandMailbox->LogicalDeviceInfo.DataTransferSize;
 983  DAC960_ExecuteCommand(Command);
 984  CommandStatus = Command->V2.CommandStatus;
 985  DAC960_DeallocateCommand(Command);
 986  return (CommandStatus == DAC960_V2_NormalCompletion);
 987}
 988
 989
 990/*
 991  DAC960_V2_PhysicalDeviceInfo executes a DAC960 V2 Firmware Controller "Read
 992  Physical Device Information" IOCTL Command and waits for completion.  It
 993  returns true on success and false on failure.
 994
 995  The Channel, TargetID, LogicalUnit arguments should be 0 the first time
 996  this function is called for a given controller.  This will return data
 997  for the "first" device on that controller.  The returned data includes a
 998  Channel, TargetID, LogicalUnit that can be passed in to this routine to
 999  get data for the NEXT device on that controller.
1000
1001  Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
1002  memory buffer.
1003
1004*/
1005
1006static bool DAC960_V2_NewPhysicalDeviceInfo(DAC960_Controller_T *Controller,
1007                                            unsigned char Channel,
1008                                            unsigned char TargetID,
1009                                            unsigned char LogicalUnit)
1010{
1011  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
1012  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
1013  DAC960_V2_CommandStatus_T CommandStatus;
1014
1015  DAC960_V2_ClearCommand(Command);
1016  Command->CommandType = DAC960_ImmediateCommand;
1017  CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
1018  CommandMailbox->PhysicalDeviceInfo.CommandControlBits
1019                                    .DataTransferControllerToHost = true;
1020  CommandMailbox->PhysicalDeviceInfo.CommandControlBits
1021                                    .NoAutoRequestSense = true;
1022  CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
1023                                sizeof(DAC960_V2_PhysicalDeviceInfo_T);
1024  CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.LogicalUnit = LogicalUnit;
1025  CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID = TargetID;
1026  CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel = Channel;
1027  CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
1028                                        DAC960_V2_GetPhysicalDeviceInfoValid;
1029  CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
1030                                    .ScatterGatherSegments[0]
1031                                    .SegmentDataPointer =
1032                                        Controller->V2.NewPhysicalDeviceInformationDMA;
1033  CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
1034                                    .ScatterGatherSegments[0]
1035                                    .SegmentByteCount =
1036    CommandMailbox->PhysicalDeviceInfo.DataTransferSize;
1037  DAC960_ExecuteCommand(Command);
1038  CommandStatus = Command->V2.CommandStatus;
1039  DAC960_DeallocateCommand(Command);
1040  return (CommandStatus == DAC960_V2_NormalCompletion);
1041}
1042
1043
1044static void DAC960_V2_ConstructNewUnitSerialNumber(
1045        DAC960_Controller_T *Controller,
1046        DAC960_V2_CommandMailbox_T *CommandMailbox, int Channel, int TargetID,
1047        int LogicalUnit)
1048{
1049      CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10_Passthru;
1050      CommandMailbox->SCSI_10.CommandControlBits
1051                             .DataTransferControllerToHost = true;
1052      CommandMailbox->SCSI_10.CommandControlBits
1053                             .NoAutoRequestSense = true;
1054      CommandMailbox->SCSI_10.DataTransferSize =
1055        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1056      CommandMailbox->SCSI_10.PhysicalDevice.LogicalUnit = LogicalUnit;
1057      CommandMailbox->SCSI_10.PhysicalDevice.TargetID = TargetID;
1058      CommandMailbox->SCSI_10.PhysicalDevice.Channel = Channel;
1059      CommandMailbox->SCSI_10.CDBLength = 6;
1060      CommandMailbox->SCSI_10.SCSI_CDB[0] = 0x12; /* INQUIRY */
1061      CommandMailbox->SCSI_10.SCSI_CDB[1] = 1; /* EVPD = 1 */
1062      CommandMailbox->SCSI_10.SCSI_CDB[2] = 0x80; /* Page Code */
1063      CommandMailbox->SCSI_10.SCSI_CDB[3] = 0; /* Reserved */
1064      CommandMailbox->SCSI_10.SCSI_CDB[4] =
1065        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1066      CommandMailbox->SCSI_10.SCSI_CDB[5] = 0; /* Control */
1067      CommandMailbox->SCSI_10.DataTransferMemoryAddress
1068                             .ScatterGatherSegments[0]
1069                             .SegmentDataPointer =
1070                Controller->V2.NewInquiryUnitSerialNumberDMA;
1071      CommandMailbox->SCSI_10.DataTransferMemoryAddress
1072                             .ScatterGatherSegments[0]
1073                             .SegmentByteCount =
1074                CommandMailbox->SCSI_10.DataTransferSize;
1075}
1076
1077
1078/*
1079  DAC960_V2_NewUnitSerialNumber executes an SCSI pass-through
1080  Inquiry command to a SCSI device identified by Channel number,
1081  Target id, Logical Unit Number.  This function Waits for completion
1082  of the command.
1083
1084  The return data includes Unit Serial Number information for the
1085  specified device.
1086
1087  Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
1088  memory buffer.
1089*/
1090
1091static bool DAC960_V2_NewInquiryUnitSerialNumber(DAC960_Controller_T *Controller,
1092                        int Channel, int TargetID, int LogicalUnit)
1093{
1094      DAC960_Command_T *Command;
1095      DAC960_V2_CommandMailbox_T *CommandMailbox;
1096      DAC960_V2_CommandStatus_T CommandStatus;
1097
1098      Command = DAC960_AllocateCommand(Controller);
1099      CommandMailbox = &Command->V2.CommandMailbox;
1100      DAC960_V2_ClearCommand(Command);
1101      Command->CommandType = DAC960_ImmediateCommand;
1102
1103      DAC960_V2_ConstructNewUnitSerialNumber(Controller, CommandMailbox,
1104                        Channel, TargetID, LogicalUnit);
1105
1106      DAC960_ExecuteCommand(Command);
1107      CommandStatus = Command->V2.CommandStatus;
1108      DAC960_DeallocateCommand(Command);
1109      return (CommandStatus == DAC960_V2_NormalCompletion);
1110}
1111
1112
1113/*
1114  DAC960_V2_DeviceOperation executes a DAC960 V2 Firmware Controller Device
1115  Operation IOCTL Command and waits for completion.  It returns true on
1116  success and false on failure.
1117*/
1118
1119static bool DAC960_V2_DeviceOperation(DAC960_Controller_T *Controller,
1120                                         DAC960_V2_IOCTL_Opcode_T IOCTL_Opcode,
1121                                         DAC960_V2_OperationDevice_T
1122                                           OperationDevice)
1123{
1124  DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
1125  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
1126  DAC960_V2_CommandStatus_T CommandStatus;
1127  DAC960_V2_ClearCommand(Command);
1128  Command->CommandType = DAC960_ImmediateCommand;
1129  CommandMailbox->DeviceOperation.CommandOpcode = DAC960_V2_IOCTL;
1130  CommandMailbox->DeviceOperation.CommandControlBits
1131                                 .DataTransferControllerToHost = true;
1132  CommandMailbox->DeviceOperation.CommandControlBits
1133                                 .NoAutoRequestSense = true;
1134  CommandMailbox->DeviceOperation.IOCTL_Opcode = IOCTL_Opcode;
1135  CommandMailbox->DeviceOperation.OperationDevice = OperationDevice;
1136  DAC960_ExecuteCommand(Command);
1137  CommandStatus = Command->V2.CommandStatus;
1138  DAC960_DeallocateCommand(Command);
1139  return (CommandStatus == DAC960_V2_NormalCompletion);
1140}
1141
1142
1143/*
1144  DAC960_V1_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
1145  for DAC960 V1 Firmware Controllers.
1146
1147  PD and P controller types have no memory mailbox, but still need the
1148  other dma mapped memory.
1149*/
1150
1151static bool DAC960_V1_EnableMemoryMailboxInterface(DAC960_Controller_T
1152                                                      *Controller)
1153{
1154  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
1155  DAC960_HardwareType_T hw_type = Controller->HardwareType;
1156  struct pci_dev *PCI_Device = Controller->PCIDevice;
1157  struct dma_loaf *DmaPages = &Controller->DmaPages;
1158  size_t DmaPagesSize;
1159  size_t CommandMailboxesSize;
1160  size_t StatusMailboxesSize;
1161
1162  DAC960_V1_CommandMailbox_T *CommandMailboxesMemory;
1163  dma_addr_t CommandMailboxesMemoryDMA;
1164
1165  DAC960_V1_StatusMailbox_T *StatusMailboxesMemory;
1166  dma_addr_t StatusMailboxesMemoryDMA;
1167
1168  DAC960_V1_CommandMailbox_T CommandMailbox;
1169  DAC960_V1_CommandStatus_T CommandStatus;
1170  int TimeoutCounter;
1171  int i;
1172
1173  
1174  if (pci_set_dma_mask(Controller->PCIDevice, DMA_BIT_MASK(32)))
1175        return DAC960_Failure(Controller, "DMA mask out of range");
1176  Controller->BounceBufferLimit = DMA_BIT_MASK(32);
1177
1178  if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller)) {
1179    CommandMailboxesSize =  0;
1180    StatusMailboxesSize = 0;
1181  } else {
1182    CommandMailboxesSize =  DAC960_V1_CommandMailboxCount * sizeof(DAC960_V1_CommandMailbox_T);
1183    StatusMailboxesSize = DAC960_V1_StatusMailboxCount * sizeof(DAC960_V1_StatusMailbox_T);
1184  }
1185  DmaPagesSize = CommandMailboxesSize + StatusMailboxesSize + 
1186        sizeof(DAC960_V1_DCDB_T) + sizeof(DAC960_V1_Enquiry_T) +
1187        sizeof(DAC960_V1_ErrorTable_T) + sizeof(DAC960_V1_EventLogEntry_T) +
1188        sizeof(DAC960_V1_RebuildProgress_T) +
1189        sizeof(DAC960_V1_LogicalDriveInformationArray_T) +
1190        sizeof(DAC960_V1_BackgroundInitializationStatus_T) +
1191        sizeof(DAC960_V1_DeviceState_T) + sizeof(DAC960_SCSI_Inquiry_T) +
1192        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1193
1194  if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize))
1195        return false;
1196
1197
1198  if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller)) 
1199        goto skip_mailboxes;
1200
1201  CommandMailboxesMemory = slice_dma_loaf(DmaPages,
1202                CommandMailboxesSize, &CommandMailboxesMemoryDMA);
1203  
1204  /* These are the base addresses for the command memory mailbox array */
1205  Controller->V1.FirstCommandMailbox = CommandMailboxesMemory;
1206  Controller->V1.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
1207
1208  CommandMailboxesMemory += DAC960_V1_CommandMailboxCount - 1;
1209  Controller->V1.LastCommandMailbox = CommandMailboxesMemory;
1210  Controller->V1.NextCommandMailbox = Controller->V1.FirstCommandMailbox;
1211  Controller->V1.PreviousCommandMailbox1 = Controller->V1.LastCommandMailbox;
1212  Controller->V1.PreviousCommandMailbox2 =
1213                                        Controller->V1.LastCommandMailbox - 1;
1214
1215  /* These are the base addresses for the status memory mailbox array */
1216  StatusMailboxesMemory = slice_dma_loaf(DmaPages,
1217                StatusMailboxesSize, &StatusMailboxesMemoryDMA);
1218
1219  Controller->V1.FirstStatusMailbox = StatusMailboxesMemory;
1220  Controller->V1.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
1221  StatusMailboxesMemory += DAC960_V1_StatusMailboxCount - 1;
1222  Controller->V1.LastStatusMailbox = StatusMailboxesMemory;
1223  Controller->V1.NextStatusMailbox = Controller->V1.FirstStatusMailbox;
1224
1225skip_mailboxes:
1226  Controller->V1.MonitoringDCDB = slice_dma_loaf(DmaPages,
1227                sizeof(DAC960_V1_DCDB_T),
1228                &Controller->V1.MonitoringDCDB_DMA);
1229
1230  Controller->V1.NewEnquiry = slice_dma_loaf(DmaPages,
1231                sizeof(DAC960_V1_Enquiry_T),
1232                &Controller->V1.NewEnquiryDMA);
1233
1234  Controller->V1.NewErrorTable = slice_dma_loaf(DmaPages,
1235                sizeof(DAC960_V1_ErrorTable_T),
1236                &Controller->V1.NewErrorTableDMA);
1237
1238  Controller->V1.EventLogEntry = slice_dma_loaf(DmaPages,
1239                sizeof(DAC960_V1_EventLogEntry_T),
1240                &Controller->V1.EventLogEntryDMA);
1241
1242  Controller->V1.RebuildProgress = slice_dma_loaf(DmaPages,
1243                sizeof(DAC960_V1_RebuildProgress_T),
1244                &Controller->V1.RebuildProgressDMA);
1245
1246  Controller->V1.NewLogicalDriveInformation = slice_dma_loaf(DmaPages,
1247                sizeof(DAC960_V1_LogicalDriveInformationArray_T),
1248                &Controller->V1.NewLogicalDriveInformationDMA);
1249
1250  Controller->V1.BackgroundInitializationStatus = slice_dma_loaf(DmaPages,
1251                sizeof(DAC960_V1_BackgroundInitializationStatus_T),
1252                &Controller->V1.BackgroundInitializationStatusDMA);
1253
1254  Controller->V1.NewDeviceState = slice_dma_loaf(DmaPages,
1255                sizeof(DAC960_V1_DeviceState_T),
1256                &Controller->V1.NewDeviceStateDMA);
1257
1258  Controller->V1.NewInquiryStandardData = slice_dma_loaf(DmaPages,
1259                sizeof(DAC960_SCSI_Inquiry_T),
1260                &Controller->V1.NewInquiryStandardDataDMA);
1261
1262  Controller->V1.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
1263                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1264                &Controller->V1.NewInquiryUnitSerialNumberDMA);
1265
1266  if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller))
1267        return true;
1268 
1269  /* Enable the Memory Mailbox Interface. */
1270  Controller->V1.DualModeMemoryMailboxInterface = true;
1271  CommandMailbox.TypeX.CommandOpcode = 0x2B;
1272  CommandMailbox.TypeX.CommandIdentifier = 0;
1273  CommandMailbox.TypeX.CommandOpcode2 = 0x14;
1274  CommandMailbox.TypeX.CommandMailboxesBusAddress =
1275                                Controller->V1.FirstCommandMailboxDMA;
1276  CommandMailbox.TypeX.StatusMailboxesBusAddress =
1277                                Controller->V1.FirstStatusMailboxDMA;
1278#define TIMEOUT_COUNT 1000000
1279
1280  for (i = 0; i < 2; i++)
1281    switch (Controller->HardwareType)
1282      {
1283      case DAC960_LA_Controller:
1284        TimeoutCounter = TIMEOUT_COUNT;
1285        while (--TimeoutCounter >= 0)
1286          {
1287            if (!DAC960_LA_HardwareMailboxFullP(ControllerBaseAddress))
1288              break;
1289            udelay(10);
1290          }
1291        if (TimeoutCounter < 0) return false;
1292        DAC960_LA_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
1293        DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
1294        TimeoutCounter = TIMEOUT_COUNT;
1295        while (--TimeoutCounter >= 0)
1296          {
1297            if (DAC960_LA_HardwareMailboxStatusAvailableP(
1298                  ControllerBaseAddress))
1299              break;
1300            udelay(10);
1301          }
1302        if (TimeoutCounter < 0) return false;
1303        CommandStatus = DAC960_LA_ReadStatusRegister(ControllerBaseAddress);
1304        DAC960_LA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1305        DAC960_LA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1306        if (CommandStatus == DAC960_V1_NormalCompletion) return true;
1307        Controller->V1.DualModeMemoryMailboxInterface = false;
1308        CommandMailbox.TypeX.CommandOpcode2 = 0x10;
1309        break;
1310      case DAC960_PG_Controller:
1311        TimeoutCounter = TIMEOUT_COUNT;
1312        while (--TimeoutCounter >= 0)
1313          {
1314            if (!DAC960_PG_HardwareMailboxFullP(ControllerBaseAddress))
1315              break;
1316            udelay(10);
1317          }
1318        if (TimeoutCounter < 0) return false;
1319        DAC960_PG_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
1320        DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
1321
1322        TimeoutCounter = TIMEOUT_COUNT;
1323        while (--TimeoutCounter >= 0)
1324          {
1325            if (DAC960_PG_HardwareMailboxStatusAvailableP(
1326                  ControllerBaseAddress))
1327              break;
1328            udelay(10);
1329          }
1330        if (TimeoutCounter < 0) return false;
1331        CommandStatus = DAC960_PG_ReadStatusRegister(ControllerBaseAddress);
1332        DAC960_PG_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1333        DAC960_PG_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1334        if (CommandStatus == DAC960_V1_NormalCompletion) return true;
1335        Controller->V1.DualModeMemoryMailboxInterface = false;
1336        CommandMailbox.TypeX.CommandOpcode2 = 0x10;
1337        break;
1338      default:
1339        DAC960_Failure(Controller, "Unknown Controller Type\n");
1340        break;
1341      }
1342  return false;
1343}
1344
1345
1346/*
1347  DAC960_V2_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
1348  for DAC960 V2 Firmware Controllers.
1349
1350  Aggregate the space needed for the controller's memory mailbox and
1351  the other data structures that will be targets of dma transfers with
1352  the controller.  Allocate a dma-mapped region of memory to hold these
1353  structures.  Then, save CPU pointers and dma_addr_t values to reference
1354  the structures that are contained in that region.
1355*/
1356
1357static bool DAC960_V2_EnableMemoryMailboxInterface(DAC960_Controller_T
1358                                                      *Controller)
1359{
1360  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
1361  struct pci_dev *PCI_Device = Controller->PCIDevice;
1362  struct dma_loaf *DmaPages = &Controller->DmaPages;
1363  size_t DmaPagesSize;
1364  size_t CommandMailboxesSize;
1365  size_t StatusMailboxesSize;
1366
1367  DAC960_V2_CommandMailbox_T *CommandMailboxesMemory;
1368  dma_addr_t CommandMailboxesMemoryDMA;
1369
1370  DAC960_V2_StatusMailbox_T *StatusMailboxesMemory;
1371  dma_addr_t StatusMailboxesMemoryDMA;
1372
1373  DAC960_V2_CommandMailbox_T *CommandMailbox;
1374  dma_addr_t    CommandMailboxDMA;
1375  DAC960_V2_CommandStatus_T CommandStatus;
1376
1377        if (!pci_set_dma_mask(Controller->PCIDevice, DMA_BIT_MASK(64)))
1378                Controller->BounceBufferLimit = DMA_BIT_MASK(64);
1379        else if (!pci_set_dma_mask(Controller->PCIDevice, DMA_BIT_MASK(32)))
1380                Controller->BounceBufferLimit = DMA_BIT_MASK(32);
1381        else
1382                return DAC960_Failure(Controller, "DMA mask out of range");
1383
1384  /* This is a temporary dma mapping, used only in the scope of this function */
1385  CommandMailbox = pci_alloc_consistent(PCI_Device,
1386                sizeof(DAC960_V2_CommandMailbox_T), &CommandMailboxDMA);
1387  if (CommandMailbox == NULL)
1388          return false;
1389
1390  CommandMailboxesSize = DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T);
1391  StatusMailboxesSize = DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T);
1392  DmaPagesSize =
1393    CommandMailboxesSize + StatusMailboxesSize +
1394    sizeof(DAC960_V2_HealthStatusBuffer_T) +
1395    sizeof(DAC960_V2_ControllerInfo_T) +
1396    sizeof(DAC960_V2_LogicalDeviceInfo_T) +
1397    sizeof(DAC960_V2_PhysicalDeviceInfo_T) +
1398    sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T) +
1399    sizeof(DAC960_V2_Event_T) +
1400    sizeof(DAC960_V2_PhysicalToLogicalDevice_T);
1401
1402  if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize)) {
1403        pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
1404                                        CommandMailbox, CommandMailboxDMA);
1405        return false;
1406  }
1407
1408  CommandMailboxesMemory = slice_dma_loaf(DmaPages,
1409                CommandMailboxesSize, &CommandMailboxesMemoryDMA);
1410
1411  /* These are the base addresses for the command memory mailbox array */
1412  Controller->V2.FirstCommandMailbox = CommandMailboxesMemory;
1413  Controller->V2.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
1414
1415  CommandMailboxesMemory += DAC960_V2_CommandMailboxCount - 1;
1416  Controller->V2.LastCommandMailbox = CommandMailboxesMemory;
1417  Controller->V2.NextCommandMailbox = Controller->V2.FirstCommandMailbox;
1418  Controller->V2.PreviousCommandMailbox1 = Controller->V2.LastCommandMailbox;
1419  Controller->V2.PreviousCommandMailbox2 =
1420                                        Controller->V2.LastCommandMailbox - 1;
1421
1422  /* These are the base addresses for the status memory mailbox array */
1423  StatusMailboxesMemory = slice_dma_loaf(DmaPages,
1424                StatusMailboxesSize, &StatusMailboxesMemoryDMA);
1425
1426  Controller->V2.FirstStatusMailbox = StatusMailboxesMemory;
1427  Controller->V2.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
1428  StatusMailboxesMemory += DAC960_V2_StatusMailboxCount - 1;
1429  Controller->V2.LastStatusMailbox = StatusMailboxesMemory;
1430  Controller->V2.NextStatusMailbox = Controller->V2.FirstStatusMailbox;
1431
1432  Controller->V2.HealthStatusBuffer = slice_dma_loaf(DmaPages,
1433                sizeof(DAC960_V2_HealthStatusBuffer_T),
1434                &Controller->V2.HealthStatusBufferDMA);
1435
1436  Controller->V2.NewControllerInformation = slice_dma_loaf(DmaPages,
1437                sizeof(DAC960_V2_ControllerInfo_T), 
1438                &Controller->V2.NewControllerInformationDMA);
1439
1440  Controller->V2.NewLogicalDeviceInformation =  slice_dma_loaf(DmaPages,
1441                sizeof(DAC960_V2_LogicalDeviceInfo_T),
1442                &Controller->V2.NewLogicalDeviceInformationDMA);
1443
1444  Controller->V2.NewPhysicalDeviceInformation = slice_dma_loaf(DmaPages,
1445                sizeof(DAC960_V2_PhysicalDeviceInfo_T),
1446                &Controller->V2.NewPhysicalDeviceInformationDMA);
1447
1448  Controller->V2.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
1449                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1450                &Controller->V2.NewInquiryUnitSerialNumberDMA);
1451
1452  Controller->V2.Event = slice_dma_loaf(DmaPages,
1453                sizeof(DAC960_V2_Event_T),
1454                &Controller->V2.EventDMA);
1455
1456  Controller->V2.PhysicalToLogicalDevice = slice_dma_loaf(DmaPages,
1457                sizeof(DAC960_V2_PhysicalToLogicalDevice_T),
1458                &Controller->V2.PhysicalToLogicalDeviceDMA);
1459
1460  /*
1461    Enable the Memory Mailbox Interface.
1462    
1463    I don't know why we can't just use one of the memory mailboxes
1464    we just allocated to do this, instead of using this temporary one.
1465    Try this change later.
1466  */
1467  memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
1468  CommandMailbox->SetMemoryMailbox.CommandIdentifier = 1;
1469  CommandMailbox->SetMemoryMailbox.CommandOpcode = DAC960_V2_IOCTL;
1470  CommandMailbox->SetMemoryMailbox.CommandControlBits.NoAutoRequestSense = true;
1471  CommandMailbox->SetMemoryMailbox.FirstCommandMailboxSizeKB =
1472    (DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T)) >> 10;
1473  CommandMailbox->SetMemoryMailbox.FirstStatusMailboxSizeKB =
1474    (DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T)) >> 10;
1475  CommandMailbox->SetMemoryMailbox.SecondCommandMailboxSizeKB = 0;
1476  CommandMailbox->SetMemoryMailbox.SecondStatusMailboxSizeKB = 0;
1477  CommandMailbox->SetMemoryMailbox.RequestSenseSize = 0;
1478  CommandMailbox->SetMemoryMailbox.IOCTL_Opcode = DAC960_V2_SetMemoryMailbox;
1479  CommandMailbox->SetMemoryMailbox.HealthStatusBufferSizeKB = 1;
1480  CommandMailbox->SetMemoryMailbox.HealthStatusBufferBusAddress =
1481                                        Controller->V2.HealthStatusBufferDMA;
1482  CommandMailbox->SetMemoryMailbox.FirstCommandMailboxBusAddress =
1483                                        Controller->V2.FirstCommandMailboxDMA;
1484  CommandMailbox->SetMemoryMailbox.FirstStatusMailboxBusAddress =
1485                                        Controller->V2.FirstStatusMailboxDMA;
1486  switch (Controller->HardwareType)
1487    {
1488    case DAC960_GEM_Controller:
1489      while (DAC960_GEM_HardwareMailboxFullP(ControllerBaseAddress))
1490        udelay(1);
1491      DAC960_GEM_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1492      DAC960_GEM_HardwareMailboxNewCommand(ControllerBaseAddress);
1493      while (!DAC960_GEM_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1494        udelay(1);
1495      CommandStatus = DAC960_GEM_ReadCommandStatus(ControllerBaseAddress);
1496      DAC960_GEM_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1497      DAC960_GEM_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1498      break;
1499    case DAC960_BA_Controller:
1500      while (DAC960_BA_HardwareMailboxFullP(ControllerBaseAddress))
1501        udelay(1);
1502      DAC960_BA_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1503      DAC960_BA_HardwareMailboxNewCommand(ControllerBaseAddress);
1504      while (!DAC960_BA_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1505        udelay(1);
1506      CommandStatus = DAC960_BA_ReadCommandStatus(ControllerBaseAddress);
1507      DAC960_BA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1508      DAC960_BA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1509      break;
1510    case DAC960_LP_Controller:
1511      while (DAC960_LP_HardwareMailboxFullP(ControllerBaseAddress))
1512        udelay(1);
1513      DAC960_LP_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1514      DAC960_LP_HardwareMailboxNewCommand(ControllerBaseAddress);
1515      while (!DAC960_LP_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1516        udelay(1);
1517      CommandStatus = DAC960_LP_ReadCommandStatus(ControllerBaseAddress);
1518      DAC960_LP_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1519      DAC960_LP_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1520      break;
1521    default:
1522      DAC960_Failure(Controller, "Unknown Controller Type\n");
1523      CommandStatus = DAC960_V2_AbormalCompletion;
1524      break;
1525    }
1526  pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
1527                                        CommandMailbox, CommandMailboxDMA);
1528  return (CommandStatus == DAC960_V2_NormalCompletion);
1529}
1530
1531
1532/*
1533  DAC960_V1_ReadControllerConfiguration reads the Configuration Information
1534  from DAC960 V1 Firmware Controllers and initializes the Controller structure.
1535*/
1536
1537static bool DAC960_V1_ReadControllerConfiguration(DAC960_Controller_T
1538                                                     *Controller)
1539{
1540  DAC960_V1_Enquiry2_T *Enquiry2;
1541  dma_addr_t Enquiry2DMA;
1542  DAC960_V1_Config2_T *Config2;
1543  dma_addr_t Config2DMA;
1544  int LogicalDriveNumber, Channel, TargetID;
1545  struct dma_loaf local_dma;
1546
1547  if (!init_dma_loaf(Controller->PCIDevice, &local_dma,
1548                sizeof(DAC960_V1_Enquiry2_T) + sizeof(DAC960_V1_Config2_T)))
1549        return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
1550
1551  Enquiry2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Enquiry2_T), &Enquiry2DMA);
1552  Config2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Config2_T), &Config2DMA);
1553
1554  if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry,
1555                              Controller->V1.NewEnquiryDMA)) {
1556    free_dma_loaf(Controller->PCIDevice, &local_dma);
1557    return DAC960_Failure(Controller, "ENQUIRY");
1558  }
1559  memcpy(&Controller->V1.Enquiry, Controller->V1.NewEnquiry,
1560                                                sizeof(DAC960_V1_Enquiry_T));
1561
1562  if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry2, Enquiry2DMA)) {
1563    free_dma_loaf(Controller->PCIDevice, &local_dma);
1564    return DAC960_Failure(Controller, "ENQUIRY2");
1565  }
1566
1567  if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_ReadConfig2, Config2DMA)) {
1568    free_dma_loaf(Controller->PCIDevice, &local_dma);
1569    return DAC960_Failure(Controller, "READ CONFIG2");
1570  }
1571
1572  if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_GetLogicalDriveInformation,
1573                              Controller->V1.NewLogicalDriveInformationDMA)) {
1574    free_dma_loaf(Controller->PCIDevice, &local_dma);
1575    return DAC960_Failure(Controller, "GET LOGICAL DRIVE INFORMATION");
1576  }
1577  memcpy(&Controller->V1.LogicalDriveInformation,
1578                Controller->V1.NewLogicalDriveInformation,
1579                sizeof(DAC960_V1_LogicalDriveInformationArray_T));
1580
1581  for (Channel = 0; Channel < Enquiry2->ActualChannels; Channel++)
1582    for (TargetID = 0; TargetID < Enquiry2->MaxTargets; TargetID++) {
1583      if (!DAC960_V1_ExecuteType3D(Controller, DAC960_V1_GetDeviceState,
1584                                   Channel, TargetID,
1585                                   Controller->V1.NewDeviceStateDMA)) {
1586                free_dma_loaf(Controller->PCIDevice, &local_dma);
1587                return DAC960_Failure(Controller, "GET DEVICE STATE");
1588        }
1589        memcpy(&Controller->V1.DeviceState[Channel][TargetID],
1590                Controller->V1.NewDeviceState, sizeof(DAC960_V1_DeviceState_T));
1591     }
1592  /*
1593    Initialize the Controller Model Name and Full Model Name fields.
1594  */
1595  switch (Enquiry2->HardwareID.SubModel)
1596    {
1597    case DAC960_V1_P_PD_PU:
1598      if (Enquiry2->SCSICapability.BusSpeed == DAC960_V1_Ultra)
1599        strcpy(Controller->ModelName, "DAC960PU");
1600      else strcpy(Controller->ModelName, "DAC960PD");
1601      break;
1602    case DAC960_V1_PL:
1603      strcpy(Controller->ModelName, "DAC960PL");
1604      break;
1605    case DAC960_V1_PG:
1606      strcpy(Controller->ModelName, "DAC960PG");
1607      break;
1608    case DAC960_V1_PJ:
1609      strcpy(Controller->ModelName, "DAC960PJ");
1610      break;
1611    case DAC960_V1_PR:
1612      strcpy(Controller->ModelName, "DAC960PR");
1613      break;
1614    case DAC960_V1_PT:
1615      strcpy(Controller->ModelName, "DAC960PT");
1616      break;
1617    case DAC960_V1_PTL0:
1618      strcpy(Controller->ModelName, "DAC960PTL0");
1619      break;
1620    case DAC960_V1_PRL:
1621      strcpy(Controller->ModelName, "DAC960PRL");
1622      break;
1623    case DAC960_V1_PTL1:
1624      strcpy(Controller->ModelName, "DAC960PTL1");
1625      break;
1626    case DAC960_V1_1164P:
1627      strcpy(Controller->ModelName, "DAC1164P");
1628      break;
1629    default:
1630      free_dma_loaf(Controller->PCIDevice, &local_dma);
1631      return DAC960_Failure(Controller, "MODEL VERIFICATION");
1632    }
1633  strcpy(Controller->FullModelName, "Mylex ");
1634  strcat(Controller->FullModelName, Controller->ModelName);
1635  /*
1636    Initialize the Controller Firmware Version field and verify that it
1637    is a supported firmware version.  The supported firmware versions are:
1638
1639    DAC1164P                5.06 and above
1640    DAC960PTL/PRL/PJ/PG     4.06 and above
1641    DAC960PU/PD/PL          3.51 and above
1642    DAC960PU/PD/PL/P        2.73 and above
1643  */
1644#if defined(CONFIG_ALPHA)
1645  /*
1646    DEC Alpha machines were often equipped with DAC960 cards that were
1647    OEMed from Mylex, and had their own custom firmware. Version 2.70,
1648    the last custom FW revision to be released by DEC for these older
1649    controllers, appears to work quite well with this driver.
1650
1651    Cards tested successfully were several versions each of the PD and
1652    PU, called by DEC the KZPSC and KZPAC, respectively, and having
1653    the Manufacturer Numbers (from Mylex), usually on a sticker on the
1654    back of the board, of:
1655
1656    KZPSC:  D040347 (1-channel) or D040348 (2-channel) or D040349 (3-channel)
1657    KZPAC:  D040395 (1-channel) or D040396 (2-channel) or D040397 (3-channel)
1658  */
1659# define FIRMWARE_27X   "2.70"
1660#else
1661# define FIRMWARE_27X   "2.73"
1662#endif
1663
1664  if (Enquiry2->FirmwareID.MajorVersion == 0)
1665    {
1666      Enquiry2->FirmwareID.MajorVersion =
1667        Controller->V1.Enquiry.MajorFirmwareVersion;
1668      Enquiry2->FirmwareID.MinorVersion =
1669        Controller->V1.Enquiry.MinorFirmwareVersion;
1670      Enquiry2->FirmwareID.FirmwareType = '0';
1671      Enquiry2->FirmwareID.TurnID = 0;
1672    }
1673  sprintf(Controller->FirmwareVersion, "%d.%02d-%c-%02d",
1674          Enquiry2->FirmwareID.MajorVersion, Enquiry2->FirmwareID.MinorVersion,
1675          Enquiry2->FirmwareID.FirmwareType, Enquiry2->FirmwareID.TurnID);
1676  if (!((Controller->FirmwareVersion[0] == '5' &&
1677         strcmp(Controller->FirmwareVersion, "5.06") >= 0) ||
1678        (Controller->FirmwareVersion[0] == '4' &&
1679         strcmp(Controller->FirmwareVersion, "4.06") >= 0) ||
1680        (Controller->FirmwareVersion[0] == '3' &&
1681         strcmp(Controller->FirmwareVersion, "3.51") >= 0) ||
1682        (Controller->FirmwareVersion[0] == '2' &&
1683         strcmp(Controller->FirmwareVersion, FIRMWARE_27X) >= 0)))
1684    {
1685      DAC960_Failure(Controller, "FIRMWARE VERSION VERIFICATION");
1686      DAC960_Error("Firmware Version = '%s'\n", Controller,
1687                   Controller->FirmwareVersion);
1688      free_dma_loaf(Controller->PCIDevice, &local_dma);
1689      return false;
1690    }
1691  /*
1692    Initialize the Controller Channels, Targets, Memory Size, and SAF-TE
1693    Enclosure Management Enabled fields.
1694  */
1695  Controller->Channels = Enquiry2->ActualChannels;
1696  Controller->Targets = Enquiry2->MaxTargets;
1697  Controller->MemorySize = Enquiry2->MemorySize >> 20;
1698  Controller->V1.SAFTE_EnclosureManagementEnabled =
1699    (Enquiry2->FaultManagementType == DAC960_V1_SAFTE);
1700  /*
1701    Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
1702    Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
1703    Driver Scatter/Gather Limit.  The Driver Queue Depth must be at most one
1704    less than the Controller Queue Depth to allow for an automatic drive
1705    rebuild operation.
1706  */
1707  Controller->ControllerQueueDepth = Controller->V1.Enquiry.MaxCommands;
1708  Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
1709  if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
1710    Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
1711  Controller->LogicalDriveCount =
1712    Controller->V1.Enquiry.NumberOfLogicalDrives;
1713  Controller->MaxBlocksPerCommand = Enquiry2->MaxBlocksPerCommand;
1714  Controller->ControllerScatterGatherLimit = Enquiry2->MaxScatterGatherEntries;
1715  Controller->DriverScatterGatherLimit =
1716    Controller->ControllerScatterGatherLimit;
1717  if (Controller->DriverScatterGatherLimit > DAC960_V1_ScatterGatherLimit)
1718    Controller->DriverScatterGatherLimit = DAC960_V1_ScatterGatherLimit;
1719  /*
1720    Initialize the Stripe Size, Segment Size, and Geometry Translation.
1721  */
1722  Controller->V1.StripeSize = Config2->BlocksPerStripe * Config2->BlockFactor
1723                              >> (10 - DAC960_BlockSizeBits);
1724  Controller->V1.SegmentSize = Config2->BlocksPerCacheLine * Config2->BlockFactor
1725                               >> (10 - DAC960_BlockSizeBits);
1726  switch (Config2->DriveGeometry)
1727    {
1728    case DAC960_V1_Geometry_128_32:
1729      Controller->V1.GeometryTranslationHeads = 128;
1730      Controller->V1.GeometryTranslationSectors = 32;
1731      break;
1732    case DAC960_V1_Geometry_255_63:
1733      Controller->V1.GeometryTranslationHeads = 255;
1734      Controller->V1.GeometryTranslationSectors = 63;
1735      break;
1736    default:
1737      free_dma_loaf(Controller->PCIDevice, &local_dma);
1738      return DAC960_Failure(Controller, "CONFIG2 DRIVE GEOMETRY");
1739    }
1740  /*
1741    Initialize the Background Initialization Status.
1742  */
1743  if ((Controller->FirmwareVersion[0] == '4' &&
1744      strcmp(Controller->FirmwareVersion, "4.08") >= 0) ||
1745      (Controller->FirmwareVersion[0] == '5' &&
1746       strcmp(Controller->FirmwareVersion, "5.08") >= 0))
1747    {
1748      Controller->V1.BackgroundInitializationStatusSupported = true;
1749      DAC960_V1_ExecuteType3B(Controller,
1750                              DAC960_V1_BackgroundInitializationControl, 0x20,
1751                              Controller->
1752                               V1.BackgroundInitializationStatusDMA);
1753      memcpy(&Controller->V1.LastBackgroundInitializationStatus,
1754                Controller->V1.BackgroundInitializationStatus,
1755                sizeof(DAC960_V1_BackgroundInitializationStatus_T));
1756    }
1757  /*
1758    Initialize the Logical Drive Initially Accessible flag.
1759  */
1760  for (LogicalDriveNumber = 0;
1761       LogicalDriveNumber < Controller->LogicalDriveCount;
1762       LogicalDriveNumber++)
1763    if (Controller->V1.LogicalDriveInformation
1764                       [LogicalDriveNumber].LogicalDriveState !=
1765        DAC960_V1_LogicalDrive_Offline)
1766      Controller->LogicalDriveInitiallyAccessible[LogicalDriveNumber] = true;
1767  Controller->V1.LastRebuildStatus = DAC960_V1_NoRebuildOrCheckInProgress;
1768  free_dma_loaf(Controller->PCIDevice, &local_dma);
1769  return true;
1770}
1771
1772
1773/*
1774  DAC960_V2_ReadControllerConfiguration reads the Configuration Information
1775  from DAC960 V2 Firmware Controllers and initializes the Controller structure.
1776*/
1777
1778static bool DAC960_V2_ReadControllerConfiguration(DAC960_Controller_T
1779                                                     *Controller)
1780{
1781  DAC960_V2_ControllerInfo_T *ControllerInfo =
1782                &Controller->V2.ControllerInformation;
1783  unsigned short LogicalDeviceNumber = 0;
1784  int ModelNameLength;
1785
1786  /* Get data into dma-able area, then copy into permanant location */
1787  if (!DAC960_V2_NewControllerInfo(Controller))
1788    return DAC960_Failure(Controller, "GET CONTROLLER INFO");
1789  memcpy(ControllerInfo, Controller->V2.NewControllerInformation,
1790                        sizeof(DAC960_V2_ControllerInfo_T));
1791         
1792  
1793  if (!DAC960_V2_GeneralInfo(Controller))
1794    return DAC960_Failure(Controller, "GET HEALTH STATUS");
1795
1796  /*
1797    Initialize the Controller Model Name and Full Model Name fields.
1798  */
1799  ModelNameLength = sizeof(ControllerInfo->ControllerName);
1800  if (ModelNameLength > sizeof(Controller->ModelName)-1)
1801    ModelNameLength = sizeof(Controller->ModelName)-1;
1802  memcpy(Controller->ModelName, ControllerInfo->ControllerName,
1803         ModelNameLength);
1804  ModelNameLength--;
1805  while (Controller->ModelName[ModelNameLength] == ' ' ||
1806         Controller->ModelName[ModelNameLength] == '\0')
1807    ModelNameLength--;
1808  Controller->ModelName[++ModelNameLength] = '\0';
1809  strcpy(Controller->FullModelName, "Mylex ");
1810  strcat(Controller->FullModelName, Controller->ModelName);
1811  /*
1812    Initialize the Controller Firmware Version field.
1813  */
1814  sprintf(Controller->FirmwareVersion, "%d.%02d-%02d",
1815          ControllerInfo->FirmwareMajorVersion,
1816          ControllerInfo->FirmwareMinorVersion,
1817          ControllerInfo->FirmwareTurnNumber);
1818  if (ControllerInfo->FirmwareMajorVersion == 6 &&
1819      ControllerInfo->FirmwareMinorVersion == 0 &&
1820      ControllerInfo->FirmwareTurnNumber < 1)
1821    {
1822      DAC960_Info("FIRMWARE VERSION %s DOES NOT PROVIDE THE CONTROLLER\n",
1823                  Controller, Controller->FirmwareVersion);
1824      DAC960_Info("STATUS MONITORING FUNCTIONALITY NEEDED BY THIS DRIVER.\n",
1825                  Controller);
1826      DAC960_Info("PLEASE UPGRADE TO VERSION 6.00-01 OR ABOVE.\n",
1827                  Controller);
1828    }
1829  /*
1830    Initialize the Controller Channels, Targets, and Memory Size.
1831  */
1832  Controller->Channels = ControllerInfo->NumberOfPhysicalChannelsPresent;
1833  Controller->Targets =
1834    ControllerInfo->MaximumTargetsPerChannel
1835                    [ControllerInfo->NumberOfPhysicalChannelsPresent-1];
1836  Controller->MemorySize = ControllerInfo->MemorySizeMB;
1837  /*
1838    Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
1839    Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
1840    Driver Scatter/Gather Limit.  The Driver Queue Depth must be at most one
1841    less than the Controller Queue Depth to allow for an automatic drive
1842    rebuild operation.
1843  */
1844  Controller->ControllerQueueDepth = ControllerInfo->MaximumParallelCommands;
1845  Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
1846  if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
1847    Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
1848  Controller->LogicalDriveCount = ControllerInfo->LogicalDevicesPresent;
1849  Controller->MaxBlocksPerCommand =
1850    ControllerInfo->MaximumDataTransferSizeInBlocks;
1851  Controller->ControllerScatterGatherLimit =
1852    ControllerInfo->MaximumScatterGatherEntries;
1853  Controller->DriverScatterGatherLimit =
1854    Controller->ControllerScatterGatherLimit;
1855  if (Controller->DriverScatterGatherLimit > DAC960_V2_ScatterGatherLimit)
1856    Controller->DriverScatterGatherLimit = DAC960_V2_ScatterGatherLimit;
1857  /*
1858    Initialize the Logical Device Information.
1859  */
1860  while (true)
1861    {
1862      DAC960_V2_LogicalDeviceInfo_T *NewLogicalDeviceInfo =
1863        Controller->V2.NewLogicalDeviceInformation;
1864      DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo;
1865      DAC960_V2_PhysicalDevice_T PhysicalDevice;
1866
1867      if (!DAC960_V2_NewLogicalDeviceInfo(Controller, LogicalDeviceNumber))
1868        break;
1869      LogicalDeviceNumber = NewLogicalDeviceInfo->LogicalDeviceNumber;
1870      if (LogicalDeviceNumber >= DAC960_MaxLogicalDrives) {
1871        DAC960_Error("DAC960: Logical Drive Number %d not supported\n",
1872                       Controller, LogicalDeviceNumber);
1873                break;
1874      }
1875      if (NewLogicalDeviceInfo->DeviceBlockSizeInBytes != DAC960_BlockSize) {
1876        DAC960_Error("DAC960: Logical Drive Block Size %d not supported\n",
1877              Controller, NewLogicalDeviceInfo->DeviceBlockSizeInBytes);
1878        LogicalDeviceNumber++;
1879        continue;
1880      }
1881      PhysicalDevice.Controller = 0;
1882      PhysicalDevice.Channel = NewLogicalDeviceInfo->Channel;
1883      PhysicalDevice.TargetID = NewLogicalDeviceInfo->TargetID;
1884      PhysicalDevice.LogicalUnit = NewLogicalDeviceInfo->LogicalUnit;
1885      Controller->V2.LogicalDriveToVirtualDevice[LogicalDeviceNumber] =
1886        PhysicalDevice;
1887      if (NewLogicalDeviceInfo->LogicalDeviceState !=
1888          DAC960_V2_LogicalDevice_Offline)
1889        Controller->LogicalDriveInitiallyAccessible[LogicalDeviceNumber] = true;
1890      LogicalDeviceInfo = kmalloc(sizeof(DAC960_V2_LogicalDeviceInfo_T),
1891                                   GFP_ATOMIC);
1892      if (LogicalDeviceInfo == NULL)
1893        return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
1894      Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber] =
1895        LogicalDeviceInfo;
1896      memcpy(LogicalDeviceInfo, NewLogicalDeviceInfo,
1897             sizeof(DAC960_V2_LogicalDeviceInfo_T));
1898      LogicalDeviceNumber++;
1899    }
1900  return true;
1901}
1902
1903
1904/*
1905  DAC960_ReportControllerConfiguration reports the Configuration Information
1906  for Controller.
1907*/
1908
1909static bool DAC960_ReportControllerConfiguration(DAC960_Controller_T
1910                                                    *Controller)
1911{
1912  DAC960_Info("Configuring Mylex %s PCI RAID Controller\n",
1913              Controller, Controller->ModelName);
1914  DAC960_Info("  Firmware Version: %s, Channels: %d, Memory Size: %dMB\n",
1915              Controller, Controller->FirmwareVersion,
1916              Controller->Channels, Controller->MemorySize);
1917  DAC960_Info("  PCI Bus: %d, Device: %d, Function: %d, I/O Address: ",
1918              Controller, Controller->Bus,
1919              Controller->Device, Controller->Function);
1920  if (Controller->IO_Address == 0)
1921    DAC960_Info("Unassigned\n", Controller);
1922  else DAC960_Info("0x%X\n", Controller, Controller->IO_Address);
1923  DAC960_Info("  PCI Address: 0x%X mapped at 0x%lX, IRQ Channel: %d\n",
1924              Controller, Controller->PCI_Address,
1925              (unsigned long) Controller->BaseAddress,
1926              Controller->IRQ_Channel);
1927  DAC960_Info("  Controller Queue Depth: %d, "
1928              "Maximum Blocks per Command: %d\n",
1929              Controller, Controller->ControllerQueueDepth,
1930              Controller->MaxBlocksPerCommand);
1931  DAC960_Info("  Driver Queue Depth: %d, "
1932              "Scatter/Gather Limit: %d of %d Segments\n",
1933              Controller, Controller->DriverQueueDepth,
1934              Controller->DriverScatterGatherLimit,
1935              Controller->ControllerScatterGatherLimit);
1936  if (Controller->FirmwareType == DAC960_V1_Controller)
1937    {
1938      DAC960_Info("  Stripe Size: %dKB, Segment Size: %dKB, "
1939                  "BIOS Geometry: %d/%d\n", Controller,
1940                  Controller->V1.StripeSize,
1941                  Controller->V1.SegmentSize,
1942                  Controller->V1.GeometryTranslationHeads,
1943                  Controller->V1.GeometryTranslationSectors);
1944      if (Controller->V1.SAFTE_EnclosureManagementEnabled)
1945        DAC960_Info("  SAF-TE Enclosure Management Enabled\n", Controller);
1946    }
1947  return true;
1948}
1949
1950
1951/*
1952  DAC960_V1_ReadDeviceConfiguration reads the Device Configuration Information
1953  for DAC960 V1 Firmware Controllers by requesting the SCSI Inquiry and SCSI
1954  Inquiry Unit Serial Number information for each device connected to
1955  Controller.
1956*/
1957
1958static bool DAC960_V1_ReadDeviceConfiguration(DAC960_Controller_T
1959                                                 *Controller)
1960{
1961  struct dma_loaf local_dma;
1962
1963  dma_addr_t DCDBs_dma[DAC960_V1_MaxChannels];
1964  DAC960_V1_DCDB_T *DCDBs_cpu[DAC960_V1_MaxChannels];
1965
1966  dma_addr_t SCSI_Inquiry_dma[DAC960_V1_MaxChannels];
1967  DAC960_SCSI_Inquiry_T *SCSI_Inquiry_cpu[DAC960_V1_MaxChannels];
1968
1969  dma_addr_t SCSI_NewInquiryUnitSerialNumberDMA[DAC960_V1_MaxChannels];
1970  DAC960_SCSI_Inquiry_UnitSerialNumber_T *SCSI_NewInquiryUnitSerialNumberCPU[DAC960_V1_MaxChannels];
1971
1972  struct completion Completions[DAC960_V1_MaxChannels];
1973  unsigned long flags;
1974  int Channel, TargetID;
1975
1976  if (!init_dma_loaf(Controller->PCIDevice, &local_dma, 
1977                DAC960_V1_MaxChannels*(sizeof(DAC960_V1_DCDB_T) +
1978                        sizeof(DAC960_SCSI_Inquiry_T) +
1979                        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T))))
1980     return DAC960_Failure(Controller,
1981                        "DMA ALLOCATION FAILED IN ReadDeviceConfiguration"); 
1982   
1983  for (Channel = 0; Channel < Controller->Channels; Channel++) {
1984        DCDBs_cpu[Channel] = slice_dma_loaf(&local_dma,
1985                        sizeof(DAC960_V1_DCDB_T), DCDBs_dma + Channel);
1986        SCSI_Inquiry_cpu[Channel] = slice_dma_loaf(&local_dma,
1987                        sizeof(DAC960_SCSI_Inquiry_T),
1988                        SCSI_Inquiry_dma + Channel);
1989        SCSI_NewInquiryUnitSerialNumberCPU[Channel] = slice_dma_loaf(&local_dma,
1990                        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1991                        SCSI_NewInquiryUnitSerialNumberDMA + Channel);
1992  }
1993                
1994  for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
1995    {
1996      /*
1997       * For each channel, submit a probe for a device on that channel.
1998       * The timeout interval for a device that is present is 10 seconds.
1999       * With this approach, the timeout periods can elapse in parallel
2000       * on each channel.
2001       */
2002      for (Channel = 0; Channel < Controller->Channels; Channel++)
2003        {
2004          dma_addr_t NewInquiryStandardDataDMA = SCSI_Inquiry_dma[Channel];
2005          DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
2006          dma_addr_t DCDB_dma = DCDBs_dma[Channel];
2007          DAC960_Command_T *Command = Controller->Commands[Channel];
2008          struct completion *Completion = &Completions[Channel];
2009
2010          init_completion(Completion);
2011          DAC960_V1_ClearCommand(Command);
2012          Command->CommandType = DAC960_ImmediateCommand;
2013          Command->Completion = Completion;
2014          Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
2015          Command->V1.CommandMailbox.Type3.BusAddress = DCDB_dma;
2016          DCDB->Channel = Channel;
2017          DCDB->TargetID = TargetID;
2018          DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
2019          DCDB->EarlyStatus = false;
2020          DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
2021          DCDB->NoAutomaticRequestSense = false;
2022          DCDB->DisconnectPermitted = true;
2023          DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_T);
2024          DCDB->BusAddress = NewInquiryStandardDataDMA;
2025          DCDB->CDBLength = 6;
2026          DCDB->TransferLengthHigh4 = 0;
2027          DCDB->SenseLength = sizeof(DCDB->SenseData);
2028          DCDB->CDB[0] = 0x12; /* INQUIRY */
2029          DCDB->CDB[1] = 0; /* EVPD = 0 */
2030          DCDB->CDB[2] = 0; /* Page Code */
2031          DCDB->CDB[3] = 0; /* Reserved */
2032          DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_T);
2033          DCDB->CDB[5] = 0; /* Control */
2034
2035          spin_lock_irqsave(&Controller->queue_lock, flags);
2036          DAC960_QueueCommand(Command);
2037          spin_unlock_irqrestore(&Controller->queue_lock, flags);
2038        }
2039      /*
2040       * Wait for the problems submitted in the previous loop
2041       * to complete.  On the probes that are successful, 
2042       * get the serial number of the device that was found.
2043       */
2044      for (Channel = 0; Channel < Controller->Channels; Channel++)
2045        {
2046          DAC960_SCSI_Inquiry_T *InquiryStandardData =
2047            &Controller->V1.InquiryStandardData[Channel][TargetID];
2048          DAC960_SCSI_Inquiry_T *NewInquiryStandardData = SCSI_Inquiry_cpu[Channel];
2049          dma_addr_t NewInquiryUnitSerialNumberDMA =
2050                        SCSI_NewInquiryUnitSerialNumberDMA[Channel];
2051          DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
2052                        SCSI_NewInquiryUnitSerialNumberCPU[Channel];
2053          DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2054            &Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
2055          DAC960_Command_T *Command = Controller->Commands[Channel];
2056          DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
2057          struct completion *Completion = &Completions[Channel];
2058
2059          wait_for_completion(Completion);
2060
2061          if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
2062            memset(InquiryStandardData, 0, sizeof(DAC960_SCSI_Inquiry_T));
2063            InquiryStandardData->PeripheralDeviceType = 0x1F;
2064            continue;
2065          } else
2066            memcpy(InquiryStandardData, NewInquiryStandardData, sizeof(DAC960_SCSI_Inquiry_T));
2067        
2068          /* Preserve Channel and TargetID values from the previous loop */
2069          Command->Completion = Completion;
2070          DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
2071          DCDB->BusAddress = NewInquiryUnitSerialNumberDMA;
2072          DCDB->SenseLength = sizeof(DCDB->SenseData);
2073          DCDB->CDB[0] = 0x12; /* INQUIRY */
2074          DCDB->CDB[1] = 1; /* EVPD = 1 */
2075          DCDB->CDB[2] = 0x80; /* Page Code */
2076          DCDB->CDB[3] = 0; /* Reserved */
2077          DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
2078          DCDB->CDB[5] = 0; /* Control */
2079
2080          spin_lock_irqsave(&Controller->queue_lock, flags);
2081          DAC960_QueueCommand(Command);
2082          spin_unlock_irqrestore(&Controller->queue_lock, flags);
2083          wait_for_completion(Completion);
2084
2085          if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
2086                memset(InquiryUnitSerialNumber, 0,
2087                        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2088                InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
2089          } else
2090                memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
2091                        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2092        }
2093    }
2094    free_dma_loaf(Controller->PCIDevice, &local_dma);
2095  return true;
2096}
2097
2098
2099/*
2100  DAC960_V2_ReadDeviceConfiguration reads the Device Configuration Information
2101  for DAC960 V2 Firmware Controllers by requesting the Physical Device
2102  Information and SCSI Inquiry Unit Serial Number information for each
2103  device connected to Controller.
2104*/
2105
2106static bool DAC960_V2_ReadDeviceConfiguration(DAC960_Controller_T
2107                                                 *Controller)
2108{
2109  unsigned char Channel = 0, TargetID = 0, LogicalUnit = 0;
2110  unsigned short PhysicalDeviceIndex = 0;
2111
2112  while (true)
2113    {
2114      DAC960_V2_PhysicalDeviceInfo_T *NewPhysicalDeviceInfo =
2115                Controller->V2.NewPhysicalDeviceInformation;
2116      DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo;
2117      DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
2118                Controller->V2.NewInquiryUnitSerialNumber;
2119      DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber;
2120
2121      if (!DAC960_V2_NewPhysicalDeviceInfo(Controller, Channel, TargetID, LogicalUnit))
2122          break;
2123
2124      PhysicalDeviceInfo = kmalloc(sizeof(DAC960_V2_PhysicalDeviceInfo_T),
2125                                    GFP_ATOMIC);
2126      if (PhysicalDeviceInfo == NULL)
2127                return DAC960_Failure(Controller, "PHYSICAL DEVICE ALLOCATION");
2128      Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex] =
2129                PhysicalDeviceInfo;
2130      memcpy(PhysicalDeviceInfo, NewPhysicalDeviceInfo,
2131                sizeof(DAC960_V2_PhysicalDeviceInfo_T));
2132
2133      InquiryUnitSerialNumber = kmalloc(
2134              sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T), GFP_ATOMIC);
2135      if (InquiryUnitSerialNumber == NULL) {
2136        kfree(PhysicalDeviceInfo);
2137        return DAC960_Failure(Controller, "SERIAL NUMBER ALLOCATION");
2138      }
2139      Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex] =
2140                InquiryUnitSerialNumber;
2141
2142      Channel = NewPhysicalDeviceInfo->Channel;
2143      TargetID = NewPhysicalDeviceInfo->TargetID;
2144      LogicalUnit = NewPhysicalDeviceInfo->LogicalUnit;
2145
2146      /*
2147         Some devices do NOT have Unit Serial Numbers.
2148         This command fails for them.  But, we still want to
2149         remember those devices are there.  Construct a
2150         UnitSerialNumber structure for the failure case.
2151      */
2152      if (!DAC960_V2_NewInquiryUnitSerialNumber(Controller, Channel, TargetID, LogicalUnit)) {
2153        memset(InquiryUnitSerialNumber, 0,
2154             sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2155        InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
2156      } else
2157        memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
2158                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2159
2160      PhysicalDeviceIndex++;
2161      LogicalUnit++;
2162    }
2163  return true;
2164}
2165
2166
2167/*
2168  DAC960_SanitizeInquiryData sanitizes the Vendor, Model, Revision, and
2169  Product Serial Number fields of the Inquiry Standard Data and Inquiry
2170  Unit Serial Number structures.
2171*/
2172
2173static void DAC960_SanitizeInquiryData(DAC960_SCSI_Inquiry_T
2174                                         *InquiryStandardData,
2175                                       DAC960_SCSI_Inquiry_UnitSerialNumber_T
2176                                         *InquiryUnitSerialNumber,
2177                                       unsigned char *Vendor,
2178                                       unsigned char *Model,
2179                                       unsigned char *Revision,
2180                                       unsigned char *SerialNumber)
2181{
2182  int SerialNumberLength, i;
2183  if (InquiryStandardData->PeripheralDeviceType == 0x1F) return;
2184  for (i = 0; i < sizeof(InquiryStandardData->VendorIdentification); i++)
2185    {
2186      unsigned char VendorCharacter =
2187        InquiryStandardData->VendorIdentification[i];
2188      Vendor[i] = (VendorCharacter >= ' ' && VendorCharacter <= '~'
2189                   ? VendorCharacter : ' ');
2190    }
2191  Vendor[sizeof(InquiryStandardData->VendorIdentification)] = '\0';
2192  for (i = 0; i < sizeof(InquiryStandardData->ProductIdentification); i++)
2193    {
2194      unsigned char ModelCharacter =
2195        InquiryStandardData->ProductIdentification[i];
2196      Model[i] = (ModelCharacter >= ' ' && ModelCharacter <= '~'
2197                  ? ModelCharacter : ' ');
2198    }
2199  Model[sizeof(InquiryStandardData->ProductIdentification)] = '\0';
2200  for (i = 0; i < sizeof(InquiryStandardData->ProductRevisionLevel); i++)
2201    {
2202      unsigned char RevisionCharacter =
2203        InquiryStandardData->ProductRevisionLevel[i];
2204      Revision[i] = (RevisionCharacter >= ' ' && RevisionCharacter <= '~'
2205                     ? RevisionCharacter : ' ');
2206    }
2207  Revision[sizeof(InquiryStandardData->ProductRevisionLevel)] = '\0';
2208  if (InquiryUnitSerialNumber->PeripheralDeviceType == 0x1F) return;
2209  SerialNumberLength = InquiryUnitSerialNumber->PageLength;
2210  if (SerialNumberLength >
2211      sizeof(InquiryUnitSerialNumber->ProductSerialNumber))
2212    SerialNumberLength = sizeof(InquiryUnitSerialNumber->ProductSerialNumber);
2213  for (i = 0; i < SerialNumberLength; i++)
2214    {
2215      unsigned char SerialNumberCharacter =
2216        InquiryUnitSerialNumber->ProductSerialNumber[i];
2217      SerialNumber[i] =
2218        (SerialNumberCharacter >= ' ' && SerialNumberCharacter <= '~'
2219         ? SerialNumberCharacter : ' ');
2220    }
2221  SerialNumber[SerialNumberLength] = '\0';
2222}
2223
2224
2225/*
2226  DAC960_V1_ReportDeviceConfiguration reports the Device Configuration
2227  Information for DAC960 V1 Firmware Controllers.
2228*/
2229
2230static bool DAC960_V1_ReportDeviceConfiguration(DAC960_Controller_T
2231                                                   *Controller)
2232{
2233  int LogicalDriveNumber, Channel, TargetID;
2234  DAC960_Info("  Physical Devices:\n", Controller);
2235  for (Channel = 0; Channel < Controller->Channels; Channel++)
2236    for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
2237      {
2238        DAC960_SCSI_Inquiry_T *InquiryStandardData =
2239          &Controller->V1.InquiryStandardData[Channel][TargetID];
2240        DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2241          &Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
2242        DAC960_V1_DeviceState_T *DeviceState =
2243          &Controller->V1.DeviceState[Channel][TargetID];
2244        DAC960_V1_ErrorTableEntry_T *ErrorEntry =
2245          &Controller->V1.ErrorTable.ErrorTableEntries[Channel][TargetID];
2246        char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
2247        char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
2248        char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
2249        char SerialNumber[1+sizeof(InquiryUnitSerialNumber
2250                                   ->ProductSerialNumber)];
2251        if (InquiryStandardData->PeripheralDeviceType == 0x1F) continue;
2252        DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
2253                                   Vendor, Model, Revision, SerialNumber);
2254        DAC960_Info("    %d:%d%s Vendor: %s  Model: %s  Revision: %s\n",
2255                    Controller, Channel, TargetID, (TargetID < 10 ? " " : ""),
2256                    Vendor, Model, Revision);
2257        if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
2258          DAC960_Info("         Serial Number: %s\n", Controller, SerialNumber);
2259        if (DeviceState->Present &&
2260            DeviceState->DeviceType == DAC960_V1_DiskType)
2261          {
2262            if (Controller->V1.DeviceResetCount[Channel][TargetID] > 0)
2263              DAC960_Info("         Disk Status: %s, %u blocks, %d resets\n",
2264                          Controller,
2265                          (DeviceState->DeviceState == DAC960_V1_Device_Dead
2266                           ? "Dead"
2267                           : DeviceState->DeviceState
2268                             == DAC960_V1_Device_WriteOnly
2269                             ? "Write-Only"
2270                             : DeviceState->DeviceState
2271                               == DAC960_V1_Device_Online
2272                               ? "Online" : "Standby"),
2273                          DeviceState->DiskSize,
2274                          Controller->V1.DeviceResetCount[Channel][TargetID]);
2275            else
2276              DAC960_Info("         Disk Status: %s, %u blocks\n", Controller,
2277                          (DeviceState->DeviceState == DAC960_V1_Device_Dead
2278                           ? "Dead"
2279                           : DeviceState->DeviceState
2280                             == DAC960_V1_Device_WriteOnly
2281                             ? "Write-Only"
2282                             : DeviceState->DeviceState
2283                               == DAC960_V1_Device_Online
2284                               ? "Online" : "Standby"),
2285                          DeviceState->DiskSize);
2286          }
2287        if (ErrorEntry->ParityErrorCount > 0 ||
2288            ErrorEntry->SoftErrorCount > 0 ||
2289            ErrorEntry->HardErrorCount > 0 ||
2290            ErrorEntry->MiscErrorCount > 0)
2291          DAC960_Info("         Errors - Parity: %d, Soft: %d, "
2292                      "Hard: %d, Misc: %d\n", Controller,
2293                      ErrorEntry->ParityErrorCount,
2294                      ErrorEntry->SoftErrorCount,
2295                      ErrorEntry->HardErrorCount,
2296                      ErrorEntry->MiscErrorCount);
2297      }
2298  DAC960_Info("  Logical Drives:\n", Controller);
2299  for (LogicalDriveNumber = 0;
2300       LogicalDriveNumber < Controller->LogicalDriveCount;
2301       LogicalDriveNumber++)
2302    {
2303      DAC960_V1_LogicalDriveInformation_T *LogicalDriveInformation =
2304        &Controller->V1.LogicalDriveInformation[LogicalDriveNumber];
2305      DAC960_Info("    /dev/rd/c%dd%d: RAID-%d, %s, %u blocks, %s\n",
2306                  Controller, Controller->ControllerNumber, LogicalDriveNumber,
2307                  LogicalDriveInformation->RAIDLevel,
2308                  (LogicalDriveInformation->LogicalDriveState
2309                   == DAC960_V1_LogicalDrive_Online
2310                   ? "Online"
2311                   : LogicalDriveInformation->LogicalDriveState
2312                     == DAC960_V1_LogicalDrive_Critical
2313                     ? "Critical" : "Offline"),
2314                  LogicalDriveInformation->LogicalDriveSize,
2315                  (LogicalDriveInformation->WriteBack
2316                   ? "Write Back" : "Write Thru"));
2317    }
2318  return true;
2319}
2320
2321
2322/*
2323  DAC960_V2_ReportDeviceConfiguration reports the Device Configuration
2324  Information for DAC960 V2 Firmware Controllers.
2325*/
2326
2327static bool DAC960_V2_ReportDeviceConfiguration(DAC960_Controller_T
2328                                                   *Controller)
2329{
2330  int PhysicalDeviceIndex, LogicalDriveNumber;
2331  DAC960_Info("  Physical Devices:\n", Controller);
2332  for (PhysicalDeviceIndex = 0;
2333       PhysicalDeviceIndex < DAC960_V2_MaxPhysicalDevices;
2334       PhysicalDeviceIndex++)
2335    {
2336      DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
2337        Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
2338      DAC960_SCSI_Inquiry_T *InquiryStandardData =
2339        (DAC960_SCSI_Inquiry_T *) &PhysicalDeviceInfo->SCSI_InquiryData;
2340      DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2341        Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
2342      char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
2343      char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
2344      char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
2345      char SerialNumber[1+sizeof(InquiryUnitSerialNumber->ProductSerialNumber)];
2346      if (PhysicalDeviceInfo == NULL) break;
2347      DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
2348                                 Vendor, Model, Revision, SerialNumber);
2349      DAC960_Info("    %d:%d%s Vendor: %s  Model: %s  Revision: %s\n",
2350                  Controller,
2351                  PhysicalDeviceInfo->Channel,
2352                  PhysicalDeviceInfo->TargetID,
2353                  (PhysicalDeviceInfo->TargetID < 10 ? " " : ""),
2354                  Vendor, Model, Revision);
2355      if (PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers == 0)
2356        DAC960_Info("         %sAsynchronous\n", Controller,
2357                    (PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
2358                     ? "Wide " :""));
2359      else
2360        DAC960_Info("         %sSynchronous at %d MB/sec\n", Controller,
2361                    (PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
2362                     ? "Wide " :""),
2363                    (PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers
2364                     * PhysicalDeviceInfo->NegotiatedDataWidthBits/8));
2365      if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
2366        DAC960_Info("         Serial Number: %s\n", Controller, SerialNumber);
2367      if (PhysicalDeviceInfo->PhysicalDeviceState ==
2368          DAC960_V2_Device_Unconfigured)
2369        continue;
2370      DAC960_Info("         Disk Status: %s, %u blocks\n", Controller,
2371                  (PhysicalDeviceInfo->PhysicalDeviceState
2372                   == DAC960_V2_Device_Online
2373                   ? "Online"
2374                   : PhysicalDeviceInfo->PhysicalDeviceState
2375                     == DAC960_V2_Device_Rebuild
2376                     ? "Rebuild"
2377                     : PhysicalDeviceInfo->PhysicalDeviceState
2378                       == DAC960_V2_Device_Missing
2379                       ? "Missing"
2380                       : PhysicalDeviceInfo->PhysicalDeviceState
2381                         == DAC960_V2_Device_Critical
2382                         ? "Critical"
2383                         : PhysicalDeviceInfo->PhysicalDeviceState
2384                           == DAC960_V2_Device_Dead
2385                           ? "Dead"
2386                           : PhysicalDeviceInfo->PhysicalDeviceState
2387                             == DAC960_V2_Device_SuspectedDead
2388                             ? "Suspected-Dead"
2389                             : PhysicalDeviceInfo->PhysicalDeviceState
2390                               == DAC960_V2_Device_CommandedOffline
2391                               ? "Commanded-Offline"
2392                               : PhysicalDeviceInfo->PhysicalDeviceState
2393                                 == DAC960_V2_Device_Standby
2394                                 ? "Standby" : "Unknown"),
2395                  PhysicalDeviceInfo->ConfigurableDeviceSize);
2396      if (PhysicalDeviceInfo->ParityErrors == 0 &&
2397          PhysicalDeviceInfo->SoftErrors == 0 &&
2398          PhysicalDeviceInfo->HardErrors == 0 &&
2399          PhysicalDeviceInfo->MiscellaneousErrors == 0 &&
2400          PhysicalDeviceInfo->CommandTimeouts == 0 &&
2401          PhysicalDeviceInfo->Retries == 0 &&
2402          PhysicalDeviceInfo->Aborts == 0 &&
2403          PhysicalDeviceInfo->PredictedFailuresDetected == 0)
2404        continue;
2405      DAC960_Info("         Errors - Parity: %d, Soft: %d, "
2406                  "Hard: %d, Misc: %d\n", Controller,
2407                  PhysicalDeviceInfo->ParityErrors,
2408                  PhysicalDeviceInfo->SoftErrors,
2409                  PhysicalDeviceInfo->HardErrors,
2410                  PhysicalDeviceInfo->MiscellaneousErrors);
2411      DAC960_Info("                  Timeouts: %d, Retries: %d, "
2412                  "Aborts: %d, Predicted: %d\n", Controller,
2413                  PhysicalDeviceInfo->CommandTimeouts,
2414                  PhysicalDeviceInfo->Retries,
2415                  PhysicalDeviceInfo->Aborts,
2416                  PhysicalDeviceInfo->PredictedFailuresDetected);
2417    }
2418  DAC960_Info("  Logical Drives:\n", Controller);
2419  for (LogicalDriveNumber = 0;
2420       LogicalDriveNumber < DAC960_MaxLogicalDrives;
2421       LogicalDriveNumber++)
2422    {
2423      DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
2424        Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
2425      unsigned char *ReadCacheStatus[] = { "Read Cache Disabled",
2426                                           "Read Cache Enabled",
2427                                           "Read Ahead Enabled",
2428                                           "Intelligent Read Ahead Enabled",
2429                                           "-", "-", "-", "-" };
2430      unsigned char *WriteCacheStatus[] = { "Write Cache Disabled",
2431                                            "Logical Device Read Only",
2432                                            "Write Cache Enabled",
2433                                            "Intelligent Write Cache Enabled",
2434                                            "-", "-", "-", "-" };
2435      unsigned char *GeometryTranslation;
2436      if (LogicalDeviceInfo == NULL) continue;
2437      switch (LogicalDeviceInfo->DriveGeometry)
2438        {
2439        case DAC960_V2_Geometry_128_32:
2440          GeometryTranslation = "128/32";
2441          break;
2442        case DAC960_V2_Geometry_255_63:
2443          GeometryTranslation = "255/63";
2444          break;
2445        default:
2446          GeometryTranslation = "Invalid";
2447          DAC960_Error("Illegal Logical Device Geometry %d\n",
2448                       Controller, LogicalDeviceInfo->DriveGeometry);
2449          break;
2450        }
2451      DAC960_Info("    /dev/rd/c%dd%d: RAID-%d, %s, %u blocks\n",
2452                  Controller, Controller->ControllerNumber, LogicalDriveNumber,
2453                  LogicalDeviceInfo->RAIDLevel,
2454                  (LogicalDeviceInfo->LogicalDeviceState
2455                   == DAC960_V2_LogicalDevice_Online
2456                   ? "Online"
2457                   : LogicalDeviceInfo->LogicalDeviceState
2458                     == DAC960_V2_LogicalDevice_Critical
2459                     ? "Critical" : "Offline"),
2460                  LogicalDeviceInfo->ConfigurableDeviceSize);
2461      DAC960_Info("                  Logical Device %s, BIOS Geometry: %s\n",
2462                  Controller,
2463                  (LogicalDeviceInfo->LogicalDeviceControl
2464                                     .LogicalDeviceInitialized
2465                   ? "Initialized" : "Uninitialized"),
2466                  GeometryTranslation);
2467      if (LogicalDeviceInfo->StripeSize == 0)
2468        {
2469          if (LogicalDeviceInfo->CacheLineSize == 0)
2470            DAC960_Info("                  Stripe Size: N/A, "
2471                        "Segment Size: N/A\n", Controller);
2472          else
2473            DAC960_Info("                  Stripe Size: N/A, "
2474                        "Segment Size: %dKB\n", Controller,
2475                        1 << (LogicalDeviceInfo->CacheLineSize - 2));
2476        }
2477      else
2478        {
2479          if (LogicalDeviceInfo->CacheLineSize == 0)
2480            DAC960_Info("                  Stripe Size: %dKB, "
2481                        "Segment Size: N/A\n", Controller,
2482                        1 << (LogicalDeviceInfo->StripeSize - 2));
2483          else
2484            DAC960_Info("                  Stripe Size: %dKB, "
2485                        "Segment Size: %dKB\n", Controller,
2486                        1 << (LogicalDeviceInfo->StripeSize - 2),
2487                        1 << (LogicalDeviceInfo->CacheLineSize - 2));
2488        }
2489      DAC960_Info("                  %s, %s\n", Controller,
2490                  ReadCacheStatus[
2491                    LogicalDeviceInfo->LogicalDeviceControl.ReadCache],
2492                  WriteCacheStatus[
2493                    LogicalDeviceInfo->LogicalDeviceControl.WriteCache]);
2494      if (LogicalDeviceInfo->SoftErrors > 0 ||
2495          LogicalDeviceInfo->CommandsFailed > 0 ||
2496          LogicalDeviceInfo->DeferredWriteErrors)
2497        DAC960_Info("                  Errors - Soft: %d, Failed: %d, "
2498                    "Deferred Write: %d\n", Controller,
2499                    LogicalDeviceInfo->SoftErrors,
2500                    LogicalDeviceInfo->CommandsFailed,
2501                    LogicalDeviceInfo->DeferredWriteErrors);
2502
2503    }
2504  return true;
2505}
2506
2507/*
2508  DAC960_RegisterBlockDevice registers the Block Device structures
2509  associated with Controller.
2510*/
2511
2512static bool DAC960_RegisterBlockDevice(DAC960_Controller_T *Controller)
2513{
2514  int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
2515  int n;
2516
2517  /*
2518    Register the Block Device Major Number for this DAC960 Controller.
2519  */
2520  if (register_blkdev(MajorNumber, "dac960") < 0)
2521      return false;
2522
2523  for (n = 0; n < DAC960_MaxLogicalDrives; n++) {
2524        struct gendisk *disk = Controller->disks[n];
2525        struct request_queue *RequestQueue;
2526
2527        /* for now, let all request queues share controller's lock */
2528        RequestQueue = blk_init_queue(DAC960_RequestFunction,&Controller->queue_lock);
2529        if (!RequestQueue) {
2530                printk("DAC960: failure to allocate request queue\n");
2531                continue;
2532        }
2533        Controller->RequestQueue[n] = RequestQueue;
2534        blk_queue_bounce_limit(RequestQueue, Controller->BounceBufferLimit);
2535        RequestQueue->queuedata = Controller;
2536        blk_queue_max_hw_segments(RequestQueue, Controller->DriverScatterGatherLimit);
2537        blk_queue_max_phys_segments(RequestQueue, Controller->DriverScatterGatherLimit);
2538        blk_queue_max_sectors(RequestQueue, Controller->MaxBlocksPerCommand);
2539        disk->queue = RequestQueue;
2540        sprintf(disk->disk_name, "rd/c%dd%d", Controller->ControllerNumber, n);
2541        disk->major = MajorNumber;
2542        disk->first_minor = n << DAC960_MaxPartitionsBits;
2543        disk->fops = &DAC960_BlockDeviceOperations;
2544   }
2545  /*
2546    Indicate the Block Device Registration completed successfully,
2547  */
2548  return true;
2549}
2550
2551
2552/*
2553  DAC960_UnregisterBlockDevice unregisters the Block Device structures
2554  associated with Controller.
2555*/
2556
2557static void DAC960_UnregisterBlockDevice(DAC960_Controller_T *Controller)
2558{
2559  int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
2560  int disk;
2561
2562  /* does order matter when deleting gendisk and cleanup in request queue? */
2563  for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
2564        del_gendisk(Controller->disks[disk]);
2565        blk_cleanup_queue(Controller->RequestQueue[disk]);
2566        Controller->RequestQueue[disk] = NULL;
2567  }
2568
2569  /*
2570    Unregister the Block Device Major Number for this DAC960 Controller.
2571  */
2572  unregister_blkdev(MajorNumber, "dac960");
2573}
2574
2575/*
2576  DAC960_ComputeGenericDiskInfo computes the values for the Generic Disk
2577  Information Partition Sector Counts and Block Sizes.
2578*/
2579
2580static void DAC960_ComputeGenericDiskInfo(DAC960_Controller_T *Controller)
2581{
2582        int disk;
2583        for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++)
2584                set_capacity(Controller->disks[disk], disk_size(Controller, disk));
2585}
2586
2587/*
2588  DAC960_ReportErrorStatus reports Controller BIOS Messages passed through
2589  the Error Status Register when the driver performs the BIOS handshaking.
2590  It returns true for fatal errors and false otherwise.
2591*/
2592
2593static bool DAC960_ReportErrorStatus(DAC960_Controller_T *Controller,
2594                                        unsigned char ErrorStatus,
2595                                        unsigned char Parameter0,
2596                                        unsigned char Parameter1)
2597{
2598  switch (ErrorStatus)
2599    {
2600    case 0x00:
2601      DAC960_Notice("Physical Device %d:%d Not Responding\n",
2602                    Controller, Parameter1, Parameter0);
2603      break;
2604    case 0x08:
2605      if (Controller->DriveSpinUpMessageDisplayed) break;
2606      DAC960_Notice("Spinning Up Drives\n", Controller);
2607      Controller->DriveSpinUpMessageDisplayed = true;
2608      break;
2609    case 0x30:
2610      DAC960_Notice("Configuration Checksum Error\n", Controller);
2611      break;
2612    case 0x60:
2613      DAC960_Notice("Mirror Race Recovery Failed\n", Controller);
2614      break;
2615    case 0x70:
2616      DAC960_Notice("Mirror Race Recovery In Progress\n", Controller);
2617      break;
2618    case 0x90:
2619      DAC960_Notice("Physical Device %d:%d COD Mismatch\n",
2620                    Controller, Parameter1, Parameter0);
2621      break;
2622    case 0xA0:
2623      DAC960_Notice("Logical Drive Installation Aborted\n", Controller);
2624      break;
2625    case 0xB0:
2626      DAC960_Notice("Mirror Race On A Critical Logical Drive\n", Controller);
2627      break;
2628    case 0xD0:
2629      DAC960_Notice("New Controller Configuration Found\n", Controller);
2630      break;
2631    case 0xF0:
2632      DAC960_Error("Fatal Memory Parity Error for Controller at\n", Controller);
2633      return true;
2634    default:
2635      DAC960_Error("Unknown Initialization Error %02X for Controller at\n",
2636                   Controller, ErrorStatus);
2637      return true;
2638    }
2639  return false;
2640}
2641
2642
2643/*
2644 * DAC960_DetectCleanup releases the resources that were allocated
2645 * during DAC960_DetectController().  DAC960_DetectController can
2646 * has several internal failure points, so not ALL resources may 
2647 * have been allocated.  It's important to free only
2648 * resources that HAVE been allocated.  The code below always
2649 * tests that the resource has been allocated before attempting to
2650 * free it.
2651 */
2652static void DAC960_DetectCleanup(DAC960_Controller_T *Controller)
2653{
2654  int i;
2655
2656  /* Free the memory mailbox, status, and related structures */
2657  free_dma_loaf(Controller->PCIDevice, &Controller->DmaPages);
2658  if (Controller->MemoryMappedAddress) {
2659        switch(Controller->HardwareType)
2660        {
2661                case DAC960_GEM_Controller:
2662                        DAC960_GEM_DisableInterrupts(Controller->BaseAddress);
2663                        break;
2664                case DAC960_BA_Controller:
2665                        DAC960_BA_DisableInterrupts(Controller->BaseAddress);
2666                        break;
2667                case DAC960_LP_Controller:
2668                        DAC960_LP_DisableInterrupts(Controller->BaseAddress);
2669                        break;
2670                case DAC960_LA_Controller:
2671                        DAC960_LA_DisableInterrupts(Controller->BaseAddress);
2672                        break;
2673                case DAC960_PG_Controller:
2674                        DAC960_PG_DisableInterrupts(Controller->BaseAddress);
2675                        break;
2676                case DAC960_PD_Controller:
2677                        DAC960_PD_DisableInterrupts(Controller->BaseAddress);
2678                        break;
2679                case DAC960_P_Controller:
2680                        DAC960_PD_DisableInterrupts(Controller->BaseAddress);
2681                        break;
2682        }
2683        iounmap(Controller->MemoryMappedAddress);
2684  }
2685  if (Controller->IRQ_Channel)
2686        free_irq(Controller->IRQ_Channel, Controller);
2687  if (Controller->IO_Address)
2688        release_region(Controller->IO_Address, 0x80);
2689  pci_disable_device(Controller->PCIDevice);
2690  for (i = 0; (i < DAC960_MaxLogicalDrives) && Controller->disks[i]; i++)
2691       put_disk(Controller->disks[i]);
2692  DAC960_Controllers[Controller->ControllerNumber] = NULL;
2693  kfree(Controller);
2694}
2695
2696
2697/*
2698  DAC960_DetectController detects Mylex DAC960/AcceleRAID/eXtremeRAID
2699  PCI RAID Controllers by interrogating the PCI Configuration Space for
2700  Controller Type.
2701*/
2702
2703static DAC960_Controller_T * 
2704DAC960_DetectController(struct pci_dev *PCI_Device,
2705                        const struct pci_device_id *entry)
2706{
2707  struct DAC960_privdata *privdata =
2708                (struct DAC960_privdata *)entry->driver_data;
2709  irq_handler_t InterruptHandler = privdata->InterruptHandler;
2710  unsigned int MemoryWindowSize = privdata->MemoryWindowSize;
2711  DAC960_Controller_T *Controller = NULL;
2712  unsigned char DeviceFunction = PCI_Device->devfn;
2713  unsigned char ErrorStatus, Parameter0, Parameter1;
2714  unsigned int IRQ_Channel;
2715  void __iomem *BaseAddress;
2716  int i;
2717
2718  Controller = kzalloc(sizeof(DAC960_Controller_T), GFP_ATOMIC);
2719  if (Controller == NULL) {
2720        DAC960_Error("Unable to allocate Controller structure for "
2721                       "Controller at\n", NULL);
2722        return NULL;
2723  }
2724  Controller->ControllerNumber = DAC960_ControllerCount;
2725  DAC960_Controllers[DAC960_ControllerCount++] = Controller;
2726  Controller->Bus = PCI_Device->bus->number;
2727  Controller->FirmwareType = privdata->FirmwareType;
2728  Controller->HardwareType = privdata->HardwareType;
2729  Controller->Device = DeviceFunction >> 3;
2730  Controller->Function = DeviceFunction & 0x7;
2731  Controller->PCIDevice = PCI_Device;
2732  strcpy(Controller->FullModelName, "DAC960");
2733
2734  if (pci_enable_device(PCI_Device))
2735        goto Failure;
2736
2737  switch (Controller->HardwareType)
2738  {
2739        case DAC960_GEM_Controller:
2740          Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2741          break;
2742        case DAC960_BA_Controller:
2743          Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2744          break;
2745        case DAC960_LP_Controller:
2746          Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2747          break;
2748        case DAC960_LA_Controller:
2749          Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2750          break;
2751        case DAC960_PG_Controller:
2752          Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2753          break;
2754        case DAC960_PD_Controller:
2755          Controller->IO_Address = pci_resource_start(PCI_Device, 0);
2756          Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
2757          break;
2758        case DAC960_P_Controller:
2759          Controller->IO_Address = pci_resource_start(PCI_Device, 0);
2760          Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
2761          break;
2762  }
2763
2764  pci_set_drvdata(PCI_Device, (void *)((long)Controller->ControllerNumber));
2765  for (i = 0; i < DAC960_MaxLogicalDrives; i++) {
2766        Controller->disks[i] = alloc_disk(1<<DAC960_MaxPartitionsBits);
2767        if (!Controller->disks[i])
2768                goto Failure;
2769        Controller->disks[i]->private_data = (void *)((long)i);
2770  }
2771  init_waitqueue_head(&Controller->CommandWaitQueue);
2772  init_waitqueue_head(&Controller->HealthStatusWaitQueue);
2773  spin_lock_init(&Controller->queue_lock);
2774  DAC960_AnnounceDriver(Controller);
2775  /*
2776    Map the Controller Register Window.
2777  */
2778 if (MemoryWindowSize < PAGE_SIZE)
2779        MemoryWindowSize = PAGE_SIZE;
2780  Controller->MemoryMappedAddress =
2781        ioremap_nocache(Controller->PCI_Address & PAGE_MASK, MemoryWindowSize);
2782  Controller->BaseAddress =
2783        Controller->MemoryMappedAddress + (Controller->PCI_Address & ~PAGE_MASK);
2784  if (Controller->MemoryMappedAddress == NULL)
2785  {
2786          DAC960_Error("Unable to map Controller Register Window for "
2787                       "Controller at\n", Controller);
2788          goto Failure;
2789  }
2790  BaseAddress = Controller->BaseAddress;
2791  switch (Controller->HardwareType)
2792  {
2793        case DAC960_GEM_Controller:
2794          DAC960_GEM_DisableInterrupts(BaseAddress);
2795          DAC960_GEM_AcknowledgeHardwareMailboxStatus(BaseAddress);
2796          udelay(1000);
2797          while (DAC960_GEM_InitializationInProgressP(BaseAddress))
2798            {
2799              if (DAC960_GEM_ReadErrorStatus(BaseAddress, &ErrorStatus,
2800                                            &Parameter0, &Parameter1) &&
2801                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2802                                           Parameter0, Parameter1))
2803                goto Failure;
2804              udelay(10);
2805            }
2806          if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2807            {
2808              DAC960_Error("Unable to Enable Memory Mailbox Interface "
2809                           "for Controller at\n", Controller);
2810              goto Failure;
2811            }
2812          DAC960_GEM_EnableInterrupts(BaseAddress);
2813          Controller->QueueCommand = DAC960_GEM_QueueCommand;
2814          Controller->ReadControllerConfiguration =
2815            DAC960_V2_ReadControllerConfiguration;
2816          Controller->ReadDeviceConfiguration =
2817            DAC960_V2_ReadDeviceConfiguration;
2818          Controller->ReportDeviceConfiguration =
2819            DAC960_V2_ReportDeviceConfiguration;
2820          Controller->QueueReadWriteCommand =
2821            DAC960_V2_QueueReadWriteCommand;
2822          break;
2823        case DAC960_BA_Controller:
2824          DAC960_BA_DisableInterrupts(BaseAddress);
2825          DAC960_BA_AcknowledgeHardwareMailboxStatus(BaseAddress);
2826          udelay(1000);
2827          while (DAC960_BA_InitializationInProgressP(BaseAddress))
2828            {
2829              if (DAC960_BA_ReadErrorStatus(BaseAddress, &ErrorStatus,
2830                                            &Parameter0, &Parameter1) &&
2831                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2832                                           Parameter0, Parameter1))
2833                goto Failure;
2834              udelay(10);
2835            }
2836          if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2837            {
2838              DAC960_Error("Unable to Enable Memory Mailbox Interface "
2839                           "for Controller at\n", Controller);
2840              goto Failure;
2841            }
2842          DAC960_BA_EnableInterrupts(BaseAddress);
2843          Controller->QueueCommand = DAC960_BA_QueueCommand;
2844          Controller->ReadControllerConfiguration =
2845            DAC960_V2_ReadControllerConfiguration;
2846          Controller->ReadDeviceConfiguration =
2847            DAC960_V2_ReadDeviceConfiguration;
2848          Controller->ReportDeviceConfiguration =
2849            DAC960_V2_ReportDeviceConfiguration;
2850          Controller->QueueReadWriteCommand =
2851            DAC960_V2_QueueReadWriteCommand;
2852          break;
2853        case DAC960_LP_Controller:
2854          DAC960_LP_DisableInterrupts(BaseAddress);
2855          DAC960_LP_AcknowledgeHardwareMailboxStatus(BaseAddress);
2856          udelay(1000);
2857          while (DAC960_LP_InitializationInProgressP(BaseAddress))
2858            {
2859              if (DAC960_LP_ReadErrorStatus(BaseAddress, &ErrorStatus,
2860                                            &Parameter0, &Parameter1) &&
2861                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2862                                           Parameter0, Parameter1))
2863                goto Failure;
2864              udelay(10);
2865            }
2866          if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2867            {
2868              DAC960_Error("Unable to Enable Memory Mailbox Interface "
2869                           "for Controller at\n", Controller);
2870              goto Failure;
2871            }
2872          DAC960_LP_EnableInterrupts(BaseAddress);
2873          Controller->QueueCommand = DAC960_LP_QueueCommand;
2874          Controller->ReadControllerConfiguration =
2875            DAC960_V2_ReadControllerConfiguration;
2876          Controller->ReadDeviceConfiguration =
2877            DAC960_V2_ReadDeviceConfiguration;
2878          Controller->ReportDeviceConfiguration =
2879            DAC960_V2_ReportDeviceConfiguration;
2880          Controller->QueueReadWriteCommand =
2881            DAC960_V2_QueueReadWriteCommand;
2882          break;
2883        case DAC960_LA_Controller:
2884          DAC960_LA_DisableInterrupts(BaseAddress);
2885          DAC960_LA_AcknowledgeHardwareMailboxStatus(BaseAddress);
2886          udelay(1000);
2887          while (DAC960_LA_InitializationInProgressP(BaseAddress))
2888            {
2889              if (DAC960_LA_ReadErrorStatus(BaseAddress, &ErrorStatus,
2890                                            &Parameter0, &Parameter1) &&
2891                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2892                                           Parameter0, Parameter1))
2893                goto Failure;
2894              udelay(10);
2895            }
2896          if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2897            {
2898              DAC960_Error("Unable to Enable Memory Mailbox Interface "
2899                           "for Controller at\n", Controller);
2900              goto Failure;
2901            }
2902          DAC960_LA_EnableInterrupts(BaseAddress);
2903          if (Controller->V1.DualModeMemoryMailboxInterface)
2904            Controller->QueueCommand = DAC960_LA_QueueCommandDualMode;
2905          else Controller->QueueCommand = DAC960_LA_QueueCommandSingleMode;
2906          Controller->ReadControllerConfiguration =
2907            DAC960_V1_ReadControllerConfiguration;
2908          Controller->ReadDeviceConfiguration =
2909            DAC960_V1_ReadDeviceConfiguration;
2910          Controller->ReportDeviceConfiguration =
2911            DAC960_V1_ReportDeviceConfiguration;
2912          Controller->QueueReadWriteCommand =
2913            DAC960_V1_QueueReadWriteCommand;
2914          break;
2915        case DAC960_PG_Controller:
2916          DAC960_PG_DisableInterrupts(BaseAddress);
2917          DAC960_PG_AcknowledgeHardwareMailboxStatus(BaseAddress);
2918          udelay(1000);
2919          while (DAC960_PG_InitializationInProgressP(BaseAddress))
2920            {
2921              if (DAC960_PG_ReadErrorStatus(BaseAddress, &ErrorStatus,
2922                                            &Parameter0, &Parameter1) &&
2923                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2924                                           Parameter0, Parameter1))
2925                goto Failure;
2926              udelay(10);
2927            }
2928          if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2929            {
2930              DAC960_Error("Unable to Enable Memory Mailbox Interface "
2931                           "for Controller at\n", Controller);
2932              goto Failure;
2933            }
2934          DAC960_PG_EnableInterrupts(BaseAddress);
2935          if (Controller->V1.DualModeMemoryMailboxInterface)
2936            Controller->QueueCommand = DAC960_PG_QueueCommandDualMode;
2937          else Controller->QueueCommand = DAC960_PG_QueueCommandSingleMode;
2938          Controller->ReadControllerConfiguration =
2939            DAC960_V1_ReadControllerConfiguration;
2940          Controller->ReadDeviceConfiguration =
2941            DAC960_V1_ReadDeviceConfiguration;
2942          Controller->ReportDeviceConfiguration =
2943            DAC960_V1_ReportDeviceConfiguration;
2944          Controller->QueueReadWriteCommand =
2945            DAC960_V1_QueueReadWriteCommand;
2946          break;
2947        case DAC960_PD_Controller:
2948          if (!request_region(Controller->IO_Address, 0x80,
2949                              Controller->FullModelName)) {
2950                DAC960_Error("IO port 0x%d busy for Controller at\n",
2951                             Controller, Controller->IO_Address);
2952                goto Failure;
2953          }
2954          DAC960_PD_DisableInterrupts(BaseAddress);
2955          DAC960_PD_AcknowledgeStatus(BaseAddress);
2956          udelay(1000);
2957          while (DAC960_PD_InitializationInProgressP(BaseAddress))
2958            {
2959              if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
2960                                            &Parameter0, &Parameter1) &&
2961                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2962                                           Parameter0, Parameter1))
2963                goto Failure;
2964              udelay(10);
2965            }
2966          if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2967            {
2968              DAC960_Error("Unable to allocate DMA mapped memory "
2969                           "for Controller at\n", Controller);
2970              goto Failure;
2971            }
2972          DAC960_PD_EnableInterrupts(BaseAddress);
2973          Controller->QueueCommand = DAC960_PD_QueueCommand;
2974          Controller->ReadControllerConfiguration =
2975            DAC960_V1_ReadControllerConfiguration;
2976          Controller->ReadDeviceConfiguration =
2977            DAC960_V1_ReadDeviceConfiguration;
2978          Controller->ReportDeviceConfiguration =
2979            DAC960_V1_ReportDeviceConfiguration;
2980          Controller->QueueReadWriteCommand =
2981            DAC960_V1_QueueReadWriteCommand;
2982          break;
2983        case DAC960_P_Controller:
2984          if (!request_region(Controller->IO_Address, 0x80,
2985                              Controller->FullModelName)){
2986                DAC960_Error("IO port 0x%d busy for Controller at\n",
2987                             Controller, Controller->IO_Address);
2988                goto Failure;
2989          }
2990          DAC960_PD_DisableInterrupts(BaseAddress);
2991          DAC960_PD_AcknowledgeStatus(BaseAddress);
2992          udelay(1000);
2993          while (DAC960_PD_InitializationInProgressP(BaseAddress))
2994            {
2995              if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
2996                                            &Parameter0, &Parameter1) &&
2997                  DAC960_ReportErrorStatus(Controller, ErrorStatus,
2998                                           Parameter0, Parameter1))
2999                goto Failure;
3000              udelay(10);
3001            }
3002          if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
3003            {
3004              DAC960_Error("Unable to allocate DMA mapped memory"
3005                           "for Controller at\n", Controller);
3006              goto Failure;
3007            }
3008          DAC960_PD_EnableInterrupts(BaseAddress);
3009          Controller->QueueCommand = DAC960_P_QueueCommand;
3010          Controller->ReadControllerConfiguration =
3011            DAC960_V1_ReadControllerConfiguration;
3012          Controller->ReadDeviceConfiguration =
3013            DAC960_V1_ReadDeviceConfiguration;
3014          Controller->ReportDeviceConfiguration =
3015            DAC960_V1_ReportDeviceConfiguration;
3016          Controller->QueueReadWriteCommand =
3017            DAC960_V1_QueueReadWriteCommand;
3018          break;
3019  }
3020  /*
3021     Acquire shared access to the IRQ Channel.
3022  */
3023  IRQ_Channel = PCI_Device->irq;
3024  if (request_irq(IRQ_Channel, InterruptHandler, IRQF_SHARED,
3025                      Controller->FullModelName, Controller) < 0)
3026  {
3027        DAC960_Error("Unable to acquire IRQ Channel %d for Controller at\n",
3028                       Controller, Controller->IRQ_Channel);
3029        goto Failure;
3030  }
3031  Controller->IRQ_Channel = IRQ_Channel;
3032  Controller->InitialCommand.CommandIdentifier = 1;
3033  Controller->InitialCommand.Controller = Controller;
3034  Controller->Commands[0] = &Controller->InitialCommand;
3035  Controller->FreeCommands = &Controller->InitialCommand;
3036  return Controller;
3037      
3038Failure:
3039  if (Controller->IO_Address == 0)
3040        DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
3041                     "PCI Address 0x%X\n", Controller,
3042                     Controller->Bus, Controller->Device,
3043                     Controller->Function, Controller->PCI_Address);
3044  else
3045        DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
3046                        "0x%X PCI Address 0x%X\n", Controller,
3047                        Controller->Bus, Controller->Device,
3048                        Controller->Function, Controller->IO_Address,
3049                        Controller->PCI_Address);
3050  DAC960_DetectCleanup(Controller);
3051  DAC960_ControllerCount--;
3052  return NULL;
3053}
3054
3055/*
3056  DAC960_InitializeController initializes Controller.
3057*/
3058
3059static bool 
3060DAC960_InitializeController(DAC960_Controller_T *Controller)
3061{
3062  if (DAC960_ReadControllerConfiguration(Controller) &&
3063      DAC960_ReportControllerConfiguration(Controller) &&
3064      DAC960_CreateAuxiliaryStructures(Controller) &&
3065      DAC960_ReadDeviceConfiguration(Controller) &&
3066      DAC960_ReportDeviceConfiguration(Controller) &&
3067      DAC960_RegisterBlockDevice(Controller))
3068    {
3069      /*
3070        Initialize the Monitoring Timer.
3071      */
3072      init_timer(&Controller->MonitoringTimer);
3073      Controller->MonitoringTimer.expires =
3074        jiffies + DAC960_MonitoringTimerInterval;
3075      Controller->MonitoringTimer.data = (unsigned long) Controller;
3076      Controller->MonitoringTimer.function = DAC960_MonitoringTimerFunction;
3077      add_timer(&Controller->MonitoringTimer);
3078      Controller->ControllerInitialized = true;
3079      return true;
3080    }
3081  return false;
3082}
3083
3084
3085/*
3086  DAC960_FinalizeController finalizes Controller.
3087*/
3088
3089static void DAC960_FinalizeController(DAC960_Controller_T *Controller)
3090{
3091  if (Controller->ControllerInitialized)
3092    {
3093      unsigned long flags;
3094
3095      /*
3096       * Acquiring and releasing lock here eliminates
3097       * a very low probability race.
3098       *
3099       * The code below allocates controller command structures
3100       * from the free list without holding the controller lock.
3101       * This is safe assuming there is no other activity on
3102       * the controller at the time.
3103       * 
3104       * But, there might be a monitoring command still
3105       * in progress.  Setting the Shutdown flag while holding
3106       * the lock ensures that there is no monitoring command
3107       * in the interrupt handler currently, and any monitoring
3108       * commands that complete from this time on will NOT return
3109       * their command structure to the free list.
3110       */
3111
3112      spin_lock_irqsave(&Controller->queue_lock, flags);
3113      Controller->ShutdownMonitoringTimer = 1;
3114      spin_unlock_irqrestore(&Controller->queue_lock, flags);
3115
3116      del_timer_sync(&Controller->MonitoringTimer);
3117      if (Controller->FirmwareType == DAC960_V1_Controller)
3118        {
3119          DAC960_Notice("Flushing Cache...", Controller);
3120          DAC960_V1_ExecuteType3(Controller, DAC960_V1_Flush, 0);
3121          DAC960_Notice("done\n", Controller);
3122
3123          if (Controller->HardwareType == DAC960_PD_Controller)
3124              release_region(Controller->IO_Address, 0x80);
3125        }
3126      else
3127        {
3128          DAC960_Notice("Flushing Cache...", Controller);
3129          DAC960_V2_DeviceOperation(Controller, DAC960_V2_PauseDevice,
3130                                    DAC960_V2_RAID_Controller);
3131          DAC960_Notice("done\n", Controller);
3132        }
3133    }
3134  DAC960_UnregisterBlockDevice(Controller);
3135  DAC960_DestroyAuxiliaryStructures(Controller);
3136  DAC960_DestroyProcEntries(Controller);
3137  DAC960_DetectCleanup(Controller);
3138}
3139
3140
3141/*
3142  DAC960_Probe verifies controller's existence and
3143  initializes the DAC960 Driver for that controller.
3144*/
3145
3146static int 
3147DAC960_Probe(struct pci_dev *dev, const struct pci_device_id *entry)
3148{
3149  int disk;
3150  DAC960_Controller_T *Controller;
3151
3152  if (DAC960_ControllerCount == DAC960_MaxControllers)
3153  {
3154        DAC960_Error("More than %d DAC960 Controllers detected - "
3155                       "ignoring from Controller at\n",
3156                       NULL, DAC960_MaxControllers);
3157        return -ENODEV;
3158  }
3159
3160  Controller = DAC960_DetectController(dev, entry);
3161  if (!Controller)
3162        return -ENODEV;
3163
3164  if (!DAC960_InitializeController(Controller)) {
3165        DAC960_FinalizeController(Controller);
3166        return -ENODEV;
3167  }
3168
3169  for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
3170        set_capacity(Controller->disks[disk], disk_size(Controller, disk));
3171        add_disk(Controller->disks[disk]);
3172  }
3173  DAC960_CreateProcEntries(Controller);
3174  return 0;
3175}
3176
3177
3178/*
3179  DAC960_Finalize finalizes the DAC960 Driver.
3180*/
3181
3182static void DAC960_Remove(struct pci_dev *PCI_Device)
3183{
3184  int Controller_Number = (long)pci_get_drvdata(PCI_Device);
3185  DAC960_Controller_T *Controller = DAC960_Controllers[Controller_Number];
3186  if (Controller != NULL)
3187      DAC960_FinalizeController(Controller);
3188}
3189
3190
3191/*
3192  DAC960_V1_QueueReadWriteCommand prepares and queues a Read/Write Command for
3193  DAC960 V1 Firmware Controllers.
3194*/
3195
3196static void DAC960_V1_QueueReadWriteCommand(DAC960_Command_T *Command)
3197{
3198  DAC960_Controller_T *Controller = Command->Controller;
3199  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
3200  DAC960_V1_ScatterGatherSegment_T *ScatterGatherList =
3201                                        Command->V1.ScatterGatherList;
3202  struct scatterlist *ScatterList = Command->V1.ScatterList;
3203
3204  DAC960_V1_ClearCommand(Command);
3205
3206  if (Command->SegmentCount == 1)
3207    {
3208      if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3209        CommandMailbox->Type5.CommandOpcode = DAC960_V1_Read;
3210      else 
3211        CommandMailbox->Type5.CommandOpcode = DAC960_V1_Write;
3212
3213      CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
3214      CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
3215      CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
3216      CommandMailbox->Type5.BusAddress =
3217                        (DAC960_BusAddress32_T)sg_dma_address(ScatterList);     
3218    }
3219  else
3220    {
3221      int i;
3222
3223      if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3224        CommandMailbox->Type5.CommandOpcode = DAC960_V1_ReadWithScatterGather;
3225      else
3226        CommandMailbox->Type5.CommandOpcode = DAC960_V1_WriteWithScatterGather;
3227
3228      CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
3229      CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
3230      CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
3231      CommandMailbox->Type5.BusAddress = Command->V1.ScatterGatherListDMA;
3232
3233      CommandMailbox->Type5.ScatterGatherCount = Command->SegmentCount;
3234
3235      for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
3236                ScatterGatherList->SegmentDataPointer =
3237                        (DAC960_BusAddress32_T)sg_dma_address(ScatterList);
3238                ScatterGatherList->SegmentByteCount =
3239                        (DAC960_ByteCount32_T)sg_dma_len(ScatterList);
3240      }
3241    }
3242  DAC960_QueueCommand(Command);
3243}
3244
3245
3246/*
3247  DAC960_V2_QueueReadWriteCommand prepares and queues a Read/Write Command for
3248  DAC960 V2 Firmware Controllers.
3249*/
3250
3251static void DAC960_V2_QueueReadWriteCommand(DAC960_Command_T *Command)
3252{
3253  DAC960_Controller_T *Controller = Command->Controller;
3254  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
3255  struct scatterlist *ScatterList = Command->V2.ScatterList;
3256
3257  DAC960_V2_ClearCommand(Command);
3258
3259  CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10;
3260  CommandMailbox->SCSI_10.CommandControlBits.DataTransferControllerToHost =
3261    (Command->DmaDirection == PCI_DMA_FROMDEVICE);
3262  CommandMailbox->SCSI_10.DataTransferSize =
3263    Command->BlockCount << DAC960_BlockSizeBits;
3264  CommandMailbox->SCSI_10.RequestSenseBusAddress = Command->V2.RequestSenseDMA;
3265  CommandMailbox->SCSI_10.PhysicalDevice =
3266    Controller->V2.LogicalDriveToVirtualDevice[Command->LogicalDriveNumber];
3267  CommandMailbox->SCSI_10.RequestSenseSize = sizeof(DAC960_SCSI_RequestSense_T);
3268  CommandMailbox->SCSI_10.CDBLength = 10;
3269  CommandMailbox->SCSI_10.SCSI_CDB[0] =
3270    (Command->DmaDirection == PCI_DMA_FROMDEVICE ? 0x28 : 0x2A);
3271  CommandMailbox->SCSI_10.SCSI_CDB[2] = Command->BlockNumber >> 24;
3272  CommandMailbox->SCSI_10.SCSI_CDB[3] = Command->BlockNumber >> 16;
3273  CommandMailbox->SCSI_10.SCSI_CDB[4] = Command->BlockNumber >> 8;
3274  CommandMailbox->SCSI_10.SCSI_CDB[5] = Command->BlockNumber;
3275  CommandMailbox->SCSI_10.SCSI_CDB[7] = Command->BlockCount >> 8;
3276  CommandMailbox->SCSI_10.SCSI_CDB[8] = Command->BlockCount;
3277
3278  if (Command->SegmentCount == 1)
3279    {
3280      CommandMailbox->SCSI_10.DataTransferMemoryAddress
3281                             .ScatterGatherSegments[0]
3282                             .SegmentDataPointer =
3283        (DAC960_BusAddress64_T)sg_dma_address(ScatterList);
3284      CommandMailbox->SCSI_10.DataTransferMemoryAddress
3285                             .ScatterGatherSegments[0]
3286                             .SegmentByteCount =
3287        CommandMailbox->SCSI_10.DataTransferSize;
3288    }
3289  else
3290    {
3291      DAC960_V2_ScatterGatherSegment_T *ScatterGatherList;
3292      int i;
3293
3294      if (Command->SegmentCount > 2)
3295        {
3296          ScatterGatherList = Command->V2.ScatterGatherList;
3297          CommandMailbox->SCSI_10.CommandControlBits
3298                         .AdditionalScatterGatherListMemory = true;
3299          CommandMailbox->SCSI_10.DataTransferMemoryAddress
3300                .ExtendedScatterGather.ScatterGatherList0Length = Command->SegmentCount;
3301          CommandMailbox->SCSI_10.DataTransferMemoryAddress
3302                         .ExtendedScatterGather.ScatterGatherList0Address =
3303            Command->V2.ScatterGatherListDMA;
3304        }
3305      else
3306        ScatterGatherList = CommandMailbox->SCSI_10.DataTransferMemoryAddress
3307                                 .ScatterGatherSegments;
3308
3309      for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
3310                ScatterGatherList->SegmentDataPointer =
3311                        (DAC960_BusAddress64_T)sg_dma_address(ScatterList);
3312                ScatterGatherList->SegmentByteCount =
3313                        (DAC960_ByteCount64_T)sg_dma_len(ScatterList);
3314      }
3315    }
3316  DAC960_QueueCommand(Command);
3317}
3318
3319
3320static int DAC960_process_queue(DAC960_Controller_T *Controller, struct request_queue *req_q)
3321{
3322        struct request *Request;
3323        DAC960_Command_T *Command;
3324
3325   while(1) {
3326        Request = blk_peek_request(req_q);
3327        if (!Request)
3328                return 1;
3329
3330        Command = DAC960_AllocateCommand(Controller);
3331        if (Command == NULL)
3332                return 0;
3333
3334        if (rq_data_dir(Request) == READ) {
3335                Command->DmaDirection = PCI_DMA_FROMDEVICE;
3336                Command->CommandType = DAC960_ReadCommand;
3337        } else {
3338                Command->DmaDirection = PCI_DMA_TODEVICE;
3339                Command->CommandType = DAC960_WriteCommand;
3340        }
3341        Command->Completion = Request->end_io_data;
3342        Command->LogicalDriveNumber = (long)Request->rq_disk->private_data;
3343        Command->BlockNumber = blk_rq_pos(Request);
3344        Command->BlockCount = blk_rq_sectors(Request);
3345        Command->Request = Request;
3346        blk_start_request(Request);
3347        Command->SegmentCount = blk_rq_map_sg(req_q,
3348                  Command->Request, Command->cmd_sglist);
3349        /* pci_map_sg MAY change the value of SegCount */
3350        Command->SegmentCount = pci_map_sg(Controller->PCIDevice, Command->cmd_sglist,
3351                 Command->SegmentCount, Command->DmaDirection);
3352
3353        DAC960_QueueReadWriteCommand(Command);
3354  }
3355}
3356
3357/*
3358  DAC960_ProcessRequest attempts to remove one I/O Request from Controller's
3359  I/O Request Queue and queues it to the Controller.  WaitForCommand is true if
3360  this function should wait for a Command to become available if necessary.
3361  This function returns true if an I/O Request was queued and false otherwise.
3362*/
3363static void DAC960_ProcessRequest(DAC960_Controller_T *controller)
3364{
3365        int i;
3366
3367        if (!controller->ControllerInitialized)
3368                return;
3369
3370        /* Do this better later! */
3371        for (i = controller->req_q_index; i < DAC960_MaxLogicalDrives; i++) {
3372                struct request_queue *req_q = controller->RequestQueue[i];
3373
3374                if (req_q == NULL)
3375                        continue;
3376
3377                if (!DAC960_process_queue(controller, req_q)) {
3378                        controller->req_q_index = i;
3379                        return;
3380                }
3381        }
3382
3383        if (controller->req_q_index == 0)
3384                return;
3385
3386        for (i = 0; i < controller->req_q_index; i++) {
3387                struct request_queue *req_q = controller->RequestQueue[i];
3388
3389                if (req_q == NULL)
3390                        continue;
3391
3392                if (!DAC960_process_queue(controller, req_q)) {
3393                        controller->req_q_index = i;
3394                        return;
3395                }
3396        }
3397}
3398
3399
3400/*
3401  DAC960_queue_partial_rw extracts one bio from the request already
3402  associated with argument command, and construct a new command block to retry I/O
3403  only on that bio.  Queue that command to the controller.
3404
3405  This function re-uses a previously-allocated Command,
3406        there is no failure mode from trying to allocate a command.
3407*/
3408
3409static void DAC960_queue_partial_rw(DAC960_Command_T *Command)
3410{
3411  DAC960_Controller_T *Controller = Command->Controller;
3412  struct request *Request = Command->Request;
3413  struct request_queue *req_q = Controller->RequestQueue[Command->LogicalDriveNumber];
3414
3415  if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3416    Command->CommandType = DAC960_ReadRetryCommand;
3417  else
3418    Command->CommandType = DAC960_WriteRetryCommand;
3419
3420  /*
3421   * We could be more efficient with these mapping requests
3422   * and map only the portions that we need.  But since this
3423   * code should almost never be called, just go with a
3424   * simple coding.
3425   */
3426  (void)blk_rq_map_sg(req_q, Command->Request, Command->cmd_sglist);
3427
3428  (void)pci_map_sg(Controller->PCIDevice, Command->cmd_sglist, 1, Command->DmaDirection);
3429  /*
3430   * Resubmitting the request sector at a time is really tedious.
3431   * But, this should almost never happen.  So, we're willing to pay
3432   * this price so that in the end, as much of the transfer is completed
3433   * successfully as possible.
3434   */
3435  Command->SegmentCount = 1;
3436  Command->BlockNumber = blk_rq_pos(Request);
3437  Command->BlockCount = 1;
3438  DAC960_QueueReadWriteCommand(Command);
3439  return;
3440}
3441
3442/*
3443  DAC960_RequestFunction is the I/O Request Function for DAC960 Controllers.
3444*/
3445
3446static void DAC960_RequestFunction(struct request_queue *RequestQueue)
3447{
3448        DAC960_ProcessRequest(RequestQueue->queuedata);
3449}
3450
3451/*
3452  DAC960_ProcessCompletedBuffer performs completion processing for an
3453  individual Buffer.
3454*/
3455
3456static inline bool DAC960_ProcessCompletedRequest(DAC960_Command_T *Command,
3457                                                 bool SuccessfulIO)
3458{
3459        struct request *Request = Command->Request;
3460        int Error = SuccessfulIO ? 0 : -EIO;
3461
3462        pci_unmap_sg(Command->Controller->PCIDevice, Command->cmd_sglist,
3463                Command->SegmentCount, Command->DmaDirection);
3464
3465         if (!__blk_end_request(Request, Error, Command->BlockCount << 9)) {
3466                if (Command->Completion) {
3467                        complete(Command->Completion);
3468                        Command->Completion = NULL;
3469                }
3470                return true;
3471        }
3472        return false;
3473}
3474
3475/*
3476  DAC960_V1_ReadWriteError prints an appropriate error message for Command
3477  when an error occurs on a Read or Write operation.
3478*/
3479
3480static void DAC960_V1_ReadWriteError(DAC960_Command_T *Command)
3481{
3482  DAC960_Controller_T *Controller = Command->Controller;
3483  unsigned char *CommandName = "UNKNOWN";
3484  switch (Command->CommandType)
3485    {
3486    case DAC960_ReadCommand:
3487    case DAC960_ReadRetryCommand:
3488      CommandName = "READ";
3489      break;
3490    case DAC960_WriteCommand:
3491    case DAC960_WriteRetryCommand:
3492      CommandName = "WRITE";
3493      break;
3494    case DAC960_MonitoringCommand:
3495    case DAC960_ImmediateCommand:
3496    case DAC960_QueuedCommand:
3497      break;
3498    }
3499  switch (Command->V1.CommandStatus)
3500    {
3501    case DAC960_V1_IrrecoverableDataError:
3502      DAC960_Error("Irrecoverable Data Error on %s:\n",
3503                   Controller, CommandName);
3504      break;
3505    case DAC960_V1_LogicalDriveNonexistentOrOffline:
3506      DAC960_Error("Logical Drive Nonexistent or Offline on %s:\n",
3507                   Controller, CommandName);
3508      break;
3509    case DAC960_V1_AccessBeyondEndOfLogicalDrive:
3510      DAC960_Error("Attempt to Access Beyond End of Logical Drive "
3511                   "on %s:\n", Controller, CommandName);
3512      break;
3513    case DAC960_V1_BadDataEncountered:
3514      DAC960_Error("Bad Data Encountered on %s:\n", Controller, CommandName);
3515      break;
3516    default:
3517      DAC960_Error("Unexpected Error Status %04X on %s:\n",
3518                   Controller, Command->V1.CommandStatus, CommandName);
3519      break;
3520    }
3521  DAC960_Error("  /dev/rd/c%dd%d:   absolute blocks %u..%u\n",
3522               Controller, Controller->ControllerNumber,
3523               Command->LogicalDriveNumber, Command->BlockNumber,
3524               Command->BlockNumber + Command->BlockCount - 1);
3525}
3526
3527
3528/*
3529  DAC960_V1_ProcessCompletedCommand performs completion processing for Command
3530  for DAC960 V1 Firmware Controllers.
3531*/
3532
3533static void DAC960_V1_ProcessCompletedCommand(DAC960_Command_T *Command)
3534{
3535  DAC960_Controller_T *Controller = Command->Controller;
3536  DAC960_CommandType_T CommandType = Command->CommandType;
3537  DAC960_V1_CommandOpcode_T CommandOpcode =
3538    Command->V1.CommandMailbox.Common.CommandOpcode;
3539  DAC960_V1_CommandStatus_T CommandStatus = Command->V1.CommandStatus;
3540
3541  if (CommandType == DAC960_ReadCommand ||
3542      CommandType == DAC960_WriteCommand)
3543    {
3544
3545#ifdef FORCE_RETRY_DEBUG
3546      CommandStatus = DAC960_V1_IrrecoverableDataError;
3547#endif
3548
3549      if (CommandStatus == DAC960_V1_NormalCompletion) {
3550
3551                if (!DAC960_ProcessCompletedRequest(Command, true))
3552                        BUG();
3553
3554      } else if (CommandStatus == DAC960_V1_IrrecoverableDataError ||
3555                CommandStatus == DAC960_V1_BadDataEncountered)
3556        {
3557          /*
3558           * break the command down into pieces and resubmit each
3559           * piece, hoping that some of them will succeed.
3560           */
3561           DAC960_queue_partial_rw(Command);
3562           return;
3563        }
3564      else
3565        {
3566          if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
3567            DAC960_V1_ReadWriteError(Command);
3568
3569         if (!DAC960_ProcessCompletedRequest(Command, false))
3570                BUG();
3571        }
3572    }
3573  else if (CommandType == DAC960_ReadRetryCommand ||
3574           CommandType == DAC960_WriteRetryCommand)
3575    {
3576      bool normal_completion;
3577#ifdef FORCE_RETRY_FAILURE_DEBUG
3578      static int retry_count = 1;
3579#endif
3580      /*
3581        Perform completion processing for the portion that was
3582        retried, and submit the next portion, if any.
3583      */
3584      normal_completion = true;
3585      if (CommandStatus != DAC960_V1_NormalCompletion) {
3586        normal_completion = false;
3587        if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
3588            DAC960_V1_ReadWriteError(Command);
3589      }
3590
3591#ifdef FORCE_RETRY_FAILURE_DEBUG
3592      if (!(++retry_count % 10000)) {
3593              printk("V1 error retry failure test\n");
3594              normal_completion = false;
3595              DAC960_V1_ReadWriteError(Command);
3596      }
3597#endif
3598
3599      if (!DAC960_ProcessCompletedRequest(Command, normal_completion)) {
3600        DAC960_queue_partial_rw(Command);
3601        return;
3602      }
3603    }
3604
3605  else if (CommandType == DAC960_MonitoringCommand)
3606    {
3607      if (Controller->ShutdownMonitoringTimer)
3608              return;
3609      if (CommandOpcode == DAC960_V1_Enquiry)
3610        {
3611          DAC960_V1_Enquiry_T *OldEnquiry = &Controller->V1.Enquiry;
3612          DAC960_V1_Enquiry_T *NewEnquiry = Controller->V1.NewEnquiry;
3613          unsigned int OldCriticalLogicalDriveCount =
3614            OldEnquiry->CriticalLogicalDriveCount;
3615          unsigned int NewCriticalLogicalDriveCount =
3616            NewEnquiry->CriticalLogicalDriveCount;
3617          if (NewEnquiry->NumberOfLogicalDrives > Controller->LogicalDriveCount)
3618            {
3619              int LogicalDriveNumber = Controller->LogicalDriveCount - 1;
3620              while (++LogicalDriveNumber < NewEnquiry->NumberOfLogicalDrives)
3621                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3622                                "Now Exists\n", Controller,
3623                                LogicalDriveNumber,
3624                                Controller->ControllerNumber,
3625                                LogicalDriveNumber);
3626              Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
3627              DAC960_ComputeGenericDiskInfo(Controller);
3628            }
3629          if (NewEnquiry->NumberOfLogicalDrives < Controller->LogicalDriveCount)
3630            {
3631              int LogicalDriveNumber = NewEnquiry->NumberOfLogicalDrives - 1;
3632              while (++LogicalDriveNumber < Controller->LogicalDriveCount)
3633                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3634                                "No Longer Exists\n", Controller,
3635                                LogicalDriveNumber,
3636                                Controller->ControllerNumber,
3637                                LogicalDriveNumber);
3638              Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
3639              DAC960_ComputeGenericDiskInfo(Controller);
3640            }
3641          if (NewEnquiry->StatusFlags.DeferredWriteError !=
3642              OldEnquiry->StatusFlags.DeferredWriteError)
3643            DAC960_Critical("Deferred Write Error Flag is now %s\n", Controller,
3644                            (NewEnquiry->StatusFlags.DeferredWriteError
3645                             ? "TRUE" : "FALSE"));
3646          if ((NewCriticalLogicalDriveCount > 0 ||
3647               NewCriticalLogicalDriveCount != OldCriticalLogicalDriveCount) ||
3648              (NewEnquiry->OfflineLogicalDriveCount > 0 ||
3649               NewEnquiry->OfflineLogicalDriveCount !=
3650               OldEnquiry->OfflineLogicalDriveCount) ||
3651              (NewEnquiry->DeadDriveCount > 0 ||
3652               NewEnquiry->DeadDriveCount !=
3653               OldEnquiry->DeadDriveCount) ||
3654              (NewEnquiry->EventLogSequenceNumber !=
3655               OldEnquiry->EventLogSequenceNumber) ||
3656              Controller->MonitoringTimerCount == 0 ||
3657              time_after_eq(jiffies, Controller->SecondaryMonitoringTime
3658               + DAC960_SecondaryMonitoringInterval))
3659            {
3660              Controller->V1.NeedLogicalDriveInformation = true;
3661              Controller->V1.NewEventLogSequenceNumber =
3662                NewEnquiry->EventLogSequenceNumber;
3663              Controller->V1.NeedErrorTableInformation = true;
3664              Controller->V1.NeedDeviceStateInformation = true;
3665              Controller->V1.StartDeviceStateScan = true;
3666              Controller->V1.NeedBackgroundInitializationStatus =
3667                Controller->V1.BackgroundInitializationStatusSupported;
3668              Controller->SecondaryMonitoringTime = jiffies;
3669            }
3670          if (NewEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
3671              NewEnquiry->RebuildFlag
3672              == DAC960_V1_BackgroundRebuildInProgress ||
3673              OldEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
3674              OldEnquiry->RebuildFlag == DAC960_V1_BackgroundRebuildInProgress)
3675            {
3676              Controller->V1.NeedRebuildProgress = true;
3677              Controller->V1.RebuildProgressFirst =
3678                (NewEnquiry->CriticalLogicalDriveCount <
3679                 OldEnquiry->CriticalLogicalDriveCount);
3680            }
3681          if (OldEnquiry->RebuildFlag == DAC960_V1_BackgroundCheckInProgress)
3682            switch (NewEnquiry->RebuildFlag)
3683              {
3684              case DAC960_V1_NoStandbyRebuildOrCheckInProgress:
3685                DAC960_Progress("Consistency Check Completed Successfully\n",
3686                                Controller);
3687                break;
3688              case DAC960_V1_StandbyRebuildInProgress:
3689              case DAC960_V1_BackgroundRebuildInProgress:
3690                break;
3691              case DAC960_V1_BackgroundCheckInProgress:
3692                Controller->V1.NeedConsistencyCheckProgress = true;
3693                break;
3694              case DAC960_V1_StandbyRebuildCompletedWithError:
3695                DAC960_Progress("Consistency Check Completed with Error\n",
3696                                Controller);
3697                break;
3698              case DAC960_V1_BackgroundRebuildOrCheckFailed_DriveFailed:
3699                DAC960_Progress("Consistency Check Failed - "
3700                                "Physical Device Failed\n", Controller);
3701                break;
3702              case DAC960_V1_BackgroundRebuildOrCheckFailed_LogicalDriveFailed:
3703                DAC960_Progress("Consistency Check Failed - "
3704                                "Logical Drive Failed\n", Controller);
3705                break;
3706              case DAC960_V1_BackgroundRebuildOrCheckFailed_OtherCauses:
3707                DAC960_Progress("Consistency Check Failed - Other Causes\n",
3708                                Controller);
3709                break;
3710              case DAC960_V1_BackgroundRebuildOrCheckSuccessfullyTerminated:
3711                DAC960_Progress("Consistency Check Successfully Terminated\n",
3712                                Controller);
3713                break;
3714              }
3715          else if (NewEnquiry->RebuildFlag
3716                   == DAC960_V1_BackgroundCheckInProgress)
3717            Controller->V1.NeedConsistencyCheckProgress = true;
3718          Controller->MonitoringAlertMode =
3719            (NewEnquiry->CriticalLogicalDriveCount > 0 ||
3720             NewEnquiry->OfflineLogicalDriveCount > 0 ||
3721             NewEnquiry->DeadDriveCount > 0);
3722          if (NewEnquiry->RebuildFlag > DAC960_V1_BackgroundCheckInProgress)
3723            {
3724              Controller->V1.PendingRebuildFlag = NewEnquiry->RebuildFlag;
3725              Controller->V1.RebuildFlagPending = true;
3726            }
3727          memcpy(&Controller->V1.Enquiry, &Controller->V1.NewEnquiry,
3728                 sizeof(DAC960_V1_Enquiry_T));
3729        }
3730      else if (CommandOpcode == DAC960_V1_PerformEventLogOperation)
3731        {
3732          static char
3733            *DAC960_EventMessages[] =
3734               { "killed because write recovery failed",
3735                 "killed because of SCSI bus reset failure",
3736                 "killed because of double check condition",
3737                 "killed because it was removed",
3738                 "killed because of gross error on SCSI chip",
3739                 "killed because of bad tag returned from drive",
3740                 "killed because of timeout on SCSI command",
3741                 "killed because of reset SCSI command issued from system",
3742                 "killed because busy or parity error count exceeded limit",
3743                 "killed because of 'kill drive' command from system",
3744                 "killed because of selection timeout",
3745                 "killed due to SCSI phase sequence error",
3746                 "killed due to unknown status" };
3747          DAC960_V1_EventLogEntry_T *EventLogEntry =
3748                Controller->V1.EventLogEntry;
3749          if (EventLogEntry->SequenceNumber ==
3750              Controller->V1.OldEventLogSequenceNumber)
3751            {
3752              unsigned char SenseKey = EventLogEntry->SenseKey;
3753              unsigned char AdditionalSenseCode =
3754                EventLogEntry->AdditionalSenseCode;
3755              unsigned char AdditionalSenseCodeQualifier =
3756                EventLogEntry->AdditionalSenseCodeQualifier;
3757              if (SenseKey == DAC960_SenseKey_VendorSpecific &&
3758                  AdditionalSenseCode == 0x80 &&
3759                  AdditionalSenseCodeQualifier <
3760                  ARRAY_SIZE(DAC960_EventMessages))
3761                DAC960_Critical("Physical Device %d:%d %s\n", Controller,
3762                                EventLogEntry->Channel,
3763                                EventLogEntry->TargetID,
3764                                DAC960_EventMessages[
3765                                  AdditionalSenseCodeQualifier]);
3766              else if (SenseKey == DAC960_SenseKey_UnitAttention &&
3767                       AdditionalSenseCode == 0x29)
3768                {
3769                  if (Controller->MonitoringTimerCount > 0)
3770                    Controller->V1.DeviceResetCount[EventLogEntry->Channel]
3771                                                   [EventLogEntry->TargetID]++;
3772                }
3773              else if (!(SenseKey == DAC960_SenseKey_NoSense ||
3774                         (SenseKey == DAC960_SenseKey_NotReady &&
3775                          AdditionalSenseCode == 0x04 &&
3776                          (AdditionalSenseCodeQualifier == 0x01 ||
3777                           AdditionalSenseCodeQualifier == 0x02))))
3778                {
3779                  DAC960_Critical("Physical Device %d:%d Error Log: "
3780                                  "Sense Key = %X, ASC = %02X, ASCQ = %02X\n",
3781                                  Controller,
3782                                  EventLogEntry->Channel,
3783                                  EventLogEntry->TargetID,
3784                                  SenseKey,
3785                                  AdditionalSenseCode,
3786                                  AdditionalSenseCodeQualifier);
3787                  DAC960_Critical("Physical Device %d:%d Error Log: "
3788                                  "Information = %02X%02X%02X%02X "
3789                                  "%02X%02X%02X%02X\n",
3790                                  Controller,
3791                                  EventLogEntry->Channel,
3792                                  EventLogEntry->TargetID,
3793                                  EventLogEntry->Information[0],
3794                                  EventLogEntry->Information[1],
3795                                  EventLogEntry->Information[2],
3796                                  EventLogEntry->Information[3],
3797                                  EventLogEntry->CommandSpecificInformation[0],
3798                                  EventLogEntry->CommandSpecificInformation[1],
3799                                  EventLogEntry->CommandSpecificInformation[2],
3800                                  EventLogEntry->CommandSpecificInformation[3]);
3801                }
3802            }
3803          Controller->V1.OldEventLogSequenceNumber++;
3804        }
3805      else if (CommandOpcode == DAC960_V1_GetErrorTable)
3806        {
3807          DAC960_V1_ErrorTable_T *OldErrorTable = &Controller->V1.ErrorTable;
3808          DAC960_V1_ErrorTable_T *NewErrorTable = Controller->V1.NewErrorTable;
3809          int Channel, TargetID;
3810          for (Channel = 0; Channel < Controller->Channels; Channel++)
3811            for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
3812              {
3813                DAC960_V1_ErrorTableEntry_T *NewErrorEntry =
3814                  &NewErrorTable->ErrorTableEntries[Channel][TargetID];
3815                DAC960_V1_ErrorTableEntry_T *OldErrorEntry =
3816                  &OldErrorTable->ErrorTableEntries[Channel][TargetID];
3817                if ((NewErrorEntry->ParityErrorCount !=
3818                     OldErrorEntry->ParityErrorCount) ||
3819                    (NewErrorEntry->SoftErrorCount !=
3820                     OldErrorEntry->SoftErrorCount) ||
3821                    (NewErrorEntry->HardErrorCount !=
3822                     OldErrorEntry->HardErrorCount) ||
3823                    (NewErrorEntry->MiscErrorCount !=
3824                     OldErrorEntry->MiscErrorCount))
3825                  DAC960_Critical("Physical Device %d:%d Errors: "
3826                                  "Parity = %d, Soft = %d, "
3827                                  "Hard = %d, Misc = %d\n",
3828                                  Controller, Channel, TargetID,
3829                                  NewErrorEntry->ParityErrorCount,
3830                                  NewErrorEntry->SoftErrorCount,
3831                                  NewErrorEntry->HardErrorCount,
3832                                  NewErrorEntry->MiscErrorCount);
3833              }
3834          memcpy(&Controller->V1.ErrorTable, Controller->V1.NewErrorTable,
3835                 sizeof(DAC960_V1_ErrorTable_T));
3836        }
3837      else if (CommandOpcode == DAC960_V1_GetDeviceState)
3838        {
3839          DAC960_V1_DeviceState_T *OldDeviceState =
3840            &Controller->V1.DeviceState[Controller->V1.DeviceStateChannel]
3841                                       [Controller->V1.DeviceStateTargetID];
3842          DAC960_V1_DeviceState_T *NewDeviceState =
3843            Controller->V1.NewDeviceState;
3844          if (NewDeviceState->DeviceState != OldDeviceState->DeviceState)
3845            DAC960_Critical("Physical Device %d:%d is now %s\n", Controller,
3846                            Controller->V1.DeviceStateChannel,
3847                            Controller->V1.DeviceStateTargetID,
3848                            (NewDeviceState->DeviceState
3849                             == DAC960_V1_Device_Dead
3850                             ? "DEAD"
3851                             : NewDeviceState->DeviceState
3852                               == DAC960_V1_Device_WriteOnly
3853                               ? "WRITE-ONLY"
3854                               : NewDeviceState->DeviceState
3855                                 == DAC960_V1_Device_Online
3856                                 ? "ONLINE" : "STANDBY"));
3857          if (OldDeviceState->DeviceState == DAC960_V1_Device_Dead &&
3858              NewDeviceState->DeviceState != DAC960_V1_Device_Dead)
3859            {
3860              Controller->V1.NeedDeviceInquiryInformation = true;
3861              Controller->V1.NeedDeviceSerialNumberInformation = true;
3862              Controller->V1.DeviceResetCount
3863                             [Controller->V1.DeviceStateChannel]
3864                             [Controller->V1.DeviceStateTargetID] = 0;
3865            }
3866          memcpy(OldDeviceState, NewDeviceState,
3867                 sizeof(DAC960_V1_DeviceState_T));
3868        }
3869      else if (CommandOpcode == DAC960_V1_GetLogicalDriveInformation)
3870        {
3871          int LogicalDriveNumber;
3872          for (LogicalDriveNumber = 0;
3873               LogicalDriveNumber < Controller->LogicalDriveCount;
3874               LogicalDriveNumber++)
3875            {
3876              DAC960_V1_LogicalDriveInformation_T *OldLogicalDriveInformation =
3877                &Controller->V1.LogicalDriveInformation[LogicalDriveNumber];
3878              DAC960_V1_LogicalDriveInformation_T *NewLogicalDriveInformation =
3879                &(*Controller->V1.NewLogicalDriveInformation)[LogicalDriveNumber];
3880              if (NewLogicalDriveInformation->LogicalDriveState !=
3881                  OldLogicalDriveInformation->LogicalDriveState)
3882                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3883                                "is now %s\n", Controller,
3884                                LogicalDriveNumber,
3885                                Controller->ControllerNumber,
3886                                LogicalDriveNumber,
3887                                (NewLogicalDriveInformation->LogicalDriveState
3888                                 == DAC960_V1_LogicalDrive_Online
3889                                 ? "ONLINE"
3890                                 : NewLogicalDriveInformation->LogicalDriveState
3891                                   == DAC960_V1_LogicalDrive_Critical
3892                                   ? "CRITICAL" : "OFFLINE"));
3893              if (NewLogicalDriveInformation->WriteBack !=
3894                  OldLogicalDriveInformation->WriteBack)
3895                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3896                                "is now %s\n", Controller,
3897                                LogicalDriveNumber,
3898                                Controller->ControllerNumber,
3899                                LogicalDriveNumber,
3900                                (NewLogicalDriveInformation->WriteBack
3901                                 ? "WRITE BACK" : "WRITE THRU"));
3902            }
3903          memcpy(&Controller->V1.LogicalDriveInformation,
3904                 Controller->V1.NewLogicalDriveInformation,
3905                 sizeof(DAC960_V1_LogicalDriveInformationArray_T));
3906        }
3907      else if (CommandOpcode == DAC960_V1_GetRebuildProgress)
3908        {
3909          unsigned int LogicalDriveNumber =
3910            Controller->V1.RebuildProgress->LogicalDriveNumber;
3911          unsigned int LogicalDriveSize =
3912            Controller->V1.RebuildProgress->LogicalDriveSize;
3913          unsigned int BlocksCompleted =
3914            LogicalDriveSize - Controller->V1.RebuildProgress->RemainingBlocks;
3915          if (CommandStatus == DAC960_V1_NoRebuildOrCheckInProgress &&
3916              Controller->V1.LastRebuildStatus == DAC960_V1_NormalCompletion)
3917            CommandStatus = DAC960_V1_RebuildSuccessful;
3918          switch (CommandStatus)
3919            {
3920            case DAC960_V1_NormalCompletion:
3921              Controller->EphemeralProgressMessage = true;
3922              DAC960_Progress("Rebuild in Progress: "
3923                              "Logical Drive %d (/dev/rd/c%dd%d) "
3924                              "%d%% completed\n",
3925                              Controller, LogicalDriveNumber,
3926                              Controller->ControllerNumber,
3927                              LogicalDriveNumber,
3928                              (100 * (BlocksCompleted >> 7))
3929                              / (LogicalDriveSize >> 7));
3930              Controller->EphemeralProgressMessage = false;
3931              break;
3932            case DAC960_V1_RebuildFailed_LogicalDriveFailure:
3933              DAC960_Progress("Rebuild Failed due to "
3934                              "Logical Drive Failure\n", Controller);
3935              break;
3936            case DAC960_V1_RebuildFailed_BadBlocksOnOther:
3937              DAC960_Progress("Rebuild Failed due to "
3938                              "Bad Blocks on Other Drives\n", Controller);
3939              break;
3940            case DAC960_V1_RebuildFailed_NewDriveFailed:
3941              DAC960_Progress("Rebuild Failed due to "
3942                              "Failure of Drive Being Rebuilt\n", Controller);
3943              break;
3944            case DAC960_V1_NoRebuildOrCheckInProgress:
3945              break;
3946            case DAC960_V1_RebuildSuccessful:
3947              DAC960_Progress("Rebuild Completed Successfully\n", Controller);
3948              break;
3949            case DAC960_V1_RebuildSuccessfullyTerminated:
3950              DAC960_Progress("Rebuild Successfully Terminated\n", Controller);
3951              break;
3952            }
3953          Controller->V1.LastRebuildStatus = CommandStatus;
3954          if (CommandType != DAC960_MonitoringCommand &&
3955              Controller->V1.RebuildStatusPending)
3956            {
3957              Command->V1.CommandStatus = Controller->V1.PendingRebuildStatus;
3958              Controller->V1.RebuildStatusPending = false;
3959            }
3960          else if (CommandType == DAC960_MonitoringCommand &&
3961                   CommandStatus != DAC960_V1_NormalCompletion &&
3962                   CommandStatus != DAC960_V1_NoRebuildOrCheckInProgress)
3963            {
3964              Controller->V1.PendingRebuildStatus = CommandStatus;
3965              Controller->V1.RebuildStatusPending = true;
3966            }
3967        }
3968      else if (CommandOpcode == DAC960_V1_RebuildStat)
3969        {
3970          unsigned int LogicalDriveNumber =
3971            Controller->V1.RebuildProgress->LogicalDriveNumber;
3972          unsigned int LogicalDriveSize =
3973            Controller->V1.RebuildProgress->LogicalDriveSize;
3974          unsigned int BlocksCompleted =
3975            LogicalDriveSize - Controller->V1.RebuildProgress->RemainingBlocks;
3976          if (CommandStatus == DAC960_V1_NormalCompletion)
3977            {
3978              Controller->EphemeralProgressMessage = true;
3979              DAC960_Progress("Consistency Check in Progress: "
3980                              "Logical Drive %d (/dev/rd/c%dd%d) "
3981                              "%d%% completed\n",
3982                              Controller, LogicalDriveNumber,
3983                              Controller->ControllerNumber,
3984                              LogicalDriveNumber,
3985                              (100 * (BlocksCompleted >> 7))
3986                              / (LogicalDriveSize >> 7));
3987              Controller->EphemeralProgressMessage = false;
3988            }
3989        }
3990      else if (CommandOpcode == DAC960_V1_BackgroundInitializationControl)
3991        {
3992          unsigned int LogicalDriveNumber =
3993            Controller->V1.BackgroundInitializationStatus->LogicalDriveNumber;
3994          unsigned int LogicalDriveSize =
3995            Controller->V1.BackgroundInitializationStatus->LogicalDriveSize;
3996          unsigned int BlocksCompleted =
3997            Controller->V1.BackgroundInitializationStatus->BlocksCompleted;
3998          switch (CommandStatus)
3999            {
4000            case DAC960_V1_NormalCompletion:
4001              switch (Controller->V1.BackgroundInitializationStatus->Status)
4002                {
4003                case DAC960_V1_BackgroundInitializationInvalid:
4004                  break;
4005                case DAC960_V1_BackgroundInitializationStarted:
4006                  DAC960_Progress("Background Initialization Started\n",
4007                                  Controller);
4008                  break;
4009                case DAC960_V1_BackgroundInitializationInProgress:
4010                  if (BlocksCompleted ==
4011                      Controller->V1.LastBackgroundInitializationStatus.
4012                                BlocksCompleted &&
4013                      LogicalDriveNumber ==
4014                      Controller->V1.LastBackgroundInitializationStatus.
4015                                LogicalDriveNumber)
4016                    break;
4017                  Controller->EphemeralProgressMessage = true;
4018                  DAC960_Progress("Background Initialization in Progress: "
4019                                  "Logical Drive %d (/dev/rd/c%dd%d) "
4020                                  "%d%% completed\n",
4021                                  Controller, LogicalDriveNumber,
4022                                  Controller->ControllerNumber,
4023                                  LogicalDriveNumber,
4024                                  (100 * (BlocksCompleted >> 7))
4025                                  / (LogicalDriveSize >> 7));
4026                  Controller->EphemeralProgressMessage = false;
4027                  break;
4028                case DAC960_V1_BackgroundInitializationSuspended:
4029                  DAC960_Progress("Background Initialization Suspended\n",
4030                                  Controller);
4031                  break;
4032                case DAC960_V1_BackgroundInitializationCancelled:
4033                  DAC960_Progress("Background Initialization Cancelled\n",
4034                                  Controller);
4035                  break;
4036                }
4037              memcpy(&Controller->V1.LastBackgroundInitializationStatus,
4038                     Controller->V1.BackgroundInitializationStatus,
4039                     sizeof(DAC960_V1_BackgroundInitializationStatus_T));
4040              break;
4041            case DAC960_V1_BackgroundInitSuccessful:
4042              if (Controller->V1.BackgroundInitializationStatus->Status ==
4043                  DAC960_V1_BackgroundInitializationInProgress)
4044                DAC960_Progress("Background Initialization "
4045                                "Completed Successfully\n", Controller);
4046              Controller->V1.BackgroundInitializationStatus->Status =
4047                DAC960_V1_BackgroundInitializationInvalid;
4048              break;
4049            case DAC960_V1_BackgroundInitAborted:
4050              if (Controller->V1.BackgroundInitializationStatus->Status ==
4051                  DAC960_V1_BackgroundInitializationInProgress)
4052                DAC960_Progress("Background Initialization Aborted\n",
4053                                Controller);
4054              Controller->V1.BackgroundInitializationStatus->Status =
4055                DAC960_V1_BackgroundInitializationInvalid;
4056              break;
4057            case DAC960_V1_NoBackgroundInitInProgress:
4058              break;
4059            }
4060        } 
4061      else if (CommandOpcode == DAC960_V1_DCDB)
4062        {
4063           /*
4064             This is a bit ugly.
4065
4066             The InquiryStandardData and 
4067             the InquiryUntitSerialNumber information
4068             retrieval operations BOTH use the DAC960_V1_DCDB
4069             commands.  the test above can't distinguish between
4070             these two cases.
4071
4072             Instead, we rely on the order of code later in this
4073             function to ensure that DeviceInquiryInformation commands
4074             are submitted before DeviceSerialNumber commands.
4075           */
4076           if (Controller->V1.NeedDeviceInquiryInformation)
4077             {
4078                DAC960_SCSI_Inquiry_T *InquiryStandardData =
4079                        &Controller->V1.InquiryStandardData
4080                                [Controller->V1.DeviceStateChannel]
4081                                [Controller->V1.DeviceStateTargetID];
4082                if (CommandStatus != DAC960_V1_NormalCompletion)
4083                   {
4084                        memset(InquiryStandardData, 0,
4085                                sizeof(DAC960_SCSI_Inquiry_T));
4086                        InquiryStandardData->PeripheralDeviceType = 0x1F;
4087                    }
4088                 else
4089                        memcpy(InquiryStandardData, 
4090                                Controller->V1.NewInquiryStandardData,
4091                                sizeof(DAC960_SCSI_Inquiry_T));
4092                 Controller->V1.NeedDeviceInquiryInformation = false;
4093              }
4094           else if (Controller->V1.NeedDeviceSerialNumberInformation) 
4095              {
4096                DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
4097                  &Controller->V1.InquiryUnitSerialNumber
4098                                [Controller->V1.DeviceStateChannel]
4099                                [Controller->V1.DeviceStateTargetID];
4100                 if (CommandStatus != DAC960_V1_NormalCompletion)
4101                   {
4102                        memset(InquiryUnitSerialNumber, 0,
4103                                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
4104                        InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
4105                    }
4106                  else
4107                        memcpy(InquiryUnitSerialNumber, 
4108                                Controller->V1.NewInquiryUnitSerialNumber,
4109                                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
4110              Controller->V1.NeedDeviceSerialNumberInformation = false;
4111             }
4112        }
4113      /*
4114        Begin submitting new monitoring commands.
4115       */
4116      if (Controller->V1.NewEventLogSequenceNumber
4117          - Controller->V1.OldEventLogSequenceNumber > 0)
4118        {
4119          Command->V1.CommandMailbox.Type3E.CommandOpcode =
4120            DAC960_V1_PerformEventLogOperation;
4121          Command->V1.CommandMailbox.Type3E.OperationType =
4122            DAC960_V1_GetEventLogEntry;
4123          Command->V1.CommandMailbox.Type3E.OperationQualifier = 1;
4124          Command->V1.CommandMailbox.Type3E.SequenceNumber =
4125            Controller->V1.OldEventLogSequenceNumber;
4126          Command->V1.CommandMailbox.Type3E.BusAddress =
4127                Controller->V1.EventLogEntryDMA;
4128          DAC960_QueueCommand(Command);
4129          return;
4130        }
4131      if (Controller->V1.NeedErrorTableInformation)
4132        {
4133          Controller->V1.NeedErrorTableInformation = false;
4134          Command->V1.CommandMailbox.Type3.CommandOpcode =
4135            DAC960_V1_GetErrorTable;
4136          Command->V1.CommandMailbox.Type3.BusAddress =
4137                Controller->V1.NewErrorTableDMA;
4138          DAC960_QueueCommand(Command);
4139          return;
4140        }
4141      if (Controller->V1.NeedRebuildProgress &&
4142          Controller->V1.RebuildProgressFirst)
4143        {
4144          Controller->V1.NeedRebuildProgress = false;
4145          Command->V1.CommandMailbox.Type3.CommandOpcode =
4146            DAC960_V1_GetRebuildProgress;
4147          Command->V1.CommandMailbox.Type3.BusAddress =
4148            Controller->V1.RebuildProgressDMA;
4149          DAC960_QueueCommand(Command);
4150          return;
4151        }
4152      if (Controller->V1.NeedDeviceStateInformation)
4153        {
4154          if (Controller->V1.NeedDeviceInquiryInformation)
4155            {
4156              DAC960_V1_DCDB_T *DCDB = Controller->V1.MonitoringDCDB;
4157              dma_addr_t DCDB_DMA = Controller->V1.MonitoringDCDB_DMA;
4158
4159              dma_addr_t NewInquiryStandardDataDMA =
4160                Controller->V1.NewInquiryStandardDataDMA;
4161
4162              Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
4163              Command->V1.CommandMailbox.Type3.BusAddress = DCDB_DMA;
4164              DCDB->Channel = Controller->V1.DeviceStateChannel;
4165              DCDB->TargetID = Controller->V1.DeviceStateTargetID;
4166              DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
4167              DCDB->EarlyStatus = false;
4168              DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
4169              DCDB->NoAutomaticRequestSense = false;
4170              DCDB->DisconnectPermitted = true;
4171              DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_T);
4172              DCDB->BusAddress = NewInquiryStandardDataDMA;
4173              DCDB->CDBLength = 6;
4174              DCDB->TransferLengthHigh4 = 0;
4175              DCDB->SenseLength = sizeof(DCDB->SenseData);
4176              DCDB->CDB[0] = 0x12; /* INQUIRY */
4177              DCDB->CDB[1] = 0; /* EVPD = 0 */
4178              DCDB->CDB[2] = 0; /* Page Code */
4179              DCDB->CDB[3] = 0; /* Reserved */
4180              DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_T);
4181              DCDB->CDB[5] = 0; /* Control */
4182              DAC960_QueueCommand(Command);
4183              return;
4184            }
4185          if (Controller->V1.NeedDeviceSerialNumberInformation)
4186            {
4187              DAC960_V1_DCDB_T *DCDB = Controller->V1.MonitoringDCDB;
4188              dma_addr_t DCDB_DMA = Controller->V1.MonitoringDCDB_DMA;
4189              dma_addr_t NewInquiryUnitSerialNumberDMA = 
4190                        Controller->V1.NewInquiryUnitSerialNumberDMA;
4191
4192              Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
4193              Command->V1.CommandMailbox.Type3.BusAddress = DCDB_DMA;
4194              DCDB->Channel = Controller->V1.DeviceStateChannel;
4195              DCDB->TargetID = Controller->V1.DeviceStateTargetID;
4196              DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
4197              DCDB->EarlyStatus = false;
4198              DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
4199              DCDB->NoAutomaticRequestSense = false;
4200              DCDB->DisconnectPermitted = true;
4201              DCDB->TransferLength =
4202                sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
4203              DCDB->BusAddress = NewInquiryUnitSerialNumberDMA;
4204              DCDB->CDBLength = 6;
4205              DCDB->TransferLengthHigh4 = 0;
4206              DCDB->SenseLength = sizeof(DCDB->SenseData);
4207              DCDB->CDB[0] = 0x12; /* INQUIRY */
4208              DCDB->CDB[1] = 1; /* EVPD = 1 */
4209              DCDB->CDB[2] = 0x80; /* Page Code */
4210              DCDB->CDB[3] = 0; /* Reserved */
4211              DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
4212              DCDB->CDB[5] = 0; /* Control */
4213              DAC960_QueueCommand(Command);
4214              return;
4215            }
4216          if (Controller->V1.StartDeviceStateScan)
4217            {
4218              Controller->V1.DeviceStateChannel = 0;
4219              Controller->V1.DeviceStateTargetID = 0;
4220              Controller->V1.StartDeviceStateScan = false;
4221            }
4222          else if (++Controller->V1.DeviceStateTargetID == Controller->Targets)
4223            {
4224              Controller->V1.DeviceStateChannel++;
4225              Controller->V1.DeviceStateTargetID = 0;
4226            }
4227          if (Controller->V1.DeviceStateChannel < Controller->Channels)
4228            {
4229              Controller->V1.NewDeviceState->DeviceState =
4230                DAC960_V1_Device_Dead;
4231              Command->V1.CommandMailbox.Type3D.CommandOpcode =
4232                DAC960_V1_GetDeviceState;
4233              Command->V1.CommandMailbox.Type3D.Channel =
4234                Controller->V1.DeviceStateChannel;
4235              Command->V1.CommandMailbox.Type3D.TargetID =
4236                Controller->V1.DeviceStateTargetID;
4237              Command->V1.CommandMailbox.Type3D.BusAddress =
4238                Controller->V1.NewDeviceStateDMA;
4239              DAC960_QueueCommand(Command);
4240              return;
4241            }
4242          Controller->V1.NeedDeviceStateInformation = false;
4243        }
4244      if (Controller->V1.NeedLogicalDriveInformation)
4245        {
4246          Controller->V1.NeedLogicalDriveInformation = false;
4247          Command->V1.CommandMailbox.Type3.CommandOpcode =
4248            DAC960_V1_GetLogicalDriveInformation;
4249          Command->V1.CommandMailbox.Type3.BusAddress =
4250            Controller->V1.NewLogicalDriveInformationDMA;
4251          DAC960_QueueCommand(Command);
4252          return;
4253        }
4254      if (Controller->V1.NeedRebuildProgress)
4255        {
4256          Controller->V1.NeedRebuildProgress = false;
4257          Command->V1.CommandMailbox.Type3.CommandOpcode =
4258            DAC960_V1_GetRebuildProgress;
4259          Command->V1.CommandMailbox.Type3.BusAddress =
4260                Controller->V1.RebuildProgressDMA;
4261          DAC960_QueueCommand(Command);
4262          return;
4263        }
4264      if (Controller->V1.NeedConsistencyCheckProgress)
4265        {
4266          Controller->V1.NeedConsistencyCheckProgress = false;
4267          Command->V1.CommandMailbox.Type3.CommandOpcode =
4268            DAC960_V1_RebuildStat;
4269          Command->V1.CommandMailbox.Type3.BusAddress =
4270            Controller->V1.RebuildProgressDMA;
4271          DAC960_QueueCommand(Command);
4272          return;
4273        }
4274      if (Controller->V1.NeedBackgroundInitializationStatus)
4275        {
4276          Controller->V1.NeedBackgroundInitializationStatus = false;
4277          Command->V1.CommandMailbox.Type3B.CommandOpcode =
4278            DAC960_V1_BackgroundInitializationControl;
4279          Command->V1.CommandMailbox.Type3B.CommandOpcode2 = 0x20;
4280          Command->V1.CommandMailbox.Type3B.BusAddress =
4281            Controller->V1.BackgroundInitializationStatusDMA;
4282          DAC960_QueueCommand(Command);
4283          return;
4284        }
4285      Controller->MonitoringTimerCount++;
4286      Controller->MonitoringTimer.expires =
4287        jiffies + DAC960_MonitoringTimerInterval;
4288        add_timer(&Controller->MonitoringTimer);
4289    }
4290  if (CommandType == DAC960_ImmediateCommand)
4291    {
4292      complete(Command->Completion);
4293      Command->Completion = NULL;
4294      return;
4295    }
4296  if (CommandType == DAC960_QueuedCommand)
4297    {
4298      DAC960_V1_KernelCommand_T *KernelCommand = Command->V1.KernelCommand;
4299      KernelCommand->CommandStatus = Command->V1.CommandStatus;
4300      Command->V1.KernelCommand = NULL;
4301      if (CommandOpcode == DAC960_V1_DCDB)
4302        Controller->V1.DirectCommandActive[KernelCommand->DCDB->Channel]
4303                                          [KernelCommand->DCDB->TargetID] =
4304          false;
4305      DAC960_DeallocateCommand(Command);
4306      KernelCommand->CompletionFunction(KernelCommand);
4307      return;
4308    }
4309  /*
4310    Queue a Status Monitoring Command to the Controller using the just
4311    completed Command if one was deferred previously due to lack of a
4312    free Command when the Monitoring Timer Function was called.
4313  */
4314  if (Controller->MonitoringCommandDeferred)
4315    {
4316      Controller->MonitoringCommandDeferred = false;
4317      DAC960_V1_QueueMonitoringCommand(Command);
4318      return;
4319    }
4320  /*
4321    Deallocate the Command.
4322  */
4323  DAC960_DeallocateCommand(Command);
4324  /*
4325    Wake up any processes waiting on a free Command.
4326  */
4327  wake_up(&Controller->CommandWaitQueue);
4328}
4329
4330
4331/*
4332  DAC960_V2_ReadWriteError prints an appropriate error message for Command
4333  when an error occurs on a Read or Write operation.
4334*/
4335
4336static void DAC960_V2_ReadWriteError(DAC960_Command_T *Command)
4337{
4338  DAC960_Controller_T *Controller = Command->Controller;
4339  unsigned char *SenseErrors[] = { "NO SENSE", "RECOVERED ERROR",
4340                                   "NOT READY", "MEDIUM ERROR",
4341                                   "HARDWARE ERROR", "ILLEGAL REQUEST",
4342                                   "UNIT ATTENTION", "DATA PROTECT",
4343                                   "BLANK CHECK", "VENDOR-SPECIFIC",
4344                                   "COPY ABORTED", "ABORTED COMMAND",
4345                                   "EQUAL", "VOLUME OVERFLOW",
4346                                   "MISCOMPARE", "RESERVED" };
4347  unsigned char *CommandName = "UNKNOWN";
4348  switch (Command->CommandType)
4349    {
4350    case DAC960_ReadCommand:
4351    case DAC960_ReadRetryCommand:
4352      CommandName = "READ";
4353      break;
4354    case DAC960_WriteCommand:
4355    case DAC960_WriteRetryCommand:
4356      CommandName = "WRITE";
4357      break;
4358    case DAC960_MonitoringCommand:
4359    case DAC960_ImmediateCommand:
4360    case DAC960_QueuedCommand:
4361      break;
4362    }
4363  DAC960_Error("Error Condition %s on %s:\n", Controller,
4364               SenseErrors[Command->V2.RequestSense->SenseKey], CommandName);
4365  DAC960_Error("  /dev/rd/c%dd%d:   absolute blocks %u..%u\n",
4366               Controller, Controller->ControllerNumber,
4367               Command->LogicalDriveNumber, Command->BlockNumber,
4368               Command->BlockNumber + Command->BlockCount - 1);
4369}
4370
4371
4372/*
4373  DAC960_V2_ReportEvent prints an appropriate message when a Controller Event
4374  occurs.
4375*/
4376
4377static void DAC960_V2_ReportEvent(DAC960_Controller_T *Controller,
4378                                  DAC960_V2_Event_T *Event)
4379{
4380  DAC960_SCSI_RequestSense_T *RequestSense =
4381    (DAC960_SCSI_RequestSense_T *) &Event->RequestSenseData;
4382  unsigned char MessageBuffer[DAC960_LineBufferSize];
4383  static struct { int EventCode; unsigned char *EventMessage; } EventList[] =
4384    { /* Physical Device Events (0x0000 - 0x007F) */
4385      { 0x0001, "P Online" },
4386      { 0x0002, "P Standby" },
4387      { 0x0005, "P Automatic Rebuild Started" },
4388      { 0x0006, "P Manual Rebuild Started" },
4389      { 0x0007, "P Rebuild Completed" },
4390      { 0x0008, "P Rebuild Cancelled" },
4391      { 0x0009, "P Rebuild Failed for Unknown Reasons" },
4392      { 0x000A, "P Rebuild Failed due to New Physical Device" },
4393      { 0x000B, "P Rebuild Failed due to Logical Drive Failure" },
4394      { 0x000C, "S Offline" },
4395      { 0x000D, "P Found" },
4396      { 0x000E, "P Removed" },
4397      { 0x000F, "P Unconfigured" },
4398      { 0x0010, "P Expand Capacity Started" },
4399      { 0x0011, "P Expand Capacity Completed" },
4400      { 0x0012, "P Expand Capacity Failed" },
4401      { 0x0013, "P Command Timed Out" },
4402      { 0x0014, "P Command Aborted" },
4403      { 0x0015, "P Command Retried" },
4404      { 0x0016, "P Parity Error" },
4405      { 0x0017, "P Soft Error" },
4406      { 0x0018, "P Miscellaneous Error" },
4407      { 0x0019, "P Reset" },
4408      { 0x001A, "P Active Spare Found" },
4409      { 0x001B, "P Warm Spare Found" },
4410      { 0x001C, "S Sense Data Received" },
4411      { 0x001D, "P Initialization Started" },
4412      { 0x001E, "P Initialization Completed" },
4413      { 0x001F, "P Initialization Failed" },
4414      { 0x0020, "P Initialization Cancelled" },
4415      { 0x0021, "P Failed because Write Recovery Failed" },
4416      { 0x0022, "P Failed because SCSI Bus Reset Failed" },
4417      { 0x0023, "P Failed because of Double Check Condition" },
4418      { 0x0024, "P Failed because Device Cannot Be Accessed" },
4419      { 0x0025, "P Failed because of Gross Error on SCSI Processor" },
4420      { 0x0026, "P Failed because of Bad Tag from Device" },
4421      { 0x0027, "P Failed because of Command Timeout" },
4422      { 0x0028, "P Failed because of System Reset" },
4423      { 0x0029, "P Failed because of Busy Status or Parity Error" },
4424      { 0x002A, "P Failed because Host Set Device to Failed State" },
4425      { 0x002B, "P Failed because of Selection Timeout" },
4426      { 0x002C, "P Failed because of SCSI Bus Phase Error" },
4427      { 0x002D, "P Failed because Device Returned Unknown Status" },
4428      { 0x002E, "P Failed because Device Not Ready" },
4429      { 0x002F, "P Failed because Device Not Found at Startup" },
4430      { 0x0030, "P Failed because COD Write Operation Failed" },
4431      { 0x0031, "P Failed because BDT Write Operation Failed" },
4432      { 0x0039, "P Missing at Startup" },
4433      { 0x003A, "P Start Rebuild Failed due to Physical Drive Too Small" },
4434      { 0x003C, "P Temporarily Offline Device Automatically Made Online" },
4435      { 0x003D, "P Standby Rebuild Started" },
4436      /* Logical Device Events (0x0080 - 0x00FF) */
4437      { 0x0080, "M Consistency Check Started" },
4438      { 0x0081, "M Consistency Check Completed" },
4439      { 0x0082, "M Consistency Check Cancelled" },
4440      { 0x0083, "M Consistency Check Completed With Errors" },
4441      { 0x0084, "M Consistency Check Failed due to Logical Drive Failure" },
4442      { 0x0085, "M Consistency Check Failed due to Physical Device Failure" },
4443      { 0x0086, "L Offline" },
4444      { 0x0087, "L Critical" },
4445      { 0x0088, "L Online" },
4446      { 0x0089, "M Automatic Rebuild Started" },
4447      { 0x008A, "M Manual Rebuild Started" },
4448      { 0x008B, "M Rebuild Completed" },
4449      { 0x008C, "M Rebuild Cancelled" },
4450      { 0x008D, "M Rebuild Failed for Unknown Reasons" },
4451      { 0x008E, "M Rebuild Failed due to New Physical Device" },
4452      { 0x008F, "M Rebuild Failed due to Logical Drive Failure" },
4453      { 0x0090, "M Initialization Started" },
4454      { 0x0091, "M Initialization Completed" },
4455      { 0x0092, "M Initialization Cancelled" },
4456      { 0x0093, "M Initialization Failed" },
4457      { 0x0094, "L Found" },
4458      { 0x0095, "L Deleted" },
4459      { 0x0096, "M Expand Capacity Started" },
4460      { 0x0097, "M Expand Capacity Completed" },
4461      { 0x0098, "M Expand Capacity Failed" },
4462      { 0x0099, "L Bad Block Found" },
4463      { 0x009A, "L Size Changed" },
4464      { 0x009B, "L Type Changed" },
4465      { 0x009C, "L Bad Data Block Found" },
4466      { 0x009E, "L Read of Data Block in BDT" },
4467      { 0x009F, "L Write Back Data for Disk Block Lost" },
4468      { 0x00A0, "L Temporarily Offline RAID-5/3 Drive Made Online" },
4469      { 0x00A1, "L Temporarily Offline RAID-6/1/0/7 Drive Made Online" },
4470      { 0x00A2, "L Standby Rebuild Started" },
4471      /* Fault Management Events (0x0100 - 0x017F) */
4472      { 0x0140, "E Fan %d Failed" },
4473      { 0x0141, "E Fan %d OK" },
4474      { 0x0142, "E Fan %d Not Present" },
4475      { 0x0143, "E Power Supply %d Failed" },
4476      { 0x0144, "E Power Supply %d OK" },
4477      { 0x0145, "E Power Supply %d Not Present" },
4478      { 0x0146, "E Temperature Sensor %d Temperature Exceeds Safe Limit" },
4479      { 0x0147, "E Temperature Sensor %d Temperature Exceeds Working Limit" },
4480      { 0x0148, "E Temperature Sensor %d Temperature Normal" },
4481      { 0x0149, "E Temperature Sensor %d Not Present" },
4482      { 0x014A, "E Enclosure Management Unit %d Access Critical" },
4483      { 0x014B, "E Enclosure Management Unit %d Access OK" },
4484      { 0x014C, "E Enclosure Management Unit %d Access Offline" },
4485      /* Controller Events (0x0180 - 0x01FF) */
4486      { 0x0181, "C Cache Write Back Error" },
4487      { 0x0188, "C Battery Backup Unit Found" },
4488      { 0x0189, "C Battery Backup Unit Charge Level Low" },
4489      { 0x018A, "C Battery Backup Unit Charge Level OK" },
4490      { 0x0193, "C Installation Aborted" },
4491      { 0x0195, "C Battery Backup Unit Physically Removed" },
4492      { 0x0196, "C Memory Error During Warm Boot" },
4493      { 0x019E, "C Memory Soft ECC Error Corrected" },
4494      { 0x019F, "C Memory Hard ECC Error Corrected" },
4495      { 0x01A2, "C Battery Backup Unit Failed" },
4496      { 0x01AB, "C Mirror Race Recovery Failed" },
4497      { 0x01AC, "C Mirror Race on Critical Drive" },
4498      /* Controller Internal Processor Events */
4499      { 0x0380, "C Internal Controller Hung" },
4500      { 0x0381, "C Internal Controller Firmware Breakpoint" },
4501      { 0x0390, "C Internal Controller i960 Processor Specific Error" },
4502      { 0x03A0, "C Internal Controller StrongARM Processor Specific Error" },
4503      { 0, "" } };
4504  int EventListIndex = 0, EventCode;
4505  unsigned char EventType, *EventMessage;
4506  if (Event->EventCode == 0x1C &&
4507      RequestSense->SenseKey == DAC960_SenseKey_VendorSpecific &&
4508      (RequestSense->AdditionalSenseCode == 0x80 ||
4509       RequestSense->AdditionalSenseCode == 0x81))
4510    Event->EventCode = ((RequestSense->AdditionalSenseCode - 0x80) << 8) |
4511                       RequestSense->AdditionalSenseCodeQualifier;
4512  while (true)
4513    {
4514      EventCode = EventList[EventListIndex].EventCode;
4515      if (EventCode == Event->EventCode || EventCode == 0) break;
4516      EventListIndex++;
4517    }
4518  EventType = EventList[EventListIndex].EventMessage[0];
4519  EventMessage = &EventList[EventListIndex].EventMessage[2];
4520  if (EventCode == 0)
4521    {
4522      DAC960_Critical("Unknown Controller Event Code %04X\n",
4523                      Controller, Event->EventCode);
4524      return;
4525    }
4526  switch (EventType)
4527    {
4528    case 'P':
4529      DAC960_Critical("Physical Device %d:%d %s\n", Controller,
4530                      Event->Channel, Event->TargetID, EventMessage);
4531      break;
4532    case 'L':
4533      DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) %s\n", Controller,
4534                      Event->LogicalUnit, Controller->ControllerNumber,
4535                      Event->LogicalUnit, EventMessage);
4536      break;
4537    case 'M':
4538      DAC960_Progress("Logical Drive %d (/dev/rd/c%dd%d) %s\n", Controller,
4539                      Event->LogicalUnit, Controller->ControllerNumber,
4540                      Event->LogicalUnit, EventMessage);
4541      break;
4542    case 'S':
4543      if (RequestSense->SenseKey == DAC960_SenseKey_NoSense ||
4544          (RequestSense->SenseKey == DAC960_SenseKey_NotReady &&
4545           RequestSense->AdditionalSenseCode == 0x04 &&
4546           (RequestSense->AdditionalSenseCodeQualifier == 0x01 ||
4547            RequestSense->AdditionalSenseCodeQualifier == 0x02)))
4548        break;
4549      DAC960_Critical("Physical Device %d:%d %s\n", Controller,
4550                      Event->Channel, Event->TargetID, EventMessage);
4551      DAC960_Critical("Physical Device %d:%d Request Sense: "
4552                      "Sense Key = %X, ASC = %02X, ASCQ = %02X\n",
4553                      Controller,
4554                      Event->Channel,
4555                      Event->TargetID,
4556                      RequestSense->SenseKey,
4557                      RequestSense->AdditionalSenseCode,
4558                      RequestSense->AdditionalSenseCodeQualifier);
4559      DAC960_Critical("Physical Device %d:%d Request Sense: "
4560                      "Information = %02X%02X%02X%02X "
4561                      "%02X%02X%02X%02X\n",
4562                      Controller,
4563                      Event->Channel,
4564                      Event->TargetID,
4565                      RequestSense->Information[0],
4566                      RequestSense->Information[1],
4567                      RequestSense->Information[2],
4568                      RequestSense->Information[3],
4569                      RequestSense->CommandSpecificInformation[0],
4570                      RequestSense->CommandSpecificInformation[1],
4571                      RequestSense->CommandSpecificInformation[2],
4572                      RequestSense->CommandSpecificInformation[3]);
4573      break;
4574    case 'E':
4575      if (Controller->SuppressEnclosureMessages) break;
4576      sprintf(MessageBuffer, EventMessage, Event->LogicalUnit);
4577      DAC960_Critical("Enclosure %d %s\n", Controller,
4578                      Event->TargetID, MessageBuffer);
4579      break;
4580    case 'C':
4581      DAC960_Critical("Controller %s\n", Controller, EventMessage);
4582      break;
4583    default:
4584      DAC960_Critical("Unknown Controller Event Code %04X\n",
4585                      Controller, Event->EventCode);
4586      break;
4587    }
4588}
4589
4590
4591/*
4592  DAC960_V2_ReportProgress prints an appropriate progress message for
4593  Logical Device Long Operations.
4594*/
4595
4596static void DAC960_V2_ReportProgress(DAC960_Controller_T *Controller,
4597                                     unsigned char *MessageString,
4598                                     unsigned int LogicalDeviceNumber,
4599                                     unsigned long BlocksCompleted,
4600                                     unsigned long LogicalDeviceSize)
4601{
4602  Controller->EphemeralProgressMessage = true;
4603  DAC960_Progress("%s in Progress: Logical Drive %d (/dev/rd/c%dd%d) "
4604                  "%d%% completed\n", Controller,
4605                  MessageString,
4606                  LogicalDeviceNumber,
4607                  Controller->ControllerNumber,
4608                  LogicalDeviceNumber,
4609                  (100 * (BlocksCompleted >> 7)) / (LogicalDeviceSize >> 7));
4610  Controller->EphemeralProgressMessage = false;
4611}
4612
4613
4614/*
4615  DAC960_V2_ProcessCompletedCommand performs completion processing for Command
4616  for DAC960 V2 Firmware Controllers.
4617*/
4618
4619static void DAC960_V2_ProcessCompletedCommand(DAC960_Command_T *Command)
4620{
4621  DAC960_Controller_T *Controller = Command->Controller;
4622  DAC960_CommandType_T CommandType = Command->CommandType;
4623  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
4624  DAC960_V2_IOCTL_Opcode_T CommandOpcode = CommandMailbox->Common.IOCTL_Opcode;
4625  DAC960_V2_CommandStatus_T CommandStatus = Command->V2.CommandStatus;
4626
4627  if (CommandType == DAC960_ReadCommand ||
4628      CommandType == DAC960_WriteCommand)
4629    {
4630
4631#ifdef FORCE_RETRY_DEBUG
4632      CommandStatus = DAC960_V2_AbormalCompletion;
4633#endif
4634      Command->V2.RequestSense->SenseKey = DAC960_SenseKey_MediumError;
4635
4636      if (CommandStatus == DAC960_V2_NormalCompletion) {
4637
4638                if (!DAC960_ProcessCompletedRequest(Command, true))
4639                        BUG();
4640
4641      } else if (Command->V2.RequestSense->SenseKey == DAC960_SenseKey_MediumError)
4642        {
4643          /*
4644           * break the command down into pieces and resubmit each
4645           * piece, hoping that some of them will succeed.
4646           */
4647           DAC960_queue_partial_rw(Command);
4648           return;
4649        }
4650      else
4651        {
4652          if (Command->V2.RequestSense->SenseKey != DAC960_SenseKey_NotReady)
4653            DAC960_V2_ReadWriteError(Command);
4654          /*
4655            Perform completion processing for all buffers in this I/O Request.
4656          */
4657          (void)DAC960_ProcessCompletedRequest(Command, false);
4658        }
4659    }
4660  else if (CommandType == DAC960_ReadRetryCommand ||
4661           CommandType == DAC960_WriteRetryCommand)
4662    {
4663      bool normal_completion;
4664
4665#ifdef FORCE_RETRY_FAILURE_DEBUG
4666      static int retry_count = 1;
4667#endif
4668      /*
4669        Perform completion processing for the portion that was
4670        retried, and submit the next portion, if any.
4671      */
4672      normal_completion = true;
4673      if (CommandStatus != DAC960_V2_NormalCompletion) {
4674        normal_completion = false;
4675        if (Command->V2.RequestSense->SenseKey != DAC960_SenseKey_NotReady)
4676            DAC960_V2_ReadWriteError(Command);
4677      }
4678
4679#ifdef FORCE_RETRY_FAILURE_DEBUG
4680      if (!(++retry_count % 10000)) {
4681              printk("V2 error retry failure test\n");
4682              normal_completion = false;
4683              DAC960_V2_ReadWriteError(Command);
4684      }
4685#endif
4686
4687      if (!DAC960_ProcessCompletedRequest(Command, normal_completion)) {
4688                DAC960_queue_partial_rw(Command);
4689                return;
4690      }
4691    }
4692  else if (CommandType == DAC960_MonitoringCommand)
4693    {
4694      if (Controller->ShutdownMonitoringTimer)
4695              return;
4696      if (CommandOpcode == DAC960_V2_GetControllerInfo)
4697        {
4698          DAC960_V2_ControllerInfo_T *NewControllerInfo =
4699            Controller->V2.NewControllerInformation;
4700          DAC960_V2_ControllerInfo_T *ControllerInfo =
4701            &Controller->V2.ControllerInformation;
4702          Controller->LogicalDriveCount =
4703            NewControllerInfo->LogicalDevicesPresent;
4704          Controller->V2.NeedLogicalDeviceInformation = true;
4705          Controller->V2.NeedPhysicalDeviceInformation = true;
4706          Controller->V2.StartLogicalDeviceInformationScan = true;
4707          Controller->V2.StartPhysicalDeviceInformationScan = true;
4708          Controller->MonitoringAlertMode =
4709            (NewControllerInfo->LogicalDevicesCritical > 0 ||
4710             NewControllerInfo->LogicalDevicesOffline > 0 ||
4711             NewControllerInfo->PhysicalDisksCritical > 0 ||
4712             NewControllerInfo->PhysicalDisksOffline > 0);
4713          memcpy(ControllerInfo, NewControllerInfo,
4714                 sizeof(DAC960_V2_ControllerInfo_T));
4715        }
4716      else if (CommandOpcode == DAC960_V2_GetEvent)
4717        {
4718          if (CommandStatus == DAC960_V2_NormalCompletion) {
4719            DAC960_V2_ReportEvent(Controller, Controller->V2.Event);
4720          }
4721          Controller->V2.NextEventSequenceNumber++;
4722        }
4723      else if (CommandOpcode == DAC960_V2_GetPhysicalDeviceInfoValid &&
4724               CommandStatus == DAC960_V2_NormalCompletion)
4725        {
4726          DAC960_V2_PhysicalDeviceInfo_T *NewPhysicalDeviceInfo =
4727            Controller->V2.NewPhysicalDeviceInformation;
4728          unsigned int PhysicalDeviceIndex = Controller->V2.PhysicalDeviceIndex;
4729          DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
4730            Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
4731          DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
4732            Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
4733          unsigned int DeviceIndex;
4734          while (PhysicalDeviceInfo != NULL &&
4735                 (NewPhysicalDeviceInfo->Channel >
4736                  PhysicalDeviceInfo->Channel ||
4737                  (NewPhysicalDeviceInfo->Channel ==
4738                   PhysicalDeviceInfo->Channel &&
4739                   (NewPhysicalDeviceInfo->TargetID >
4740                    PhysicalDeviceInfo->TargetID ||
4741                   (NewPhysicalDeviceInfo->TargetID ==
4742                    PhysicalDeviceInfo->TargetID &&
4743                    NewPhysicalDeviceInfo->LogicalUnit >
4744                    PhysicalDeviceInfo->LogicalUnit)))))
4745            {
4746              DAC960_Critical("Physical Device %d:%d No Longer Exists\n",
4747                              Controller,
4748                              PhysicalDeviceInfo->Channel,
4749                              PhysicalDeviceInfo->TargetID);
4750              Controller->V2.PhysicalDeviceInformation
4751                             [PhysicalDeviceIndex] = NULL;
4752              Controller->V2.InquiryUnitSerialNumber
4753                             [PhysicalDeviceIndex] = NULL;
4754              kfree(PhysicalDeviceInfo);
4755              kfree(InquiryUnitSerialNumber);
4756              for (DeviceIndex = PhysicalDeviceIndex;
4757                   DeviceIndex < DAC960_V2_MaxPhysicalDevices - 1;
4758                   DeviceIndex++)
4759                {
4760                  Controller->V2.PhysicalDeviceInformation[DeviceIndex] =
4761                    Controller->V2.PhysicalDeviceInformation[DeviceIndex+1];
4762                  Controller->V2.InquiryUnitSerialNumber[DeviceIndex] =
4763                    Controller->V2.InquiryUnitSerialNumber[DeviceIndex+1];
4764                }
4765              Controller->V2.PhysicalDeviceInformation
4766                             [DAC960_V2_MaxPhysicalDevices-1] = NULL;
4767              Controller->V2.InquiryUnitSerialNumber
4768                             [DAC960_V2_MaxPhysicalDevices-1] = NULL;
4769              PhysicalDeviceInfo =
4770                Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
4771              InquiryUnitSerialNumber =
4772                Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
4773            }
4774          if (PhysicalDeviceInfo == NULL ||
4775              (NewPhysicalDeviceInfo->Channel !=
4776               PhysicalDeviceInfo->Channel) ||
4777              (NewPhysicalDeviceInfo->TargetID !=
4778               PhysicalDeviceInfo->TargetID) ||
4779              (NewPhysicalDeviceInfo->LogicalUnit !=
4780               PhysicalDeviceInfo->LogicalUnit))
4781            {
4782              PhysicalDeviceInfo =
4783                kmalloc(sizeof(DAC960_V2_PhysicalDeviceInfo_T), GFP_ATOMIC);
4784              InquiryUnitSerialNumber =
4785                  kmalloc(sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
4786                          GFP_ATOMIC);
4787              if (InquiryUnitSerialNumber == NULL ||
4788                  PhysicalDeviceInfo == NULL)
4789                {
4790                  kfree(InquiryUnitSerialNumber);
4791                  InquiryUnitSerialNumber = NULL;
4792                  kfree(PhysicalDeviceInfo);
4793                  PhysicalDeviceInfo = NULL;
4794                }
4795              DAC960_Critical("Physical Device %d:%d Now Exists%s\n",
4796                              Controller,
4797                              NewPhysicalDeviceInfo->Channel,
4798                              NewPhysicalDeviceInfo->TargetID,
4799                              (PhysicalDeviceInfo != NULL
4800                               ? "" : " - Allocation Failed"));
4801              if (PhysicalDeviceInfo != NULL)
4802                {
4803                  memset(PhysicalDeviceInfo, 0,
4804                         sizeof(DAC960_V2_PhysicalDeviceInfo_T));
4805                  PhysicalDeviceInfo->PhysicalDeviceState =
4806                    DAC960_V2_Device_InvalidState;
4807                  memset(InquiryUnitSerialNumber, 0,
4808                         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
4809                  InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
4810                  for (DeviceIndex = DAC960_V2_MaxPhysicalDevices - 1;
4811                       DeviceIndex > PhysicalDeviceIndex;
4812                       DeviceIndex--)
4813                    {
4814                      Controller->V2.PhysicalDeviceInformation[DeviceIndex] =
4815                        Controller->V2.PhysicalDeviceInformation[DeviceIndex-1];
4816                      Controller->V2.InquiryUnitSerialNumber[DeviceIndex] =
4817                        Controller->V2.InquiryUnitSerialNumber[DeviceIndex-1];
4818                    }
4819                  Controller->V2.PhysicalDeviceInformation
4820                                 [PhysicalDeviceIndex] =
4821                    PhysicalDeviceInfo;
4822                  Controller->V2.InquiryUnitSerialNumber
4823                                 [PhysicalDeviceIndex] =
4824                    InquiryUnitSerialNumber;
4825                  Controller->V2.NeedDeviceSerialNumberInformation = true;
4826                }
4827            }
4828          if (PhysicalDeviceInfo != NULL)
4829            {
4830              if (NewPhysicalDeviceInfo->PhysicalDeviceState !=
4831                  PhysicalDeviceInfo->PhysicalDeviceState)
4832                DAC960_Critical(
4833                  "Physical Device %d:%d is now %s\n", Controller,
4834                  NewPhysicalDeviceInfo->Channel,
4835                  NewPhysicalDeviceInfo->TargetID,
4836                  (NewPhysicalDeviceInfo->PhysicalDeviceState
4837                   == DAC960_V2_Device_Online
4838                   ? "ONLINE"
4839                   : NewPhysicalDeviceInfo->PhysicalDeviceState
4840                     == DAC960_V2_Device_Rebuild
4841                     ? "REBUILD"
4842                     : NewPhysicalDeviceInfo->PhysicalDeviceState
4843                       == DAC960_V2_Device_Missing
4844                       ? "MISSING"
4845                       : NewPhysicalDeviceInfo->PhysicalDeviceState
4846                         == DAC960_V2_Device_Critical
4847                         ? "CRITICAL"
4848                         : NewPhysicalDeviceInfo->PhysicalDeviceState
4849                           == DAC960_V2_Device_Dead
4850                           ? "DEAD"
4851                           : NewPhysicalDeviceInfo->PhysicalDeviceState
4852                             == DAC960_V2_Device_SuspectedDead
4853                             ? "SUSPECTED-DEAD"
4854                             : NewPhysicalDeviceInfo->PhysicalDeviceState
4855                               == DAC960_V2_Device_CommandedOffline
4856                               ? "COMMANDED-OFFLINE"
4857                               : NewPhysicalDeviceInfo->PhysicalDeviceState
4858                                 == DAC960_V2_Device_Standby
4859                                 ? "STANDBY" : "UNKNOWN"));
4860              if ((NewPhysicalDeviceInfo->ParityErrors !=
4861                   PhysicalDeviceInfo->ParityErrors) ||
4862                  (NewPhysicalDeviceInfo->SoftErrors !=
4863                   PhysicalDeviceInfo->SoftErrors) ||
4864                  (NewPhysicalDeviceInfo->HardErrors !=
4865                   PhysicalDeviceInfo->HardErrors) ||
4866                  (NewPhysicalDeviceInfo->MiscellaneousErrors !=
4867                   PhysicalDeviceInfo->MiscellaneousErrors) ||
4868                  (NewPhysicalDeviceInfo->CommandTimeouts !=
4869                   PhysicalDeviceInfo->CommandTimeouts) ||
4870                  (NewPhysicalDeviceInfo->Retries !=
4871                   PhysicalDeviceInfo->Retries) ||
4872                  (NewPhysicalDeviceInfo->Aborts !=
4873                   PhysicalDeviceInfo->Aborts) ||
4874                  (NewPhysicalDeviceInfo->PredictedFailuresDetected !=
4875                   PhysicalDeviceInfo->PredictedFailuresDetected))
4876                {
4877                  DAC960_Critical("Physical Device %d:%d Errors: "
4878                                  "Parity = %d, Soft = %d, "
4879                                  "Hard = %d, Misc = %d\n",
4880                                  Controller,
4881                                  NewPhysicalDeviceInfo->Channel,
4882                                  NewPhysicalDeviceInfo->TargetID,
4883                                  NewPhysicalDeviceInfo->ParityErrors,
4884                                  NewPhysicalDeviceInfo->SoftErrors,
4885                                  NewPhysicalDeviceInfo->HardErrors,
4886                                  NewPhysicalDeviceInfo->MiscellaneousErrors);
4887                  DAC960_Critical("Physical Device %d:%d Errors: "
4888                                  "Timeouts = %d, Retries = %d, "
4889                                  "Aborts = %d, Predicted = %d\n",
4890                                  Controller,
4891                                  NewPhysicalDeviceInfo->Channel,
4892                                  NewPhysicalDeviceInfo->TargetID,
4893                                  NewPhysicalDeviceInfo->CommandTimeouts,
4894                                  NewPhysicalDeviceInfo->Retries,
4895                                  NewPhysicalDeviceInfo->Aborts,
4896                                  NewPhysicalDeviceInfo
4897                                  ->PredictedFailuresDetected);
4898                }
4899              if ((PhysicalDeviceInfo->PhysicalDeviceState
4900                   == DAC960_V2_Device_Dead ||
4901                   PhysicalDeviceInfo->PhysicalDeviceState
4902                   == DAC960_V2_Device_InvalidState) &&
4903                  NewPhysicalDeviceInfo->PhysicalDeviceState
4904                  != DAC960_V2_Device_Dead)
4905                Controller->V2.NeedDeviceSerialNumberInformation = true;
4906              memcpy(PhysicalDeviceInfo, NewPhysicalDeviceInfo,
4907                     sizeof(DAC960_V2_PhysicalDeviceInfo_T));
4908            }
4909          NewPhysicalDeviceInfo->LogicalUnit++;
4910          Controller->V2.PhysicalDeviceIndex++;
4911        }
4912      else if (CommandOpcode == DAC960_V2_GetPhysicalDeviceInfoValid)
4913        {
4914          unsigned int DeviceIndex;
4915          for (DeviceIndex = Controller->V2.PhysicalDeviceIndex;
4916               DeviceIndex < DAC960_V2_MaxPhysicalDevices;
4917               DeviceIndex++)
4918            {
4919              DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
4920                Controller->V2.PhysicalDeviceInformation[DeviceIndex];
4921              DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
4922                Controller->V2.InquiryUnitSerialNumber[DeviceIndex];
4923              if (PhysicalDeviceInfo == NULL) break;
4924              DAC960_Critical("Physical Device %d:%d No Longer Exists\n",
4925                              Controller,
4926                              PhysicalDeviceInfo->Channel,
4927                              PhysicalDeviceInfo->TargetID);
4928              Controller->V2.PhysicalDeviceInformation[DeviceIndex] = NULL;
4929              Controller->V2.InquiryUnitSerialNumber[DeviceIndex] = NULL;
4930              kfree(PhysicalDeviceInfo);
4931              kfree(InquiryUnitSerialNumber);
4932            }
4933          Controller->V2.NeedPhysicalDeviceInformation = false;
4934        }
4935      else if (CommandOpcode == DAC960_V2_GetLogicalDeviceInfoValid &&
4936               CommandStatus == DAC960_V2_NormalCompletion)
4937        {
4938          DAC960_V2_LogicalDeviceInfo_T *NewLogicalDeviceInfo =
4939            Controller->V2.NewLogicalDeviceInformation;
4940          unsigned short LogicalDeviceNumber =
4941            NewLogicalDeviceInfo->LogicalDeviceNumber;
4942          DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
4943            Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber];
4944          if (LogicalDeviceInfo == NULL)
4945            {
4946              DAC960_V2_PhysicalDevice_T PhysicalDevice;
4947              PhysicalDevice.Controller = 0;
4948              PhysicalDevice.Channel = NewLogicalDeviceInfo->Channel;
4949              PhysicalDevice.TargetID = NewLogicalDeviceInfo->TargetID;
4950              PhysicalDevice.LogicalUnit = NewLogicalDeviceInfo->LogicalUnit;
4951              Controller->V2.LogicalDriveToVirtualDevice[LogicalDeviceNumber] =
4952                PhysicalDevice;
4953              LogicalDeviceInfo = kmalloc(sizeof(DAC960_V2_LogicalDeviceInfo_T),
4954                                          GFP_ATOMIC);
4955              Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber] =
4956                LogicalDeviceInfo;
4957              DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
4958                              "Now Exists%s\n", Controller,
4959                              LogicalDeviceNumber,
4960                              Controller->ControllerNumber,
4961                              LogicalDeviceNumber,
4962                              (LogicalDeviceInfo != NULL
4963                               ? "" : " - Allocation Failed"));
4964              if (LogicalDeviceInfo != NULL)
4965                {
4966                  memset(LogicalDeviceInfo, 0,
4967                         sizeof(DAC960_V2_LogicalDeviceInfo_T));
4968                  DAC960_ComputeGenericDiskInfo(Controller);
4969                }
4970            }
4971          if (LogicalDeviceInfo != NULL)
4972            {
4973              unsigned long LogicalDeviceSize =
4974                NewLogicalDeviceInfo->ConfigurableDeviceSize;
4975              if (NewLogicalDeviceInfo->LogicalDeviceState !=
4976                  LogicalDeviceInfo->LogicalDeviceState)
4977                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
4978                                "is now %s\n", Controller,
4979                                LogicalDeviceNumber,
4980                                Controller->ControllerNumber,
4981                                LogicalDeviceNumber,
4982                                (NewLogicalDeviceInfo->LogicalDeviceState
4983                                 == DAC960_V2_LogicalDevice_Online
4984                                 ? "ONLINE"
4985                                 : NewLogicalDeviceInfo->LogicalDeviceState
4986                                   == DAC960_V2_LogicalDevice_Critical
4987                                   ? "CRITICAL" : "OFFLINE"));
4988              if ((NewLogicalDeviceInfo->SoftErrors !=
4989                   LogicalDeviceInfo->SoftErrors) ||
4990                  (NewLogicalDeviceInfo->CommandsFailed !=
4991                   LogicalDeviceInfo->CommandsFailed) ||
4992                  (NewLogicalDeviceInfo->DeferredWriteErrors !=
4993                   LogicalDeviceInfo->DeferredWriteErrors))
4994                DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) Errors: "
4995                                "Soft = %d, Failed = %d, Deferred Write = %d\n",
4996                                Controller, LogicalDeviceNumber,
4997                                Controller->ControllerNumber,
4998                                LogicalDeviceNumber,
4999                                NewLogicalDeviceInfo->SoftErrors,
5000                                NewLogicalDeviceInfo->CommandsFailed,
5001                                NewLogicalDeviceInfo->DeferredWriteErrors);
5002              if (NewLogicalDeviceInfo->ConsistencyCheckInProgress)
5003                DAC960_V2_ReportProgress(Controller,
5004                                         "Consistency Check",
5005                                         LogicalDeviceNumber,
5006                                         NewLogicalDeviceInfo
5007                                         ->ConsistencyCheckBlockNumber,
5008                                         LogicalDeviceSize);
5009              else if (NewLogicalDeviceInfo->RebuildInProgress)
5010                DAC960_V2_ReportProgress(Controller,
5011                                         "Rebuild",
5012                                         LogicalDeviceNumber,
5013                                         NewLogicalDeviceInfo
5014                                         ->RebuildBlockNumber,
5015                                         LogicalDeviceSize);
5016              else if (NewLogicalDeviceInfo->BackgroundInitializationInProgress)
5017                DAC960_V2_ReportProgress(Controller,
5018                                         "Background Initialization",
5019                                         LogicalDeviceNumber,
5020                                         NewLogicalDeviceInfo
5021                                         ->BackgroundInitializationBlockNumber,
5022                                         LogicalDeviceSize);
5023              else if (NewLogicalDeviceInfo->ForegroundInitializationInProgress)
5024                DAC960_V2_ReportProgress(Controller,
5025                                         "Foreground Initialization",
5026                                         LogicalDeviceNumber,
5027                                         NewLogicalDeviceInfo
5028                                         ->ForegroundInitializationBlockNumber,
5029                                         LogicalDeviceSize);
5030              else if (NewLogicalDeviceInfo->DataMigrationInProgress)
5031                DAC960_V2_ReportProgress(Controller,
5032                                         "Data Migration",
5033                                         LogicalDeviceNumber,
5034                                         NewLogicalDeviceInfo
5035                                         ->DataMigrationBlockNumber,
5036                                         LogicalDeviceSize);
5037              else if (NewLogicalDeviceInfo->PatrolOperationInProgress)
5038                DAC960_V2_ReportProgress(Controller,
5039                                         "Patrol Operation",
5040                                         LogicalDeviceNumber,
5041                                         NewLogicalDeviceInfo
5042                                         ->PatrolOperationBlockNumber,
5043                                         LogicalDeviceSize);
5044              if (LogicalDeviceInfo->BackgroundInitializationInProgress &&
5045                  !NewLogicalDeviceInfo->BackgroundInitializationInProgress)
5046                DAC960_Progress("Logical Drive %d (/dev/rd/c%dd%d) "
5047                                "Background Initialization %s\n",
5048                                Controller,
5049                                LogicalDeviceNumber,
5050                                Controller->ControllerNumber,
5051                                LogicalDeviceNumber,
5052                                (NewLogicalDeviceInfo->LogicalDeviceControl
5053                                                      .LogicalDeviceInitialized
5054                                 ? "Completed" : "Failed"));
5055              memcpy(LogicalDeviceInfo, NewLogicalDeviceInfo,
5056                     sizeof(DAC960_V2_LogicalDeviceInfo_T));
5057            }
5058          Controller->V2.LogicalDriveFoundDuringScan
5059                         [LogicalDeviceNumber] = true;
5060          NewLogicalDeviceInfo->LogicalDeviceNumber++;
5061        }
5062      else if (CommandOpcode == DAC960_V2_GetLogicalDeviceInfoValid)
5063        {
5064          int LogicalDriveNumber;
5065          for (LogicalDriveNumber = 0;
5066               LogicalDriveNumber < DAC960_MaxLogicalDrives;
5067               LogicalDriveNumber++)
5068            {
5069              DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
5070                Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
5071              if (LogicalDeviceInfo == NULL ||
5072                  Controller->V2.LogicalDriveFoundDuringScan
5073                                 [LogicalDriveNumber])
5074                continue;
5075              DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
5076                              "No Longer Exists\n", Controller,
5077                              LogicalDriveNumber,
5078                              Controller->ControllerNumber,
5079                              LogicalDriveNumber);
5080              Controller->V2.LogicalDeviceInformation
5081                             [LogicalDriveNumber] = NULL;
5082              kfree(LogicalDeviceInfo);
5083              Controller->LogicalDriveInitiallyAccessible
5084                          [LogicalDriveNumber] = false;
5085              DAC960_ComputeGenericDiskInfo(Controller);
5086            }
5087          Controller->V2.NeedLogicalDeviceInformation = false;
5088        }
5089      else if (CommandOpcode == DAC960_V2_SCSI_10_Passthru)
5090        {
5091            DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
5092                Controller->V2.InquiryUnitSerialNumber[Controller->V2.PhysicalDeviceIndex - 1];
5093
5094            if (CommandStatus != DAC960_V2_NormalCompletion) {
5095                memset(InquiryUnitSerialNumber,
5096                        0, sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
5097                InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
5098            } else
5099                memcpy(InquiryUnitSerialNumber,
5100                        Controller->V2.NewInquiryUnitSerialNumber,
5101                        sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
5102
5103             Controller->V2.NeedDeviceSerialNumberInformation = false;
5104        }
5105
5106      if (Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
5107          - Controller->V2.NextEventSequenceNumber > 0)
5108        {
5109          CommandMailbox->GetEvent.CommandOpcode = DAC960_V2_IOCTL;
5110          CommandMailbox->GetEvent.DataTransferSize = sizeof(DAC960_V2_Event_T);
5111          CommandMailbox->GetEvent.EventSequenceNumberHigh16 =
5112            Controller->V2.NextEventSequenceNumber >> 16;
5113          CommandMailbox->GetEvent.ControllerNumber = 0;
5114          CommandMailbox->GetEvent.IOCTL_Opcode =
5115            DAC960_V2_GetEvent;
5116          CommandMailbox->GetEvent.EventSequenceNumberLow16 =
5117            Controller->V2.NextEventSequenceNumber & 0xFFFF;
5118          CommandMailbox->GetEvent.DataTransferMemoryAddress
5119                                  .ScatterGatherSegments[0]
5120                                  .SegmentDataPointer =
5121            Controller->V2.EventDMA;
5122          CommandMailbox->GetEvent.DataTransferMemoryAddress
5123                                  .ScatterGatherSegments[0]
5124                                  .SegmentByteCount =
5125            CommandMailbox->GetEvent.DataTransferSize;
5126          DAC960_QueueCommand(Command);
5127          return;
5128        }
5129      if (Controller->V2.NeedPhysicalDeviceInformation)
5130        {
5131          if (Controller->V2.NeedDeviceSerialNumberInformation)
5132            {
5133              DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
5134                Controller->V2.NewInquiryUnitSerialNumber;
5135              InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
5136
5137              DAC960_V2_ConstructNewUnitSerialNumber(Controller, CommandMailbox,
5138                        Controller->V2.NewPhysicalDeviceInformation->Channel,
5139                        Controller->V2.NewPhysicalDeviceInformation->TargetID,
5140                Controller->V2.NewPhysicalDeviceInformation->LogicalUnit - 1);
5141
5142
5143              DAC960_QueueCommand(Command);
5144              return;
5145            }
5146          if (Controller->V2.StartPhysicalDeviceInformationScan)
5147            {
5148              Controller->V2.PhysicalDeviceIndex = 0;
5149              Controller->V2.NewPhysicalDeviceInformation->Channel = 0;
5150              Controller->V2.NewPhysicalDeviceInformation->TargetID = 0;
5151              Controller->V2.NewPhysicalDeviceInformation->LogicalUnit = 0;
5152              Controller->V2.StartPhysicalDeviceInformationScan = false;
5153            }
5154          CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
5155          CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
5156            sizeof(DAC960_V2_PhysicalDeviceInfo_T);
5157          CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.LogicalUnit =
5158            Controller->V2.NewPhysicalDeviceInformation->LogicalUnit;
5159          CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID =
5160            Controller->V2.NewPhysicalDeviceInformation->TargetID;
5161          CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel =
5162            Controller->V2.NewPhysicalDeviceInformation->Channel;
5163          CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
5164            DAC960_V2_GetPhysicalDeviceInfoValid;
5165          CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
5166                                            .ScatterGatherSegments[0]
5167                                            .SegmentDataPointer =
5168            Controller->V2.NewPhysicalDeviceInformationDMA;
5169          CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
5170                                            .ScatterGatherSegments[0]
5171                                            .SegmentByteCount =
5172            CommandMailbox->PhysicalDeviceInfo.DataTransferSize;
5173          DAC960_QueueCommand(Command);
5174          return;
5175        }
5176      if (Controller->V2.NeedLogicalDeviceInformation)
5177        {
5178          if (Controller->V2.StartLogicalDeviceInformationScan)
5179            {
5180              int LogicalDriveNumber;
5181              for (LogicalDriveNumber = 0;
5182                   LogicalDriveNumber < DAC960_MaxLogicalDrives;
5183                   LogicalDriveNumber++)
5184                Controller->V2.LogicalDriveFoundDuringScan
5185                               [LogicalDriveNumber] = false;
5186              Controller->V2.NewLogicalDeviceInformation->LogicalDeviceNumber = 0;
5187              Controller->V2.StartLogicalDeviceInformationScan = false;
5188            }
5189          CommandMailbox->LogicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
5190          CommandMailbox->LogicalDeviceInfo.DataTransferSize =
5191            sizeof(DAC960_V2_LogicalDeviceInfo_T);
5192          CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
5193            Controller->V2.NewLogicalDeviceInformation->LogicalDeviceNumber;
5194          CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
5195            DAC960_V2_GetLogicalDeviceInfoValid;
5196          CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
5197                                           .ScatterGatherSegments[0]
5198                                           .SegmentDataPointer =
5199            Controller->V2.NewLogicalDeviceInformationDMA;
5200          CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
5201                                           .ScatterGatherSegments[0]
5202                                           .SegmentByteCount =
5203            CommandMailbox->LogicalDeviceInfo.DataTransferSize;
5204          DAC960_QueueCommand(Command);
5205          return;
5206        }
5207      Controller->MonitoringTimerCount++;
5208      Controller->MonitoringTimer.expires =
5209        jiffies + DAC960_HealthStatusMonitoringInterval;
5210        add_timer(&Controller->MonitoringTimer);
5211    }
5212  if (CommandType == DAC960_ImmediateCommand)
5213    {
5214      complete(Command->Completion);
5215      Command->Completion = NULL;
5216      return;
5217    }
5218  if (CommandType == DAC960_QueuedCommand)
5219    {
5220      DAC960_V2_KernelCommand_T *KernelCommand = Command->V2.KernelCommand;
5221      KernelCommand->CommandStatus = CommandStatus;
5222      KernelCommand->RequestSenseLength = Command->V2.RequestSenseLength;
5223      KernelCommand->DataTransferLength = Command->V2.DataTransferResidue;
5224      Command->V2.KernelCommand = NULL;
5225      DAC960_DeallocateCommand(Command);
5226      KernelCommand->CompletionFunction(KernelCommand);
5227      return;
5228    }
5229  /*
5230    Queue a Status Monitoring Command to the Controller using the just
5231    completed Command if one was deferred previously due to lack of a
5232    free Command when the Monitoring Timer Function was called.
5233  */
5234  if (Controller->MonitoringCommandDeferred)
5235    {
5236      Controller->MonitoringCommandDeferred = false;
5237      DAC960_V2_QueueMonitoringCommand(Command);
5238      return;
5239    }
5240  /*
5241    Deallocate the Command.
5242  */
5243  DAC960_DeallocateCommand(Command);
5244  /*
5245    Wake up any processes waiting on a free Command.
5246  */
5247  wake_up(&Controller->CommandWaitQueue);
5248}
5249
5250/*
5251  DAC960_GEM_InterruptHandler handles hardware interrupts from DAC960 GEM Series
5252  Controllers.
5253*/
5254
5255static irqreturn_t DAC960_GEM_InterruptHandler(int IRQ_Channel,
5256                                       void *DeviceIdentifier)
5257{
5258  DAC960_Controller_T *Controller = DeviceIdentifier;
5259  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5260  DAC960_V2_StatusMailbox_T *NextStatusMailbox;
5261  unsigned long flags;
5262
5263  spin_lock_irqsave(&Controller->queue_lock, flags);
5264  DAC960_GEM_AcknowledgeInterrupt(ControllerBaseAddress);
5265  NextStatusMailbox = Controller->V2.NextStatusMailbox;
5266  while (NextStatusMailbox->Fields.CommandIdentifier > 0)
5267    {
5268       DAC960_V2_CommandIdentifier_T CommandIdentifier =
5269           NextStatusMailbox->Fields.CommandIdentifier;
5270       DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5271       Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
5272       Command->V2.RequestSenseLength =
5273           NextStatusMailbox->Fields.RequestSenseLength;
5274       Command->V2.DataTransferResidue =
5275           NextStatusMailbox->Fields.DataTransferResidue;
5276       NextStatusMailbox->Words[0] = 0;
5277       if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
5278           NextStatusMailbox = Controller->V2.FirstStatusMailbox;
5279       DAC960_V2_ProcessCompletedCommand(Command);
5280    }
5281  Controller->V2.NextStatusMailbox = NextStatusMailbox;
5282  /*
5283    Attempt to remove additional I/O Requests from the Controller's
5284    I/O Request Queue and queue them to the Controller.
5285  */
5286  DAC960_ProcessRequest(Controller);
5287  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5288  return IRQ_HANDLED;
5289}
5290
5291/*
5292  DAC960_BA_InterruptHandler handles hardware interrupts from DAC960 BA Series
5293  Controllers.
5294*/
5295
5296static irqreturn_t DAC960_BA_InterruptHandler(int IRQ_Channel,
5297                                       void *DeviceIdentifier)
5298{
5299  DAC960_Controller_T *Controller = DeviceIdentifier;
5300  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5301  DAC960_V2_StatusMailbox_T *NextStatusMailbox;
5302  unsigned long flags;
5303
5304  spin_lock_irqsave(&Controller->queue_lock, flags);
5305  DAC960_BA_AcknowledgeInterrupt(ControllerBaseAddress);
5306  NextStatusMailbox = Controller->V2.NextStatusMailbox;
5307  while (NextStatusMailbox->Fields.CommandIdentifier > 0)
5308    {
5309      DAC960_V2_CommandIdentifier_T CommandIdentifier =
5310        NextStatusMailbox->Fields.CommandIdentifier;
5311      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5312      Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
5313      Command->V2.RequestSenseLength =
5314        NextStatusMailbox->Fields.RequestSenseLength;
5315      Command->V2.DataTransferResidue =
5316        NextStatusMailbox->Fields.DataTransferResidue;
5317      NextStatusMailbox->Words[0] = 0;
5318      if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
5319        NextStatusMailbox = Controller->V2.FirstStatusMailbox;
5320      DAC960_V2_ProcessCompletedCommand(Command);
5321    }
5322  Controller->V2.NextStatusMailbox = NextStatusMailbox;
5323  /*
5324    Attempt to remove additional I/O Requests from the Controller's
5325    I/O Request Queue and queue them to the Controller.
5326  */
5327  DAC960_ProcessRequest(Controller);
5328  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5329  return IRQ_HANDLED;
5330}
5331
5332
5333/*
5334  DAC960_LP_InterruptHandler handles hardware interrupts from DAC960 LP Series
5335  Controllers.
5336*/
5337
5338static irqreturn_t DAC960_LP_InterruptHandler(int IRQ_Channel,
5339                                       void *DeviceIdentifier)
5340{
5341  DAC960_Controller_T *Controller = DeviceIdentifier;
5342  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5343  DAC960_V2_StatusMailbox_T *NextStatusMailbox;
5344  unsigned long flags;
5345
5346  spin_lock_irqsave(&Controller->queue_lock, flags);
5347  DAC960_LP_AcknowledgeInterrupt(ControllerBaseAddress);
5348  NextStatusMailbox = Controller->V2.NextStatusMailbox;
5349  while (NextStatusMailbox->Fields.CommandIdentifier > 0)
5350    {
5351      DAC960_V2_CommandIdentifier_T CommandIdentifier =
5352        NextStatusMailbox->Fields.CommandIdentifier;
5353      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5354      Command->V2.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
5355      Command->V2.RequestSenseLength =
5356        NextStatusMailbox->Fields.RequestSenseLength;
5357      Command->V2.DataTransferResidue =
5358        NextStatusMailbox->Fields.DataTransferResidue;
5359      NextStatusMailbox->Words[0] = 0;
5360      if (++NextStatusMailbox > Controller->V2.LastStatusMailbox)
5361        NextStatusMailbox = Controller->V2.FirstStatusMailbox;
5362      DAC960_V2_ProcessCompletedCommand(Command);
5363    }
5364  Controller->V2.NextStatusMailbox = NextStatusMailbox;
5365  /*
5366    Attempt to remove additional I/O Requests from the Controller's
5367    I/O Request Queue and queue them to the Controller.
5368  */
5369  DAC960_ProcessRequest(Controller);
5370  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5371  return IRQ_HANDLED;
5372}
5373
5374
5375/*
5376  DAC960_LA_InterruptHandler handles hardware interrupts from DAC960 LA Series
5377  Controllers.
5378*/
5379
5380static irqreturn_t DAC960_LA_InterruptHandler(int IRQ_Channel,
5381                                       void *DeviceIdentifier)
5382{
5383  DAC960_Controller_T *Controller = DeviceIdentifier;
5384  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5385  DAC960_V1_StatusMailbox_T *NextStatusMailbox;
5386  unsigned long flags;
5387
5388  spin_lock_irqsave(&Controller->queue_lock, flags);
5389  DAC960_LA_AcknowledgeInterrupt(ControllerBaseAddress);
5390  NextStatusMailbox = Controller->V1.NextStatusMailbox;
5391  while (NextStatusMailbox->Fields.Valid)
5392    {
5393      DAC960_V1_CommandIdentifier_T CommandIdentifier =
5394        NextStatusMailbox->Fields.CommandIdentifier;
5395      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5396      Command->V1.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
5397      NextStatusMailbox->Word = 0;
5398      if (++NextStatusMailbox > Controller->V1.LastStatusMailbox)
5399        NextStatusMailbox = Controller->V1.FirstStatusMailbox;
5400      DAC960_V1_ProcessCompletedCommand(Command);
5401    }
5402  Controller->V1.NextStatusMailbox = NextStatusMailbox;
5403  /*
5404    Attempt to remove additional I/O Requests from the Controller's
5405    I/O Request Queue and queue them to the Controller.
5406  */
5407  DAC960_ProcessRequest(Controller);
5408  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5409  return IRQ_HANDLED;
5410}
5411
5412
5413/*
5414  DAC960_PG_InterruptHandler handles hardware interrupts from DAC960 PG Series
5415  Controllers.
5416*/
5417
5418static irqreturn_t DAC960_PG_InterruptHandler(int IRQ_Channel,
5419                                       void *DeviceIdentifier)
5420{
5421  DAC960_Controller_T *Controller = DeviceIdentifier;
5422  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5423  DAC960_V1_StatusMailbox_T *NextStatusMailbox;
5424  unsigned long flags;
5425
5426  spin_lock_irqsave(&Controller->queue_lock, flags);
5427  DAC960_PG_AcknowledgeInterrupt(ControllerBaseAddress);
5428  NextStatusMailbox = Controller->V1.NextStatusMailbox;
5429  while (NextStatusMailbox->Fields.Valid)
5430    {
5431      DAC960_V1_CommandIdentifier_T CommandIdentifier =
5432        NextStatusMailbox->Fields.CommandIdentifier;
5433      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5434      Command->V1.CommandStatus = NextStatusMailbox->Fields.CommandStatus;
5435      NextStatusMailbox->Word = 0;
5436      if (++NextStatusMailbox > Controller->V1.LastStatusMailbox)
5437        NextStatusMailbox = Controller->V1.FirstStatusMailbox;
5438      DAC960_V1_ProcessCompletedCommand(Command);
5439    }
5440  Controller->V1.NextStatusMailbox = NextStatusMailbox;
5441  /*
5442    Attempt to remove additional I/O Requests from the Controller's
5443    I/O Request Queue and queue them to the Controller.
5444  */
5445  DAC960_ProcessRequest(Controller);
5446  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5447  return IRQ_HANDLED;
5448}
5449
5450
5451/*
5452  DAC960_PD_InterruptHandler handles hardware interrupts from DAC960 PD Series
5453  Controllers.
5454*/
5455
5456static irqreturn_t DAC960_PD_InterruptHandler(int IRQ_Channel,
5457                                       void *DeviceIdentifier)
5458{
5459  DAC960_Controller_T *Controller = DeviceIdentifier;
5460  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5461  unsigned long flags;
5462
5463  spin_lock_irqsave(&Controller->queue_lock, flags);
5464  while (DAC960_PD_StatusAvailableP(ControllerBaseAddress))
5465    {
5466      DAC960_V1_CommandIdentifier_T CommandIdentifier =
5467        DAC960_PD_ReadStatusCommandIdentifier(ControllerBaseAddress);
5468      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5469      Command->V1.CommandStatus =
5470        DAC960_PD_ReadStatusRegister(ControllerBaseAddress);
5471      DAC960_PD_AcknowledgeInterrupt(ControllerBaseAddress);
5472      DAC960_PD_AcknowledgeStatus(ControllerBaseAddress);
5473      DAC960_V1_ProcessCompletedCommand(Command);
5474    }
5475  /*
5476    Attempt to remove additional I/O Requests from the Controller's
5477    I/O Request Queue and queue them to the Controller.
5478  */
5479  DAC960_ProcessRequest(Controller);
5480  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5481  return IRQ_HANDLED;
5482}
5483
5484
5485/*
5486  DAC960_P_InterruptHandler handles hardware interrupts from DAC960 P Series
5487  Controllers.
5488
5489  Translations of DAC960_V1_Enquiry and DAC960_V1_GetDeviceState rely
5490  on the data having been placed into DAC960_Controller_T, rather than
5491  an arbitrary buffer.
5492*/
5493
5494static irqreturn_t DAC960_P_InterruptHandler(int IRQ_Channel,
5495                                      void *DeviceIdentifier)
5496{
5497  DAC960_Controller_T *Controller = DeviceIdentifier;
5498  void __iomem *ControllerBaseAddress = Controller->BaseAddress;
5499  unsigned long flags;
5500
5501  spin_lock_irqsave(&Controller->queue_lock, flags);
5502  while (DAC960_PD_StatusAvailableP(ControllerBaseAddress))
5503    {
5504      DAC960_V1_CommandIdentifier_T CommandIdentifier =
5505        DAC960_PD_ReadStatusCommandIdentifier(ControllerBaseAddress);
5506      DAC960_Command_T *Command = Controller->Commands[CommandIdentifier-1];
5507      DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
5508      DAC960_V1_CommandOpcode_T CommandOpcode =
5509        CommandMailbox->Common.CommandOpcode;
5510      Command->V1.CommandStatus =
5511        DAC960_PD_ReadStatusRegister(ControllerBaseAddress);
5512      DAC960_PD_AcknowledgeInterrupt(ControllerBaseAddress);
5513      DAC960_PD_AcknowledgeStatus(ControllerBaseAddress);
5514      switch (CommandOpcode)
5515        {
5516        case DAC960_V1_Enquiry_Old:
5517          Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Enquiry;
5518          DAC960_P_To_PD_TranslateEnquiry(Controller->V1.NewEnquiry);
5519          break;
5520        case DAC960_V1_GetDeviceState_Old:
5521          Command->V1.CommandMailbox.Common.CommandOpcode =
5522                                                DAC960_V1_GetDeviceState;
5523          DAC960_P_To_PD_TranslateDeviceState(Controller->V1.NewDeviceState);
5524          break;
5525        case DAC960_V1_Read_Old:
5526          Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Read;
5527          DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
5528          break;
5529        case DAC960_V1_Write_Old:
5530          Command->V1.CommandMailbox.Common.CommandOpcode = DAC960_V1_Write;
5531          DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
5532          break;
5533        case DAC960_V1_ReadWithScatterGather_Old:
5534          Command->V1.CommandMailbox.Common.CommandOpcode =
5535            DAC960_V1_ReadWithScatterGather;
5536          DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
5537          break;
5538        case DAC960_V1_WriteWithScatterGather_Old:
5539          Command->V1.CommandMailbox.Common.CommandOpcode =
5540            DAC960_V1_WriteWithScatterGather;
5541          DAC960_P_To_PD_TranslateReadWriteCommand(CommandMailbox);
5542          break;
5543        default:
5544          break;
5545        }
5546      DAC960_V1_ProcessCompletedCommand(Command);
5547    }
5548  /*
5549    Attempt to remove additional I/O Requests from the Controller's
5550    I/O Request Queue and queue them to the Controller.
5551  */
5552  DAC960_ProcessRequest(Controller);
5553  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5554  return IRQ_HANDLED;
5555}
5556
5557
5558/*
5559  DAC960_V1_QueueMonitoringCommand queues a Monitoring Command to DAC960 V1
5560  Firmware Controllers.
5561*/
5562
5563static void DAC960_V1_QueueMonitoringCommand(DAC960_Command_T *Command)
5564{
5565  DAC960_Controller_T *Controller = Command->Controller;
5566  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
5567  DAC960_V1_ClearCommand(Command);
5568  Command->CommandType = DAC960_MonitoringCommand;
5569  CommandMailbox->Type3.CommandOpcode = DAC960_V1_Enquiry;
5570  CommandMailbox->Type3.BusAddress = Controller->V1.NewEnquiryDMA;
5571  DAC960_QueueCommand(Command);
5572}
5573
5574
5575/*
5576  DAC960_V2_QueueMonitoringCommand queues a Monitoring Command to DAC960 V2
5577  Firmware Controllers.
5578*/
5579
5580static void DAC960_V2_QueueMonitoringCommand(DAC960_Command_T *Command)
5581{
5582  DAC960_Controller_T *Controller = Command->Controller;
5583  DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
5584  DAC960_V2_ClearCommand(Command);
5585  Command->CommandType = DAC960_MonitoringCommand;
5586  CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
5587  CommandMailbox->ControllerInfo.CommandControlBits
5588                                .DataTransferControllerToHost = true;
5589  CommandMailbox->ControllerInfo.CommandControlBits
5590                                .NoAutoRequestSense = true;
5591  CommandMailbox->ControllerInfo.DataTransferSize =
5592    sizeof(DAC960_V2_ControllerInfo_T);
5593  CommandMailbox->ControllerInfo.ControllerNumber = 0;
5594  CommandMailbox->ControllerInfo.IOCTL_Opcode = DAC960_V2_GetControllerInfo;
5595  CommandMailbox->ControllerInfo.DataTransferMemoryAddress
5596                                .ScatterGatherSegments[0]
5597                                .SegmentDataPointer =
5598    Controller->V2.NewControllerInformationDMA;
5599  CommandMailbox->ControllerInfo.DataTransferMemoryAddress
5600                                .ScatterGatherSegments[0]
5601                                .SegmentByteCount =
5602    CommandMailbox->ControllerInfo.DataTransferSize;
5603  DAC960_QueueCommand(Command);
5604}
5605
5606
5607/*
5608  DAC960_MonitoringTimerFunction is the timer function for monitoring
5609  the status of DAC960 Controllers.
5610*/
5611
5612static void DAC960_MonitoringTimerFunction(unsigned long TimerData)
5613{
5614  DAC960_Controller_T *Controller = (DAC960_Controller_T *) TimerData;
5615  DAC960_Command_T *Command;
5616  unsigned long flags;
5617
5618  if (Controller->FirmwareType == DAC960_V1_Controller)
5619    {
5620      spin_lock_irqsave(&Controller->queue_lock, flags);
5621      /*
5622        Queue a Status Monitoring Command to Controller.
5623      */
5624      Command = DAC960_AllocateCommand(Controller);
5625      if (Command != NULL)
5626        DAC960_V1_QueueMonitoringCommand(Command);
5627      else Controller->MonitoringCommandDeferred = true;
5628      spin_unlock_irqrestore(&Controller->queue_lock, flags);
5629    }
5630  else
5631    {
5632      DAC960_V2_ControllerInfo_T *ControllerInfo =
5633        &Controller->V2.ControllerInformation;
5634      unsigned int StatusChangeCounter =
5635        Controller->V2.HealthStatusBuffer->StatusChangeCounter;
5636      bool ForceMonitoringCommand = false;
5637      if (time_after(jiffies, Controller->SecondaryMonitoringTime
5638          + DAC960_SecondaryMonitoringInterval))
5639        {
5640          int LogicalDriveNumber;
5641          for (LogicalDriveNumber = 0;
5642               LogicalDriveNumber < DAC960_MaxLogicalDrives;
5643               LogicalDriveNumber++)
5644            {
5645              DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
5646                Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
5647              if (LogicalDeviceInfo == NULL) continue;
5648              if (!LogicalDeviceInfo->LogicalDeviceControl
5649                                     .LogicalDeviceInitialized)
5650                {
5651                  ForceMonitoringCommand = true;
5652                  break;
5653                }
5654            }
5655          Controller->SecondaryMonitoringTime = jiffies;
5656        }
5657      if (StatusChangeCounter == Controller->V2.StatusChangeCounter &&
5658          Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
5659          == Controller->V2.NextEventSequenceNumber &&
5660          (ControllerInfo->BackgroundInitializationsActive +
5661           ControllerInfo->LogicalDeviceInitializationsActive +
5662           ControllerInfo->PhysicalDeviceInitializationsActive +
5663           ControllerInfo->ConsistencyChecksActive +
5664           ControllerInfo->RebuildsActive +
5665           ControllerInfo->OnlineExpansionsActive == 0 ||
5666           time_before(jiffies, Controller->PrimaryMonitoringTime
5667           + DAC960_MonitoringTimerInterval)) &&
5668          !ForceMonitoringCommand)
5669        {
5670          Controller->MonitoringTimer.expires =
5671            jiffies + DAC960_HealthStatusMonitoringInterval;
5672            add_timer(&Controller->MonitoringTimer);
5673          return;
5674        }
5675      Controller->V2.StatusChangeCounter = StatusChangeCounter;
5676      Controller->PrimaryMonitoringTime = jiffies;
5677
5678      spin_lock_irqsave(&Controller->queue_lock, flags);
5679      /*
5680        Queue a Status Monitoring Command to Controller.
5681      */
5682      Command = DAC960_AllocateCommand(Controller);
5683      if (Command != NULL)
5684        DAC960_V2_QueueMonitoringCommand(Command);
5685      else Controller->MonitoringCommandDeferred = true;
5686      spin_unlock_irqrestore(&Controller->queue_lock, flags);
5687      /*
5688        Wake up any processes waiting on a Health Status Buffer change.
5689      */
5690      wake_up(&Controller->HealthStatusWaitQueue);
5691    }
5692}
5693
5694/*
5695  DAC960_CheckStatusBuffer verifies that there is room to hold ByteCount
5696  additional bytes in the Combined Status Buffer and grows the buffer if
5697  necessary.  It returns true if there is enough room and false otherwise.
5698*/
5699
5700static bool DAC960_CheckStatusBuffer(DAC960_Controller_T *Controller,
5701                                        unsigned int ByteCount)
5702{
5703  unsigned char *NewStatusBuffer;
5704  if (Controller->InitialStatusLength + 1 +
5705      Controller->CurrentStatusLength + ByteCount + 1 <=
5706      Controller->CombinedStatusBufferLength)
5707    return true;
5708  if (Controller->CombinedStatusBufferLength == 0)
5709    {
5710      unsigned int NewStatusBufferLength = DAC960_InitialStatusBufferSize;
5711      while (NewStatusBufferLength < ByteCount)
5712        NewStatusBufferLength *= 2;
5713      Controller->CombinedStatusBuffer = kmalloc(NewStatusBufferLength,
5714                                                  GFP_ATOMIC);
5715      if (Controller->CombinedStatusBuffer == NULL) return false;
5716      Controller->CombinedStatusBufferLength = NewStatusBufferLength;
5717      return true;
5718    }
5719  NewStatusBuffer = kmalloc(2 * Controller->CombinedStatusBufferLength,
5720                             GFP_ATOMIC);
5721  if (NewStatusBuffer == NULL)
5722    {
5723      DAC960_Warning("Unable to expand Combined Status Buffer - Truncating\n",
5724                     Controller);
5725      return false;
5726    }
5727  memcpy(NewStatusBuffer, Controller->CombinedStatusBuffer,
5728         Controller->CombinedStatusBufferLength);
5729  kfree(Controller->CombinedStatusBuffer);
5730  Controller->CombinedStatusBuffer = NewStatusBuffer;
5731  Controller->CombinedStatusBufferLength *= 2;
5732  Controller->CurrentStatusBuffer =
5733    &NewStatusBuffer[Controller->InitialStatusLength + 1];
5734  return true;
5735}
5736
5737
5738/*
5739  DAC960_Message prints Driver Messages.
5740*/
5741
5742static void DAC960_Message(DAC960_MessageLevel_T MessageLevel,
5743                           unsigned char *Format,
5744                           DAC960_Controller_T *Controller,
5745                           ...)
5746{
5747  static unsigned char Buffer[DAC960_LineBufferSize];
5748  static bool BeginningOfLine = true;
5749  va_list Arguments;
5750  int Length = 0;
5751  va_start(Arguments, Controller);
5752  Length = vsprintf(Buffer, Format, Arguments);
5753  va_end(Arguments);
5754  if (Controller == NULL)
5755    printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
5756           DAC960_ControllerCount, Buffer);
5757  else if (MessageLevel == DAC960_AnnounceLevel ||
5758           MessageLevel == DAC960_InfoLevel)
5759    {
5760      if (!Controller->ControllerInitialized)
5761        {
5762          if (DAC960_CheckStatusBuffer(Controller, Length))
5763            {
5764              strcpy(&Controller->CombinedStatusBuffer
5765                                  [Controller->InitialStatusLength],
5766                     Buffer);
5767              Controller->InitialStatusLength += Length;
5768              Controller->CurrentStatusBuffer =
5769                &Controller->CombinedStatusBuffer
5770                             [Controller->InitialStatusLength + 1];
5771            }
5772          if (MessageLevel == DAC960_AnnounceLevel)
5773            {
5774              static int AnnouncementLines = 0;
5775              if (++AnnouncementLines <= 2)
5776                printk("%sDAC960: %s", DAC960_MessageLevelMap[MessageLevel],
5777                       Buffer);
5778            }
5779          else
5780            {
5781              if (BeginningOfLine)
5782                {
5783                  if (Buffer[0] != '\n' || Length > 1)
5784                    printk("%sDAC960#%d: %s",
5785                           DAC960_MessageLevelMap[MessageLevel],
5786                           Controller->ControllerNumber, Buffer);
5787                }
5788              else printk("%s", Buffer);
5789            }
5790        }
5791      else if (DAC960_CheckStatusBuffer(Controller, Length))
5792        {
5793          strcpy(&Controller->CurrentStatusBuffer[
5794                    Controller->CurrentStatusLength], Buffer);
5795          Controller->CurrentStatusLength += Length;
5796        }
5797    }
5798  else if (MessageLevel == DAC960_ProgressLevel)
5799    {
5800      strcpy(Controller->ProgressBuffer, Buffer);
5801      Controller->ProgressBufferLength = Length;
5802      if (Controller->EphemeralProgressMessage)
5803        {
5804          if (time_after_eq(jiffies, Controller->LastProgressReportTime
5805              + DAC960_ProgressReportingInterval))
5806            {
5807              printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
5808                     Controller->ControllerNumber, Buffer);
5809              Controller->LastProgressReportTime = jiffies;
5810            }
5811        }
5812      else printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
5813                  Controller->ControllerNumber, Buffer);
5814    }
5815  else if (MessageLevel == DAC960_UserCriticalLevel)
5816    {
5817      strcpy(&Controller->UserStatusBuffer[Controller->UserStatusLength],
5818             Buffer);
5819      Controller->UserStatusLength += Length;
5820      if (Buffer[0] != '\n' || Length > 1)
5821        printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
5822               Controller->ControllerNumber, Buffer);
5823    }
5824  else
5825    {
5826      if (BeginningOfLine)
5827        printk("%sDAC960#%d: %s", DAC960_MessageLevelMap[MessageLevel],
5828               Controller->ControllerNumber, Buffer);
5829      else printk("%s", Buffer);
5830    }
5831  BeginningOfLine = (Buffer[Length-1] == '\n');
5832}
5833
5834
5835/*
5836  DAC960_ParsePhysicalDevice parses spaces followed by a Physical Device
5837  Channel:TargetID specification from a User Command string.  It updates
5838  Channel and TargetID and returns true on success and false on failure.
5839*/
5840
5841static bool DAC960_ParsePhysicalDevice(DAC960_Controller_T *Controller,
5842                                          char *UserCommandString,
5843                                          unsigned char *Channel,
5844                                          unsigned char *TargetID)
5845{
5846  char *NewUserCommandString = UserCommandString;
5847  unsigned long XChannel, XTargetID;
5848  while (*UserCommandString == ' ') UserCommandString++;
5849  if (UserCommandString == NewUserCommandString)
5850    return false;
5851  XChannel = simple_strtoul(UserCommandString, &NewUserCommandString, 10);
5852  if (NewUserCommandString == UserCommandString ||
5853      *NewUserCommandString != ':' ||
5854      XChannel >= Controller->Channels)
5855    return false;
5856  UserCommandString = ++NewUserCommandString;
5857  XTargetID = simple_strtoul(UserCommandString, &NewUserCommandString, 10);
5858  if (NewUserCommandString == UserCommandString ||
5859      *NewUserCommandString != '\0' ||
5860      XTargetID >= Controller->Targets)
5861    return false;
5862  *Channel = XChannel;
5863  *TargetID = XTargetID;
5864  return true;
5865}
5866
5867
5868/*
5869  DAC960_ParseLogicalDrive parses spaces followed by a Logical Drive Number
5870  specification from a User Command string.  It updates LogicalDriveNumber and
5871  returns true on success and false on failure.
5872*/
5873
5874static bool DAC960_ParseLogicalDrive(DAC960_Controller_T *Controller,
5875                                        char *UserCommandString,
5876                                        unsigned char *LogicalDriveNumber)
5877{
5878  char *NewUserCommandString = UserCommandString;
5879  unsigned long XLogicalDriveNumber;
5880  while (*UserCommandString == ' ') UserCommandString++;
5881  if (UserCommandString == NewUserCommandString)
5882    return false;
5883  XLogicalDriveNumber =
5884    simple_strtoul(UserCommandString, &NewUserCommandString, 10);
5885  if (NewUserCommandString == UserCommandString ||
5886      *NewUserCommandString != '\0' ||
5887      XLogicalDriveNumber > DAC960_MaxLogicalDrives - 1)
5888    return false;
5889  *LogicalDriveNumber = XLogicalDriveNumber;
5890  return true;
5891}
5892
5893
5894/*
5895  DAC960_V1_SetDeviceState sets the Device State for a Physical Device for
5896  DAC960 V1 Firmware Controllers.
5897*/
5898
5899static void DAC960_V1_SetDeviceState(DAC960_Controller_T *Controller,
5900                                     DAC960_Command_T *Command,
5901                                     unsigned char Channel,
5902                                     unsigned char TargetID,
5903                                     DAC960_V1_PhysicalDeviceState_T
5904                                       DeviceState,
5905                                     const unsigned char *DeviceStateString)
5906{
5907  DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
5908  CommandMailbox->Type3D.CommandOpcode = DAC960_V1_StartDevice;
5909  CommandMailbox->Type3D.Channel = Channel;
5910  CommandMailbox->Type3D.TargetID = TargetID;
5911  CommandMailbox->Type3D.DeviceState = DeviceState;
5912  CommandMailbox->Type3D.Modifier = 0;
5913  DAC960_ExecuteCommand(Command);
5914  switch (Command->V1.CommandStatus)
5915    {
5916    case DAC960_V1_NormalCompletion:
5917      DAC960_UserCritical("%s of Physical Device %d:%d Succeeded\n", Controller,
5918                          DeviceStateString, Channel, TargetID);
5919      break;
5920    case DAC960_V1_UnableToStartDevice:
5921      DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
5922                          "Unable to Start Device\n", Controller,
5923                          DeviceStateString, Channel, TargetID);
5924      break;
5925    case DAC960_V1_NoDeviceAtAddress:
5926      DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
5927                          "No Device at Address\n", Controller,
5928                          DeviceStateString, Channel, TargetID);
5929      break;
5930    case DAC960_V1_InvalidChannelOrTargetOrModifier:
5931      DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
5932                          "Invalid Channel or Target or Modifier\n",
5933                          Controller, DeviceStateString, Channel, TargetID);
5934      break;
5935    case DAC960_V1_ChannelBusy:
5936      DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
5937                          "Channel Busy\n", Controller,
5938                          DeviceStateString, Channel, TargetID);
5939      break;
5940    default:
5941      DAC960_UserCritical("%s of Physical Device %d:%d Failed - "
5942                          "Unexpected Status %04X\n", Controller,
5943                          DeviceStateString, Channel, TargetID,
5944                          Command->V1.CommandStatus);
5945      break;
5946    }
5947}
5948
5949
5950/*
5951  DAC960_V1_ExecuteUserCommand executes a User Command for DAC960 V1 Firmware
5952  Controllers.
5953*/
5954
5955static bool DAC960_V1_ExecuteUserCommand(DAC960_Controller_T *Controller,
5956                                            unsigned char *UserCommand)
5957{
5958  DAC960_Command_T *Command;
5959  DAC960_V1_CommandMailbox_T *CommandMailbox;
5960  unsigned long flags;
5961  unsigned char Channel, TargetID, LogicalDriveNumber;
5962
5963  spin_lock_irqsave(&Controller->queue_lock, flags);
5964  while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
5965    DAC960_WaitForCommand(Controller);
5966  spin_unlock_irqrestore(&Controller->queue_lock, flags);
5967  Controller->UserStatusLength = 0;
5968  DAC960_V1_ClearCommand(Command);
5969  Command->CommandType = DAC960_ImmediateCommand;
5970  CommandMailbox = &Command->V1.CommandMailbox;
5971  if (strcmp(UserCommand, "flush-cache") == 0)
5972    {
5973      CommandMailbox->Type3.CommandOpcode = DAC960_V1_Flush;
5974      DAC960_ExecuteCommand(Command);
5975      DAC960_UserCritical("Cache Flush Completed\n", Controller);
5976    }
5977  else if (strncmp(UserCommand, "kill", 4) == 0 &&
5978           DAC960_ParsePhysicalDevice(Controller, &UserCommand[4],
5979                                      &Channel, &TargetID))
5980    {
5981      DAC960_V1_DeviceState_T *DeviceState =
5982        &Controller->V1.DeviceState[Channel][TargetID];
5983      if (DeviceState->Present &&
5984          DeviceState->DeviceType == DAC960_V1_DiskType &&
5985          DeviceState->DeviceState != DAC960_V1_Device_Dead)
5986        DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
5987                                 DAC960_V1_Device_Dead, "Kill");
5988      else DAC960_UserCritical("Kill of Physical Device %d:%d Illegal\n",
5989                               Controller, Channel, TargetID);
5990    }
5991  else if (strncmp(UserCommand, "make-online", 11) == 0 &&
5992           DAC960_ParsePhysicalDevice(Controller, &UserCommand[11],
5993                                      &Channel, &TargetID))
5994    {
5995      DAC960_V1_DeviceState_T *DeviceState =
5996        &Controller->V1.DeviceState[Channel][TargetID];
5997      if (DeviceState->Present &&
5998          DeviceState->DeviceType == DAC960_V1_DiskType &&
5999          DeviceState->DeviceState == DAC960_V1_Device_Dead)
6000        DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
6001                                 DAC960_V1_Device_Online, "Make Online");
6002      else DAC960_UserCritical("Make Online of Physical Device %d:%d Illegal\n",
6003                               Controller, Channel, TargetID);
6004
6005    }
6006  else if (strncmp(UserCommand, "make-standby", 12) == 0 &&
6007           DAC960_ParsePhysicalDevice(Controller, &UserCommand[12],
6008                                      &Channel, &TargetID))
6009    {
6010      DAC960_V1_DeviceState_T *DeviceState =
6011        &Controller->V1.DeviceState[Channel][TargetID];
6012      if (DeviceState->Present &&
6013          DeviceState->DeviceType == DAC960_V1_DiskType &&
6014          DeviceState->DeviceState == DAC960_V1_Device_Dead)
6015        DAC960_V1_SetDeviceState(Controller, Command, Channel, TargetID,
6016                                 DAC960_V1_Device_Standby, "Make Standby");
6017      else DAC960_UserCritical("Make Standby of Physical "
6018                               "Device %d:%d Illegal\n",
6019                               Controller, Channel, TargetID);
6020    }
6021  else if (strncmp(UserCommand, "rebuild", 7) == 0 &&
6022           DAC960_ParsePhysicalDevice(Controller, &UserCommand[7],
6023                                      &Channel, &TargetID))
6024    {
6025      CommandMailbox->Type3D.CommandOpcode = DAC960_V1_RebuildAsync;
6026      CommandMailbox->Type3D.Channel = Channel;
6027      CommandMailbox->Type3D.TargetID = TargetID;
6028      DAC960_ExecuteCommand(Command);
6029      switch (Command->V1.CommandStatus)
6030        {
6031        case DAC960_V1_NormalCompletion:
6032          DAC960_UserCritical("Rebuild of Physical Device %d:%d Initiated\n",
6033                              Controller, Channel, TargetID);
6034          break;
6035        case DAC960_V1_AttemptToRebuildOnlineDrive:
6036          DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
6037                              "Attempt to Rebuild Online or "
6038                              "Unresponsive Drive\n",
6039                              Controller, Channel, TargetID);
6040          break;
6041        case DAC960_V1_NewDiskFailedDuringRebuild:
6042          DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
6043                              "New Disk Failed During Rebuild\n",
6044                              Controller, Channel, TargetID);
6045          break;
6046        case DAC960_V1_InvalidDeviceAddress:
6047          DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
6048                              "Invalid Device Address\n",
6049                              Controller, Channel, TargetID);
6050          break;
6051        case DAC960_V1_RebuildOrCheckAlreadyInProgress:
6052          DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
6053                              "Rebuild or Consistency Check Already "
6054                              "in Progress\n", Controller, Channel, TargetID);
6055          break;
6056        default:
6057          DAC960_UserCritical("Rebuild of Physical Device %d:%d Failed - "
6058                              "Unexpected Status %04X\n", Controller,
6059                              Channel, TargetID, Command->V1.CommandStatus);
6060          break;
6061        }
6062    }
6063  else if (strncmp(UserCommand, "check-consistency", 17) == 0 &&
6064           DAC960_ParseLogicalDrive(Controller, &UserCommand[17],
6065                                    &LogicalDriveNumber))
6066    {
6067      CommandMailbox->Type3C.CommandOpcode = DAC960_V1_CheckConsistencyAsync;
6068      CommandMailbox->Type3C.LogicalDriveNumber = LogicalDriveNumber;
6069      CommandMailbox->Type3C.AutoRestore = true;
6070      DAC960_ExecuteCommand(Command);
6071      switch (Command->V1.CommandStatus)
6072        {
6073        case DAC960_V1_NormalCompletion:
6074          DAC960_UserCritical("Consistency Check of Logical Drive %d "
6075                              "(/dev/rd/c%dd%d) Initiated\n",
6076                              Controller, LogicalDriveNumber,
6077                              Controller->ControllerNumber,
6078                              LogicalDriveNumber);
6079          break;
6080        case DAC960_V1_DependentDiskIsDead:
6081          DAC960_UserCritical("Consistency Check of Logical Drive %d "
6082                              "(/dev/rd/c%dd%d) Failed - "
6083                              "Dependent Physical Device is DEAD\n",
6084                              Controller, LogicalDriveNumber,
6085                              Controller->ControllerNumber,
6086                              LogicalDriveNumber);
6087          break;
6088        case DAC960_V1_InvalidOrNonredundantLogicalDrive:
6089          DAC960_UserCritical("Consistency Check of Logical Drive %d "
6090                              "(/dev/rd/c%dd%d) Failed - "
6091                              "Invalid or Nonredundant Logical Drive\n",
6092                              Controller, LogicalDriveNumber,
6093                              Controller->ControllerNumber,
6094                              LogicalDriveNumber);
6095          break;
6096        case DAC960_V1_RebuildOrCheckAlreadyInProgress:
6097          DAC960_UserCritical("Consistency Check of Logical Drive %d "
6098                              "(/dev/rd/c%dd%d) Failed - Rebuild or "
6099                              "Consistency Check Already in Progress\n",
6100                              Controller, LogicalDriveNumber,
6101                              Controller->ControllerNumber,
6102                              LogicalDriveNumber);
6103          break;
6104        default:
6105          DAC960_UserCritical("Consistency Check of Logical Drive %d "
6106                              "(/dev/rd/c%dd%d) Failed - "
6107                              "Unexpected Status %04X\n",
6108                              Controller, LogicalDriveNumber,
6109                              Controller->ControllerNumber,
6110                              LogicalDriveNumber, Command->V1.CommandStatus);
6111          break;
6112        }
6113    }
6114  else if (strcmp(UserCommand, "cancel-rebuild") == 0 ||
6115           strcmp(UserCommand, "cancel-consistency-check") == 0)
6116    {
6117      /*
6118        the OldRebuildRateConstant is never actually used
6119        once its value is retrieved from the controller.
6120       */
6121      unsigned char *OldRebuildRateConstant;
6122      dma_addr_t OldRebuildRateConstantDMA;
6123
6124      OldRebuildRateConstant = pci_alloc_consistent( Controller->PCIDevice,
6125                sizeof(char), &OldRebuildRateConstantDMA);
6126      if (OldRebuildRateConstant == NULL) {
6127         DAC960_UserCritical("Cancellation of Rebuild or "
6128                             "Consistency Check Failed - "
6129                             "Out of Memory",
6130                             Controller);
6131         goto failure;
6132      }
6133      CommandMailbox->Type3R.CommandOpcode = DAC960_V1_RebuildControl;
6134      CommandMailbox->Type3R.RebuildRateConstant = 0xFF;
6135      CommandMailbox->Type3R.BusAddress = OldRebuildRateConstantDMA;
6136      DAC960_ExecuteCommand(Command);
6137      switch (Command->V1.CommandStatus)
6138        {
6139        case DAC960_V1_NormalCompletion:
6140          DAC960_UserCritical("Rebuild or Consistency Check Cancelled\n",
6141                              Controller);
6142          break;
6143        default:
6144          DAC960_UserCritical("Cancellation of Rebuild or "
6145                              "Consistency Check Failed - "
6146                              "Unexpected Status %04X\n",
6147                              Controller, Command->V1.CommandStatus);
6148          break;
6149        }
6150failure:
6151        pci_free_consistent(Controller->PCIDevice, sizeof(char),
6152                OldRebuildRateConstant, OldRebuildRateConstantDMA);
6153    }
6154  else DAC960_UserCritical("Illegal User Command: '%s'\n",
6155                           Controller, UserCommand);
6156
6157  spin_lock_irqsave(&Controller->queue_lock, flags);
6158  DAC960_DeallocateCommand(Command);
6159  spin_unlock_irqrestore(&Controller->queue_lock, flags);
6160  return true;
6161}
6162
6163
6164/*
6165  DAC960_V2_TranslatePhysicalDevice translates a Physical Device Channel and
6166  TargetID into a Logical Device.  It returns true on success and false
6167  on failure.
6168*/
6169
6170static bool DAC960_V2_TranslatePhysicalDevice(DAC960_Command_T *Command,
6171                                                 unsigned char Channel,
6172                                                 unsigned char TargetID,
6173                                                 unsigned short
6174                                                   *LogicalDeviceNumber)
6175{
6176  DAC960_V2_CommandMailbox_T SavedCommandMailbox, *CommandMailbox;
6177  DAC960_Controller_T *Controller =  Command->Controller;
6178
6179  CommandMailbox = &Command->V2.CommandMailbox;
6180  memcpy(&SavedCommandMailbox, CommandMailbox,
6181         sizeof(DAC960_V2_CommandMailbox_T));
6182
6183  CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
6184  CommandMailbox->PhysicalDeviceInfo.CommandControlBits
6185                                    .DataTransferControllerToHost = true;
6186  CommandMailbox->PhysicalDeviceInfo.CommandControlBits
6187                                    .NoAutoRequestSense = true;
6188  CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
6189    sizeof(DAC960_V2_PhysicalToLogicalDevice_T);
6190  CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID = TargetID;
6191  CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel = Channel;
6192  CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
6193    DAC960_V2_TranslatePhysicalToLogicalDevice;
6194  CommandMailbox->Common.DataTransferMemoryAddress
6195                        .ScatterGatherSegments[0]
6196                        .SegmentDataPointer =
6197                Controller->V2.PhysicalToLogicalDeviceDMA;
6198  CommandMailbox->Common.DataTransferMemoryAddress
6199                        .ScatterGatherSegments[0]
6200                        .SegmentByteCount =
6201                CommandMailbox->Common.DataTransferSize;
6202
6203  DAC960_ExecuteCommand(Command);
6204  *LogicalDeviceNumber = Controller->V2.PhysicalToLogicalDevice->LogicalDeviceNumber;
6205
6206  memcpy(CommandMailbox, &SavedCommandMailbox,
6207         sizeof(DAC960_V2_CommandMailbox_T));
6208  return (Command->V2.CommandStatus == DAC960_V2_NormalCompletion);
6209}
6210
6211
6212/*
6213  DAC960_V2_ExecuteUserCommand executes a User Command for DAC960 V2 Firmware
6214  Controllers.
6215*/
6216
6217static bool DAC960_V2_ExecuteUserCommand(DAC960_Controller_T *Controller,
6218                                            unsigned char *UserCommand)
6219{
6220  DAC960_Command_T *Command;
6221  DAC960_V2_CommandMailbox_T *CommandMailbox;
6222  unsigned long flags;
6223  unsigned char Channel, TargetID, LogicalDriveNumber;
6224  unsigned short LogicalDeviceNumber;
6225
6226  spin_lock_irqsave(&Controller->queue_lock, flags);
6227  while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
6228    DAC960_WaitForCommand(Controller);
6229  spin_unlock_irqrestore(&Controller->queue_lock, flags);
6230  Controller->UserStatusLength = 0;
6231  DAC960_V2_ClearCommand(Command);
6232  Command->CommandType = DAC960_ImmediateCommand;
6233  CommandMailbox = &Command->V2.CommandMailbox;
6234  CommandMailbox->Common.CommandOpcode = DAC960_V2_IOCTL;
6235  CommandMailbox->Common.CommandControlBits.DataTransferControllerToHost = true;
6236  CommandMailbox->Common.CommandControlBits.NoAutoRequestSense = true;
6237  if (strcmp(UserCommand, "flush-cache") == 0)
6238    {
6239      CommandMailbox->DeviceOperation.IOCTL_Opcode = DAC960_V2_PauseDevice;
6240      CommandMailbox->DeviceOperation.OperationDevice =
6241        DAC960_V2_RAID_Controller;
6242      DAC960_ExecuteCommand(Command);
6243      DAC960_UserCritical("Cache Flush Completed\n", Controller);
6244    }
6245  else if (strncmp(UserCommand, "kill", 4) == 0 &&
6246           DAC960_ParsePhysicalDevice(Controller, &UserCommand[4],
6247                                      &Channel, &TargetID) &&
6248           DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
6249                                             &LogicalDeviceNumber))
6250    {
6251      CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
6252        LogicalDeviceNumber;
6253      CommandMailbox->SetDeviceState.IOCTL_Opcode =
6254        DAC960_V2_SetDeviceState;
6255      CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
6256        DAC960_V2_Device_Dead;
6257      DAC960_ExecuteCommand(Command);
6258      DAC960_UserCritical("Kill of Physical Device %d:%d %s\n",
6259                          Controller, Channel, TargetID,
6260                          (Command->V2.CommandStatus
6261                           == DAC960_V2_NormalCompletion
6262                           ? "Succeeded" : "Failed"));
6263    }
6264  else if (strncmp(UserCommand, "make-online", 11) == 0 &&
6265           DAC960_ParsePhysicalDevice(Controller, &UserCommand[11],
6266                                      &Channel, &TargetID) &&
6267           DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
6268                                             &LogicalDeviceNumber))
6269    {
6270      CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
6271        LogicalDeviceNumber;
6272      CommandMailbox->SetDeviceState.IOCTL_Opcode =
6273        DAC960_V2_SetDeviceState;
6274      CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
6275        DAC960_V2_Device_Online;
6276      DAC960_ExecuteCommand(Command);
6277      DAC960_UserCritical("Make Online of Physical Device %d:%d %s\n",
6278                          Controller, Channel, TargetID,
6279                          (Command->V2.CommandStatus
6280                           == DAC960_V2_NormalCompletion
6281                           ? "Succeeded" : "Failed"));
6282    }
6283  else if (strncmp(UserCommand, "make-standby", 12) == 0 &&
6284           DAC960_ParsePhysicalDevice(Controller, &UserCommand[12],
6285                                      &Channel, &TargetID) &&
6286           DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
6287                                             &LogicalDeviceNumber))
6288    {
6289      CommandMailbox->SetDeviceState.LogicalDevice.LogicalDeviceNumber =
6290        LogicalDeviceNumber;
6291      CommandMailbox->SetDeviceState.IOCTL_Opcode =
6292        DAC960_V2_SetDeviceState;
6293      CommandMailbox->SetDeviceState.DeviceState.PhysicalDeviceState =
6294        DAC960_V2_Device_Standby;
6295      DAC960_ExecuteCommand(Command);
6296      DAC960_UserCritical("Make Standby of Physical Device %d:%d %s\n",
6297                          Controller, Channel, TargetID,
6298                          (Command->V2.CommandStatus
6299                           == DAC960_V2_NormalCompletion
6300                           ? "Succeeded" : "Failed"));
6301    }
6302  else if (strncmp(UserCommand, "rebuild", 7) == 0 &&
6303           DAC960_ParsePhysicalDevice(Controller, &UserCommand[7],
6304                                      &Channel, &TargetID) &&
6305           DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
6306                                             &LogicalDeviceNumber))
6307    {
6308      CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
6309        LogicalDeviceNumber;
6310      CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
6311        DAC960_V2_RebuildDeviceStart;
6312      DAC960_ExecuteCommand(Command);
6313      DAC960_UserCritical("Rebuild of Physical Device %d:%d %s\n",
6314                          Controller, Channel, TargetID,
6315                          (Command->V2.CommandStatus
6316                           == DAC960_V2_NormalCompletion
6317                           ? "Initiated" : "Not Initiated"));
6318    }
6319  else if (strncmp(UserCommand, "cancel-rebuild", 14) == 0 &&
6320           DAC960_ParsePhysicalDevice(Controller, &UserCommand[14],
6321                                      &Channel, &TargetID) &&
6322           DAC960_V2_TranslatePhysicalDevice(Command, Channel, TargetID,
6323                                             &LogicalDeviceNumber))
6324    {
6325      CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
6326        LogicalDeviceNumber;
6327      CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode =
6328        DAC960_V2_RebuildDeviceStop;
6329      DAC960_ExecuteCommand(Command);
6330      DAC960_UserCritical("Rebuild of Physical Device %d:%d %s\n",
6331                          Controller, Channel, TargetID,
6332                          (Command->V2.CommandStatus
6333                           == DAC960_V2_NormalCompletion
6334                           ? "Cancelled" : "Not Cancelled"));
6335    }
6336  else if (strncmp(UserCommand, "check-consistency", 17) == 0 &&
6337           DAC960_ParseLogicalDrive(Controller, &UserCommand[17],
6338                                    &LogicalDriveNumber))
6339    {
6340      CommandMailbox->ConsistencyCheck.LogicalDevice.LogicalDeviceNumber =
6341        LogicalDriveNumber;
6342      CommandMailbox->ConsistencyCheck.IOCTL_Opcode =
6343        DAC960_V2_ConsistencyCheckStart;
6344      CommandMailbox->ConsistencyCheck.RestoreConsistency = true;
6345      CommandMailbox->ConsistencyCheck.InitializedAreaOnly = false;
6346      DAC960_ExecuteCommand(Command);
6347      DAC960_UserCritical("Consistency Check of Logical Drive %d "
6348                          "(/dev/rd/c%dd%d) %s\n",
6349                          Controller, LogicalDriveNumber,
6350                          Controller->ControllerNumber,
6351                          LogicalDriveNumber,
6352                          (Command->V2.CommandStatus
6353                           == DAC960_V2_NormalCompletion
6354                           ? "Initiated" : "Not Initiated"));
6355    }
6356  else if (strncmp(UserCommand, "cancel-consistency-check", 24) == 0 &&
6357           DAC960_ParseLogicalDrive(Controller, &UserCommand[24],
6358                                    &LogicalDriveNumber))
6359    {
6360      CommandMailbox->ConsistencyCheck.LogicalDevice.LogicalDeviceNumber =
6361        LogicalDriveNumber;
6362      CommandMailbox->ConsistencyCheck.IOCTL_Opcode =
6363        DAC960_V2_ConsistencyCheckStop;
6364      DAC960_ExecuteCommand(Command);
6365      DAC960_UserCritical("Consistency Check of Logical Drive %d "
6366                          "(/dev/rd/c%dd%d) %s\n",
6367                          Controller, LogicalDriveNumber,
6368                          Controller->ControllerNumber,
6369                          LogicalDriveNumber,
6370                          (Command->V2.CommandStatus
6371                           == DAC960_V2_NormalCompletion
6372                           ? "Cancelled" : "Not Cancelled"));
6373    }
6374  else if (strcmp(UserCommand, "perform-discovery") == 0)
6375    {
6376      CommandMailbox->Common.IOCTL_Opcode = DAC960_V2_StartDiscovery;
6377      DAC960_ExecuteCommand(Command);
6378      DAC960_UserCritical("Discovery %s\n", Controller,
6379                          (Command->V2.CommandStatus
6380                           == DAC960_V2_NormalCompletion
6381                           ? "Initiated" : "Not Initiated"));
6382      if (Command->V2.CommandStatus == DAC960_V2_NormalCompletion)
6383        {
6384          CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
6385          CommandMailbox->ControllerInfo.CommandControlBits
6386                                        .DataTransferControllerToHost = true;
6387          CommandMailbox->ControllerInfo.CommandControlBits
6388                                        .NoAutoRequestSense = true;
6389          CommandMailbox->ControllerInfo.DataTransferSize =
6390            sizeof(DAC960_V2_ControllerInfo_T);
6391          CommandMailbox->ControllerInfo.ControllerNumber = 0;
6392          CommandMailbox->ControllerInfo.IOCTL_Opcode =
6393            DAC960_V2_GetControllerInfo;
6394          /*
6395           * How does this NOT race with the queued Monitoring
6396           * usage of this structure?
6397           */
6398          CommandMailbox->ControllerInfo.DataTransferMemoryAddress
6399                                        .ScatterGatherSegments[0]
6400                                        .SegmentDataPointer =
6401            Controller->V2.NewControllerInformationDMA;
6402          CommandMailbox->ControllerInfo.DataTransferMemoryAddress
6403                                        .ScatterGatherSegments[0]
6404                                        .SegmentByteCount =
6405            CommandMailbox->ControllerInfo.DataTransferSize;
6406          DAC960_ExecuteCommand(Command);
6407          while (Controller->V2.NewControllerInformation->PhysicalScanActive)
6408            {
6409              DAC960_ExecuteCommand(Command);
6410              sleep_on_timeout(&Controller->CommandWaitQueue, HZ);
6411            }
6412          DAC960_UserCritical("Discovery Completed\n", Controller);
6413        }
6414    }
6415  else if (strcmp(UserCommand, "suppress-enclosure-messages") == 0)
6416    Controller->SuppressEnclosureMessages = true;
6417  else DAC960_UserCritical("Illegal User Command: '%s'\n",
6418                           Controller, UserCommand);
6419
6420  spin_lock_irqsave(&Controller->queue_lock, flags);
6421  DAC960_DeallocateCommand(Command);
6422  spin_unlock_irqrestore(&Controller->queue_lock, flags);
6423  return true;
6424}
6425
6426static int dac960_proc_show(struct seq_file *m, void *v)
6427{
6428  unsigned char *StatusMessage = "OK\n";
6429  int ControllerNumber;
6430  for (ControllerNumber = 0;
6431       ControllerNumber < DAC960_ControllerCount;
6432       ControllerNumber++)
6433    {
6434      DAC960_Controller_T *Controller = DAC960_Controllers[ControllerNumber];
6435      if (Controller == NULL) continue;
6436      if (Controller->MonitoringAlertMode)
6437        {
6438          StatusMessage = "ALERT\n";
6439          break;
6440        }
6441    }
6442  seq_puts(m, StatusMessage);
6443  return 0;
6444}
6445
6446static int dac960_proc_open(struct inode *inode, struct file *file)
6447{
6448        return single_open(file, dac960_proc_show, NULL);
6449}
6450
6451static const struct file_operations dac960_proc_fops = {
6452        .owner          = THIS_MODULE,
6453        .open           = dac960_proc_open,
6454        .read           = seq_read,
6455        .llseek         = seq_lseek,
6456        .release        = single_release,
6457};
6458
6459static int dac960_initial_status_proc_show(struct seq_file *m, void *v)
6460{
6461        DAC960_Controller_T *Controller = (DAC960_Controller_T *)m->private;
6462        seq_printf(m, "%.*s", Controller->InitialStatusLength, Controller->CombinedStatusBuffer);
6463        return 0;
6464}
6465
6466static int dac960_initial_status_proc_open(struct inode *inode, struct file *file)
6467{
6468        return single_open(file, dac960_initial_status_proc_show, PDE(inode)->data);
6469}
6470
6471static const struct file_operations dac960_initial_status_proc_fops = {
6472        .owner          = THIS_MODULE,
6473        .open           = dac960_initial_status_proc_open,
6474        .read           = seq_read,
6475        .llseek         = seq_lseek,
6476        .release        = single_release,
6477};
6478
6479static int dac960_current_status_proc_show(struct seq_file *m, void *v)
6480{
6481  DAC960_Controller_T *Controller = (DAC960_Controller_T *) m->private;
6482  unsigned char *StatusMessage =
6483    "No Rebuild or Consistency Check in Progress\n";
6484  int ProgressMessageLength = strlen(StatusMessage);
6485  if (jiffies != Controller->LastCurrentStatusTime)
6486    {
6487      Controller->CurrentStatusLength = 0;
6488      DAC960_AnnounceDriver(Controller);
6489      DAC960_ReportControllerConfiguration(Controller);
6490      DAC960_ReportDeviceConfiguration(Controller);
6491      if (Controller->ProgressBufferLength > 0)
6492        ProgressMessageLength = Controller->ProgressBufferLength;
6493      if (DAC960_CheckStatusBuffer(Controller, 2 + ProgressMessageLength))
6494        {
6495          unsigned char *CurrentStatusBuffer = Controller->CurrentStatusBuffer;
6496          CurrentStatusBuffer[Controller->CurrentStatusLength++] = ' ';
6497          CurrentStatusBuffer[Controller->CurrentStatusLength++] = ' ';
6498          if (Controller->ProgressBufferLength > 0)
6499            strcpy(&CurrentStatusBuffer[Controller->CurrentStatusLength],
6500                   Controller->ProgressBuffer);
6501          else
6502            strcpy(&CurrentStatusBuffer[Controller->CurrentStatusLength],
6503                   StatusMessage);
6504          Controller->CurrentStatusLength += ProgressMessageLength;
6505        }
6506      Controller->LastCurrentStatusTime = jiffies;
6507    }
6508        seq_printf(m, "%.*s", Controller->CurrentStatusLength, Controller->CurrentStatusBuffer);
6509        return 0;
6510}
6511
6512static int dac960_current_status_proc_open(struct inode *inode, struct file *file)
6513{
6514        return single_open(file, dac960_current_status_proc_show, PDE(inode)->data);
6515}
6516
6517static const struct file_operations dac960_current_status_proc_fops = {
6518        .owner          = THIS_MODULE,
6519        .open           = dac960_current_status_proc_open,
6520        .read           = seq_read,
6521        .llseek         = seq_lseek,
6522        .release        = single_release,
6523};
6524
6525static int dac960_user_command_proc_show(struct seq_file *m, void *v)
6526{
6527        DAC960_Controller_T *Controller = (DAC960_Controller_T *)m->private;
6528
6529        seq_printf(m, "%.*s", Controller->UserStatusLength, Controller->UserStatusBuffer);
6530        return 0;
6531}
6532
6533static int dac960_user_command_proc_open(struct inode *inode, struct file *file)
6534{
6535        return single_open(file, dac960_user_command_proc_show, PDE(inode)->data);
6536}
6537
6538static ssize_t dac960_user_command_proc_write(struct file *file,
6539                                       const char __user *Buffer,
6540                                       size_t Count, loff_t *pos)
6541{
6542  DAC960_Controller_T *Controller = (DAC960_Controller_T *) PDE(file->f_path.dentry->d_inode)->data;
6543  unsigned char CommandBuffer[80];
6544  int Length;
6545  if (Count > sizeof(CommandBuffer)-1) return -EINVAL;
6546  if (copy_from_user(CommandBuffer, Buffer, Count)) return -EFAULT;
6547  CommandBuffer[Count] = '\0';
6548  Length = strlen(CommandBuffer);
6549  if (Length > 0 && CommandBuffer[Length-1] == '\n')
6550    CommandBuffer[--Length] = '\0';
6551  if (Controller->FirmwareType == DAC960_V1_Controller)
6552    return (DAC960_V1_ExecuteUserCommand(Controller, CommandBuffer)
6553            ? Count : -EBUSY);
6554  else
6555    return (DAC960_V2_ExecuteUserCommand(Controller, CommandBuffer)
6556            ? Count : -EBUSY);
6557}
6558
6559static const struct file_operations dac960_user_command_proc_fops = {
6560        .owner          = THIS_MODULE,
6561        .open           = dac960_user_command_proc_open,
6562        .read           = seq_read,
6563        .llseek         = seq_lseek,
6564        .release        = single_release,
6565        .write          = dac960_user_command_proc_write,
6566};
6567
6568/*
6569  DAC960_CreateProcEntries creates the /proc/rd/... entries for the
6570  DAC960 Driver.
6571*/
6572
6573static void DAC960_CreateProcEntries(DAC960_Controller_T *Controller)
6574{
6575        struct proc_dir_entry *StatusProcEntry;
6576        struct proc_dir_entry *ControllerProcEntry;
6577        struct proc_dir_entry *UserCommandProcEntry;
6578
6579        if (DAC960_ProcDirectoryEntry == NULL) {
6580                DAC960_ProcDirectoryEntry = proc_mkdir("rd", NULL);
6581                StatusProcEntry = proc_create("status", 0,
6582                                           DAC960_ProcDirectoryEntry,
6583                                           &dac960_proc_fops);
6584        }
6585
6586      sprintf(Controller->ControllerName, "c%d", Controller->ControllerNumber);
6587      ControllerProcEntry = proc_mkdir(Controller->ControllerName,
6588                                       DAC960_ProcDirectoryEntry);
6589      proc_create_data("initial_status", 0, ControllerProcEntry, &dac960_initial_status_proc_fops, Controller);
6590      proc_create_data("current_status", 0, ControllerProcEntry, &dac960_current_status_proc_fops, Controller);
6591      UserCommandProcEntry = proc_create_data("user_command", S_IWUSR | S_IRUSR, ControllerProcEntry, &dac960_user_command_proc_fops, Controller);
6592      Controller->ControllerProcEntry = ControllerProcEntry;
6593}
6594
6595
6596/*
6597  DAC960_DestroyProcEntries destroys the /proc/rd/... entries for the
6598  DAC960 Driver.
6599*/
6600
6601static void DAC960_DestroyProcEntries(DAC960_Controller_T *Controller)
6602{
6603      if (Controller->ControllerProcEntry == NULL)
6604              return;
6605      remove_proc_entry("initial_status", Controller->ControllerProcEntry);
6606      remove_proc_entry("current_status", Controller->ControllerProcEntry);
6607      remove_proc_entry("user_command", Controller->ControllerProcEntry);
6608      remove_proc_entry(Controller->ControllerName, DAC960_ProcDirectoryEntry);
6609      Controller->ControllerProcEntry = NULL;
6610}
6611
6612#ifdef DAC960_GAM_MINOR
6613
6614/*
6615 * DAC960_gam_ioctl is the ioctl function for performing RAID operations.
6616*/
6617
6618static long DAC960_gam_ioctl(struct file *file, unsigned int Request,
6619                                                unsigned long Argument)
6620{
6621  long ErrorCode = 0;
6622  if (!capable(CAP_SYS_ADMIN)) return -EACCES;
6623
6624  lock_kernel();
6625  switch (Request)
6626    {
6627    case DAC960_IOCTL_GET_CONTROLLER_COUNT:
6628      ErrorCode = DAC960_ControllerCount;
6629      break;
6630    case DAC960_IOCTL_GET_CONTROLLER_INFO:
6631      {
6632        DAC960_ControllerInfo_T __user *UserSpaceControllerInfo =
6633          (DAC960_ControllerInfo_T __user *) Argument;
6634        DAC960_ControllerInfo_T ControllerInfo;
6635        DAC960_Controller_T *Controller;
6636        int ControllerNumber;
6637        if (UserSpaceControllerInfo == NULL)
6638                ErrorCode = -EINVAL;
6639        else ErrorCode = get_user(ControllerNumber,
6640                             &UserSpaceControllerInfo->ControllerNumber);
6641        if (ErrorCode != 0)
6642                break;
6643        ErrorCode = -ENXIO;
6644        if (ControllerNumber < 0 ||
6645            ControllerNumber > DAC960_ControllerCount - 1) {
6646          break;
6647        }
6648        Controller = DAC960_Controllers[ControllerNumber];
6649        if (Controller == NULL)
6650                break;
6651        memset(&ControllerInfo, 0, sizeof(DAC960_ControllerInfo_T));
6652        ControllerInfo.ControllerNumber = ControllerNumber;
6653        ControllerInfo.FirmwareType = Controller->FirmwareType;
6654        ControllerInfo.Channels = Controller->Channels;
6655        ControllerInfo.Targets = Controller->Targets;
6656        ControllerInfo.PCI_Bus = Controller->Bus;
6657        ControllerInfo.PCI_Device = Controller->Device;
6658        ControllerInfo.PCI_Function = Controller->Function;
6659        ControllerInfo.IRQ_Channel = Controller->IRQ_Channel;
6660        ControllerInfo.PCI_Address = Controller->PCI_Address;
6661        strcpy(ControllerInfo.ModelName, Controller->ModelName);
6662        strcpy(ControllerInfo.FirmwareVersion, Controller->FirmwareVersion);
6663        ErrorCode = (copy_to_user(UserSpaceControllerInfo, &ControllerInfo,
6664                             sizeof(DAC960_ControllerInfo_T)) ? -EFAULT : 0);
6665        break;
6666      }
6667    case DAC960_IOCTL_V1_EXECUTE_COMMAND:
6668      {
6669        DAC960_V1_UserCommand_T __user *UserSpaceUserCommand =
6670          (DAC960_V1_UserCommand_T __user *) Argument;
6671        DAC960_V1_UserCommand_T UserCommand;
6672        DAC960_Controller_T *Controller;
6673        DAC960_Command_T *Command = NULL;
6674        DAC960_V1_CommandOpcode_T CommandOpcode;
6675        DAC960_V1_CommandStatus_T CommandStatus;
6676        DAC960_V1_DCDB_T DCDB;
6677        DAC960_V1_DCDB_T *DCDB_IOBUF = NULL;
6678        dma_addr_t      DCDB_IOBUFDMA;
6679        unsigned long flags;
6680        int ControllerNumber, DataTransferLength;
6681        unsigned char *DataTransferBuffer = NULL;
6682        dma_addr_t DataTransferBufferDMA;
6683        if (UserSpaceUserCommand == NULL) {
6684                ErrorCode = -EINVAL;
6685                break;
6686        }
6687        if (copy_from_user(&UserCommand, UserSpaceUserCommand,
6688                                   sizeof(DAC960_V1_UserCommand_T))) {
6689                ErrorCode = -EFAULT;
6690                break;
6691        }
6692        ControllerNumber = UserCommand.ControllerNumber;
6693        ErrorCode = -ENXIO;
6694        if (ControllerNumber < 0 ||
6695            ControllerNumber > DAC960_ControllerCount - 1)
6696                break;
6697        Controller = DAC960_Controllers[ControllerNumber];
6698        if (Controller == NULL)
6699                break;
6700        ErrorCode = -EINVAL;
6701        if (Controller->FirmwareType != DAC960_V1_Controller)
6702                break;
6703        CommandOpcode = UserCommand.CommandMailbox.Common.CommandOpcode;
6704        DataTransferLength = UserCommand.DataTransferLength;
6705        if (CommandOpcode & 0x80)
6706                break;
6707        if (CommandOpcode == DAC960_V1_DCDB)
6708          {
6709            if (copy_from_user(&DCDB, UserCommand.DCDB,
6710                               sizeof(DAC960_V1_DCDB_T))) {
6711                ErrorCode = -EFAULT;
6712                break;
6713            }
6714            if (DCDB.Channel >= DAC960_V1_MaxChannels)
6715                        break;
6716            if (!((DataTransferLength == 0 &&
6717                   DCDB.Direction
6718                   == DAC960_V1_DCDB_NoDataTransfer) ||
6719                  (DataTransferLength > 0 &&
6720                   DCDB.Direction
6721                   == DAC960_V1_DCDB_DataTransferDeviceToSystem) ||
6722                  (DataTransferLength < 0 &&
6723                   DCDB.Direction
6724                   == DAC960_V1_DCDB_DataTransferSystemToDevice)))
6725                        break;
6726            if (((DCDB.TransferLengthHigh4 << 16) | DCDB.TransferLength)
6727                != abs(DataTransferLength))
6728                        break;
6729            DCDB_IOBUF = pci_alloc_consistent(Controller->PCIDevice,
6730                        sizeof(DAC960_V1_DCDB_T), &DCDB_IOBUFDMA);
6731            if (DCDB_IOBUF == NULL) {
6732                        ErrorCode = -ENOMEM;
6733                        break;
6734                }
6735          }
6736        ErrorCode = -ENOMEM;
6737        if (DataTransferLength > 0)
6738          {
6739            DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
6740                                DataTransferLength, &DataTransferBufferDMA);
6741            if (DataTransferBuffer == NULL)
6742                break;
6743            memset(DataTransferBuffer, 0, DataTransferLength);
6744          }
6745        else if (DataTransferLength < 0)
6746          {
6747            DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
6748                                -DataTransferLength, &DataTransferBufferDMA);
6749            if (DataTransferBuffer == NULL)
6750                break;
6751            if (copy_from_user(DataTransferBuffer,
6752                               UserCommand.DataTransferBuffer,
6753                               -DataTransferLength)) {
6754                ErrorCode = -EFAULT;
6755                break;
6756            }
6757          }
6758        if (CommandOpcode == DAC960_V1_DCDB)
6759          {
6760            spin_lock_irqsave(&Controller->queue_lock, flags);
6761            while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
6762              DAC960_WaitForCommand(Controller);
6763            while (Controller->V1.DirectCommandActive[DCDB.Channel]
6764                                                     [DCDB.TargetID])
6765              {
6766                spin_unlock_irq(&Controller->queue_lock);
6767                __wait_event(Controller->CommandWaitQueue,
6768                             !Controller->V1.DirectCommandActive
6769                                             [DCDB.Channel][DCDB.TargetID]);
6770                spin_lock_irq(&Controller->queue_lock);
6771              }
6772            Controller->V1.DirectCommandActive[DCDB.Channel]
6773                                              [DCDB.TargetID] = true;
6774            spin_unlock_irqrestore(&Controller->queue_lock, flags);
6775            DAC960_V1_ClearCommand(Command);
6776            Command->CommandType = DAC960_ImmediateCommand;
6777            memcpy(&Command->V1.CommandMailbox, &UserCommand.CommandMailbox,
6778                   sizeof(DAC960_V1_CommandMailbox_T));
6779            Command->V1.CommandMailbox.Type3.BusAddress = DCDB_IOBUFDMA;
6780            DCDB.BusAddress = DataTransferBufferDMA;
6781            memcpy(DCDB_IOBUF, &DCDB, sizeof(DAC960_V1_DCDB_T));
6782          }
6783        else
6784          {
6785            spin_lock_irqsave(&Controller->queue_lock, flags);
6786            while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
6787              DAC960_WaitForCommand(Controller);
6788            spin_unlock_irqrestore(&Controller->queue_lock, flags);
6789            DAC960_V1_ClearCommand(Command);
6790            Command->CommandType = DAC960_ImmediateCommand;
6791            memcpy(&Command->V1.CommandMailbox, &UserCommand.CommandMailbox,
6792                   sizeof(DAC960_V1_CommandMailbox_T));
6793            if (DataTransferBuffer != NULL)
6794              Command->V1.CommandMailbox.Type3.BusAddress =
6795                DataTransferBufferDMA;
6796          }
6797        DAC960_ExecuteCommand(Command);
6798        CommandStatus = Command->V1.CommandStatus;
6799        spin_lock_irqsave(&Controller->queue_lock, flags);
6800        DAC960_DeallocateCommand(Command);
6801        spin_unlock_irqrestore(&Controller->queue_lock, flags);
6802        if (DataTransferLength > 0)
6803          {
6804            if (copy_to_user(UserCommand.DataTransferBuffer,
6805                             DataTransferBuffer, DataTransferLength)) {
6806                ErrorCode = -EFAULT;
6807                goto Failure1;
6808            }
6809          }
6810        if (CommandOpcode == DAC960_V1_DCDB)
6811          {
6812            /*
6813              I don't believe Target or Channel in the DCDB_IOBUF
6814              should be any different from the contents of DCDB.
6815             */
6816            Controller->V1.DirectCommandActive[DCDB.Channel]
6817                                              [DCDB.TargetID] = false;
6818            if (copy_to_user(UserCommand.DCDB, DCDB_IOBUF,
6819                             sizeof(DAC960_V1_DCDB_T))) {
6820                ErrorCode = -EFAULT;
6821                goto Failure1;
6822            }
6823          }
6824        ErrorCode = CommandStatus;
6825      Failure1:
6826        if (DataTransferBuffer != NULL)
6827          pci_free_consistent(Controller->PCIDevice, abs(DataTransferLength),
6828                        DataTransferBuffer, DataTransferBufferDMA);
6829        if (DCDB_IOBUF != NULL)
6830          pci_free_consistent(Controller->PCIDevice, sizeof(DAC960_V1_DCDB_T),
6831                        DCDB_IOBUF, DCDB_IOBUFDMA);
6832        break;
6833      }
6834    case DAC960_IOCTL_V2_EXECUTE_COMMAND:
6835      {
6836        DAC960_V2_UserCommand_T __user *UserSpaceUserCommand =
6837          (DAC960_V2_UserCommand_T __user *) Argument;
6838        DAC960_V2_UserCommand_T UserCommand;
6839        DAC960_Controller_T *Controller;
6840        DAC960_Command_T *Command = NULL;
6841        DAC960_V2_CommandMailbox_T *CommandMailbox;
6842        DAC960_V2_CommandStatus_T CommandStatus;
6843        unsigned long flags;
6844        int ControllerNumber, DataTransferLength;
6845        int DataTransferResidue, RequestSenseLength;
6846        unsigned char *DataTransferBuffer = NULL;
6847        dma_addr_t DataTransferBufferDMA;
6848        unsigned char *RequestSenseBuffer = NULL;
6849        dma_addr_t RequestSenseBufferDMA;
6850
6851        ErrorCode = -EINVAL;
6852        if (UserSpaceUserCommand == NULL)
6853                break;
6854        if (copy_from_user(&UserCommand, UserSpaceUserCommand,
6855                           sizeof(DAC960_V2_UserCommand_T))) {
6856                ErrorCode = -EFAULT;
6857                break;
6858        }
6859        ErrorCode = -ENXIO;
6860        ControllerNumber = UserCommand.ControllerNumber;
6861        if (ControllerNumber < 0 ||
6862            ControllerNumber > DAC960_ControllerCount - 1)
6863                break;
6864        Controller = DAC960_Controllers[ControllerNumber];
6865        if (Controller == NULL)
6866                break;
6867        if (Controller->FirmwareType != DAC960_V2_Controller){
6868                ErrorCode = -EINVAL;
6869                break;
6870        }
6871        DataTransferLength = UserCommand.DataTransferLength;
6872        ErrorCode = -ENOMEM;
6873        if (DataTransferLength > 0)
6874          {
6875            DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
6876                                DataTransferLength, &DataTransferBufferDMA);
6877            if (DataTransferBuffer == NULL)
6878                break;
6879            memset(DataTransferBuffer, 0, DataTransferLength);
6880          }
6881        else if (DataTransferLength < 0)
6882          {
6883            DataTransferBuffer = pci_alloc_consistent(Controller->PCIDevice,
6884                                -DataTransferLength, &DataTransferBufferDMA);
6885            if (DataTransferBuffer == NULL)
6886                break;
6887            if (copy_from_user(DataTransferBuffer,
6888                               UserCommand.DataTransferBuffer,
6889                               -DataTransferLength)) {
6890                ErrorCode = -EFAULT;
6891                goto Failure2;
6892            }
6893          }
6894        RequestSenseLength = UserCommand.RequestSenseLength;
6895        if (RequestSenseLength > 0)
6896          {
6897            RequestSenseBuffer = pci_alloc_consistent(Controller->PCIDevice,
6898                        RequestSenseLength, &RequestSenseBufferDMA);
6899            if (RequestSenseBuffer == NULL)
6900              {
6901                ErrorCode = -ENOMEM;
6902                goto Failure2;
6903              }
6904            memset(RequestSenseBuffer, 0, RequestSenseLength);
6905          }
6906        spin_lock_irqsave(&Controller->queue_lock, flags);
6907        while ((Command = DAC960_AllocateCommand(Controller)) == NULL)
6908          DAC960_WaitForCommand(Controller);
6909        spin_unlock_irqrestore(&Controller->queue_lock, flags);
6910        DAC960_V2_ClearCommand(Command);
6911        Command->CommandType = DAC960_ImmediateCommand;
6912        CommandMailbox = &Command->V2.CommandMailbox;
6913        memcpy(CommandMailbox, &UserCommand.CommandMailbox,
6914               sizeof(DAC960_V2_CommandMailbox_T));
6915        CommandMailbox->Common.CommandControlBits
6916                              .AdditionalScatterGatherListMemory = false;
6917        CommandMailbox->Common.CommandControlBits
6918                              .NoAutoRequestSense = true;
6919        CommandMailbox->Common.DataTransferSize = 0;
6920        CommandMailbox->Common.DataTransferPageNumber = 0;
6921        memset(&CommandMailbox->Common.DataTransferMemoryAddress, 0,
6922               sizeof(DAC960_V2_DataTransferMemoryAddress_T));
6923        if (DataTransferLength != 0)
6924          {
6925            if (DataTransferLength > 0)
6926              {
6927                CommandMailbox->Common.CommandControlBits
6928                                      .DataTransferControllerToHost = true;
6929                CommandMailbox->Common.DataTransferSize = DataTransferLength;
6930              }
6931            else
6932              {
6933                CommandMailbox->Common.CommandControlBits
6934                                      .DataTransferControllerToHost = false;
6935                CommandMailbox->Common.DataTransferSize = -DataTransferLength;
6936              }
6937            CommandMailbox->Common.DataTransferMemoryAddress
6938                                  .ScatterGatherSegments[0]
6939                                  .SegmentDataPointer = DataTransferBufferDMA;
6940            CommandMailbox->Common.DataTransferMemoryAddress
6941                                  .ScatterGatherSegments[0]
6942                                  .SegmentByteCount =
6943              CommandMailbox->Common.DataTransferSize;
6944          }
6945        if (RequestSenseLength > 0)
6946          {
6947            CommandMailbox->Common.CommandControlBits
6948                                  .NoAutoRequestSense = false;
6949            CommandMailbox->Common.RequestSenseSize = RequestSenseLength;
6950            CommandMailbox->Common.RequestSenseBusAddress =
6951                                                        RequestSenseBufferDMA;
6952          }
6953        DAC960_ExecuteCommand(Command);
6954        CommandStatus = Command->V2.CommandStatus;
6955        RequestSenseLength = Command->V2.RequestSenseLength;
6956        DataTransferResidue = Command->V2.DataTransferResidue;
6957        spin_lock_irqsave(&Controller->queue_lock, flags);
6958        DAC960_DeallocateCommand(Command);
6959        spin_unlock_irqrestore(&Controller->queue_lock, flags);
6960        if (RequestSenseLength > UserCommand.RequestSenseLength)
6961          RequestSenseLength = UserCommand.RequestSenseLength;
6962        if (copy_to_user(&UserSpaceUserCommand->DataTransferLength,
6963                                 &DataTransferResidue,
6964                                 sizeof(DataTransferResidue))) {
6965                ErrorCode = -EFAULT;
6966                goto Failure2;
6967        }
6968        if (copy_to_user(&UserSpaceUserCommand->RequestSenseLength,
6969                         &RequestSenseLength, sizeof(RequestSenseLength))) {
6970                ErrorCode = -EFAULT;
6971                goto Failure2;
6972        }
6973        if (DataTransferLength > 0)
6974          {
6975            if (copy_to_user(UserCommand.DataTransferBuffer,
6976                             DataTransferBuffer, DataTransferLength)) {
6977                ErrorCode = -EFAULT;
6978                goto Failure2;
6979            }
6980          }
6981        if (RequestSenseLength > 0)
6982          {
6983            if (copy_to_user(UserCommand.RequestSenseBuffer,
6984                             RequestSenseBuffer, RequestSenseLength)) {
6985                ErrorCode = -EFAULT;
6986                goto Failure2;
6987            }
6988          }
6989        ErrorCode = CommandStatus;
6990      Failure2:
6991          pci_free_consistent(Controller->PCIDevice, abs(DataTransferLength),
6992                DataTransferBuffer, DataTransferBufferDMA);
6993        if (RequestSenseBuffer != NULL)
6994          pci_free_consistent(Controller->PCIDevice, RequestSenseLength,
6995                RequestSenseBuffer, RequestSenseBufferDMA);
6996        break;
6997      }
6998    case DAC960_IOCTL_V2_GET_HEALTH_STATUS:
6999      {
7000        DAC960_V2_GetHealthStatus_T __user *UserSpaceGetHealthStatus =
7001          (DAC960_V2_GetHealthStatus_T __user *) Argument;
7002        DAC960_V2_GetHealthStatus_T GetHealthStatus;
7003        DAC960_V2_HealthStatusBuffer_T HealthStatusBuffer;
7004        DAC960_Controller_T *Controller;
7005        int ControllerNumber;
7006        if (UserSpaceGetHealthStatus == NULL) {
7007                ErrorCode = -EINVAL;
7008                break;
7009        }
7010        if (copy_from_user(&GetHealthStatus, UserSpaceGetHealthStatus,
7011                           sizeof(DAC960_V2_GetHealthStatus_T))) {
7012                ErrorCode = -EFAULT;
7013                break;
7014        }
7015        ErrorCode = -ENXIO;
7016        ControllerNumber = GetHealthStatus.ControllerNumber;
7017        if (ControllerNumber < 0 ||
7018            ControllerNumber > DAC960_ControllerCount - 1)
7019                    break;
7020        Controller = DAC960_Controllers[ControllerNumber];
7021        if (Controller == NULL)
7022                break;
7023        if (Controller->FirmwareType != DAC960_V2_Controller) {
7024                ErrorCode = -EINVAL;
7025                break;
7026        }
7027        if (copy_from_user(&HealthStatusBuffer,
7028                           GetHealthStatus.HealthStatusBuffer,
7029                           sizeof(DAC960_V2_HealthStatusBuffer_T))) {
7030                ErrorCode = -EFAULT;
7031                break;
7032        }
7033        while (Controller->V2.HealthStatusBuffer->StatusChangeCounter
7034               == HealthStatusBuffer.StatusChangeCounter &&
7035               Controller->V2.HealthStatusBuffer->NextEventSequenceNumber
7036               == HealthStatusBuffer.NextEventSequenceNumber)
7037          {
7038            interruptible_sleep_on_timeout(&Controller->HealthStatusWaitQueue,
7039                                           DAC960_MonitoringTimerInterval);
7040            if (signal_pending(current)) {
7041                ErrorCode = -EINTR;
7042                break;
7043            }
7044          }
7045        if (copy_to_user(GetHealthStatus.HealthStatusBuffer,
7046                         Controller->V2.HealthStatusBuffer,
7047                         sizeof(DAC960_V2_HealthStatusBuffer_T)))
7048                ErrorCode = -EFAULT;
7049        else
7050                ErrorCode =  0;
7051      }
7052      default:
7053        ErrorCode = -ENOTTY;
7054    }
7055  unlock_kernel();
7056  return ErrorCode;
7057}
7058
7059static const struct file_operations DAC960_gam_fops = {
7060        .owner          = THIS_MODULE,
7061        .unlocked_ioctl = DAC960_gam_ioctl
7062};
7063
7064static struct miscdevice DAC960_gam_dev = {
7065        DAC960_GAM_MINOR,
7066        "dac960_gam",
7067        &DAC960_gam_fops
7068};
7069
7070static int DAC960_gam_init(void)
7071{
7072        int ret;
7073
7074        ret = misc_register(&DAC960_gam_dev);
7075        if (ret)
7076                printk(KERN_ERR "DAC960_gam: can't misc_register on minor %d\n", DAC960_GAM_MINOR);
7077        return ret;
7078}
7079
7080static void DAC960_gam_cleanup(void)
7081{
7082        misc_deregister(&DAC960_gam_dev);
7083}
7084
7085#endif /* DAC960_GAM_MINOR */
7086
7087static struct DAC960_privdata DAC960_GEM_privdata = {
7088        .HardwareType =         DAC960_GEM_Controller,
7089        .FirmwareType   =       DAC960_V2_Controller,
7090        .InterruptHandler =     DAC960_GEM_InterruptHandler,
7091        .MemoryWindowSize =     DAC960_GEM_RegisterWindowSize,
7092};
7093
7094
7095static struct DAC960_privdata DAC960_BA_privdata = {
7096        .HardwareType =         DAC960_BA_Controller,
7097        .FirmwareType   =       DAC960_V2_Controller,
7098        .InterruptHandler =     DAC960_BA_InterruptHandler,
7099        .MemoryWindowSize =     DAC960_BA_RegisterWindowSize,
7100};
7101
7102static struct DAC960_privdata DAC960_LP_privdata = {
7103        .HardwareType =         DAC960_LP_Controller,
7104        .FirmwareType   =       DAC960_LP_Controller,
7105        .InterruptHandler =     DAC960_LP_InterruptHandler,
7106        .MemoryWindowSize =     DAC960_LP_RegisterWindowSize,
7107};
7108
7109static struct DAC960_privdata DAC960_LA_privdata = {
7110        .HardwareType =         DAC960_LA_Controller,
7111        .FirmwareType   =       DAC960_V1_Controller,
7112        .InterruptHandler =     DAC960_LA_InterruptHandler,
7113        .MemoryWindowSize =     DAC960_LA_RegisterWindowSize,
7114};
7115
7116static struct DAC960_privdata DAC960_PG_privdata = {
7117        .HardwareType =         DAC960_PG_Controller,
7118        .FirmwareType   =       DAC960_V1_Controller,
7119        .InterruptHandler =     DAC960_PG_InterruptHandler,
7120        .MemoryWindowSize =     DAC960_PG_RegisterWindowSize,
7121};
7122
7123static struct DAC960_privdata DAC960_PD_privdata = {
7124        .HardwareType =         DAC960_PD_Controller,
7125        .FirmwareType   =       DAC960_V1_Controller,
7126        .InterruptHandler =     DAC960_PD_InterruptHandler,
7127        .MemoryWindowSize =     DAC960_PD_RegisterWindowSize,
7128};
7129
7130static struct DAC960_privdata DAC960_P_privdata = {
7131        .HardwareType =         DAC960_P_Controller,
7132        .FirmwareType   =       DAC960_V1_Controller,
7133        .InterruptHandler =     DAC960_P_InterruptHandler,
7134        .MemoryWindowSize =     DAC960_PD_RegisterWindowSize,
7135};
7136
7137static struct pci_device_id DAC960_id_table[] = {
7138        {
7139                .vendor         = PCI_VENDOR_ID_MYLEX,
7140                .device         = PCI_DEVICE_ID_MYLEX_DAC960_GEM,
7141                .subvendor      = PCI_VENDOR_ID_MYLEX,
7142                .subdevice      = PCI_ANY_ID,
7143                .driver_data    = (unsigned long) &DAC960_GEM_privdata,
7144        },
7145        {
7146                .vendor         = PCI_VENDOR_ID_MYLEX,
7147                .device         = PCI_DEVICE_ID_MYLEX_DAC960_BA,
7148                .subvendor      = PCI_ANY_ID,
7149                .subdevice      = PCI_ANY_ID,
7150                .driver_data    = (unsigned long) &DAC960_BA_privdata,
7151        },
7152        {
7153                .vendor         = PCI_VENDOR_ID_MYLEX,
7154                .device         = PCI_DEVICE_ID_MYLEX_DAC960_LP,
7155                .subvendor      = PCI_ANY_ID,
7156                .subdevice      = PCI_ANY_ID,
7157                .driver_data    = (unsigned long) &DAC960_LP_privdata,
7158        },
7159        {
7160                .vendor         = PCI_VENDOR_ID_DEC,
7161                .device         = PCI_DEVICE_ID_DEC_21285,
7162                .subvendor      = PCI_VENDOR_ID_MYLEX,
7163                .subdevice      = PCI_DEVICE_ID_MYLEX_DAC960_LA,
7164                .driver_data    = (unsigned long) &DAC960_LA_privdata,
7165        },
7166        {
7167                .vendor         = PCI_VENDOR_ID_MYLEX,
7168                .device         = PCI_DEVICE_ID_MYLEX_DAC960_PG,
7169                .subvendor      = PCI_ANY_ID,
7170                .subdevice      = PCI_ANY_ID,
7171                .driver_data    = (unsigned long) &DAC960_PG_privdata,
7172        },
7173        {
7174                .vendor         = PCI_VENDOR_ID_MYLEX,
7175                .device         = PCI_DEVICE_ID_MYLEX_DAC960_PD,
7176                .subvendor      = PCI_ANY_ID,
7177                .subdevice      = PCI_ANY_ID,
7178                .driver_data    = (unsigned long) &DAC960_PD_privdata,
7179        },
7180        {
7181                .vendor         = PCI_VENDOR_ID_MYLEX,
7182                .device         = PCI_DEVICE_ID_MYLEX_DAC960_P,
7183                .subvendor      = PCI_ANY_ID,
7184                .subdevice      = PCI_ANY_ID,
7185                .driver_data    = (unsigned long) &DAC960_P_privdata,
7186        },
7187        {0, },
7188};
7189
7190MODULE_DEVICE_TABLE(pci, DAC960_id_table);
7191
7192static struct pci_driver DAC960_pci_driver = {
7193        .name           = "DAC960",
7194        .id_table       = DAC960_id_table,
7195        .probe          = DAC960_Probe,
7196        .remove         = DAC960_Remove,
7197};
7198
7199static int __init DAC960_init_module(void)
7200{
7201        int ret;
7202
7203        ret =  pci_register_driver(&DAC960_pci_driver);
7204#ifdef DAC960_GAM_MINOR
7205        if (!ret)
7206                DAC960_gam_init();
7207#endif
7208        return ret;
7209}
7210
7211static void __exit DAC960_cleanup_module(void)
7212{
7213        int i;
7214
7215#ifdef DAC960_GAM_MINOR
7216        DAC960_gam_cleanup();
7217#endif
7218
7219        for (i = 0; i < DAC960_ControllerCount; i++) {
7220                DAC960_Controller_T *Controller = DAC960_Controllers[i];
7221                if (Controller == NULL)
7222                        continue;
7223                DAC960_FinalizeController(Controller);
7224        }
7225        if (DAC960_ProcDirectoryEntry != NULL) {
7226                remove_proc_entry("rd/status", NULL);
7227                remove_proc_entry("rd", NULL);
7228        }
7229        DAC960_ControllerCount = 0;
7230        pci_unregister_driver(&DAC960_pci_driver);
7231}
7232
7233module_init(DAC960_init_module);
7234module_exit(DAC960_cleanup_module);
7235
7236MODULE_LICENSE("GPL");
7237