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