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