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