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