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