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