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