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