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