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