[PATCH] DAC960: add support for Mylex AcceleRAID 4/5/600
[linux-2.6.git] / drivers / block / DAC960.c
1 /*
2
3   Linux Driver for Mylex DAC960/AcceleRAID/eXtremeRAID PCI RAID Controllers
4
5   Copyright 1998-2001 by Leonard N. Zubkoff <lnz@dandelion.com>
6   Portions Copyright 2002 by Mylex (An IBM Business Unit)
7
8   This program is free software; you may redistribute and/or modify it under
9   the terms of the GNU General Public License Version 2 as published by the
10   Free Software Foundation.
11
12   This program is distributed in the hope that it will be useful, but
13   WITHOUT ANY WARRANTY, without even the implied warranty of MERCHANTABILITY
14   or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15   for complete details.
16
17 */
18
19
20 #define DAC960_DriverVersion                    "2.5.47"
21 #define DAC960_DriverDate                       "14 November 2002"
22
23
24 #include <linux/module.h>
25 #include <linux/types.h>
26 #include <linux/miscdevice.h>
27 #include <linux/blkdev.h>
28 #include <linux/bio.h>
29 #include <linux/completion.h>
30 #include <linux/delay.h>
31 #include <linux/genhd.h>
32 #include <linux/hdreg.h>
33 #include <linux/blkpg.h>
34 #include <linux/interrupt.h>
35 #include <linux/ioport.h>
36 #include <linux/mm.h>
37 #include <linux/slab.h>
38 #include <linux/proc_fs.h>
39 #include <linux/reboot.h>
40 #include <linux/spinlock.h>
41 #include <linux/timer.h>
42 #include <linux/pci.h>
43 #include <linux/init.h>
44 #include <asm/io.h>
45 #include <asm/uaccess.h>
46 #include "DAC960.h"
47
48 #define DAC960_GAM_MINOR        252
49
50
51 static DAC960_Controller_T *DAC960_Controllers[DAC960_MaxControllers];
52 static int DAC960_ControllerCount;
53 static struct proc_dir_entry *DAC960_ProcDirectoryEntry;
54
55 static long disk_size(DAC960_Controller_T *p, int drive_nr)
56 {
57         if (p->FirmwareType == DAC960_V1_Controller) {
58                 if (drive_nr >= p->LogicalDriveCount)
59                         return 0;
60                 return p->V1.LogicalDriveInformation[drive_nr].
61                         LogicalDriveSize;
62         } else {
63                 DAC960_V2_LogicalDeviceInfo_T *i =
64                         p->V2.LogicalDeviceInformation[drive_nr];
65                 if (i == NULL)
66                         return 0;
67                 return i->ConfigurableDeviceSize;
68         }
69 }
70
71 static int DAC960_open(struct inode *inode, struct file *file)
72 {
73         struct gendisk *disk = inode->i_bdev->bd_disk;
74         DAC960_Controller_T *p = disk->queue->queuedata;
75         int drive_nr = (long)disk->private_data;
76
77         if (p->FirmwareType == DAC960_V1_Controller) {
78                 if (p->V1.LogicalDriveInformation[drive_nr].
79                     LogicalDriveState == DAC960_V1_LogicalDrive_Offline)
80                         return -ENXIO;
81         } else {
82                 DAC960_V2_LogicalDeviceInfo_T *i =
83                         p->V2.LogicalDeviceInformation[drive_nr];
84                 if (!i || i->LogicalDeviceState == DAC960_V2_LogicalDevice_Offline)
85                         return -ENXIO;
86         }
87
88         check_disk_change(inode->i_bdev);
89
90         if (!get_capacity(p->disks[drive_nr]))
91                 return -ENXIO;
92         return 0;
93 }
94
95 static int DAC960_ioctl(struct inode *inode, struct file *file,
96                         unsigned int cmd, unsigned long arg)
97 {
98         struct gendisk *disk = inode->i_bdev->bd_disk;
99         DAC960_Controller_T *p = disk->queue->queuedata;
100         int drive_nr = (long)disk->private_data;
101         struct hd_geometry g;
102         struct hd_geometry __user *loc = (struct hd_geometry __user *)arg;
103
104         if (cmd != HDIO_GETGEO || !loc)
105                 return -EINVAL;
106
107         if (p->FirmwareType == DAC960_V1_Controller) {
108                 g.heads = p->V1.GeometryTranslationHeads;
109                 g.sectors = p->V1.GeometryTranslationSectors;
110                 g.cylinders = p->V1.LogicalDriveInformation[drive_nr].
111                         LogicalDriveSize / (g.heads * g.sectors);
112         } else {
113                 DAC960_V2_LogicalDeviceInfo_T *i =
114                         p->V2.LogicalDeviceInformation[drive_nr];
115                 switch (i->DriveGeometry) {
116                 case DAC960_V2_Geometry_128_32:
117                         g.heads = 128;
118                         g.sectors = 32;
119                         break;
120                 case DAC960_V2_Geometry_255_63:
121                         g.heads = 255;
122                         g.sectors = 63;
123                         break;
124                 default:
125                         DAC960_Error("Illegal Logical Device Geometry %d\n",
126                                         p, i->DriveGeometry);
127                         return -EINVAL;
128                 }
129
130                 g.cylinders = i->ConfigurableDeviceSize / (g.heads * g.sectors);
131         }
132         
133         g.start = get_start_sect(inode->i_bdev);
134
135         return copy_to_user(loc, &g, sizeof g) ? -EFAULT : 0; 
136 }
137
138 static int DAC960_media_changed(struct gendisk *disk)
139 {
140         DAC960_Controller_T *p = disk->queue->queuedata;
141         int drive_nr = (long)disk->private_data;
142
143         if (!p->LogicalDriveInitiallyAccessible[drive_nr])
144                 return 1;
145         return 0;
146 }
147
148 static int DAC960_revalidate_disk(struct gendisk *disk)
149 {
150         DAC960_Controller_T *p = disk->queue->queuedata;
151         int unit = (long)disk->private_data;
152
153         set_capacity(disk, disk_size(p, unit));
154         return 0;
155 }
156
157 static struct block_device_operations DAC960_BlockDeviceOperations = {
158         .owner                  = THIS_MODULE,
159         .open                   = DAC960_open,
160         .ioctl                  = DAC960_ioctl,
161         .media_changed          = DAC960_media_changed,
162         .revalidate_disk        = DAC960_revalidate_disk,
163 };
164
165
166 /*
167   DAC960_AnnounceDriver announces the Driver Version and Date, Author's Name,
168   Copyright Notice, and Electronic Mail Address.
169 */
170
171 static void DAC960_AnnounceDriver(DAC960_Controller_T *Controller)
172 {
173   DAC960_Announce("***** DAC960 RAID Driver Version "
174                   DAC960_DriverVersion " of "
175                   DAC960_DriverDate " *****\n", Controller);
176   DAC960_Announce("Copyright 1998-2001 by Leonard N. Zubkoff "
177                   "<lnz@dandelion.com>\n", Controller);
178 }
179
180
181 /*
182   DAC960_Failure prints a standardized error message, and then returns false.
183 */
184
185 static boolean DAC960_Failure(DAC960_Controller_T *Controller,
186                               unsigned char *ErrorMessage)
187 {
188   DAC960_Error("While configuring DAC960 PCI RAID Controller at\n",
189                Controller);
190   if (Controller->IO_Address == 0)
191     DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
192                  "PCI Address 0x%X\n", Controller,
193                  Controller->Bus, Controller->Device,
194                  Controller->Function, Controller->PCI_Address);
195   else DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
196                     "0x%X PCI Address 0x%X\n", Controller,
197                     Controller->Bus, Controller->Device,
198                     Controller->Function, Controller->IO_Address,
199                     Controller->PCI_Address);
200   DAC960_Error("%s FAILED - DETACHING\n", Controller, ErrorMessage);
201   return false;
202 }
203
204 /*
205   init_dma_loaf() and slice_dma_loaf() are helper functions for
206   aggregating the dma-mapped memory for a well-known collection of
207   data structures that are of different lengths.
208
209   These routines don't guarantee any alignment.  The caller must
210   include any space needed for alignment in the sizes of the structures
211   that are passed in.
212  */
213
214 static boolean init_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf,
215                                                                  size_t len)
216 {
217         void *cpu_addr;
218         dma_addr_t dma_handle;
219
220         cpu_addr = pci_alloc_consistent(dev, len, &dma_handle);
221         if (cpu_addr == NULL)
222                 return false;
223         
224         loaf->cpu_free = loaf->cpu_base = cpu_addr;
225         loaf->dma_free =loaf->dma_base = dma_handle;
226         loaf->length = len;
227         memset(cpu_addr, 0, len);
228         return true;
229 }
230
231 static void *slice_dma_loaf(struct dma_loaf *loaf, size_t len,
232                                         dma_addr_t *dma_handle)
233 {
234         void *cpu_end = loaf->cpu_free + len;
235         void *cpu_addr = loaf->cpu_free;
236
237         if (cpu_end > loaf->cpu_base + loaf->length)
238                 BUG();
239         *dma_handle = loaf->dma_free;
240         loaf->cpu_free = cpu_end;
241         loaf->dma_free += len;
242         return cpu_addr;
243 }
244
245 static void free_dma_loaf(struct pci_dev *dev, struct dma_loaf *loaf_handle)
246 {
247         if (loaf_handle->cpu_base != NULL)
248                 pci_free_consistent(dev, loaf_handle->length,
249                         loaf_handle->cpu_base, loaf_handle->dma_base);
250 }
251
252
253 /*
254   DAC960_CreateAuxiliaryStructures allocates and initializes the auxiliary
255   data structures for Controller.  It returns true on success and false on
256   failure.
257 */
258
259 static boolean DAC960_CreateAuxiliaryStructures(DAC960_Controller_T *Controller)
260 {
261   int CommandAllocationLength, CommandAllocationGroupSize;
262   int CommandsRemaining = 0, CommandIdentifier, CommandGroupByteCount;
263   void *AllocationPointer = NULL;
264   void *ScatterGatherCPU = NULL;
265   dma_addr_t ScatterGatherDMA;
266   struct pci_pool *ScatterGatherPool;
267   void *RequestSenseCPU = NULL;
268   dma_addr_t RequestSenseDMA;
269   struct pci_pool *RequestSensePool = NULL;
270
271   if (Controller->FirmwareType == DAC960_V1_Controller)
272     {
273       CommandAllocationLength = offsetof(DAC960_Command_T, V1.EndMarker);
274       CommandAllocationGroupSize = DAC960_V1_CommandAllocationGroupSize;
275       ScatterGatherPool = pci_pool_create("DAC960_V1_ScatterGather",
276                 Controller->PCIDevice,
277         DAC960_V1_ScatterGatherLimit * sizeof(DAC960_V1_ScatterGatherSegment_T),
278         sizeof(DAC960_V1_ScatterGatherSegment_T), 0);
279       if (ScatterGatherPool == NULL)
280             return DAC960_Failure(Controller,
281                         "AUXILIARY STRUCTURE CREATION (SG)");
282       Controller->ScatterGatherPool = ScatterGatherPool;
283     }
284   else
285     {
286       CommandAllocationLength = offsetof(DAC960_Command_T, V2.EndMarker);
287       CommandAllocationGroupSize = DAC960_V2_CommandAllocationGroupSize;
288       ScatterGatherPool = pci_pool_create("DAC960_V2_ScatterGather",
289                 Controller->PCIDevice,
290         DAC960_V2_ScatterGatherLimit * sizeof(DAC960_V2_ScatterGatherSegment_T),
291         sizeof(DAC960_V2_ScatterGatherSegment_T), 0);
292       if (ScatterGatherPool == NULL)
293             return DAC960_Failure(Controller,
294                         "AUXILIARY STRUCTURE CREATION (SG)");
295       RequestSensePool = pci_pool_create("DAC960_V2_RequestSense",
296                 Controller->PCIDevice, sizeof(DAC960_SCSI_RequestSense_T),
297                 sizeof(int), 0);
298       if (RequestSensePool == NULL) {
299             pci_pool_destroy(ScatterGatherPool);
300             return DAC960_Failure(Controller,
301                         "AUXILIARY STRUCTURE CREATION (SG)");
302       }
303       Controller->ScatterGatherPool = ScatterGatherPool;
304       Controller->V2.RequestSensePool = RequestSensePool;
305     }
306   Controller->CommandAllocationGroupSize = CommandAllocationGroupSize;
307   Controller->FreeCommands = NULL;
308   for (CommandIdentifier = 1;
309        CommandIdentifier <= Controller->DriverQueueDepth;
310        CommandIdentifier++)
311     {
312       DAC960_Command_T *Command;
313       if (--CommandsRemaining <= 0)
314         {
315           CommandsRemaining =
316                 Controller->DriverQueueDepth - CommandIdentifier + 1;
317           if (CommandsRemaining > CommandAllocationGroupSize)
318                 CommandsRemaining = CommandAllocationGroupSize;
319           CommandGroupByteCount =
320                 CommandsRemaining * CommandAllocationLength;
321           AllocationPointer = kmalloc(CommandGroupByteCount, GFP_ATOMIC);
322           if (AllocationPointer == NULL)
323                 return DAC960_Failure(Controller,
324                                         "AUXILIARY STRUCTURE CREATION");
325           memset(AllocationPointer, 0, CommandGroupByteCount);
326          }
327       Command = (DAC960_Command_T *) AllocationPointer;
328       AllocationPointer += CommandAllocationLength;
329       Command->CommandIdentifier = CommandIdentifier;
330       Command->Controller = Controller;
331       Command->Next = Controller->FreeCommands;
332       Controller->FreeCommands = Command;
333       Controller->Commands[CommandIdentifier-1] = Command;
334       ScatterGatherCPU = pci_pool_alloc(ScatterGatherPool, SLAB_ATOMIC,
335                                                         &ScatterGatherDMA);
336       if (ScatterGatherCPU == NULL)
337           return DAC960_Failure(Controller, "AUXILIARY STRUCTURE CREATION");
338
339       if (RequestSensePool != NULL) {
340           RequestSenseCPU = pci_pool_alloc(RequestSensePool, SLAB_ATOMIC,
341                                                 &RequestSenseDMA);
342           if (RequestSenseCPU == NULL) {
343                 pci_pool_free(ScatterGatherPool, ScatterGatherCPU,
344                                 ScatterGatherDMA);
345                 return DAC960_Failure(Controller,
346                                         "AUXILIARY STRUCTURE CREATION");
347           }
348         }
349      if (Controller->FirmwareType == DAC960_V1_Controller) {
350         Command->cmd_sglist = Command->V1.ScatterList;
351         Command->V1.ScatterGatherList =
352                 (DAC960_V1_ScatterGatherSegment_T *)ScatterGatherCPU;
353         Command->V1.ScatterGatherListDMA = ScatterGatherDMA;
354       } else {
355         Command->cmd_sglist = Command->V2.ScatterList;
356         Command->V2.ScatterGatherList =
357                 (DAC960_V2_ScatterGatherSegment_T *)ScatterGatherCPU;
358         Command->V2.ScatterGatherListDMA = ScatterGatherDMA;
359         Command->V2.RequestSense =
360                                 (DAC960_SCSI_RequestSense_T *)RequestSenseCPU;
361         Command->V2.RequestSenseDMA = RequestSenseDMA;
362       }
363     }
364   return true;
365 }
366
367
368 /*
369   DAC960_DestroyAuxiliaryStructures deallocates the auxiliary data
370   structures for Controller.
371 */
372
373 static void DAC960_DestroyAuxiliaryStructures(DAC960_Controller_T *Controller)
374 {
375   int i;
376   struct pci_pool *ScatterGatherPool = Controller->ScatterGatherPool;
377   struct pci_pool *RequestSensePool = NULL;
378   void *ScatterGatherCPU;
379   dma_addr_t ScatterGatherDMA;
380   void *RequestSenseCPU;
381   dma_addr_t RequestSenseDMA;
382   DAC960_Command_T *CommandGroup = NULL;
383   
384
385   if (Controller->FirmwareType == DAC960_V2_Controller)
386         RequestSensePool = Controller->V2.RequestSensePool;
387
388   Controller->FreeCommands = NULL;
389   for (i = 0; i < Controller->DriverQueueDepth; i++)
390     {
391       DAC960_Command_T *Command = Controller->Commands[i];
392
393       if (Command == NULL)
394           continue;
395
396       if (Controller->FirmwareType == DAC960_V1_Controller) {
397           ScatterGatherCPU = (void *)Command->V1.ScatterGatherList;
398           ScatterGatherDMA = Command->V1.ScatterGatherListDMA;
399           RequestSenseCPU = NULL;
400           RequestSenseDMA = (dma_addr_t)0;
401       } else {
402           ScatterGatherCPU = (void *)Command->V2.ScatterGatherList;
403           ScatterGatherDMA = Command->V2.ScatterGatherListDMA;
404           RequestSenseCPU = (void *)Command->V2.RequestSense;
405           RequestSenseDMA = Command->V2.RequestSenseDMA;
406       }
407       if (ScatterGatherCPU != NULL)
408           pci_pool_free(ScatterGatherPool, ScatterGatherCPU, ScatterGatherDMA);
409       if (RequestSenseCPU != NULL)
410           pci_pool_free(RequestSensePool, RequestSenseCPU, RequestSenseDMA);
411
412       if ((Command->CommandIdentifier
413            % Controller->CommandAllocationGroupSize) == 1) {
414            /*
415             * We can't free the group of commands until all of the
416             * request sense and scatter gather dma structures are free.
417             * Remember the beginning of the group, but don't free it
418             * until we've reached the beginning of the next group.
419             */
420            if (CommandGroup != NULL)
421                 kfree(CommandGroup);
422             CommandGroup = Command;
423       }
424       Controller->Commands[i] = NULL;
425     }
426   if (CommandGroup != NULL)
427       kfree(CommandGroup);
428
429   if (Controller->CombinedStatusBuffer != NULL)
430     {
431       kfree(Controller->CombinedStatusBuffer);
432       Controller->CombinedStatusBuffer = NULL;
433       Controller->CurrentStatusBuffer = NULL;
434     }
435
436   if (ScatterGatherPool != NULL)
437         pci_pool_destroy(ScatterGatherPool);
438   if (Controller->FirmwareType == DAC960_V1_Controller) return;
439
440   if (RequestSensePool != NULL)
441         pci_pool_destroy(RequestSensePool);
442
443   for (i = 0; i < DAC960_MaxLogicalDrives; i++)
444     if (Controller->V2.LogicalDeviceInformation[i] != NULL)
445       {
446         kfree(Controller->V2.LogicalDeviceInformation[i]);
447         Controller->V2.LogicalDeviceInformation[i] = NULL;
448       }
449
450   for (i = 0; i < DAC960_V2_MaxPhysicalDevices; i++)
451     {
452       if (Controller->V2.PhysicalDeviceInformation[i] != NULL)
453         {
454           kfree(Controller->V2.PhysicalDeviceInformation[i]);
455           Controller->V2.PhysicalDeviceInformation[i] = NULL;
456         }
457       if (Controller->V2.InquiryUnitSerialNumber[i] != NULL)
458         {
459           kfree(Controller->V2.InquiryUnitSerialNumber[i]);
460           Controller->V2.InquiryUnitSerialNumber[i] = NULL;
461         }
462     }
463 }
464
465
466 /*
467   DAC960_V1_ClearCommand clears critical fields of Command for DAC960 V1
468   Firmware Controllers.
469 */
470
471 static inline void DAC960_V1_ClearCommand(DAC960_Command_T *Command)
472 {
473   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
474   memset(CommandMailbox, 0, sizeof(DAC960_V1_CommandMailbox_T));
475   Command->V1.CommandStatus = 0;
476 }
477
478
479 /*
480   DAC960_V2_ClearCommand clears critical fields of Command for DAC960 V2
481   Firmware Controllers.
482 */
483
484 static inline void DAC960_V2_ClearCommand(DAC960_Command_T *Command)
485 {
486   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
487   memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
488   Command->V2.CommandStatus = 0;
489 }
490
491
492 /*
493   DAC960_AllocateCommand allocates a Command structure from Controller's
494   free list.  During driver initialization, a special initialization command
495   has been placed on the free list to guarantee that command allocation can
496   never fail.
497 */
498
499 static inline DAC960_Command_T *DAC960_AllocateCommand(DAC960_Controller_T
500                                                        *Controller)
501 {
502   DAC960_Command_T *Command = Controller->FreeCommands;
503   if (Command == NULL) return NULL;
504   Controller->FreeCommands = Command->Next;
505   Command->Next = NULL;
506   return Command;
507 }
508
509
510 /*
511   DAC960_DeallocateCommand deallocates Command, returning it to Controller's
512   free list.
513 */
514
515 static inline void DAC960_DeallocateCommand(DAC960_Command_T *Command)
516 {
517   DAC960_Controller_T *Controller = Command->Controller;
518
519   Command->Request = NULL;
520   Command->Next = Controller->FreeCommands;
521   Controller->FreeCommands = Command;
522 }
523
524
525 /*
526   DAC960_WaitForCommand waits for a wake_up on Controller's Command Wait Queue.
527 */
528
529 static void DAC960_WaitForCommand(DAC960_Controller_T *Controller)
530 {
531   spin_unlock_irq(&Controller->queue_lock);
532   __wait_event(Controller->CommandWaitQueue, Controller->FreeCommands);
533   spin_lock_irq(&Controller->queue_lock);
534 }
535
536 /*
537   DAC960_GEM_QueueCommand queues Command for DAC960 GEM Series Controllers.
538 */
539
540 static void DAC960_GEM_QueueCommand(DAC960_Command_T *Command)
541 {
542   DAC960_Controller_T *Controller = Command->Controller;
543   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
544   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
545   DAC960_V2_CommandMailbox_T *NextCommandMailbox =
546       Controller->V2.NextCommandMailbox;
547
548   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
549   DAC960_GEM_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
550
551   if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
552       Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
553       DAC960_GEM_MemoryMailboxNewCommand(ControllerBaseAddress);
554
555   Controller->V2.PreviousCommandMailbox2 =
556       Controller->V2.PreviousCommandMailbox1;
557   Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
558
559   if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
560       NextCommandMailbox = Controller->V2.FirstCommandMailbox;
561
562   Controller->V2.NextCommandMailbox = NextCommandMailbox;
563 }
564
565 /*
566   DAC960_BA_QueueCommand queues Command for DAC960 BA Series Controllers.
567 */
568
569 static void DAC960_BA_QueueCommand(DAC960_Command_T *Command)
570 {
571   DAC960_Controller_T *Controller = Command->Controller;
572   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
573   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
574   DAC960_V2_CommandMailbox_T *NextCommandMailbox =
575     Controller->V2.NextCommandMailbox;
576   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
577   DAC960_BA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
578   if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
579       Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
580     DAC960_BA_MemoryMailboxNewCommand(ControllerBaseAddress);
581   Controller->V2.PreviousCommandMailbox2 =
582     Controller->V2.PreviousCommandMailbox1;
583   Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
584   if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
585     NextCommandMailbox = Controller->V2.FirstCommandMailbox;
586   Controller->V2.NextCommandMailbox = NextCommandMailbox;
587 }
588
589
590 /*
591   DAC960_LP_QueueCommand queues Command for DAC960 LP Series Controllers.
592 */
593
594 static void DAC960_LP_QueueCommand(DAC960_Command_T *Command)
595 {
596   DAC960_Controller_T *Controller = Command->Controller;
597   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
598   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
599   DAC960_V2_CommandMailbox_T *NextCommandMailbox =
600     Controller->V2.NextCommandMailbox;
601   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
602   DAC960_LP_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
603   if (Controller->V2.PreviousCommandMailbox1->Words[0] == 0 ||
604       Controller->V2.PreviousCommandMailbox2->Words[0] == 0)
605     DAC960_LP_MemoryMailboxNewCommand(ControllerBaseAddress);
606   Controller->V2.PreviousCommandMailbox2 =
607     Controller->V2.PreviousCommandMailbox1;
608   Controller->V2.PreviousCommandMailbox1 = NextCommandMailbox;
609   if (++NextCommandMailbox > Controller->V2.LastCommandMailbox)
610     NextCommandMailbox = Controller->V2.FirstCommandMailbox;
611   Controller->V2.NextCommandMailbox = NextCommandMailbox;
612 }
613
614
615 /*
616   DAC960_LA_QueueCommandDualMode queues Command for DAC960 LA Series
617   Controllers with Dual Mode Firmware.
618 */
619
620 static void DAC960_LA_QueueCommandDualMode(DAC960_Command_T *Command)
621 {
622   DAC960_Controller_T *Controller = Command->Controller;
623   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
624   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
625   DAC960_V1_CommandMailbox_T *NextCommandMailbox =
626     Controller->V1.NextCommandMailbox;
627   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
628   DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
629   if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
630       Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
631     DAC960_LA_MemoryMailboxNewCommand(ControllerBaseAddress);
632   Controller->V1.PreviousCommandMailbox2 =
633     Controller->V1.PreviousCommandMailbox1;
634   Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
635   if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
636     NextCommandMailbox = Controller->V1.FirstCommandMailbox;
637   Controller->V1.NextCommandMailbox = NextCommandMailbox;
638 }
639
640
641 /*
642   DAC960_LA_QueueCommandSingleMode queues Command for DAC960 LA Series
643   Controllers with Single Mode Firmware.
644 */
645
646 static void DAC960_LA_QueueCommandSingleMode(DAC960_Command_T *Command)
647 {
648   DAC960_Controller_T *Controller = Command->Controller;
649   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
650   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
651   DAC960_V1_CommandMailbox_T *NextCommandMailbox =
652     Controller->V1.NextCommandMailbox;
653   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
654   DAC960_LA_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
655   if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
656       Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
657     DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
658   Controller->V1.PreviousCommandMailbox2 =
659     Controller->V1.PreviousCommandMailbox1;
660   Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
661   if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
662     NextCommandMailbox = Controller->V1.FirstCommandMailbox;
663   Controller->V1.NextCommandMailbox = NextCommandMailbox;
664 }
665
666
667 /*
668   DAC960_PG_QueueCommandDualMode queues Command for DAC960 PG Series
669   Controllers with Dual Mode Firmware.
670 */
671
672 static void DAC960_PG_QueueCommandDualMode(DAC960_Command_T *Command)
673 {
674   DAC960_Controller_T *Controller = Command->Controller;
675   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
676   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
677   DAC960_V1_CommandMailbox_T *NextCommandMailbox =
678     Controller->V1.NextCommandMailbox;
679   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
680   DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
681   if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
682       Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
683     DAC960_PG_MemoryMailboxNewCommand(ControllerBaseAddress);
684   Controller->V1.PreviousCommandMailbox2 =
685     Controller->V1.PreviousCommandMailbox1;
686   Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
687   if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
688     NextCommandMailbox = Controller->V1.FirstCommandMailbox;
689   Controller->V1.NextCommandMailbox = NextCommandMailbox;
690 }
691
692
693 /*
694   DAC960_PG_QueueCommandSingleMode queues Command for DAC960 PG Series
695   Controllers with Single Mode Firmware.
696 */
697
698 static void DAC960_PG_QueueCommandSingleMode(DAC960_Command_T *Command)
699 {
700   DAC960_Controller_T *Controller = Command->Controller;
701   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
702   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
703   DAC960_V1_CommandMailbox_T *NextCommandMailbox =
704     Controller->V1.NextCommandMailbox;
705   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
706   DAC960_PG_WriteCommandMailbox(NextCommandMailbox, CommandMailbox);
707   if (Controller->V1.PreviousCommandMailbox1->Words[0] == 0 ||
708       Controller->V1.PreviousCommandMailbox2->Words[0] == 0)
709     DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
710   Controller->V1.PreviousCommandMailbox2 =
711     Controller->V1.PreviousCommandMailbox1;
712   Controller->V1.PreviousCommandMailbox1 = NextCommandMailbox;
713   if (++NextCommandMailbox > Controller->V1.LastCommandMailbox)
714     NextCommandMailbox = Controller->V1.FirstCommandMailbox;
715   Controller->V1.NextCommandMailbox = NextCommandMailbox;
716 }
717
718
719 /*
720   DAC960_PD_QueueCommand queues Command for DAC960 PD Series Controllers.
721 */
722
723 static void DAC960_PD_QueueCommand(DAC960_Command_T *Command)
724 {
725   DAC960_Controller_T *Controller = Command->Controller;
726   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
727   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
728   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
729   while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
730     udelay(1);
731   DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
732   DAC960_PD_NewCommand(ControllerBaseAddress);
733 }
734
735
736 /*
737   DAC960_P_QueueCommand queues Command for DAC960 P Series Controllers.
738 */
739
740 static void DAC960_P_QueueCommand(DAC960_Command_T *Command)
741 {
742   DAC960_Controller_T *Controller = Command->Controller;
743   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
744   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
745   CommandMailbox->Common.CommandIdentifier = Command->CommandIdentifier;
746   switch (CommandMailbox->Common.CommandOpcode)
747     {
748     case DAC960_V1_Enquiry:
749       CommandMailbox->Common.CommandOpcode = DAC960_V1_Enquiry_Old;
750       break;
751     case DAC960_V1_GetDeviceState:
752       CommandMailbox->Common.CommandOpcode = DAC960_V1_GetDeviceState_Old;
753       break;
754     case DAC960_V1_Read:
755       CommandMailbox->Common.CommandOpcode = DAC960_V1_Read_Old;
756       DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
757       break;
758     case DAC960_V1_Write:
759       CommandMailbox->Common.CommandOpcode = DAC960_V1_Write_Old;
760       DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
761       break;
762     case DAC960_V1_ReadWithScatterGather:
763       CommandMailbox->Common.CommandOpcode =
764         DAC960_V1_ReadWithScatterGather_Old;
765       DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
766       break;
767     case DAC960_V1_WriteWithScatterGather:
768       CommandMailbox->Common.CommandOpcode =
769         DAC960_V1_WriteWithScatterGather_Old;
770       DAC960_PD_To_P_TranslateReadWriteCommand(CommandMailbox);
771       break;
772     default:
773       break;
774     }
775   while (DAC960_PD_MailboxFullP(ControllerBaseAddress))
776     udelay(1);
777   DAC960_PD_WriteCommandMailbox(ControllerBaseAddress, CommandMailbox);
778   DAC960_PD_NewCommand(ControllerBaseAddress);
779 }
780
781
782 /*
783   DAC960_ExecuteCommand executes Command and waits for completion.
784 */
785
786 static void DAC960_ExecuteCommand(DAC960_Command_T *Command)
787 {
788   DAC960_Controller_T *Controller = Command->Controller;
789   DECLARE_COMPLETION(Completion);
790   unsigned long flags;
791   Command->Completion = &Completion;
792
793   spin_lock_irqsave(&Controller->queue_lock, flags);
794   DAC960_QueueCommand(Command);
795   spin_unlock_irqrestore(&Controller->queue_lock, flags);
796  
797   if (in_interrupt())
798           return;
799   wait_for_completion(&Completion);
800 }
801
802
803 /*
804   DAC960_V1_ExecuteType3 executes a DAC960 V1 Firmware Controller Type 3
805   Command and waits for completion.  It returns true on success and false
806   on failure.
807 */
808
809 static boolean DAC960_V1_ExecuteType3(DAC960_Controller_T *Controller,
810                                       DAC960_V1_CommandOpcode_T CommandOpcode,
811                                       dma_addr_t DataDMA)
812 {
813   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
814   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
815   DAC960_V1_CommandStatus_T CommandStatus;
816   DAC960_V1_ClearCommand(Command);
817   Command->CommandType = DAC960_ImmediateCommand;
818   CommandMailbox->Type3.CommandOpcode = CommandOpcode;
819   CommandMailbox->Type3.BusAddress = DataDMA;
820   DAC960_ExecuteCommand(Command);
821   CommandStatus = Command->V1.CommandStatus;
822   DAC960_DeallocateCommand(Command);
823   return (CommandStatus == DAC960_V1_NormalCompletion);
824 }
825
826
827 /*
828   DAC960_V1_ExecuteTypeB executes a DAC960 V1 Firmware Controller Type 3B
829   Command and waits for completion.  It returns true on success and false
830   on failure.
831 */
832
833 static boolean DAC960_V1_ExecuteType3B(DAC960_Controller_T *Controller,
834                                        DAC960_V1_CommandOpcode_T CommandOpcode,
835                                        unsigned char CommandOpcode2,
836                                        dma_addr_t DataDMA)
837 {
838   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
839   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
840   DAC960_V1_CommandStatus_T CommandStatus;
841   DAC960_V1_ClearCommand(Command);
842   Command->CommandType = DAC960_ImmediateCommand;
843   CommandMailbox->Type3B.CommandOpcode = CommandOpcode;
844   CommandMailbox->Type3B.CommandOpcode2 = CommandOpcode2;
845   CommandMailbox->Type3B.BusAddress = DataDMA;
846   DAC960_ExecuteCommand(Command);
847   CommandStatus = Command->V1.CommandStatus;
848   DAC960_DeallocateCommand(Command);
849   return (CommandStatus == DAC960_V1_NormalCompletion);
850 }
851
852
853 /*
854   DAC960_V1_ExecuteType3D executes a DAC960 V1 Firmware Controller Type 3D
855   Command and waits for completion.  It returns true on success and false
856   on failure.
857 */
858
859 static boolean DAC960_V1_ExecuteType3D(DAC960_Controller_T *Controller,
860                                        DAC960_V1_CommandOpcode_T CommandOpcode,
861                                        unsigned char Channel,
862                                        unsigned char TargetID,
863                                        dma_addr_t DataDMA)
864 {
865   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
866   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
867   DAC960_V1_CommandStatus_T CommandStatus;
868   DAC960_V1_ClearCommand(Command);
869   Command->CommandType = DAC960_ImmediateCommand;
870   CommandMailbox->Type3D.CommandOpcode = CommandOpcode;
871   CommandMailbox->Type3D.Channel = Channel;
872   CommandMailbox->Type3D.TargetID = TargetID;
873   CommandMailbox->Type3D.BusAddress = DataDMA;
874   DAC960_ExecuteCommand(Command);
875   CommandStatus = Command->V1.CommandStatus;
876   DAC960_DeallocateCommand(Command);
877   return (CommandStatus == DAC960_V1_NormalCompletion);
878 }
879
880
881 /*
882   DAC960_V2_GeneralInfo executes a DAC960 V2 Firmware General Information
883   Reading IOCTL Command and waits for completion.  It returns true on success
884   and false on failure.
885
886   Return data in The controller's HealthStatusBuffer, which is dma-able memory
887 */
888
889 static boolean DAC960_V2_GeneralInfo(DAC960_Controller_T *Controller)
890 {
891   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
892   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
893   DAC960_V2_CommandStatus_T CommandStatus;
894   DAC960_V2_ClearCommand(Command);
895   Command->CommandType = DAC960_ImmediateCommand;
896   CommandMailbox->Common.CommandOpcode = DAC960_V2_IOCTL;
897   CommandMailbox->Common.CommandControlBits
898                         .DataTransferControllerToHost = true;
899   CommandMailbox->Common.CommandControlBits
900                         .NoAutoRequestSense = true;
901   CommandMailbox->Common.DataTransferSize = sizeof(DAC960_V2_HealthStatusBuffer_T);
902   CommandMailbox->Common.IOCTL_Opcode = DAC960_V2_GetHealthStatus;
903   CommandMailbox->Common.DataTransferMemoryAddress
904                         .ScatterGatherSegments[0]
905                         .SegmentDataPointer =
906     Controller->V2.HealthStatusBufferDMA;
907   CommandMailbox->Common.DataTransferMemoryAddress
908                         .ScatterGatherSegments[0]
909                         .SegmentByteCount =
910     CommandMailbox->Common.DataTransferSize;
911   DAC960_ExecuteCommand(Command);
912   CommandStatus = Command->V2.CommandStatus;
913   DAC960_DeallocateCommand(Command);
914   return (CommandStatus == DAC960_V2_NormalCompletion);
915 }
916
917
918 /*
919   DAC960_V2_ControllerInfo executes a DAC960 V2 Firmware Controller
920   Information Reading IOCTL Command and waits for completion.  It returns
921   true on success and false on failure.
922
923   Data is returned in the controller's V2.NewControllerInformation dma-able
924   memory buffer.
925 */
926
927 static boolean DAC960_V2_NewControllerInfo(DAC960_Controller_T *Controller)
928 {
929   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
930   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
931   DAC960_V2_CommandStatus_T CommandStatus;
932   DAC960_V2_ClearCommand(Command);
933   Command->CommandType = DAC960_ImmediateCommand;
934   CommandMailbox->ControllerInfo.CommandOpcode = DAC960_V2_IOCTL;
935   CommandMailbox->ControllerInfo.CommandControlBits
936                                 .DataTransferControllerToHost = true;
937   CommandMailbox->ControllerInfo.CommandControlBits
938                                 .NoAutoRequestSense = true;
939   CommandMailbox->ControllerInfo.DataTransferSize = sizeof(DAC960_V2_ControllerInfo_T);
940   CommandMailbox->ControllerInfo.ControllerNumber = 0;
941   CommandMailbox->ControllerInfo.IOCTL_Opcode = DAC960_V2_GetControllerInfo;
942   CommandMailbox->ControllerInfo.DataTransferMemoryAddress
943                                 .ScatterGatherSegments[0]
944                                 .SegmentDataPointer =
945         Controller->V2.NewControllerInformationDMA;
946   CommandMailbox->ControllerInfo.DataTransferMemoryAddress
947                                 .ScatterGatherSegments[0]
948                                 .SegmentByteCount =
949     CommandMailbox->ControllerInfo.DataTransferSize;
950   DAC960_ExecuteCommand(Command);
951   CommandStatus = Command->V2.CommandStatus;
952   DAC960_DeallocateCommand(Command);
953   return (CommandStatus == DAC960_V2_NormalCompletion);
954 }
955
956
957 /*
958   DAC960_V2_LogicalDeviceInfo executes a DAC960 V2 Firmware Controller Logical
959   Device Information Reading IOCTL Command and waits for completion.  It
960   returns true on success and false on failure.
961
962   Data is returned in the controller's V2.NewLogicalDeviceInformation
963 */
964
965 static boolean DAC960_V2_NewLogicalDeviceInfo(DAC960_Controller_T *Controller,
966                                            unsigned short LogicalDeviceNumber)
967 {
968   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
969   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
970   DAC960_V2_CommandStatus_T CommandStatus;
971
972   DAC960_V2_ClearCommand(Command);
973   Command->CommandType = DAC960_ImmediateCommand;
974   CommandMailbox->LogicalDeviceInfo.CommandOpcode =
975                                 DAC960_V2_IOCTL;
976   CommandMailbox->LogicalDeviceInfo.CommandControlBits
977                                    .DataTransferControllerToHost = true;
978   CommandMailbox->LogicalDeviceInfo.CommandControlBits
979                                    .NoAutoRequestSense = true;
980   CommandMailbox->LogicalDeviceInfo.DataTransferSize = 
981                                 sizeof(DAC960_V2_LogicalDeviceInfo_T);
982   CommandMailbox->LogicalDeviceInfo.LogicalDevice.LogicalDeviceNumber =
983     LogicalDeviceNumber;
984   CommandMailbox->LogicalDeviceInfo.IOCTL_Opcode = DAC960_V2_GetLogicalDeviceInfoValid;
985   CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
986                                    .ScatterGatherSegments[0]
987                                    .SegmentDataPointer =
988         Controller->V2.NewLogicalDeviceInformationDMA;
989   CommandMailbox->LogicalDeviceInfo.DataTransferMemoryAddress
990                                    .ScatterGatherSegments[0]
991                                    .SegmentByteCount =
992     CommandMailbox->LogicalDeviceInfo.DataTransferSize;
993   DAC960_ExecuteCommand(Command);
994   CommandStatus = Command->V2.CommandStatus;
995   DAC960_DeallocateCommand(Command);
996   return (CommandStatus == DAC960_V2_NormalCompletion);
997 }
998
999
1000 /*
1001   DAC960_V2_PhysicalDeviceInfo executes a DAC960 V2 Firmware Controller "Read
1002   Physical Device Information" IOCTL Command and waits for completion.  It
1003   returns true on success and false on failure.
1004
1005   The Channel, TargetID, LogicalUnit arguments should be 0 the first time
1006   this function is called for a given controller.  This will return data
1007   for the "first" device on that controller.  The returned data includes a
1008   Channel, TargetID, LogicalUnit that can be passed in to this routine to
1009   get data for the NEXT device on that controller.
1010
1011   Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
1012   memory buffer.
1013
1014 */
1015
1016 static boolean DAC960_V2_NewPhysicalDeviceInfo(DAC960_Controller_T *Controller,
1017                                             unsigned char Channel,
1018                                             unsigned char TargetID,
1019                                             unsigned char LogicalUnit)
1020 {
1021   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
1022   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
1023   DAC960_V2_CommandStatus_T CommandStatus;
1024
1025   DAC960_V2_ClearCommand(Command);
1026   Command->CommandType = DAC960_ImmediateCommand;
1027   CommandMailbox->PhysicalDeviceInfo.CommandOpcode = DAC960_V2_IOCTL;
1028   CommandMailbox->PhysicalDeviceInfo.CommandControlBits
1029                                     .DataTransferControllerToHost = true;
1030   CommandMailbox->PhysicalDeviceInfo.CommandControlBits
1031                                     .NoAutoRequestSense = true;
1032   CommandMailbox->PhysicalDeviceInfo.DataTransferSize =
1033                                 sizeof(DAC960_V2_PhysicalDeviceInfo_T);
1034   CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.LogicalUnit = LogicalUnit;
1035   CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.TargetID = TargetID;
1036   CommandMailbox->PhysicalDeviceInfo.PhysicalDevice.Channel = Channel;
1037   CommandMailbox->PhysicalDeviceInfo.IOCTL_Opcode =
1038                                         DAC960_V2_GetPhysicalDeviceInfoValid;
1039   CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
1040                                     .ScatterGatherSegments[0]
1041                                     .SegmentDataPointer =
1042                                         Controller->V2.NewPhysicalDeviceInformationDMA;
1043   CommandMailbox->PhysicalDeviceInfo.DataTransferMemoryAddress
1044                                     .ScatterGatherSegments[0]
1045                                     .SegmentByteCount =
1046     CommandMailbox->PhysicalDeviceInfo.DataTransferSize;
1047   DAC960_ExecuteCommand(Command);
1048   CommandStatus = Command->V2.CommandStatus;
1049   DAC960_DeallocateCommand(Command);
1050   return (CommandStatus == DAC960_V2_NormalCompletion);
1051 }
1052
1053
1054 static void DAC960_V2_ConstructNewUnitSerialNumber(
1055         DAC960_Controller_T *Controller,
1056         DAC960_V2_CommandMailbox_T *CommandMailbox, int Channel, int TargetID,
1057         int LogicalUnit)
1058 {
1059       CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10_Passthru;
1060       CommandMailbox->SCSI_10.CommandControlBits
1061                              .DataTransferControllerToHost = true;
1062       CommandMailbox->SCSI_10.CommandControlBits
1063                              .NoAutoRequestSense = true;
1064       CommandMailbox->SCSI_10.DataTransferSize =
1065         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1066       CommandMailbox->SCSI_10.PhysicalDevice.LogicalUnit = LogicalUnit;
1067       CommandMailbox->SCSI_10.PhysicalDevice.TargetID = TargetID;
1068       CommandMailbox->SCSI_10.PhysicalDevice.Channel = Channel;
1069       CommandMailbox->SCSI_10.CDBLength = 6;
1070       CommandMailbox->SCSI_10.SCSI_CDB[0] = 0x12; /* INQUIRY */
1071       CommandMailbox->SCSI_10.SCSI_CDB[1] = 1; /* EVPD = 1 */
1072       CommandMailbox->SCSI_10.SCSI_CDB[2] = 0x80; /* Page Code */
1073       CommandMailbox->SCSI_10.SCSI_CDB[3] = 0; /* Reserved */
1074       CommandMailbox->SCSI_10.SCSI_CDB[4] =
1075         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1076       CommandMailbox->SCSI_10.SCSI_CDB[5] = 0; /* Control */
1077       CommandMailbox->SCSI_10.DataTransferMemoryAddress
1078                              .ScatterGatherSegments[0]
1079                              .SegmentDataPointer =
1080                 Controller->V2.NewInquiryUnitSerialNumberDMA;
1081       CommandMailbox->SCSI_10.DataTransferMemoryAddress
1082                              .ScatterGatherSegments[0]
1083                              .SegmentByteCount =
1084                 CommandMailbox->SCSI_10.DataTransferSize;
1085 }
1086
1087
1088 /*
1089   DAC960_V2_NewUnitSerialNumber executes an SCSI pass-through
1090   Inquiry command to a SCSI device identified by Channel number,
1091   Target id, Logical Unit Number.  This function Waits for completion
1092   of the command.
1093
1094   The return data includes Unit Serial Number information for the
1095   specified device.
1096
1097   Data is stored in the controller's V2.NewPhysicalDeviceInfo dma-able
1098   memory buffer.
1099 */
1100
1101 static boolean DAC960_V2_NewInquiryUnitSerialNumber(DAC960_Controller_T *Controller,
1102                         int Channel, int TargetID, int LogicalUnit)
1103 {
1104       DAC960_Command_T *Command;
1105       DAC960_V2_CommandMailbox_T *CommandMailbox;
1106       DAC960_V2_CommandStatus_T CommandStatus;
1107
1108       Command = DAC960_AllocateCommand(Controller);
1109       CommandMailbox = &Command->V2.CommandMailbox;
1110       DAC960_V2_ClearCommand(Command);
1111       Command->CommandType = DAC960_ImmediateCommand;
1112
1113       DAC960_V2_ConstructNewUnitSerialNumber(Controller, CommandMailbox,
1114                         Channel, TargetID, LogicalUnit);
1115
1116       DAC960_ExecuteCommand(Command);
1117       CommandStatus = Command->V2.CommandStatus;
1118       DAC960_DeallocateCommand(Command);
1119       return (CommandStatus == DAC960_V2_NormalCompletion);
1120 }
1121
1122
1123 /*
1124   DAC960_V2_DeviceOperation executes a DAC960 V2 Firmware Controller Device
1125   Operation IOCTL Command and waits for completion.  It returns true on
1126   success and false on failure.
1127 */
1128
1129 static boolean DAC960_V2_DeviceOperation(DAC960_Controller_T *Controller,
1130                                          DAC960_V2_IOCTL_Opcode_T IOCTL_Opcode,
1131                                          DAC960_V2_OperationDevice_T
1132                                            OperationDevice)
1133 {
1134   DAC960_Command_T *Command = DAC960_AllocateCommand(Controller);
1135   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
1136   DAC960_V2_CommandStatus_T CommandStatus;
1137   DAC960_V2_ClearCommand(Command);
1138   Command->CommandType = DAC960_ImmediateCommand;
1139   CommandMailbox->DeviceOperation.CommandOpcode = DAC960_V2_IOCTL;
1140   CommandMailbox->DeviceOperation.CommandControlBits
1141                                  .DataTransferControllerToHost = true;
1142   CommandMailbox->DeviceOperation.CommandControlBits
1143                                  .NoAutoRequestSense = true;
1144   CommandMailbox->DeviceOperation.IOCTL_Opcode = IOCTL_Opcode;
1145   CommandMailbox->DeviceOperation.OperationDevice = OperationDevice;
1146   DAC960_ExecuteCommand(Command);
1147   CommandStatus = Command->V2.CommandStatus;
1148   DAC960_DeallocateCommand(Command);
1149   return (CommandStatus == DAC960_V2_NormalCompletion);
1150 }
1151
1152
1153 /*
1154   DAC960_V1_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
1155   for DAC960 V1 Firmware Controllers.
1156
1157   PD and P controller types have no memory mailbox, but still need the
1158   other dma mapped memory.
1159 */
1160
1161 static boolean DAC960_V1_EnableMemoryMailboxInterface(DAC960_Controller_T
1162                                                       *Controller)
1163 {
1164   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
1165   DAC960_HardwareType_T hw_type = Controller->HardwareType;
1166   struct pci_dev *PCI_Device = Controller->PCIDevice;
1167   struct dma_loaf *DmaPages = &Controller->DmaPages;
1168   size_t DmaPagesSize;
1169   size_t CommandMailboxesSize;
1170   size_t StatusMailboxesSize;
1171
1172   DAC960_V1_CommandMailbox_T *CommandMailboxesMemory;
1173   dma_addr_t CommandMailboxesMemoryDMA;
1174
1175   DAC960_V1_StatusMailbox_T *StatusMailboxesMemory;
1176   dma_addr_t StatusMailboxesMemoryDMA;
1177
1178   DAC960_V1_CommandMailbox_T CommandMailbox;
1179   DAC960_V1_CommandStatus_T CommandStatus;
1180   int TimeoutCounter;
1181   int i;
1182
1183   
1184   if (pci_set_dma_mask(Controller->PCIDevice, DAC690_V1_PciDmaMask))
1185         return DAC960_Failure(Controller, "DMA mask out of range");
1186   Controller->BounceBufferLimit = DAC690_V1_PciDmaMask;
1187
1188   if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller)) {
1189     CommandMailboxesSize =  0;
1190     StatusMailboxesSize = 0;
1191   } else {
1192     CommandMailboxesSize =  DAC960_V1_CommandMailboxCount * sizeof(DAC960_V1_CommandMailbox_T);
1193     StatusMailboxesSize = DAC960_V1_StatusMailboxCount * sizeof(DAC960_V1_StatusMailbox_T);
1194   }
1195   DmaPagesSize = CommandMailboxesSize + StatusMailboxesSize + 
1196         sizeof(DAC960_V1_DCDB_T) + sizeof(DAC960_V1_Enquiry_T) +
1197         sizeof(DAC960_V1_ErrorTable_T) + sizeof(DAC960_V1_EventLogEntry_T) +
1198         sizeof(DAC960_V1_RebuildProgress_T) +
1199         sizeof(DAC960_V1_LogicalDriveInformationArray_T) +
1200         sizeof(DAC960_V1_BackgroundInitializationStatus_T) +
1201         sizeof(DAC960_V1_DeviceState_T) + sizeof(DAC960_SCSI_Inquiry_T) +
1202         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
1203
1204   if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize))
1205         return false;
1206
1207
1208   if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller)) 
1209         goto skip_mailboxes;
1210
1211   CommandMailboxesMemory = slice_dma_loaf(DmaPages,
1212                 CommandMailboxesSize, &CommandMailboxesMemoryDMA);
1213   
1214   /* These are the base addresses for the command memory mailbox array */
1215   Controller->V1.FirstCommandMailbox = CommandMailboxesMemory;
1216   Controller->V1.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
1217
1218   CommandMailboxesMemory += DAC960_V1_CommandMailboxCount - 1;
1219   Controller->V1.LastCommandMailbox = CommandMailboxesMemory;
1220   Controller->V1.NextCommandMailbox = Controller->V1.FirstCommandMailbox;
1221   Controller->V1.PreviousCommandMailbox1 = Controller->V1.LastCommandMailbox;
1222   Controller->V1.PreviousCommandMailbox2 =
1223                                         Controller->V1.LastCommandMailbox - 1;
1224
1225   /* These are the base addresses for the status memory mailbox array */
1226   StatusMailboxesMemory = slice_dma_loaf(DmaPages,
1227                 StatusMailboxesSize, &StatusMailboxesMemoryDMA);
1228
1229   Controller->V1.FirstStatusMailbox = StatusMailboxesMemory;
1230   Controller->V1.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
1231   StatusMailboxesMemory += DAC960_V1_StatusMailboxCount - 1;
1232   Controller->V1.LastStatusMailbox = StatusMailboxesMemory;
1233   Controller->V1.NextStatusMailbox = Controller->V1.FirstStatusMailbox;
1234
1235 skip_mailboxes:
1236   Controller->V1.MonitoringDCDB = slice_dma_loaf(DmaPages,
1237                 sizeof(DAC960_V1_DCDB_T),
1238                 &Controller->V1.MonitoringDCDB_DMA);
1239
1240   Controller->V1.NewEnquiry = slice_dma_loaf(DmaPages,
1241                 sizeof(DAC960_V1_Enquiry_T),
1242                 &Controller->V1.NewEnquiryDMA);
1243
1244   Controller->V1.NewErrorTable = slice_dma_loaf(DmaPages,
1245                 sizeof(DAC960_V1_ErrorTable_T),
1246                 &Controller->V1.NewErrorTableDMA);
1247
1248   Controller->V1.EventLogEntry = slice_dma_loaf(DmaPages,
1249                 sizeof(DAC960_V1_EventLogEntry_T),
1250                 &Controller->V1.EventLogEntryDMA);
1251
1252   Controller->V1.RebuildProgress = slice_dma_loaf(DmaPages,
1253                 sizeof(DAC960_V1_RebuildProgress_T),
1254                 &Controller->V1.RebuildProgressDMA);
1255
1256   Controller->V1.NewLogicalDriveInformation = slice_dma_loaf(DmaPages,
1257                 sizeof(DAC960_V1_LogicalDriveInformationArray_T),
1258                 &Controller->V1.NewLogicalDriveInformationDMA);
1259
1260   Controller->V1.BackgroundInitializationStatus = slice_dma_loaf(DmaPages,
1261                 sizeof(DAC960_V1_BackgroundInitializationStatus_T),
1262                 &Controller->V1.BackgroundInitializationStatusDMA);
1263
1264   Controller->V1.NewDeviceState = slice_dma_loaf(DmaPages,
1265                 sizeof(DAC960_V1_DeviceState_T),
1266                 &Controller->V1.NewDeviceStateDMA);
1267
1268   Controller->V1.NewInquiryStandardData = slice_dma_loaf(DmaPages,
1269                 sizeof(DAC960_SCSI_Inquiry_T),
1270                 &Controller->V1.NewInquiryStandardDataDMA);
1271
1272   Controller->V1.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
1273                 sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1274                 &Controller->V1.NewInquiryUnitSerialNumberDMA);
1275
1276   if ((hw_type == DAC960_PD_Controller) || (hw_type == DAC960_P_Controller))
1277         return true;
1278  
1279   /* Enable the Memory Mailbox Interface. */
1280   Controller->V1.DualModeMemoryMailboxInterface = true;
1281   CommandMailbox.TypeX.CommandOpcode = 0x2B;
1282   CommandMailbox.TypeX.CommandIdentifier = 0;
1283   CommandMailbox.TypeX.CommandOpcode2 = 0x14;
1284   CommandMailbox.TypeX.CommandMailboxesBusAddress =
1285                                 Controller->V1.FirstCommandMailboxDMA;
1286   CommandMailbox.TypeX.StatusMailboxesBusAddress =
1287                                 Controller->V1.FirstStatusMailboxDMA;
1288 #define TIMEOUT_COUNT 1000000
1289
1290   for (i = 0; i < 2; i++)
1291     switch (Controller->HardwareType)
1292       {
1293       case DAC960_LA_Controller:
1294         TimeoutCounter = TIMEOUT_COUNT;
1295         while (--TimeoutCounter >= 0)
1296           {
1297             if (!DAC960_LA_HardwareMailboxFullP(ControllerBaseAddress))
1298               break;
1299             udelay(10);
1300           }
1301         if (TimeoutCounter < 0) return false;
1302         DAC960_LA_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
1303         DAC960_LA_HardwareMailboxNewCommand(ControllerBaseAddress);
1304         TimeoutCounter = TIMEOUT_COUNT;
1305         while (--TimeoutCounter >= 0)
1306           {
1307             if (DAC960_LA_HardwareMailboxStatusAvailableP(
1308                   ControllerBaseAddress))
1309               break;
1310             udelay(10);
1311           }
1312         if (TimeoutCounter < 0) return false;
1313         CommandStatus = DAC960_LA_ReadStatusRegister(ControllerBaseAddress);
1314         DAC960_LA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1315         DAC960_LA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1316         if (CommandStatus == DAC960_V1_NormalCompletion) return true;
1317         Controller->V1.DualModeMemoryMailboxInterface = false;
1318         CommandMailbox.TypeX.CommandOpcode2 = 0x10;
1319         break;
1320       case DAC960_PG_Controller:
1321         TimeoutCounter = TIMEOUT_COUNT;
1322         while (--TimeoutCounter >= 0)
1323           {
1324             if (!DAC960_PG_HardwareMailboxFullP(ControllerBaseAddress))
1325               break;
1326             udelay(10);
1327           }
1328         if (TimeoutCounter < 0) return false;
1329         DAC960_PG_WriteHardwareMailbox(ControllerBaseAddress, &CommandMailbox);
1330         DAC960_PG_HardwareMailboxNewCommand(ControllerBaseAddress);
1331
1332         TimeoutCounter = TIMEOUT_COUNT;
1333         while (--TimeoutCounter >= 0)
1334           {
1335             if (DAC960_PG_HardwareMailboxStatusAvailableP(
1336                   ControllerBaseAddress))
1337               break;
1338             udelay(10);
1339           }
1340         if (TimeoutCounter < 0) return false;
1341         CommandStatus = DAC960_PG_ReadStatusRegister(ControllerBaseAddress);
1342         DAC960_PG_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1343         DAC960_PG_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1344         if (CommandStatus == DAC960_V1_NormalCompletion) return true;
1345         Controller->V1.DualModeMemoryMailboxInterface = false;
1346         CommandMailbox.TypeX.CommandOpcode2 = 0x10;
1347         break;
1348       default:
1349         DAC960_Failure(Controller, "Unknown Controller Type\n");
1350         break;
1351       }
1352   return false;
1353 }
1354
1355
1356 /*
1357   DAC960_V2_EnableMemoryMailboxInterface enables the Memory Mailbox Interface
1358   for DAC960 V2 Firmware Controllers.
1359
1360   Aggregate the space needed for the controller's memory mailbox and
1361   the other data structures that will be targets of dma transfers with
1362   the controller.  Allocate a dma-mapped region of memory to hold these
1363   structures.  Then, save CPU pointers and dma_addr_t values to reference
1364   the structures that are contained in that region.
1365 */
1366
1367 static boolean DAC960_V2_EnableMemoryMailboxInterface(DAC960_Controller_T
1368                                                       *Controller)
1369 {
1370   void __iomem *ControllerBaseAddress = Controller->BaseAddress;
1371   struct pci_dev *PCI_Device = Controller->PCIDevice;
1372   struct dma_loaf *DmaPages = &Controller->DmaPages;
1373   size_t DmaPagesSize;
1374   size_t CommandMailboxesSize;
1375   size_t StatusMailboxesSize;
1376
1377   DAC960_V2_CommandMailbox_T *CommandMailboxesMemory;
1378   dma_addr_t CommandMailboxesMemoryDMA;
1379
1380   DAC960_V2_StatusMailbox_T *StatusMailboxesMemory;
1381   dma_addr_t StatusMailboxesMemoryDMA;
1382
1383   DAC960_V2_CommandMailbox_T *CommandMailbox;
1384   dma_addr_t    CommandMailboxDMA;
1385   DAC960_V2_CommandStatus_T CommandStatus;
1386
1387   if (pci_set_dma_mask(Controller->PCIDevice, DAC690_V2_PciDmaMask))
1388         return DAC960_Failure(Controller, "DMA mask out of range");
1389   Controller->BounceBufferLimit = DAC690_V2_PciDmaMask;
1390
1391   /* This is a temporary dma mapping, used only in the scope of this function */
1392   CommandMailbox =
1393           (DAC960_V2_CommandMailbox_T *)pci_alloc_consistent( PCI_Device,
1394                 sizeof(DAC960_V2_CommandMailbox_T), &CommandMailboxDMA);
1395   if (CommandMailbox == NULL)
1396           return false;
1397
1398   CommandMailboxesSize = DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T);
1399   StatusMailboxesSize = DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T);
1400   DmaPagesSize =
1401     CommandMailboxesSize + StatusMailboxesSize +
1402     sizeof(DAC960_V2_HealthStatusBuffer_T) +
1403     sizeof(DAC960_V2_ControllerInfo_T) +
1404     sizeof(DAC960_V2_LogicalDeviceInfo_T) +
1405     sizeof(DAC960_V2_PhysicalDeviceInfo_T) +
1406     sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T) +
1407     sizeof(DAC960_V2_Event_T) +
1408     sizeof(DAC960_V2_PhysicalToLogicalDevice_T);
1409
1410   if (!init_dma_loaf(PCI_Device, DmaPages, DmaPagesSize)) {
1411         pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
1412                                         CommandMailbox, CommandMailboxDMA);
1413         return false;
1414   }
1415
1416   CommandMailboxesMemory = slice_dma_loaf(DmaPages,
1417                 CommandMailboxesSize, &CommandMailboxesMemoryDMA);
1418
1419   /* These are the base addresses for the command memory mailbox array */
1420   Controller->V2.FirstCommandMailbox = CommandMailboxesMemory;
1421   Controller->V2.FirstCommandMailboxDMA = CommandMailboxesMemoryDMA;
1422
1423   CommandMailboxesMemory += DAC960_V2_CommandMailboxCount - 1;
1424   Controller->V2.LastCommandMailbox = CommandMailboxesMemory;
1425   Controller->V2.NextCommandMailbox = Controller->V2.FirstCommandMailbox;
1426   Controller->V2.PreviousCommandMailbox1 = Controller->V2.LastCommandMailbox;
1427   Controller->V2.PreviousCommandMailbox2 =
1428                                         Controller->V2.LastCommandMailbox - 1;
1429
1430   /* These are the base addresses for the status memory mailbox array */
1431   StatusMailboxesMemory = slice_dma_loaf(DmaPages,
1432                 StatusMailboxesSize, &StatusMailboxesMemoryDMA);
1433
1434   Controller->V2.FirstStatusMailbox = StatusMailboxesMemory;
1435   Controller->V2.FirstStatusMailboxDMA = StatusMailboxesMemoryDMA;
1436   StatusMailboxesMemory += DAC960_V2_StatusMailboxCount - 1;
1437   Controller->V2.LastStatusMailbox = StatusMailboxesMemory;
1438   Controller->V2.NextStatusMailbox = Controller->V2.FirstStatusMailbox;
1439
1440   Controller->V2.HealthStatusBuffer = slice_dma_loaf(DmaPages,
1441                 sizeof(DAC960_V2_HealthStatusBuffer_T),
1442                 &Controller->V2.HealthStatusBufferDMA);
1443
1444   Controller->V2.NewControllerInformation = slice_dma_loaf(DmaPages,
1445                 sizeof(DAC960_V2_ControllerInfo_T), 
1446                 &Controller->V2.NewControllerInformationDMA);
1447
1448   Controller->V2.NewLogicalDeviceInformation =  slice_dma_loaf(DmaPages,
1449                 sizeof(DAC960_V2_LogicalDeviceInfo_T),
1450                 &Controller->V2.NewLogicalDeviceInformationDMA);
1451
1452   Controller->V2.NewPhysicalDeviceInformation = slice_dma_loaf(DmaPages,
1453                 sizeof(DAC960_V2_PhysicalDeviceInfo_T),
1454                 &Controller->V2.NewPhysicalDeviceInformationDMA);
1455
1456   Controller->V2.NewInquiryUnitSerialNumber = slice_dma_loaf(DmaPages,
1457                 sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1458                 &Controller->V2.NewInquiryUnitSerialNumberDMA);
1459
1460   Controller->V2.Event = slice_dma_loaf(DmaPages,
1461                 sizeof(DAC960_V2_Event_T),
1462                 &Controller->V2.EventDMA);
1463
1464   Controller->V2.PhysicalToLogicalDevice = slice_dma_loaf(DmaPages,
1465                 sizeof(DAC960_V2_PhysicalToLogicalDevice_T),
1466                 &Controller->V2.PhysicalToLogicalDeviceDMA);
1467
1468   /*
1469     Enable the Memory Mailbox Interface.
1470     
1471     I don't know why we can't just use one of the memory mailboxes
1472     we just allocated to do this, instead of using this temporary one.
1473     Try this change later.
1474   */
1475   memset(CommandMailbox, 0, sizeof(DAC960_V2_CommandMailbox_T));
1476   CommandMailbox->SetMemoryMailbox.CommandIdentifier = 1;
1477   CommandMailbox->SetMemoryMailbox.CommandOpcode = DAC960_V2_IOCTL;
1478   CommandMailbox->SetMemoryMailbox.CommandControlBits.NoAutoRequestSense = true;
1479   CommandMailbox->SetMemoryMailbox.FirstCommandMailboxSizeKB =
1480     (DAC960_V2_CommandMailboxCount * sizeof(DAC960_V2_CommandMailbox_T)) >> 10;
1481   CommandMailbox->SetMemoryMailbox.FirstStatusMailboxSizeKB =
1482     (DAC960_V2_StatusMailboxCount * sizeof(DAC960_V2_StatusMailbox_T)) >> 10;
1483   CommandMailbox->SetMemoryMailbox.SecondCommandMailboxSizeKB = 0;
1484   CommandMailbox->SetMemoryMailbox.SecondStatusMailboxSizeKB = 0;
1485   CommandMailbox->SetMemoryMailbox.RequestSenseSize = 0;
1486   CommandMailbox->SetMemoryMailbox.IOCTL_Opcode = DAC960_V2_SetMemoryMailbox;
1487   CommandMailbox->SetMemoryMailbox.HealthStatusBufferSizeKB = 1;
1488   CommandMailbox->SetMemoryMailbox.HealthStatusBufferBusAddress =
1489                                         Controller->V2.HealthStatusBufferDMA;
1490   CommandMailbox->SetMemoryMailbox.FirstCommandMailboxBusAddress =
1491                                         Controller->V2.FirstCommandMailboxDMA;
1492   CommandMailbox->SetMemoryMailbox.FirstStatusMailboxBusAddress =
1493                                         Controller->V2.FirstStatusMailboxDMA;
1494   switch (Controller->HardwareType)
1495     {
1496     case DAC960_GEM_Controller:
1497       while (DAC960_GEM_HardwareMailboxFullP(ControllerBaseAddress))
1498         udelay(1);
1499       DAC960_GEM_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1500       DAC960_GEM_HardwareMailboxNewCommand(ControllerBaseAddress);
1501       while (!DAC960_GEM_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1502         udelay(1);
1503       CommandStatus = DAC960_GEM_ReadCommandStatus(ControllerBaseAddress);
1504       DAC960_GEM_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1505       DAC960_GEM_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1506       break;
1507     case DAC960_BA_Controller:
1508       while (DAC960_BA_HardwareMailboxFullP(ControllerBaseAddress))
1509         udelay(1);
1510       DAC960_BA_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1511       DAC960_BA_HardwareMailboxNewCommand(ControllerBaseAddress);
1512       while (!DAC960_BA_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1513         udelay(1);
1514       CommandStatus = DAC960_BA_ReadCommandStatus(ControllerBaseAddress);
1515       DAC960_BA_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1516       DAC960_BA_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1517       break;
1518     case DAC960_LP_Controller:
1519       while (DAC960_LP_HardwareMailboxFullP(ControllerBaseAddress))
1520         udelay(1);
1521       DAC960_LP_WriteHardwareMailbox(ControllerBaseAddress, CommandMailboxDMA);
1522       DAC960_LP_HardwareMailboxNewCommand(ControllerBaseAddress);
1523       while (!DAC960_LP_HardwareMailboxStatusAvailableP(ControllerBaseAddress))
1524         udelay(1);
1525       CommandStatus = DAC960_LP_ReadCommandStatus(ControllerBaseAddress);
1526       DAC960_LP_AcknowledgeHardwareMailboxInterrupt(ControllerBaseAddress);
1527       DAC960_LP_AcknowledgeHardwareMailboxStatus(ControllerBaseAddress);
1528       break;
1529     default:
1530       DAC960_Failure(Controller, "Unknown Controller Type\n");
1531       CommandStatus = DAC960_V2_AbormalCompletion;
1532       break;
1533     }
1534   pci_free_consistent(PCI_Device, sizeof(DAC960_V2_CommandMailbox_T),
1535                                         CommandMailbox, CommandMailboxDMA);
1536   return (CommandStatus == DAC960_V2_NormalCompletion);
1537 }
1538
1539
1540 /*
1541   DAC960_V1_ReadControllerConfiguration reads the Configuration Information
1542   from DAC960 V1 Firmware Controllers and initializes the Controller structure.
1543 */
1544
1545 static boolean DAC960_V1_ReadControllerConfiguration(DAC960_Controller_T
1546                                                      *Controller)
1547 {
1548   DAC960_V1_Enquiry2_T *Enquiry2;
1549   dma_addr_t Enquiry2DMA;
1550   DAC960_V1_Config2_T *Config2;
1551   dma_addr_t Config2DMA;
1552   int LogicalDriveNumber, Channel, TargetID;
1553   struct dma_loaf local_dma;
1554
1555   if (!init_dma_loaf(Controller->PCIDevice, &local_dma,
1556                 sizeof(DAC960_V1_Enquiry2_T) + sizeof(DAC960_V1_Config2_T)))
1557         return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
1558
1559   Enquiry2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Enquiry2_T), &Enquiry2DMA);
1560   Config2 = slice_dma_loaf(&local_dma, sizeof(DAC960_V1_Config2_T), &Config2DMA);
1561
1562   if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry,
1563                               Controller->V1.NewEnquiryDMA)) {
1564     free_dma_loaf(Controller->PCIDevice, &local_dma);
1565     return DAC960_Failure(Controller, "ENQUIRY");
1566   }
1567   memcpy(&Controller->V1.Enquiry, Controller->V1.NewEnquiry,
1568                                                 sizeof(DAC960_V1_Enquiry_T));
1569
1570   if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_Enquiry2, Enquiry2DMA)) {
1571     free_dma_loaf(Controller->PCIDevice, &local_dma);
1572     return DAC960_Failure(Controller, "ENQUIRY2");
1573   }
1574
1575   if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_ReadConfig2, Config2DMA)) {
1576     free_dma_loaf(Controller->PCIDevice, &local_dma);
1577     return DAC960_Failure(Controller, "READ CONFIG2");
1578   }
1579
1580   if (!DAC960_V1_ExecuteType3(Controller, DAC960_V1_GetLogicalDriveInformation,
1581                               Controller->V1.NewLogicalDriveInformationDMA)) {
1582     free_dma_loaf(Controller->PCIDevice, &local_dma);
1583     return DAC960_Failure(Controller, "GET LOGICAL DRIVE INFORMATION");
1584   }
1585   memcpy(&Controller->V1.LogicalDriveInformation,
1586                 Controller->V1.NewLogicalDriveInformation,
1587                 sizeof(DAC960_V1_LogicalDriveInformationArray_T));
1588
1589   for (Channel = 0; Channel < Enquiry2->ActualChannels; Channel++)
1590     for (TargetID = 0; TargetID < Enquiry2->MaxTargets; TargetID++) {
1591       if (!DAC960_V1_ExecuteType3D(Controller, DAC960_V1_GetDeviceState,
1592                                    Channel, TargetID,
1593                                    Controller->V1.NewDeviceStateDMA)) {
1594                 free_dma_loaf(Controller->PCIDevice, &local_dma);
1595                 return DAC960_Failure(Controller, "GET DEVICE STATE");
1596         }
1597         memcpy(&Controller->V1.DeviceState[Channel][TargetID],
1598                 Controller->V1.NewDeviceState, sizeof(DAC960_V1_DeviceState_T));
1599      }
1600   /*
1601     Initialize the Controller Model Name and Full Model Name fields.
1602   */
1603   switch (Enquiry2->HardwareID.SubModel)
1604     {
1605     case DAC960_V1_P_PD_PU:
1606       if (Enquiry2->SCSICapability.BusSpeed == DAC960_V1_Ultra)
1607         strcpy(Controller->ModelName, "DAC960PU");
1608       else strcpy(Controller->ModelName, "DAC960PD");
1609       break;
1610     case DAC960_V1_PL:
1611       strcpy(Controller->ModelName, "DAC960PL");
1612       break;
1613     case DAC960_V1_PG:
1614       strcpy(Controller->ModelName, "DAC960PG");
1615       break;
1616     case DAC960_V1_PJ:
1617       strcpy(Controller->ModelName, "DAC960PJ");
1618       break;
1619     case DAC960_V1_PR:
1620       strcpy(Controller->ModelName, "DAC960PR");
1621       break;
1622     case DAC960_V1_PT:
1623       strcpy(Controller->ModelName, "DAC960PT");
1624       break;
1625     case DAC960_V1_PTL0:
1626       strcpy(Controller->ModelName, "DAC960PTL0");
1627       break;
1628     case DAC960_V1_PRL:
1629       strcpy(Controller->ModelName, "DAC960PRL");
1630       break;
1631     case DAC960_V1_PTL1:
1632       strcpy(Controller->ModelName, "DAC960PTL1");
1633       break;
1634     case DAC960_V1_1164P:
1635       strcpy(Controller->ModelName, "DAC1164P");
1636       break;
1637     default:
1638       free_dma_loaf(Controller->PCIDevice, &local_dma);
1639       return DAC960_Failure(Controller, "MODEL VERIFICATION");
1640     }
1641   strcpy(Controller->FullModelName, "Mylex ");
1642   strcat(Controller->FullModelName, Controller->ModelName);
1643   /*
1644     Initialize the Controller Firmware Version field and verify that it
1645     is a supported firmware version.  The supported firmware versions are:
1646
1647     DAC1164P                5.06 and above
1648     DAC960PTL/PRL/PJ/PG     4.06 and above
1649     DAC960PU/PD/PL          3.51 and above
1650     DAC960PU/PD/PL/P        2.73 and above
1651   */
1652 #if defined(CONFIG_ALPHA)
1653   /*
1654     DEC Alpha machines were often equipped with DAC960 cards that were
1655     OEMed from Mylex, and had their own custom firmware. Version 2.70,
1656     the last custom FW revision to be released by DEC for these older
1657     controllers, appears to work quite well with this driver.
1658
1659     Cards tested successfully were several versions each of the PD and
1660     PU, called by DEC the KZPSC and KZPAC, respectively, and having
1661     the Manufacturer Numbers (from Mylex), usually on a sticker on the
1662     back of the board, of:
1663
1664     KZPSC:  D040347 (1-channel) or D040348 (2-channel) or D040349 (3-channel)
1665     KZPAC:  D040395 (1-channel) or D040396 (2-channel) or D040397 (3-channel)
1666   */
1667 # define FIRMWARE_27X   "2.70"
1668 #else
1669 # define FIRMWARE_27X   "2.73"
1670 #endif
1671
1672   if (Enquiry2->FirmwareID.MajorVersion == 0)
1673     {
1674       Enquiry2->FirmwareID.MajorVersion =
1675         Controller->V1.Enquiry.MajorFirmwareVersion;
1676       Enquiry2->FirmwareID.MinorVersion =
1677         Controller->V1.Enquiry.MinorFirmwareVersion;
1678       Enquiry2->FirmwareID.FirmwareType = '0';
1679       Enquiry2->FirmwareID.TurnID = 0;
1680     }
1681   sprintf(Controller->FirmwareVersion, "%d.%02d-%c-%02d",
1682           Enquiry2->FirmwareID.MajorVersion, Enquiry2->FirmwareID.MinorVersion,
1683           Enquiry2->FirmwareID.FirmwareType, Enquiry2->FirmwareID.TurnID);
1684   if (!((Controller->FirmwareVersion[0] == '5' &&
1685          strcmp(Controller->FirmwareVersion, "5.06") >= 0) ||
1686         (Controller->FirmwareVersion[0] == '4' &&
1687          strcmp(Controller->FirmwareVersion, "4.06") >= 0) ||
1688         (Controller->FirmwareVersion[0] == '3' &&
1689          strcmp(Controller->FirmwareVersion, "3.51") >= 0) ||
1690         (Controller->FirmwareVersion[0] == '2' &&
1691          strcmp(Controller->FirmwareVersion, FIRMWARE_27X) >= 0)))
1692     {
1693       DAC960_Failure(Controller, "FIRMWARE VERSION VERIFICATION");
1694       DAC960_Error("Firmware Version = '%s'\n", Controller,
1695                    Controller->FirmwareVersion);
1696       free_dma_loaf(Controller->PCIDevice, &local_dma);
1697       return false;
1698     }
1699   /*
1700     Initialize the Controller Channels, Targets, Memory Size, and SAF-TE
1701     Enclosure Management Enabled fields.
1702   */
1703   Controller->Channels = Enquiry2->ActualChannels;
1704   Controller->Targets = Enquiry2->MaxTargets;
1705   Controller->MemorySize = Enquiry2->MemorySize >> 20;
1706   Controller->V1.SAFTE_EnclosureManagementEnabled =
1707     (Enquiry2->FaultManagementType == DAC960_V1_SAFTE);
1708   /*
1709     Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
1710     Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
1711     Driver Scatter/Gather Limit.  The Driver Queue Depth must be at most one
1712     less than the Controller Queue Depth to allow for an automatic drive
1713     rebuild operation.
1714   */
1715   Controller->ControllerQueueDepth = Controller->V1.Enquiry.MaxCommands;
1716   Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
1717   if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
1718     Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
1719   Controller->LogicalDriveCount =
1720     Controller->V1.Enquiry.NumberOfLogicalDrives;
1721   Controller->MaxBlocksPerCommand = Enquiry2->MaxBlocksPerCommand;
1722   Controller->ControllerScatterGatherLimit = Enquiry2->MaxScatterGatherEntries;
1723   Controller->DriverScatterGatherLimit =
1724     Controller->ControllerScatterGatherLimit;
1725   if (Controller->DriverScatterGatherLimit > DAC960_V1_ScatterGatherLimit)
1726     Controller->DriverScatterGatherLimit = DAC960_V1_ScatterGatherLimit;
1727   /*
1728     Initialize the Stripe Size, Segment Size, and Geometry Translation.
1729   */
1730   Controller->V1.StripeSize = Config2->BlocksPerStripe * Config2->BlockFactor
1731                               >> (10 - DAC960_BlockSizeBits);
1732   Controller->V1.SegmentSize = Config2->BlocksPerCacheLine * Config2->BlockFactor
1733                                >> (10 - DAC960_BlockSizeBits);
1734   switch (Config2->DriveGeometry)
1735     {
1736     case DAC960_V1_Geometry_128_32:
1737       Controller->V1.GeometryTranslationHeads = 128;
1738       Controller->V1.GeometryTranslationSectors = 32;
1739       break;
1740     case DAC960_V1_Geometry_255_63:
1741       Controller->V1.GeometryTranslationHeads = 255;
1742       Controller->V1.GeometryTranslationSectors = 63;
1743       break;
1744     default:
1745       free_dma_loaf(Controller->PCIDevice, &local_dma);
1746       return DAC960_Failure(Controller, "CONFIG2 DRIVE GEOMETRY");
1747     }
1748   /*
1749     Initialize the Background Initialization Status.
1750   */
1751   if ((Controller->FirmwareVersion[0] == '4' &&
1752       strcmp(Controller->FirmwareVersion, "4.08") >= 0) ||
1753       (Controller->FirmwareVersion[0] == '5' &&
1754        strcmp(Controller->FirmwareVersion, "5.08") >= 0))
1755     {
1756       Controller->V1.BackgroundInitializationStatusSupported = true;
1757       DAC960_V1_ExecuteType3B(Controller,
1758                               DAC960_V1_BackgroundInitializationControl, 0x20,
1759                               Controller->
1760                                V1.BackgroundInitializationStatusDMA);
1761       memcpy(&Controller->V1.LastBackgroundInitializationStatus,
1762                 Controller->V1.BackgroundInitializationStatus,
1763                 sizeof(DAC960_V1_BackgroundInitializationStatus_T));
1764     }
1765   /*
1766     Initialize the Logical Drive Initially Accessible flag.
1767   */
1768   for (LogicalDriveNumber = 0;
1769        LogicalDriveNumber < Controller->LogicalDriveCount;
1770        LogicalDriveNumber++)
1771     if (Controller->V1.LogicalDriveInformation
1772                        [LogicalDriveNumber].LogicalDriveState !=
1773         DAC960_V1_LogicalDrive_Offline)
1774       Controller->LogicalDriveInitiallyAccessible[LogicalDriveNumber] = true;
1775   Controller->V1.LastRebuildStatus = DAC960_V1_NoRebuildOrCheckInProgress;
1776   free_dma_loaf(Controller->PCIDevice, &local_dma);
1777   return true;
1778 }
1779
1780
1781 /*
1782   DAC960_V2_ReadControllerConfiguration reads the Configuration Information
1783   from DAC960 V2 Firmware Controllers and initializes the Controller structure.
1784 */
1785
1786 static boolean DAC960_V2_ReadControllerConfiguration(DAC960_Controller_T
1787                                                      *Controller)
1788 {
1789   DAC960_V2_ControllerInfo_T *ControllerInfo =
1790                 &Controller->V2.ControllerInformation;
1791   unsigned short LogicalDeviceNumber = 0;
1792   int ModelNameLength;
1793
1794   /* Get data into dma-able area, then copy into permanant location */
1795   if (!DAC960_V2_NewControllerInfo(Controller))
1796     return DAC960_Failure(Controller, "GET CONTROLLER INFO");
1797   memcpy(ControllerInfo, Controller->V2.NewControllerInformation,
1798                         sizeof(DAC960_V2_ControllerInfo_T));
1799          
1800   
1801   if (!DAC960_V2_GeneralInfo(Controller))
1802     return DAC960_Failure(Controller, "GET HEALTH STATUS");
1803
1804   /*
1805     Initialize the Controller Model Name and Full Model Name fields.
1806   */
1807   ModelNameLength = sizeof(ControllerInfo->ControllerName);
1808   if (ModelNameLength > sizeof(Controller->ModelName)-1)
1809     ModelNameLength = sizeof(Controller->ModelName)-1;
1810   memcpy(Controller->ModelName, ControllerInfo->ControllerName,
1811          ModelNameLength);
1812   ModelNameLength--;
1813   while (Controller->ModelName[ModelNameLength] == ' ' ||
1814          Controller->ModelName[ModelNameLength] == '\0')
1815     ModelNameLength--;
1816   Controller->ModelName[++ModelNameLength] = '\0';
1817   strcpy(Controller->FullModelName, "Mylex ");
1818   strcat(Controller->FullModelName, Controller->ModelName);
1819   /*
1820     Initialize the Controller Firmware Version field.
1821   */
1822   sprintf(Controller->FirmwareVersion, "%d.%02d-%02d",
1823           ControllerInfo->FirmwareMajorVersion,
1824           ControllerInfo->FirmwareMinorVersion,
1825           ControllerInfo->FirmwareTurnNumber);
1826   if (ControllerInfo->FirmwareMajorVersion == 6 &&
1827       ControllerInfo->FirmwareMinorVersion == 0 &&
1828       ControllerInfo->FirmwareTurnNumber < 1)
1829     {
1830       DAC960_Info("FIRMWARE VERSION %s DOES NOT PROVIDE THE CONTROLLER\n",
1831                   Controller, Controller->FirmwareVersion);
1832       DAC960_Info("STATUS MONITORING FUNCTIONALITY NEEDED BY THIS DRIVER.\n",
1833                   Controller);
1834       DAC960_Info("PLEASE UPGRADE TO VERSION 6.00-01 OR ABOVE.\n",
1835                   Controller);
1836     }
1837   /*
1838     Initialize the Controller Channels, Targets, and Memory Size.
1839   */
1840   Controller->Channels = ControllerInfo->NumberOfPhysicalChannelsPresent;
1841   Controller->Targets =
1842     ControllerInfo->MaximumTargetsPerChannel
1843                     [ControllerInfo->NumberOfPhysicalChannelsPresent-1];
1844   Controller->MemorySize = ControllerInfo->MemorySizeMB;
1845   /*
1846     Initialize the Controller Queue Depth, Driver Queue Depth, Logical Drive
1847     Count, Maximum Blocks per Command, Controller Scatter/Gather Limit, and
1848     Driver Scatter/Gather Limit.  The Driver Queue Depth must be at most one
1849     less than the Controller Queue Depth to allow for an automatic drive
1850     rebuild operation.
1851   */
1852   Controller->ControllerQueueDepth = ControllerInfo->MaximumParallelCommands;
1853   Controller->DriverQueueDepth = Controller->ControllerQueueDepth - 1;
1854   if (Controller->DriverQueueDepth > DAC960_MaxDriverQueueDepth)
1855     Controller->DriverQueueDepth = DAC960_MaxDriverQueueDepth;
1856   Controller->LogicalDriveCount = ControllerInfo->LogicalDevicesPresent;
1857   Controller->MaxBlocksPerCommand =
1858     ControllerInfo->MaximumDataTransferSizeInBlocks;
1859   Controller->ControllerScatterGatherLimit =
1860     ControllerInfo->MaximumScatterGatherEntries;
1861   Controller->DriverScatterGatherLimit =
1862     Controller->ControllerScatterGatherLimit;
1863   if (Controller->DriverScatterGatherLimit > DAC960_V2_ScatterGatherLimit)
1864     Controller->DriverScatterGatherLimit = DAC960_V2_ScatterGatherLimit;
1865   /*
1866     Initialize the Logical Device Information.
1867   */
1868   while (true)
1869     {
1870       DAC960_V2_LogicalDeviceInfo_T *NewLogicalDeviceInfo =
1871         Controller->V2.NewLogicalDeviceInformation;
1872       DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo;
1873       DAC960_V2_PhysicalDevice_T PhysicalDevice;
1874
1875       if (!DAC960_V2_NewLogicalDeviceInfo(Controller, LogicalDeviceNumber))
1876         break;
1877       LogicalDeviceNumber = NewLogicalDeviceInfo->LogicalDeviceNumber;
1878       if (LogicalDeviceNumber >= DAC960_MaxLogicalDrives) {
1879         DAC960_Error("DAC960: Logical Drive Number %d not supported\n",
1880                        Controller, LogicalDeviceNumber);
1881                 break;
1882       }
1883       if (NewLogicalDeviceInfo->DeviceBlockSizeInBytes != DAC960_BlockSize) {
1884         DAC960_Error("DAC960: Logical Drive Block Size %d not supported\n",
1885               Controller, NewLogicalDeviceInfo->DeviceBlockSizeInBytes);
1886         LogicalDeviceNumber++;
1887         continue;
1888       }
1889       PhysicalDevice.Controller = 0;
1890       PhysicalDevice.Channel = NewLogicalDeviceInfo->Channel;
1891       PhysicalDevice.TargetID = NewLogicalDeviceInfo->TargetID;
1892       PhysicalDevice.LogicalUnit = NewLogicalDeviceInfo->LogicalUnit;
1893       Controller->V2.LogicalDriveToVirtualDevice[LogicalDeviceNumber] =
1894         PhysicalDevice;
1895       if (NewLogicalDeviceInfo->LogicalDeviceState !=
1896           DAC960_V2_LogicalDevice_Offline)
1897         Controller->LogicalDriveInitiallyAccessible[LogicalDeviceNumber] = true;
1898       LogicalDeviceInfo = (DAC960_V2_LogicalDeviceInfo_T *)
1899         kmalloc(sizeof(DAC960_V2_LogicalDeviceInfo_T), GFP_ATOMIC);
1900       if (LogicalDeviceInfo == NULL)
1901         return DAC960_Failure(Controller, "LOGICAL DEVICE ALLOCATION");
1902       Controller->V2.LogicalDeviceInformation[LogicalDeviceNumber] =
1903         LogicalDeviceInfo;
1904       memcpy(LogicalDeviceInfo, NewLogicalDeviceInfo,
1905              sizeof(DAC960_V2_LogicalDeviceInfo_T));
1906       LogicalDeviceNumber++;
1907     }
1908   return true;
1909 }
1910
1911
1912 /*
1913   DAC960_ReportControllerConfiguration reports the Configuration Information
1914   for Controller.
1915 */
1916
1917 static boolean DAC960_ReportControllerConfiguration(DAC960_Controller_T
1918                                                     *Controller)
1919 {
1920   DAC960_Info("Configuring Mylex %s PCI RAID Controller\n",
1921               Controller, Controller->ModelName);
1922   DAC960_Info("  Firmware Version: %s, Channels: %d, Memory Size: %dMB\n",
1923               Controller, Controller->FirmwareVersion,
1924               Controller->Channels, Controller->MemorySize);
1925   DAC960_Info("  PCI Bus: %d, Device: %d, Function: %d, I/O Address: ",
1926               Controller, Controller->Bus,
1927               Controller->Device, Controller->Function);
1928   if (Controller->IO_Address == 0)
1929     DAC960_Info("Unassigned\n", Controller);
1930   else DAC960_Info("0x%X\n", Controller, Controller->IO_Address);
1931   DAC960_Info("  PCI Address: 0x%X mapped at 0x%lX, IRQ Channel: %d\n",
1932               Controller, Controller->PCI_Address,
1933               (unsigned long) Controller->BaseAddress,
1934               Controller->IRQ_Channel);
1935   DAC960_Info("  Controller Queue Depth: %d, "
1936               "Maximum Blocks per Command: %d\n",
1937               Controller, Controller->ControllerQueueDepth,
1938               Controller->MaxBlocksPerCommand);
1939   DAC960_Info("  Driver Queue Depth: %d, "
1940               "Scatter/Gather Limit: %d of %d Segments\n",
1941               Controller, Controller->DriverQueueDepth,
1942               Controller->DriverScatterGatherLimit,
1943               Controller->ControllerScatterGatherLimit);
1944   if (Controller->FirmwareType == DAC960_V1_Controller)
1945     {
1946       DAC960_Info("  Stripe Size: %dKB, Segment Size: %dKB, "
1947                   "BIOS Geometry: %d/%d\n", Controller,
1948                   Controller->V1.StripeSize,
1949                   Controller->V1.SegmentSize,
1950                   Controller->V1.GeometryTranslationHeads,
1951                   Controller->V1.GeometryTranslationSectors);
1952       if (Controller->V1.SAFTE_EnclosureManagementEnabled)
1953         DAC960_Info("  SAF-TE Enclosure Management Enabled\n", Controller);
1954     }
1955   return true;
1956 }
1957
1958
1959 /*
1960   DAC960_V1_ReadDeviceConfiguration reads the Device Configuration Information
1961   for DAC960 V1 Firmware Controllers by requesting the SCSI Inquiry and SCSI
1962   Inquiry Unit Serial Number information for each device connected to
1963   Controller.
1964 */
1965
1966 static boolean DAC960_V1_ReadDeviceConfiguration(DAC960_Controller_T
1967                                                  *Controller)
1968 {
1969   struct dma_loaf local_dma;
1970
1971   dma_addr_t DCDBs_dma[DAC960_V1_MaxChannels];
1972   DAC960_V1_DCDB_T *DCDBs_cpu[DAC960_V1_MaxChannels];
1973
1974   dma_addr_t SCSI_Inquiry_dma[DAC960_V1_MaxChannels];
1975   DAC960_SCSI_Inquiry_T *SCSI_Inquiry_cpu[DAC960_V1_MaxChannels];
1976
1977   dma_addr_t SCSI_NewInquiryUnitSerialNumberDMA[DAC960_V1_MaxChannels];
1978   DAC960_SCSI_Inquiry_UnitSerialNumber_T *SCSI_NewInquiryUnitSerialNumberCPU[DAC960_V1_MaxChannels];
1979
1980   struct completion Completions[DAC960_V1_MaxChannels];
1981   unsigned long flags;
1982   int Channel, TargetID;
1983
1984   if (!init_dma_loaf(Controller->PCIDevice, &local_dma, 
1985                 DAC960_V1_MaxChannels*(sizeof(DAC960_V1_DCDB_T) +
1986                         sizeof(DAC960_SCSI_Inquiry_T) +
1987                         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T))))
1988      return DAC960_Failure(Controller,
1989                         "DMA ALLOCATION FAILED IN ReadDeviceConfiguration"); 
1990    
1991   for (Channel = 0; Channel < Controller->Channels; Channel++) {
1992         DCDBs_cpu[Channel] = slice_dma_loaf(&local_dma,
1993                         sizeof(DAC960_V1_DCDB_T), DCDBs_dma + Channel);
1994         SCSI_Inquiry_cpu[Channel] = slice_dma_loaf(&local_dma,
1995                         sizeof(DAC960_SCSI_Inquiry_T),
1996                         SCSI_Inquiry_dma + Channel);
1997         SCSI_NewInquiryUnitSerialNumberCPU[Channel] = slice_dma_loaf(&local_dma,
1998                         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T),
1999                         SCSI_NewInquiryUnitSerialNumberDMA + Channel);
2000   }
2001                 
2002   for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
2003     {
2004       /*
2005        * For each channel, submit a probe for a device on that channel.
2006        * The timeout interval for a device that is present is 10 seconds.
2007        * With this approach, the timeout periods can elapse in parallel
2008        * on each channel.
2009        */
2010       for (Channel = 0; Channel < Controller->Channels; Channel++)
2011         {
2012           dma_addr_t NewInquiryStandardDataDMA = SCSI_Inquiry_dma[Channel];
2013           DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
2014           dma_addr_t DCDB_dma = DCDBs_dma[Channel];
2015           DAC960_Command_T *Command = Controller->Commands[Channel];
2016           struct completion *Completion = &Completions[Channel];
2017
2018           init_completion(Completion);
2019           DAC960_V1_ClearCommand(Command);
2020           Command->CommandType = DAC960_ImmediateCommand;
2021           Command->Completion = Completion;
2022           Command->V1.CommandMailbox.Type3.CommandOpcode = DAC960_V1_DCDB;
2023           Command->V1.CommandMailbox.Type3.BusAddress = DCDB_dma;
2024           DCDB->Channel = Channel;
2025           DCDB->TargetID = TargetID;
2026           DCDB->Direction = DAC960_V1_DCDB_DataTransferDeviceToSystem;
2027           DCDB->EarlyStatus = false;
2028           DCDB->Timeout = DAC960_V1_DCDB_Timeout_10_seconds;
2029           DCDB->NoAutomaticRequestSense = false;
2030           DCDB->DisconnectPermitted = true;
2031           DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_T);
2032           DCDB->BusAddress = NewInquiryStandardDataDMA;
2033           DCDB->CDBLength = 6;
2034           DCDB->TransferLengthHigh4 = 0;
2035           DCDB->SenseLength = sizeof(DCDB->SenseData);
2036           DCDB->CDB[0] = 0x12; /* INQUIRY */
2037           DCDB->CDB[1] = 0; /* EVPD = 0 */
2038           DCDB->CDB[2] = 0; /* Page Code */
2039           DCDB->CDB[3] = 0; /* Reserved */
2040           DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_T);
2041           DCDB->CDB[5] = 0; /* Control */
2042
2043           spin_lock_irqsave(&Controller->queue_lock, flags);
2044           DAC960_QueueCommand(Command);
2045           spin_unlock_irqrestore(&Controller->queue_lock, flags);
2046         }
2047       /*
2048        * Wait for the problems submitted in the previous loop
2049        * to complete.  On the probes that are successful, 
2050        * get the serial number of the device that was found.
2051        */
2052       for (Channel = 0; Channel < Controller->Channels; Channel++)
2053         {
2054           DAC960_SCSI_Inquiry_T *InquiryStandardData =
2055             &Controller->V1.InquiryStandardData[Channel][TargetID];
2056           DAC960_SCSI_Inquiry_T *NewInquiryStandardData = SCSI_Inquiry_cpu[Channel];
2057           dma_addr_t NewInquiryUnitSerialNumberDMA =
2058                         SCSI_NewInquiryUnitSerialNumberDMA[Channel];
2059           DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
2060                         SCSI_NewInquiryUnitSerialNumberCPU[Channel];
2061           DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2062             &Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
2063           DAC960_Command_T *Command = Controller->Commands[Channel];
2064           DAC960_V1_DCDB_T *DCDB = DCDBs_cpu[Channel];
2065           struct completion *Completion = &Completions[Channel];
2066
2067           wait_for_completion(Completion);
2068
2069           if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
2070             memset(InquiryStandardData, 0, sizeof(DAC960_SCSI_Inquiry_T));
2071             InquiryStandardData->PeripheralDeviceType = 0x1F;
2072             continue;
2073           } else
2074             memcpy(InquiryStandardData, NewInquiryStandardData, sizeof(DAC960_SCSI_Inquiry_T));
2075         
2076           /* Preserve Channel and TargetID values from the previous loop */
2077           Command->Completion = Completion;
2078           DCDB->TransferLength = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
2079           DCDB->BusAddress = NewInquiryUnitSerialNumberDMA;
2080           DCDB->SenseLength = sizeof(DCDB->SenseData);
2081           DCDB->CDB[0] = 0x12; /* INQUIRY */
2082           DCDB->CDB[1] = 1; /* EVPD = 1 */
2083           DCDB->CDB[2] = 0x80; /* Page Code */
2084           DCDB->CDB[3] = 0; /* Reserved */
2085           DCDB->CDB[4] = sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T);
2086           DCDB->CDB[5] = 0; /* Control */
2087
2088           spin_lock_irqsave(&Controller->queue_lock, flags);
2089           DAC960_QueueCommand(Command);
2090           spin_unlock_irqrestore(&Controller->queue_lock, flags);
2091           wait_for_completion(Completion);
2092
2093           if (Command->V1.CommandStatus != DAC960_V1_NormalCompletion) {
2094                 memset(InquiryUnitSerialNumber, 0,
2095                         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2096                 InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
2097           } else
2098                 memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
2099                         sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2100         }
2101     }
2102     free_dma_loaf(Controller->PCIDevice, &local_dma);
2103   return true;
2104 }
2105
2106
2107 /*
2108   DAC960_V2_ReadDeviceConfiguration reads the Device Configuration Information
2109   for DAC960 V2 Firmware Controllers by requesting the Physical Device
2110   Information and SCSI Inquiry Unit Serial Number information for each
2111   device connected to Controller.
2112 */
2113
2114 static boolean DAC960_V2_ReadDeviceConfiguration(DAC960_Controller_T
2115                                                  *Controller)
2116 {
2117   unsigned char Channel = 0, TargetID = 0, LogicalUnit = 0;
2118   unsigned short PhysicalDeviceIndex = 0;
2119
2120   while (true)
2121     {
2122       DAC960_V2_PhysicalDeviceInfo_T *NewPhysicalDeviceInfo =
2123                 Controller->V2.NewPhysicalDeviceInformation;
2124       DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo;
2125       DAC960_SCSI_Inquiry_UnitSerialNumber_T *NewInquiryUnitSerialNumber =
2126                 Controller->V2.NewInquiryUnitSerialNumber;
2127       DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber;
2128
2129       if (!DAC960_V2_NewPhysicalDeviceInfo(Controller, Channel, TargetID, LogicalUnit))
2130           break;
2131
2132       PhysicalDeviceInfo = (DAC960_V2_PhysicalDeviceInfo_T *)
2133                 kmalloc(sizeof(DAC960_V2_PhysicalDeviceInfo_T), GFP_ATOMIC);
2134       if (PhysicalDeviceInfo == NULL)
2135                 return DAC960_Failure(Controller, "PHYSICAL DEVICE ALLOCATION");
2136       Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex] =
2137                 PhysicalDeviceInfo;
2138       memcpy(PhysicalDeviceInfo, NewPhysicalDeviceInfo,
2139                 sizeof(DAC960_V2_PhysicalDeviceInfo_T));
2140
2141       InquiryUnitSerialNumber = (DAC960_SCSI_Inquiry_UnitSerialNumber_T *)
2142         kmalloc(sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T), GFP_ATOMIC);
2143       if (InquiryUnitSerialNumber == NULL) {
2144         kfree(PhysicalDeviceInfo);
2145         return DAC960_Failure(Controller, "SERIAL NUMBER ALLOCATION");
2146       }
2147       Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex] =
2148                 InquiryUnitSerialNumber;
2149
2150       Channel = NewPhysicalDeviceInfo->Channel;
2151       TargetID = NewPhysicalDeviceInfo->TargetID;
2152       LogicalUnit = NewPhysicalDeviceInfo->LogicalUnit;
2153
2154       /*
2155          Some devices do NOT have Unit Serial Numbers.
2156          This command fails for them.  But, we still want to
2157          remember those devices are there.  Construct a
2158          UnitSerialNumber structure for the failure case.
2159       */
2160       if (!DAC960_V2_NewInquiryUnitSerialNumber(Controller, Channel, TargetID, LogicalUnit)) {
2161         memset(InquiryUnitSerialNumber, 0,
2162              sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2163         InquiryUnitSerialNumber->PeripheralDeviceType = 0x1F;
2164       } else
2165         memcpy(InquiryUnitSerialNumber, NewInquiryUnitSerialNumber,
2166                 sizeof(DAC960_SCSI_Inquiry_UnitSerialNumber_T));
2167
2168       PhysicalDeviceIndex++;
2169       LogicalUnit++;
2170     }
2171   return true;
2172 }
2173
2174
2175 /*
2176   DAC960_SanitizeInquiryData sanitizes the Vendor, Model, Revision, and
2177   Product Serial Number fields of the Inquiry Standard Data and Inquiry
2178   Unit Serial Number structures.
2179 */
2180
2181 static void DAC960_SanitizeInquiryData(DAC960_SCSI_Inquiry_T
2182                                          *InquiryStandardData,
2183                                        DAC960_SCSI_Inquiry_UnitSerialNumber_T
2184                                          *InquiryUnitSerialNumber,
2185                                        unsigned char *Vendor,
2186                                        unsigned char *Model,
2187                                        unsigned char *Revision,
2188                                        unsigned char *SerialNumber)
2189 {
2190   int SerialNumberLength, i;
2191   if (InquiryStandardData->PeripheralDeviceType == 0x1F) return;
2192   for (i = 0; i < sizeof(InquiryStandardData->VendorIdentification); i++)
2193     {
2194       unsigned char VendorCharacter =
2195         InquiryStandardData->VendorIdentification[i];
2196       Vendor[i] = (VendorCharacter >= ' ' && VendorCharacter <= '~'
2197                    ? VendorCharacter : ' ');
2198     }
2199   Vendor[sizeof(InquiryStandardData->VendorIdentification)] = '\0';
2200   for (i = 0; i < sizeof(InquiryStandardData->ProductIdentification); i++)
2201     {
2202       unsigned char ModelCharacter =
2203         InquiryStandardData->ProductIdentification[i];
2204       Model[i] = (ModelCharacter >= ' ' && ModelCharacter <= '~'
2205                   ? ModelCharacter : ' ');
2206     }
2207   Model[sizeof(InquiryStandardData->ProductIdentification)] = '\0';
2208   for (i = 0; i < sizeof(InquiryStandardData->ProductRevisionLevel); i++)
2209     {
2210       unsigned char RevisionCharacter =
2211         InquiryStandardData->ProductRevisionLevel[i];
2212       Revision[i] = (RevisionCharacter >= ' ' && RevisionCharacter <= '~'
2213                      ? RevisionCharacter : ' ');
2214     }
2215   Revision[sizeof(InquiryStandardData->ProductRevisionLevel)] = '\0';
2216   if (InquiryUnitSerialNumber->PeripheralDeviceType == 0x1F) return;
2217   SerialNumberLength = InquiryUnitSerialNumber->PageLength;
2218   if (SerialNumberLength >
2219       sizeof(InquiryUnitSerialNumber->ProductSerialNumber))
2220     SerialNumberLength = sizeof(InquiryUnitSerialNumber->ProductSerialNumber);
2221   for (i = 0; i < SerialNumberLength; i++)
2222     {
2223       unsigned char SerialNumberCharacter =
2224         InquiryUnitSerialNumber->ProductSerialNumber[i];
2225       SerialNumber[i] =
2226         (SerialNumberCharacter >= ' ' && SerialNumberCharacter <= '~'
2227          ? SerialNumberCharacter : ' ');
2228     }
2229   SerialNumber[SerialNumberLength] = '\0';
2230 }
2231
2232
2233 /*
2234   DAC960_V1_ReportDeviceConfiguration reports the Device Configuration
2235   Information for DAC960 V1 Firmware Controllers.
2236 */
2237
2238 static boolean DAC960_V1_ReportDeviceConfiguration(DAC960_Controller_T
2239                                                    *Controller)
2240 {
2241   int LogicalDriveNumber, Channel, TargetID;
2242   DAC960_Info("  Physical Devices:\n", Controller);
2243   for (Channel = 0; Channel < Controller->Channels; Channel++)
2244     for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
2245       {
2246         DAC960_SCSI_Inquiry_T *InquiryStandardData =
2247           &Controller->V1.InquiryStandardData[Channel][TargetID];
2248         DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2249           &Controller->V1.InquiryUnitSerialNumber[Channel][TargetID];
2250         DAC960_V1_DeviceState_T *DeviceState =
2251           &Controller->V1.DeviceState[Channel][TargetID];
2252         DAC960_V1_ErrorTableEntry_T *ErrorEntry =
2253           &Controller->V1.ErrorTable.ErrorTableEntries[Channel][TargetID];
2254         char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
2255         char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
2256         char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
2257         char SerialNumber[1+sizeof(InquiryUnitSerialNumber
2258                                    ->ProductSerialNumber)];
2259         if (InquiryStandardData->PeripheralDeviceType == 0x1F) continue;
2260         DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
2261                                    Vendor, Model, Revision, SerialNumber);
2262         DAC960_Info("    %d:%d%s Vendor: %s  Model: %s  Revision: %s\n",
2263                     Controller, Channel, TargetID, (TargetID < 10 ? " " : ""),
2264                     Vendor, Model, Revision);
2265         if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
2266           DAC960_Info("         Serial Number: %s\n", Controller, SerialNumber);
2267         if (DeviceState->Present &&
2268             DeviceState->DeviceType == DAC960_V1_DiskType)
2269           {
2270             if (Controller->V1.DeviceResetCount[Channel][TargetID] > 0)
2271               DAC960_Info("         Disk Status: %s, %u blocks, %d resets\n",
2272                           Controller,
2273                           (DeviceState->DeviceState == DAC960_V1_Device_Dead
2274                            ? "Dead"
2275                            : DeviceState->DeviceState
2276                              == DAC960_V1_Device_WriteOnly
2277                              ? "Write-Only"
2278                              : DeviceState->DeviceState
2279                                == DAC960_V1_Device_Online
2280                                ? "Online" : "Standby"),
2281                           DeviceState->DiskSize,
2282                           Controller->V1.DeviceResetCount[Channel][TargetID]);
2283             else
2284               DAC960_Info("         Disk Status: %s, %u blocks\n", Controller,
2285                           (DeviceState->DeviceState == DAC960_V1_Device_Dead
2286                            ? "Dead"
2287                            : DeviceState->DeviceState
2288                              == DAC960_V1_Device_WriteOnly
2289                              ? "Write-Only"
2290                              : DeviceState->DeviceState
2291                                == DAC960_V1_Device_Online
2292                                ? "Online" : "Standby"),
2293                           DeviceState->DiskSize);
2294           }
2295         if (ErrorEntry->ParityErrorCount > 0 ||
2296             ErrorEntry->SoftErrorCount > 0 ||
2297             ErrorEntry->HardErrorCount > 0 ||
2298             ErrorEntry->MiscErrorCount > 0)
2299           DAC960_Info("         Errors - Parity: %d, Soft: %d, "
2300                       "Hard: %d, Misc: %d\n", Controller,
2301                       ErrorEntry->ParityErrorCount,
2302                       ErrorEntry->SoftErrorCount,
2303                       ErrorEntry->HardErrorCount,
2304                       ErrorEntry->MiscErrorCount);
2305       }
2306   DAC960_Info("  Logical Drives:\n", Controller);
2307   for (LogicalDriveNumber = 0;
2308        LogicalDriveNumber < Controller->LogicalDriveCount;
2309        LogicalDriveNumber++)
2310     {
2311       DAC960_V1_LogicalDriveInformation_T *LogicalDriveInformation =
2312         &Controller->V1.LogicalDriveInformation[LogicalDriveNumber];
2313       DAC960_Info("    /dev/rd/c%dd%d: RAID-%d, %s, %u blocks, %s\n",
2314                   Controller, Controller->ControllerNumber, LogicalDriveNumber,
2315                   LogicalDriveInformation->RAIDLevel,
2316                   (LogicalDriveInformation->LogicalDriveState
2317                    == DAC960_V1_LogicalDrive_Online
2318                    ? "Online"
2319                    : LogicalDriveInformation->LogicalDriveState
2320                      == DAC960_V1_LogicalDrive_Critical
2321                      ? "Critical" : "Offline"),
2322                   LogicalDriveInformation->LogicalDriveSize,
2323                   (LogicalDriveInformation->WriteBack
2324                    ? "Write Back" : "Write Thru"));
2325     }
2326   return true;
2327 }
2328
2329
2330 /*
2331   DAC960_V2_ReportDeviceConfiguration reports the Device Configuration
2332   Information for DAC960 V2 Firmware Controllers.
2333 */
2334
2335 static boolean DAC960_V2_ReportDeviceConfiguration(DAC960_Controller_T
2336                                                    *Controller)
2337 {
2338   int PhysicalDeviceIndex, LogicalDriveNumber;
2339   DAC960_Info("  Physical Devices:\n", Controller);
2340   for (PhysicalDeviceIndex = 0;
2341        PhysicalDeviceIndex < DAC960_V2_MaxPhysicalDevices;
2342        PhysicalDeviceIndex++)
2343     {
2344       DAC960_V2_PhysicalDeviceInfo_T *PhysicalDeviceInfo =
2345         Controller->V2.PhysicalDeviceInformation[PhysicalDeviceIndex];
2346       DAC960_SCSI_Inquiry_T *InquiryStandardData =
2347         (DAC960_SCSI_Inquiry_T *) &PhysicalDeviceInfo->SCSI_InquiryData;
2348       DAC960_SCSI_Inquiry_UnitSerialNumber_T *InquiryUnitSerialNumber =
2349         Controller->V2.InquiryUnitSerialNumber[PhysicalDeviceIndex];
2350       char Vendor[1+sizeof(InquiryStandardData->VendorIdentification)];
2351       char Model[1+sizeof(InquiryStandardData->ProductIdentification)];
2352       char Revision[1+sizeof(InquiryStandardData->ProductRevisionLevel)];
2353       char SerialNumber[1+sizeof(InquiryUnitSerialNumber->ProductSerialNumber)];
2354       if (PhysicalDeviceInfo == NULL) break;
2355       DAC960_SanitizeInquiryData(InquiryStandardData, InquiryUnitSerialNumber,
2356                                  Vendor, Model, Revision, SerialNumber);
2357       DAC960_Info("    %d:%d%s Vendor: %s  Model: %s  Revision: %s\n",
2358                   Controller,
2359                   PhysicalDeviceInfo->Channel,
2360                   PhysicalDeviceInfo->TargetID,
2361                   (PhysicalDeviceInfo->TargetID < 10 ? " " : ""),
2362                   Vendor, Model, Revision);
2363       if (PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers == 0)
2364         DAC960_Info("         %sAsynchronous\n", Controller,
2365                     (PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
2366                      ? "Wide " :""));
2367       else
2368         DAC960_Info("         %sSynchronous at %d MB/sec\n", Controller,
2369                     (PhysicalDeviceInfo->NegotiatedDataWidthBits == 16
2370                      ? "Wide " :""),
2371                     (PhysicalDeviceInfo->NegotiatedSynchronousMegaTransfers
2372                      * PhysicalDeviceInfo->NegotiatedDataWidthBits/8));
2373       if (InquiryUnitSerialNumber->PeripheralDeviceType != 0x1F)
2374         DAC960_Info("         Serial Number: %s\n", Controller, SerialNumber);
2375       if (PhysicalDeviceInfo->PhysicalDeviceState ==
2376           DAC960_V2_Device_Unconfigured)
2377         continue;
2378       DAC960_Info("         Disk Status: %s, %u blocks\n", Controller,
2379                   (PhysicalDeviceInfo->PhysicalDeviceState
2380                    == DAC960_V2_Device_Online
2381                    ? "Online"
2382                    : PhysicalDeviceInfo->PhysicalDeviceState
2383                      == DAC960_V2_Device_Rebuild
2384                      ? "Rebuild"
2385                      : PhysicalDeviceInfo->PhysicalDeviceState
2386                        == DAC960_V2_Device_Missing
2387                        ? "Missing"
2388                        : PhysicalDeviceInfo->PhysicalDeviceState
2389                          == DAC960_V2_Device_Critical
2390                          ? "Critical"
2391                          : PhysicalDeviceInfo->PhysicalDeviceState
2392                            == DAC960_V2_Device_Dead
2393                            ? "Dead"
2394                            : PhysicalDeviceInfo->PhysicalDeviceState
2395                              == DAC960_V2_Device_SuspectedDead
2396                              ? "Suspected-Dead"
2397                              : PhysicalDeviceInfo->PhysicalDeviceState
2398                                == DAC960_V2_Device_CommandedOffline
2399                                ? "Commanded-Offline"
2400                                : PhysicalDeviceInfo->PhysicalDeviceState
2401                                  == DAC960_V2_Device_Standby
2402                                  ? "Standby" : "Unknown"),
2403                   PhysicalDeviceInfo->ConfigurableDeviceSize);
2404       if (PhysicalDeviceInfo->ParityErrors == 0 &&
2405           PhysicalDeviceInfo->SoftErrors == 0 &&
2406           PhysicalDeviceInfo->HardErrors == 0 &&
2407           PhysicalDeviceInfo->MiscellaneousErrors == 0 &&
2408           PhysicalDeviceInfo->CommandTimeouts == 0 &&
2409           PhysicalDeviceInfo->Retries == 0 &&
2410           PhysicalDeviceInfo->Aborts == 0 &&
2411           PhysicalDeviceInfo->PredictedFailuresDetected == 0)
2412         continue;
2413       DAC960_Info("         Errors - Parity: %d, Soft: %d, "
2414                   "Hard: %d, Misc: %d\n", Controller,
2415                   PhysicalDeviceInfo->ParityErrors,
2416                   PhysicalDeviceInfo->SoftErrors,
2417                   PhysicalDeviceInfo->HardErrors,
2418                   PhysicalDeviceInfo->MiscellaneousErrors);
2419       DAC960_Info("                  Timeouts: %d, Retries: %d, "
2420                   "Aborts: %d, Predicted: %d\n", Controller,
2421                   PhysicalDeviceInfo->CommandTimeouts,
2422                   PhysicalDeviceInfo->Retries,
2423                   PhysicalDeviceInfo->Aborts,
2424                   PhysicalDeviceInfo->PredictedFailuresDetected);
2425     }
2426   DAC960_Info("  Logical Drives:\n", Controller);
2427   for (LogicalDriveNumber = 0;
2428        LogicalDriveNumber < DAC960_MaxLogicalDrives;
2429        LogicalDriveNumber++)
2430     {
2431       DAC960_V2_LogicalDeviceInfo_T *LogicalDeviceInfo =
2432         Controller->V2.LogicalDeviceInformation[LogicalDriveNumber];
2433       unsigned char *ReadCacheStatus[] = { "Read Cache Disabled",
2434                                            "Read Cache Enabled",
2435                                            "Read Ahead Enabled",
2436                                            "Intelligent Read Ahead Enabled",
2437                                            "-", "-", "-", "-" };
2438       unsigned char *WriteCacheStatus[] = { "Write Cache Disabled",
2439                                             "Logical Device Read Only",
2440                                             "Write Cache Enabled",
2441                                             "Intelligent Write Cache Enabled",
2442                                             "-", "-", "-", "-" };
2443       unsigned char *GeometryTranslation;
2444       if (LogicalDeviceInfo == NULL) continue;
2445       switch (LogicalDeviceInfo->DriveGeometry)
2446         {
2447         case DAC960_V2_Geometry_128_32:
2448           GeometryTranslation = "128/32";
2449           break;
2450         case DAC960_V2_Geometry_255_63:
2451           GeometryTranslation = "255/63";
2452           break;
2453         default:
2454           GeometryTranslation = "Invalid";
2455           DAC960_Error("Illegal Logical Device Geometry %d\n",
2456                        Controller, LogicalDeviceInfo->DriveGeometry);
2457           break;
2458         }
2459       DAC960_Info("    /dev/rd/c%dd%d: RAID-%d, %s, %u blocks\n",
2460                   Controller, Controller->ControllerNumber, LogicalDriveNumber,
2461                   LogicalDeviceInfo->RAIDLevel,
2462                   (LogicalDeviceInfo->LogicalDeviceState
2463                    == DAC960_V2_LogicalDevice_Online
2464                    ? "Online"
2465                    : LogicalDeviceInfo->LogicalDeviceState
2466                      == DAC960_V2_LogicalDevice_Critical
2467                      ? "Critical" : "Offline"),
2468                   LogicalDeviceInfo->ConfigurableDeviceSize);
2469       DAC960_Info("                  Logical Device %s, BIOS Geometry: %s\n",
2470                   Controller,
2471                   (LogicalDeviceInfo->LogicalDeviceControl
2472                                      .LogicalDeviceInitialized
2473                    ? "Initialized" : "Uninitialized"),
2474                   GeometryTranslation);
2475       if (LogicalDeviceInfo->StripeSize == 0)
2476         {
2477           if (LogicalDeviceInfo->CacheLineSize == 0)
2478             DAC960_Info("                  Stripe Size: N/A, "
2479                         "Segment Size: N/A\n", Controller);
2480           else
2481             DAC960_Info("                  Stripe Size: N/A, "
2482                         "Segment Size: %dKB\n", Controller,
2483                         1 << (LogicalDeviceInfo->CacheLineSize - 2));
2484         }
2485       else
2486         {
2487           if (LogicalDeviceInfo->CacheLineSize == 0)
2488             DAC960_Info("                  Stripe Size: %dKB, "
2489                         "Segment Size: N/A\n", Controller,
2490                         1 << (LogicalDeviceInfo->StripeSize - 2));
2491           else
2492             DAC960_Info("                  Stripe Size: %dKB, "
2493                         "Segment Size: %dKB\n", Controller,
2494                         1 << (LogicalDeviceInfo->StripeSize - 2),
2495                         1 << (LogicalDeviceInfo->CacheLineSize - 2));
2496         }
2497       DAC960_Info("                  %s, %s\n", Controller,
2498                   ReadCacheStatus[
2499                     LogicalDeviceInfo->LogicalDeviceControl.ReadCache],
2500                   WriteCacheStatus[
2501                     LogicalDeviceInfo->LogicalDeviceControl.WriteCache]);
2502       if (LogicalDeviceInfo->SoftErrors > 0 ||
2503           LogicalDeviceInfo->CommandsFailed > 0 ||
2504           LogicalDeviceInfo->DeferredWriteErrors)
2505         DAC960_Info("                  Errors - Soft: %d, Failed: %d, "
2506                     "Deferred Write: %d\n", Controller,
2507                     LogicalDeviceInfo->SoftErrors,
2508                     LogicalDeviceInfo->CommandsFailed,
2509                     LogicalDeviceInfo->DeferredWriteErrors);
2510
2511     }
2512   return true;
2513 }
2514
2515 /*
2516   DAC960_RegisterBlockDevice registers the Block Device structures
2517   associated with Controller.
2518 */
2519
2520 static boolean DAC960_RegisterBlockDevice(DAC960_Controller_T *Controller)
2521 {
2522   int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
2523   int n;
2524
2525   /*
2526     Register the Block Device Major Number for this DAC960 Controller.
2527   */
2528   if (register_blkdev(MajorNumber, "dac960") < 0)
2529       return false;
2530
2531   for (n = 0; n < DAC960_MaxLogicalDrives; n++) {
2532         struct gendisk *disk = Controller->disks[n];
2533         struct request_queue *RequestQueue;
2534
2535         /* for now, let all request queues share controller's lock */
2536         RequestQueue = blk_init_queue(DAC960_RequestFunction,&Controller->queue_lock);
2537         if (!RequestQueue) {
2538                 printk("DAC960: failure to allocate request queue\n");
2539                 continue;
2540         }
2541         Controller->RequestQueue[n] = RequestQueue;
2542         blk_queue_bounce_limit(RequestQueue, Controller->BounceBufferLimit);
2543         RequestQueue->queuedata = Controller;
2544         blk_queue_max_hw_segments(RequestQueue, Controller->DriverScatterGatherLimit);
2545         blk_queue_max_phys_segments(RequestQueue, Controller->DriverScatterGatherLimit);
2546         blk_queue_max_sectors(RequestQueue, Controller->MaxBlocksPerCommand);
2547         disk->queue = RequestQueue;
2548         sprintf(disk->disk_name, "rd/c%dd%d", Controller->ControllerNumber, n);
2549         sprintf(disk->devfs_name, "rd/host%d/target%d", Controller->ControllerNumber, n);
2550         disk->major = MajorNumber;
2551         disk->first_minor = n << DAC960_MaxPartitionsBits;
2552         disk->fops = &DAC960_BlockDeviceOperations;
2553    }
2554   /*
2555     Indicate the Block Device Registration completed successfully,
2556   */
2557   return true;
2558 }
2559
2560
2561 /*
2562   DAC960_UnregisterBlockDevice unregisters the Block Device structures
2563   associated with Controller.
2564 */
2565
2566 static void DAC960_UnregisterBlockDevice(DAC960_Controller_T *Controller)
2567 {
2568   int MajorNumber = DAC960_MAJOR + Controller->ControllerNumber;
2569   int disk;
2570
2571   /* does order matter when deleting gendisk and cleanup in request queue? */
2572   for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
2573         del_gendisk(Controller->disks[disk]);
2574         blk_cleanup_queue(Controller->RequestQueue[disk]);
2575         Controller->RequestQueue[disk] = NULL;
2576   }
2577
2578   /*
2579     Unregister the Block Device Major Number for this DAC960 Controller.
2580   */
2581   unregister_blkdev(MajorNumber, "dac960");
2582 }
2583
2584 /*
2585   DAC960_ComputeGenericDiskInfo computes the values for the Generic Disk
2586   Information Partition Sector Counts and Block Sizes.
2587 */
2588
2589 static void DAC960_ComputeGenericDiskInfo(DAC960_Controller_T *Controller)
2590 {
2591         int disk;
2592         for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++)
2593                 set_capacity(Controller->disks[disk], disk_size(Controller, disk));
2594 }
2595
2596 /*
2597   DAC960_ReportErrorStatus reports Controller BIOS Messages passed through
2598   the Error Status Register when the driver performs the BIOS handshaking.
2599   It returns true for fatal errors and false otherwise.
2600 */
2601
2602 static boolean DAC960_ReportErrorStatus(DAC960_Controller_T *Controller,
2603                                         unsigned char ErrorStatus,
2604                                         unsigned char Parameter0,
2605                                         unsigned char Parameter1)
2606 {
2607   switch (ErrorStatus)
2608     {
2609     case 0x00:
2610       DAC960_Notice("Physical Device %d:%d Not Responding\n",
2611                     Controller, Parameter1, Parameter0);
2612       break;
2613     case 0x08:
2614       if (Controller->DriveSpinUpMessageDisplayed) break;
2615       DAC960_Notice("Spinning Up Drives\n", Controller);
2616       Controller->DriveSpinUpMessageDisplayed = true;
2617       break;
2618     case 0x30:
2619       DAC960_Notice("Configuration Checksum Error\n", Controller);
2620       break;
2621     case 0x60:
2622       DAC960_Notice("Mirror Race Recovery Failed\n", Controller);
2623       break;
2624     case 0x70:
2625       DAC960_Notice("Mirror Race Recovery In Progress\n", Controller);
2626       break;
2627     case 0x90:
2628       DAC960_Notice("Physical Device %d:%d COD Mismatch\n",
2629                     Controller, Parameter1, Parameter0);
2630       break;
2631     case 0xA0:
2632       DAC960_Notice("Logical Drive Installation Aborted\n", Controller);
2633       break;
2634     case 0xB0:
2635       DAC960_Notice("Mirror Race On A Critical Logical Drive\n", Controller);
2636       break;
2637     case 0xD0:
2638       DAC960_Notice("New Controller Configuration Found\n", Controller);
2639       break;
2640     case 0xF0:
2641       DAC960_Error("Fatal Memory Parity Error for Controller at\n", Controller);
2642       return true;
2643     default:
2644       DAC960_Error("Unknown Initialization Error %02X for Controller at\n",
2645                    Controller, ErrorStatus);
2646       return true;
2647     }
2648   return false;
2649 }
2650
2651
2652 /*
2653  * DAC960_DetectCleanup releases the resources that were allocated
2654  * during DAC960_DetectController().  DAC960_DetectController can
2655  * has several internal failure points, so not ALL resources may 
2656  * have been allocated.  It's important to free only
2657  * resources that HAVE been allocated.  The code below always
2658  * tests that the resource has been allocated before attempting to
2659  * free it.
2660  */
2661 static void DAC960_DetectCleanup(DAC960_Controller_T *Controller)
2662 {
2663   int i;
2664
2665   /* Free the memory mailbox, status, and related structures */
2666   free_dma_loaf(Controller->PCIDevice, &Controller->DmaPages);
2667   if (Controller->MemoryMappedAddress) {
2668         switch(Controller->HardwareType)
2669         {
2670                 case DAC960_GEM_Controller:
2671                         DAC960_GEM_DisableInterrupts(Controller->BaseAddress);
2672                         break;
2673                 case DAC960_BA_Controller:
2674                         DAC960_BA_DisableInterrupts(Controller->BaseAddress);
2675                         break;
2676                 case DAC960_LP_Controller:
2677                         DAC960_LP_DisableInterrupts(Controller->BaseAddress);
2678                         break;
2679                 case DAC960_LA_Controller:
2680                         DAC960_LA_DisableInterrupts(Controller->BaseAddress);
2681                         break;
2682                 case DAC960_PG_Controller:
2683                         DAC960_PG_DisableInterrupts(Controller->BaseAddress);
2684                         break;
2685                 case DAC960_PD_Controller:
2686                         DAC960_PD_DisableInterrupts(Controller->BaseAddress);
2687                         break;
2688                 case DAC960_P_Controller:
2689                         DAC960_PD_DisableInterrupts(Controller->BaseAddress);
2690                         break;
2691         }
2692         iounmap(Controller->MemoryMappedAddress);
2693   }
2694   if (Controller->IRQ_Channel)
2695         free_irq(Controller->IRQ_Channel, Controller);
2696   if (Controller->IO_Address)
2697         release_region(Controller->IO_Address, 0x80);
2698   pci_disable_device(Controller->PCIDevice);
2699   for (i = 0; (i < DAC960_MaxLogicalDrives) && Controller->disks[i]; i++)
2700        put_disk(Controller->disks[i]);
2701   DAC960_Controllers[Controller->ControllerNumber] = NULL;
2702   kfree(Controller);
2703 }
2704
2705
2706 /*
2707   DAC960_DetectController detects Mylex DAC960/AcceleRAID/eXtremeRAID
2708   PCI RAID Controllers by interrogating the PCI Configuration Space for
2709   Controller Type.
2710 */
2711
2712 static DAC960_Controller_T * 
2713 DAC960_DetectController(struct pci_dev *PCI_Device,
2714                         const struct pci_device_id *entry)
2715 {
2716   struct DAC960_privdata *privdata =
2717                 (struct DAC960_privdata *)entry->driver_data;
2718   irqreturn_t (*InterruptHandler)(int, void *, struct pt_regs *) =
2719                 privdata->InterruptHandler;
2720   unsigned int MemoryWindowSize = privdata->MemoryWindowSize;
2721   DAC960_Controller_T *Controller = NULL;
2722   unsigned char DeviceFunction = PCI_Device->devfn;
2723   unsigned char ErrorStatus, Parameter0, Parameter1;
2724   unsigned int IRQ_Channel;
2725   void __iomem *BaseAddress;
2726   int i;
2727
2728   Controller = (DAC960_Controller_T *)
2729         kmalloc(sizeof(DAC960_Controller_T), GFP_ATOMIC);
2730   if (Controller == NULL) {
2731         DAC960_Error("Unable to allocate Controller structure for "
2732                        "Controller at\n", NULL);
2733         return NULL;
2734   }
2735   memset(Controller, 0, sizeof(DAC960_Controller_T));
2736   Controller->ControllerNumber = DAC960_ControllerCount;
2737   DAC960_Controllers[DAC960_ControllerCount++] = Controller;
2738   Controller->Bus = PCI_Device->bus->number;
2739   Controller->FirmwareType = privdata->FirmwareType;
2740   Controller->HardwareType = privdata->HardwareType;
2741   Controller->Device = DeviceFunction >> 3;
2742   Controller->Function = DeviceFunction & 0x7;
2743   Controller->PCIDevice = PCI_Device;
2744   strcpy(Controller->FullModelName, "DAC960");
2745
2746   if (pci_enable_device(PCI_Device))
2747         goto Failure;
2748
2749   switch (Controller->HardwareType)
2750   {
2751         case DAC960_GEM_Controller:
2752           Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2753           break;
2754         case DAC960_BA_Controller:
2755           Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2756           break;
2757         case DAC960_LP_Controller:
2758           Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2759           break;
2760         case DAC960_LA_Controller:
2761           Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2762           break;
2763         case DAC960_PG_Controller:
2764           Controller->PCI_Address = pci_resource_start(PCI_Device, 0);
2765           break;
2766         case DAC960_PD_Controller:
2767           Controller->IO_Address = pci_resource_start(PCI_Device, 0);
2768           Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
2769           break;
2770         case DAC960_P_Controller:
2771           Controller->IO_Address = pci_resource_start(PCI_Device, 0);
2772           Controller->PCI_Address = pci_resource_start(PCI_Device, 1);
2773           break;
2774   }
2775
2776   pci_set_drvdata(PCI_Device, (void *)((long)Controller->ControllerNumber));
2777   for (i = 0; i < DAC960_MaxLogicalDrives; i++) {
2778         Controller->disks[i] = alloc_disk(1<<DAC960_MaxPartitionsBits);
2779         if (!Controller->disks[i])
2780                 goto Failure;
2781         Controller->disks[i]->private_data = (void *)((long)i);
2782   }
2783   init_waitqueue_head(&Controller->CommandWaitQueue);
2784   init_waitqueue_head(&Controller->HealthStatusWaitQueue);
2785   spin_lock_init(&Controller->queue_lock);
2786   DAC960_AnnounceDriver(Controller);
2787   /*
2788     Map the Controller Register Window.
2789   */
2790  if (MemoryWindowSize < PAGE_SIZE)
2791         MemoryWindowSize = PAGE_SIZE;
2792   Controller->MemoryMappedAddress =
2793         ioremap_nocache(Controller->PCI_Address & PAGE_MASK, MemoryWindowSize);
2794   Controller->BaseAddress =
2795         Controller->MemoryMappedAddress + (Controller->PCI_Address & ~PAGE_MASK);
2796   if (Controller->MemoryMappedAddress == NULL)
2797   {
2798           DAC960_Error("Unable to map Controller Register Window for "
2799                        "Controller at\n", Controller);
2800           goto Failure;
2801   }
2802   BaseAddress = Controller->BaseAddress;
2803   switch (Controller->HardwareType)
2804   {
2805         case DAC960_GEM_Controller:
2806           DAC960_GEM_DisableInterrupts(BaseAddress);
2807           DAC960_GEM_AcknowledgeHardwareMailboxStatus(BaseAddress);
2808           udelay(1000);
2809           while (DAC960_GEM_InitializationInProgressP(BaseAddress))
2810             {
2811               if (DAC960_GEM_ReadErrorStatus(BaseAddress, &ErrorStatus,
2812                                             &Parameter0, &Parameter1) &&
2813                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2814                                            Parameter0, Parameter1))
2815                 goto Failure;
2816               udelay(10);
2817             }
2818           if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2819             {
2820               DAC960_Error("Unable to Enable Memory Mailbox Interface "
2821                            "for Controller at\n", Controller);
2822               goto Failure;
2823             }
2824           DAC960_GEM_EnableInterrupts(BaseAddress);
2825           Controller->QueueCommand = DAC960_GEM_QueueCommand;
2826           Controller->ReadControllerConfiguration =
2827             DAC960_V2_ReadControllerConfiguration;
2828           Controller->ReadDeviceConfiguration =
2829             DAC960_V2_ReadDeviceConfiguration;
2830           Controller->ReportDeviceConfiguration =
2831             DAC960_V2_ReportDeviceConfiguration;
2832           Controller->QueueReadWriteCommand =
2833             DAC960_V2_QueueReadWriteCommand;
2834           break;
2835         case DAC960_BA_Controller:
2836           DAC960_BA_DisableInterrupts(BaseAddress);
2837           DAC960_BA_AcknowledgeHardwareMailboxStatus(BaseAddress);
2838           udelay(1000);
2839           while (DAC960_BA_InitializationInProgressP(BaseAddress))
2840             {
2841               if (DAC960_BA_ReadErrorStatus(BaseAddress, &ErrorStatus,
2842                                             &Parameter0, &Parameter1) &&
2843                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2844                                            Parameter0, Parameter1))
2845                 goto Failure;
2846               udelay(10);
2847             }
2848           if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2849             {
2850               DAC960_Error("Unable to Enable Memory Mailbox Interface "
2851                            "for Controller at\n", Controller);
2852               goto Failure;
2853             }
2854           DAC960_BA_EnableInterrupts(BaseAddress);
2855           Controller->QueueCommand = DAC960_BA_QueueCommand;
2856           Controller->ReadControllerConfiguration =
2857             DAC960_V2_ReadControllerConfiguration;
2858           Controller->ReadDeviceConfiguration =
2859             DAC960_V2_ReadDeviceConfiguration;
2860           Controller->ReportDeviceConfiguration =
2861             DAC960_V2_ReportDeviceConfiguration;
2862           Controller->QueueReadWriteCommand =
2863             DAC960_V2_QueueReadWriteCommand;
2864           break;
2865         case DAC960_LP_Controller:
2866           DAC960_LP_DisableInterrupts(BaseAddress);
2867           DAC960_LP_AcknowledgeHardwareMailboxStatus(BaseAddress);
2868           udelay(1000);
2869           while (DAC960_LP_InitializationInProgressP(BaseAddress))
2870             {
2871               if (DAC960_LP_ReadErrorStatus(BaseAddress, &ErrorStatus,
2872                                             &Parameter0, &Parameter1) &&
2873                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2874                                            Parameter0, Parameter1))
2875                 goto Failure;
2876               udelay(10);
2877             }
2878           if (!DAC960_V2_EnableMemoryMailboxInterface(Controller))
2879             {
2880               DAC960_Error("Unable to Enable Memory Mailbox Interface "
2881                            "for Controller at\n", Controller);
2882               goto Failure;
2883             }
2884           DAC960_LP_EnableInterrupts(BaseAddress);
2885           Controller->QueueCommand = DAC960_LP_QueueCommand;
2886           Controller->ReadControllerConfiguration =
2887             DAC960_V2_ReadControllerConfiguration;
2888           Controller->ReadDeviceConfiguration =
2889             DAC960_V2_ReadDeviceConfiguration;
2890           Controller->ReportDeviceConfiguration =
2891             DAC960_V2_ReportDeviceConfiguration;
2892           Controller->QueueReadWriteCommand =
2893             DAC960_V2_QueueReadWriteCommand;
2894           break;
2895         case DAC960_LA_Controller:
2896           DAC960_LA_DisableInterrupts(BaseAddress);
2897           DAC960_LA_AcknowledgeHardwareMailboxStatus(BaseAddress);
2898           udelay(1000);
2899           while (DAC960_LA_InitializationInProgressP(BaseAddress))
2900             {
2901               if (DAC960_LA_ReadErrorStatus(BaseAddress, &ErrorStatus,
2902                                             &Parameter0, &Parameter1) &&
2903                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2904                                            Parameter0, Parameter1))
2905                 goto Failure;
2906               udelay(10);
2907             }
2908           if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2909             {
2910               DAC960_Error("Unable to Enable Memory Mailbox Interface "
2911                            "for Controller at\n", Controller);
2912               goto Failure;
2913             }
2914           DAC960_LA_EnableInterrupts(BaseAddress);
2915           if (Controller->V1.DualModeMemoryMailboxInterface)
2916             Controller->QueueCommand = DAC960_LA_QueueCommandDualMode;
2917           else Controller->QueueCommand = DAC960_LA_QueueCommandSingleMode;
2918           Controller->ReadControllerConfiguration =
2919             DAC960_V1_ReadControllerConfiguration;
2920           Controller->ReadDeviceConfiguration =
2921             DAC960_V1_ReadDeviceConfiguration;
2922           Controller->ReportDeviceConfiguration =
2923             DAC960_V1_ReportDeviceConfiguration;
2924           Controller->QueueReadWriteCommand =
2925             DAC960_V1_QueueReadWriteCommand;
2926           break;
2927         case DAC960_PG_Controller:
2928           DAC960_PG_DisableInterrupts(BaseAddress);
2929           DAC960_PG_AcknowledgeHardwareMailboxStatus(BaseAddress);
2930           udelay(1000);
2931           while (DAC960_PG_InitializationInProgressP(BaseAddress))
2932             {
2933               if (DAC960_PG_ReadErrorStatus(BaseAddress, &ErrorStatus,
2934                                             &Parameter0, &Parameter1) &&
2935                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2936                                            Parameter0, Parameter1))
2937                 goto Failure;
2938               udelay(10);
2939             }
2940           if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2941             {
2942               DAC960_Error("Unable to Enable Memory Mailbox Interface "
2943                            "for Controller at\n", Controller);
2944               goto Failure;
2945             }
2946           DAC960_PG_EnableInterrupts(BaseAddress);
2947           if (Controller->V1.DualModeMemoryMailboxInterface)
2948             Controller->QueueCommand = DAC960_PG_QueueCommandDualMode;
2949           else Controller->QueueCommand = DAC960_PG_QueueCommandSingleMode;
2950           Controller->ReadControllerConfiguration =
2951             DAC960_V1_ReadControllerConfiguration;
2952           Controller->ReadDeviceConfiguration =
2953             DAC960_V1_ReadDeviceConfiguration;
2954           Controller->ReportDeviceConfiguration =
2955             DAC960_V1_ReportDeviceConfiguration;
2956           Controller->QueueReadWriteCommand =
2957             DAC960_V1_QueueReadWriteCommand;
2958           break;
2959         case DAC960_PD_Controller:
2960           if (!request_region(Controller->IO_Address, 0x80,
2961                               Controller->FullModelName)) {
2962                 DAC960_Error("IO port 0x%d busy for Controller at\n",
2963                              Controller, Controller->IO_Address);
2964                 goto Failure;
2965           }
2966           DAC960_PD_DisableInterrupts(BaseAddress);
2967           DAC960_PD_AcknowledgeStatus(BaseAddress);
2968           udelay(1000);
2969           while (DAC960_PD_InitializationInProgressP(BaseAddress))
2970             {
2971               if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
2972                                             &Parameter0, &Parameter1) &&
2973                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
2974                                            Parameter0, Parameter1))
2975                 goto Failure;
2976               udelay(10);
2977             }
2978           if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
2979             {
2980               DAC960_Error("Unable to allocate DMA mapped memory "
2981                            "for Controller at\n", Controller);
2982               goto Failure;
2983             }
2984           DAC960_PD_EnableInterrupts(BaseAddress);
2985           Controller->QueueCommand = DAC960_PD_QueueCommand;
2986           Controller->ReadControllerConfiguration =
2987             DAC960_V1_ReadControllerConfiguration;
2988           Controller->ReadDeviceConfiguration =
2989             DAC960_V1_ReadDeviceConfiguration;
2990           Controller->ReportDeviceConfiguration =
2991             DAC960_V1_ReportDeviceConfiguration;
2992           Controller->QueueReadWriteCommand =
2993             DAC960_V1_QueueReadWriteCommand;
2994           break;
2995         case DAC960_P_Controller:
2996           if (!request_region(Controller->IO_Address, 0x80,
2997                               Controller->FullModelName)){
2998                 DAC960_Error("IO port 0x%d busy for Controller at\n",
2999                              Controller, Controller->IO_Address);
3000                 goto Failure;
3001           }
3002           DAC960_PD_DisableInterrupts(BaseAddress);
3003           DAC960_PD_AcknowledgeStatus(BaseAddress);
3004           udelay(1000);
3005           while (DAC960_PD_InitializationInProgressP(BaseAddress))
3006             {
3007               if (DAC960_PD_ReadErrorStatus(BaseAddress, &ErrorStatus,
3008                                             &Parameter0, &Parameter1) &&
3009                   DAC960_ReportErrorStatus(Controller, ErrorStatus,
3010                                            Parameter0, Parameter1))
3011                 goto Failure;
3012               udelay(10);
3013             }
3014           if (!DAC960_V1_EnableMemoryMailboxInterface(Controller))
3015             {
3016               DAC960_Error("Unable to allocate DMA mapped memory"
3017                            "for Controller at\n", Controller);
3018               goto Failure;
3019             }
3020           DAC960_PD_EnableInterrupts(BaseAddress);
3021           Controller->QueueCommand = DAC960_P_QueueCommand;
3022           Controller->ReadControllerConfiguration =
3023             DAC960_V1_ReadControllerConfiguration;
3024           Controller->ReadDeviceConfiguration =
3025             DAC960_V1_ReadDeviceConfiguration;
3026           Controller->ReportDeviceConfiguration =
3027             DAC960_V1_ReportDeviceConfiguration;
3028           Controller->QueueReadWriteCommand =
3029             DAC960_V1_QueueReadWriteCommand;
3030           break;
3031   }
3032   /*
3033      Acquire shared access to the IRQ Channel.
3034   */
3035   IRQ_Channel = PCI_Device->irq;
3036   if (request_irq(IRQ_Channel, InterruptHandler, SA_SHIRQ,
3037                       Controller->FullModelName, Controller) < 0)
3038   {
3039         DAC960_Error("Unable to acquire IRQ Channel %d for Controller at\n",
3040                        Controller, Controller->IRQ_Channel);
3041         goto Failure;
3042   }
3043   Controller->IRQ_Channel = IRQ_Channel;
3044   Controller->InitialCommand.CommandIdentifier = 1;
3045   Controller->InitialCommand.Controller = Controller;
3046   Controller->Commands[0] = &Controller->InitialCommand;
3047   Controller->FreeCommands = &Controller->InitialCommand;
3048   return Controller;
3049       
3050 Failure:
3051   if (Controller->IO_Address == 0)
3052         DAC960_Error("PCI Bus %d Device %d Function %d I/O Address N/A "
3053                      "PCI Address 0x%X\n", Controller,
3054                      Controller->Bus, Controller->Device,
3055                      Controller->Function, Controller->PCI_Address);
3056   else
3057         DAC960_Error("PCI Bus %d Device %d Function %d I/O Address "
3058                         "0x%X PCI Address 0x%X\n", Controller,
3059                         Controller->Bus, Controller->Device,
3060                         Controller->Function, Controller->IO_Address,
3061                         Controller->PCI_Address);
3062   DAC960_DetectCleanup(Controller);
3063   DAC960_ControllerCount--;
3064   return NULL;
3065 }
3066
3067 /*
3068   DAC960_InitializeController initializes Controller.
3069 */
3070
3071 static boolean 
3072 DAC960_InitializeController(DAC960_Controller_T *Controller)
3073 {
3074   if (DAC960_ReadControllerConfiguration(Controller) &&
3075       DAC960_ReportControllerConfiguration(Controller) &&
3076       DAC960_CreateAuxiliaryStructures(Controller) &&
3077       DAC960_ReadDeviceConfiguration(Controller) &&
3078       DAC960_ReportDeviceConfiguration(Controller) &&
3079       DAC960_RegisterBlockDevice(Controller))
3080     {
3081       /*
3082         Initialize the Monitoring Timer.
3083       */
3084       init_timer(&Controller->MonitoringTimer);
3085       Controller->MonitoringTimer.expires =
3086         jiffies + DAC960_MonitoringTimerInterval;
3087       Controller->MonitoringTimer.data = (unsigned long) Controller;
3088       Controller->MonitoringTimer.function = DAC960_MonitoringTimerFunction;
3089       add_timer(&Controller->MonitoringTimer);
3090       Controller->ControllerInitialized = true;
3091       return true;
3092     }
3093   return false;
3094 }
3095
3096
3097 /*
3098   DAC960_FinalizeController finalizes Controller.
3099 */
3100
3101 static void DAC960_FinalizeController(DAC960_Controller_T *Controller)
3102 {
3103   if (Controller->ControllerInitialized)
3104     {
3105       unsigned long flags;
3106
3107       /*
3108        * Acquiring and releasing lock here eliminates
3109        * a very low probability race.
3110        *
3111        * The code below allocates controller command structures
3112        * from the free list without holding the controller lock.
3113        * This is safe assuming there is no other activity on
3114        * the controller at the time.
3115        * 
3116        * But, there might be a monitoring command still
3117        * in progress.  Setting the Shutdown flag while holding
3118        * the lock ensures that there is no monitoring command
3119        * in the interrupt handler currently, and any monitoring
3120        * commands that complete from this time on will NOT return
3121        * their command structure to the free list.
3122        */
3123
3124       spin_lock_irqsave(&Controller->queue_lock, flags);
3125       Controller->ShutdownMonitoringTimer = 1;
3126       spin_unlock_irqrestore(&Controller->queue_lock, flags);
3127
3128       del_timer_sync(&Controller->MonitoringTimer);
3129       if (Controller->FirmwareType == DAC960_V1_Controller)
3130         {
3131           DAC960_Notice("Flushing Cache...", Controller);
3132           DAC960_V1_ExecuteType3(Controller, DAC960_V1_Flush, 0);
3133           DAC960_Notice("done\n", Controller);
3134
3135           if (Controller->HardwareType == DAC960_PD_Controller)
3136               release_region(Controller->IO_Address, 0x80);
3137         }
3138       else
3139         {
3140           DAC960_Notice("Flushing Cache...", Controller);
3141           DAC960_V2_DeviceOperation(Controller, DAC960_V2_PauseDevice,
3142                                     DAC960_V2_RAID_Controller);
3143           DAC960_Notice("done\n", Controller);
3144         }
3145     }
3146   DAC960_UnregisterBlockDevice(Controller);
3147   DAC960_DestroyAuxiliaryStructures(Controller);
3148   DAC960_DestroyProcEntries(Controller);
3149   DAC960_DetectCleanup(Controller);
3150 }
3151
3152
3153 /*
3154   DAC960_Probe verifies controller's existence and
3155   initializes the DAC960 Driver for that controller.
3156 */
3157
3158 static int 
3159 DAC960_Probe(struct pci_dev *dev, const struct pci_device_id *entry)
3160 {
3161   int disk;
3162   DAC960_Controller_T *Controller;
3163
3164   if (DAC960_ControllerCount == DAC960_MaxControllers)
3165   {
3166         DAC960_Error("More than %d DAC960 Controllers detected - "
3167                        "ignoring from Controller at\n",
3168                        NULL, DAC960_MaxControllers);
3169         return -ENODEV;
3170   }
3171
3172   Controller = DAC960_DetectController(dev, entry);
3173   if (!Controller)
3174         return -ENODEV;
3175
3176   if (!DAC960_InitializeController(Controller)) {
3177         DAC960_FinalizeController(Controller);
3178         return -ENODEV;
3179   }
3180
3181   for (disk = 0; disk < DAC960_MaxLogicalDrives; disk++) {
3182         set_capacity(Controller->disks[disk], disk_size(Controller, disk));
3183         add_disk(Controller->disks[disk]);
3184   }
3185   DAC960_CreateProcEntries(Controller);
3186   return 0;
3187 }
3188
3189
3190 /*
3191   DAC960_Finalize finalizes the DAC960 Driver.
3192 */
3193
3194 static void DAC960_Remove(struct pci_dev *PCI_Device)
3195 {
3196   int Controller_Number = (long)pci_get_drvdata(PCI_Device);
3197   DAC960_Controller_T *Controller = DAC960_Controllers[Controller_Number];
3198   if (Controller != NULL)
3199       DAC960_FinalizeController(Controller);
3200 }
3201
3202
3203 /*
3204   DAC960_V1_QueueReadWriteCommand prepares and queues a Read/Write Command for
3205   DAC960 V1 Firmware Controllers.
3206 */
3207
3208 static void DAC960_V1_QueueReadWriteCommand(DAC960_Command_T *Command)
3209 {
3210   DAC960_Controller_T *Controller = Command->Controller;
3211   DAC960_V1_CommandMailbox_T *CommandMailbox = &Command->V1.CommandMailbox;
3212   DAC960_V1_ScatterGatherSegment_T *ScatterGatherList =
3213                                         Command->V1.ScatterGatherList;
3214   struct scatterlist *ScatterList = Command->V1.ScatterList;
3215
3216   DAC960_V1_ClearCommand(Command);
3217
3218   if (Command->SegmentCount == 1)
3219     {
3220       if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3221         CommandMailbox->Type5.CommandOpcode = DAC960_V1_Read;
3222       else 
3223         CommandMailbox->Type5.CommandOpcode = DAC960_V1_Write;
3224
3225       CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
3226       CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
3227       CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
3228       CommandMailbox->Type5.BusAddress =
3229                         (DAC960_BusAddress32_T)sg_dma_address(ScatterList);     
3230     }
3231   else
3232     {
3233       int i;
3234
3235       if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3236         CommandMailbox->Type5.CommandOpcode = DAC960_V1_ReadWithScatterGather;
3237       else
3238         CommandMailbox->Type5.CommandOpcode = DAC960_V1_WriteWithScatterGather;
3239
3240       CommandMailbox->Type5.LD.TransferLength = Command->BlockCount;
3241       CommandMailbox->Type5.LD.LogicalDriveNumber = Command->LogicalDriveNumber;
3242       CommandMailbox->Type5.LogicalBlockAddress = Command->BlockNumber;
3243       CommandMailbox->Type5.BusAddress = Command->V1.ScatterGatherListDMA;
3244
3245       CommandMailbox->Type5.ScatterGatherCount = Command->SegmentCount;
3246
3247       for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
3248                 ScatterGatherList->SegmentDataPointer =
3249                         (DAC960_BusAddress32_T)sg_dma_address(ScatterList);
3250                 ScatterGatherList->SegmentByteCount =
3251                         (DAC960_ByteCount32_T)sg_dma_len(ScatterList);
3252       }
3253     }
3254   DAC960_QueueCommand(Command);
3255 }
3256
3257
3258 /*
3259   DAC960_V2_QueueReadWriteCommand prepares and queues a Read/Write Command for
3260   DAC960 V2 Firmware Controllers.
3261 */
3262
3263 static void DAC960_V2_QueueReadWriteCommand(DAC960_Command_T *Command)
3264 {
3265   DAC960_Controller_T *Controller = Command->Controller;
3266   DAC960_V2_CommandMailbox_T *CommandMailbox = &Command->V2.CommandMailbox;
3267   struct scatterlist *ScatterList = Command->V2.ScatterList;
3268
3269   DAC960_V2_ClearCommand(Command);
3270
3271   CommandMailbox->SCSI_10.CommandOpcode = DAC960_V2_SCSI_10;
3272   CommandMailbox->SCSI_10.CommandControlBits.DataTransferControllerToHost =
3273     (Command->DmaDirection == PCI_DMA_FROMDEVICE);
3274   CommandMailbox->SCSI_10.DataTransferSize =
3275     Command->BlockCount << DAC960_BlockSizeBits;
3276   CommandMailbox->SCSI_10.RequestSenseBusAddress = Command->V2.RequestSenseDMA;
3277   CommandMailbox->SCSI_10.PhysicalDevice =
3278     Controller->V2.LogicalDriveToVirtualDevice[Command->LogicalDriveNumber];
3279   CommandMailbox->SCSI_10.RequestSenseSize = sizeof(DAC960_SCSI_RequestSense_T);
3280   CommandMailbox->SCSI_10.CDBLength = 10;
3281   CommandMailbox->SCSI_10.SCSI_CDB[0] =
3282     (Command->DmaDirection == PCI_DMA_FROMDEVICE ? 0x28 : 0x2A);
3283   CommandMailbox->SCSI_10.SCSI_CDB[2] = Command->BlockNumber >> 24;
3284   CommandMailbox->SCSI_10.SCSI_CDB[3] = Command->BlockNumber >> 16;
3285   CommandMailbox->SCSI_10.SCSI_CDB[4] = Command->BlockNumber >> 8;
3286   CommandMailbox->SCSI_10.SCSI_CDB[5] = Command->BlockNumber;
3287   CommandMailbox->SCSI_10.SCSI_CDB[7] = Command->BlockCount >> 8;
3288   CommandMailbox->SCSI_10.SCSI_CDB[8] = Command->BlockCount;
3289
3290   if (Command->SegmentCount == 1)
3291     {
3292       CommandMailbox->SCSI_10.DataTransferMemoryAddress
3293                              .ScatterGatherSegments[0]
3294                              .SegmentDataPointer =
3295         (DAC960_BusAddress64_T)sg_dma_address(ScatterList);
3296       CommandMailbox->SCSI_10.DataTransferMemoryAddress
3297                              .ScatterGatherSegments[0]
3298                              .SegmentByteCount =
3299         CommandMailbox->SCSI_10.DataTransferSize;
3300     }
3301   else
3302     {
3303       DAC960_V2_ScatterGatherSegment_T *ScatterGatherList;
3304       int i;
3305
3306       if (Command->SegmentCount > 2)
3307         {
3308           ScatterGatherList = Command->V2.ScatterGatherList;
3309           CommandMailbox->SCSI_10.CommandControlBits
3310                          .AdditionalScatterGatherListMemory = true;
3311           CommandMailbox->SCSI_10.DataTransferMemoryAddress
3312                 .ExtendedScatterGather.ScatterGatherList0Length = Command->SegmentCount;
3313           CommandMailbox->SCSI_10.DataTransferMemoryAddress
3314                          .ExtendedScatterGather.ScatterGatherList0Address =
3315             Command->V2.ScatterGatherListDMA;
3316         }
3317       else
3318         ScatterGatherList = CommandMailbox->SCSI_10.DataTransferMemoryAddress
3319                                  .ScatterGatherSegments;
3320
3321       for (i = 0; i < Command->SegmentCount; i++, ScatterList++, ScatterGatherList++) {
3322                 ScatterGatherList->SegmentDataPointer =
3323                         (DAC960_BusAddress64_T)sg_dma_address(ScatterList);
3324                 ScatterGatherList->SegmentByteCount =
3325                         (DAC960_ByteCount64_T)sg_dma_len(ScatterList);
3326       }
3327     }
3328   DAC960_QueueCommand(Command);
3329 }
3330
3331
3332 static int DAC960_process_queue(DAC960_Controller_T *Controller, struct request_queue *req_q)
3333 {
3334         struct request *Request;
3335         DAC960_Command_T *Command;
3336
3337    while(1) {
3338         Request = elv_next_request(req_q);
3339         if (!Request)
3340                 return 1;
3341
3342         Command = DAC960_AllocateCommand(Controller);
3343         if (Command == NULL)
3344                 return 0;
3345
3346         if (rq_data_dir(Request) == READ) {
3347                 Command->DmaDirection = PCI_DMA_FROMDEVICE;
3348                 Command->CommandType = DAC960_ReadCommand;
3349         } else {
3350                 Command->DmaDirection = PCI_DMA_TODEVICE;
3351                 Command->CommandType = DAC960_WriteCommand;
3352         }
3353         Command->Completion = Request->waiting;
3354         Command->LogicalDriveNumber = (long)Request->rq_disk->private_data;
3355         Command->BlockNumber = Request->sector;
3356         Command->BlockCount = Request->nr_sectors;
3357         Command->Request = Request;
3358         blkdev_dequeue_request(Request);
3359         Command->SegmentCount = blk_rq_map_sg(req_q,
3360                   Command->Request, Command->cmd_sglist);
3361         /* pci_map_sg MAY change the value of SegCount */
3362         Command->SegmentCount = pci_map_sg(Controller->PCIDevice, Command->cmd_sglist,
3363                  Command->SegmentCount, Command->DmaDirection);
3364
3365         DAC960_QueueReadWriteCommand(Command);
3366   }
3367 }
3368
3369 /*
3370   DAC960_ProcessRequest attempts to remove one I/O Request from Controller's
3371   I/O Request Queue and queues it to the Controller.  WaitForCommand is true if
3372   this function should wait for a Command to become available if necessary.
3373   This function returns true if an I/O Request was queued and false otherwise.
3374 */
3375 static void DAC960_ProcessRequest(DAC960_Controller_T *controller)
3376 {
3377         int i;
3378
3379         if (!controller->ControllerInitialized)
3380                 return;
3381
3382         /* Do this better later! */
3383         for (i = controller->req_q_index; i < DAC960_MaxLogicalDrives; i++) {
3384                 struct request_queue *req_q = controller->RequestQueue[i];
3385
3386                 if (req_q == NULL)
3387                         continue;
3388
3389                 if (!DAC960_process_queue(controller, req_q)) {
3390                         controller->req_q_index = i;
3391                         return;
3392                 }
3393         }
3394
3395         if (controller->req_q_index == 0)
3396                 return;
3397
3398         for (i = 0; i < controller->req_q_index; i++) {
3399                 struct request_queue *req_q = controller->RequestQueue[i];
3400
3401                 if (req_q == NULL)
3402                         continue;
3403
3404                 if (!DAC960_process_queue(controller, req_q)) {
3405                         controller->req_q_index = i;
3406                         return;
3407                 }
3408         }
3409 }
3410
3411
3412 /*
3413   DAC960_queue_partial_rw extracts one bio from the request already
3414   associated with argument command, and construct a new command block to retry I/O
3415   only on that bio.  Queue that command to the controller.
3416
3417   This function re-uses a previously-allocated Command,
3418         there is no failure mode from trying to allocate a command.
3419 */
3420
3421 static void DAC960_queue_partial_rw(DAC960_Command_T *Command)
3422 {
3423   DAC960_Controller_T *Controller = Command->Controller;
3424   struct request *Request = Command->Request;
3425   struct request_queue *req_q = Controller->RequestQueue[Command->LogicalDriveNumber];
3426
3427   if (Command->DmaDirection == PCI_DMA_FROMDEVICE)
3428     Command->CommandType = DAC960_ReadRetryCommand;
3429   else
3430     Command->CommandType = DAC960_WriteRetryCommand;
3431
3432   /*
3433    * We could be more efficient with these mapping requests
3434    * and map only the portions that we need.  But since this
3435    * code should almost never be called, just go with a
3436    * simple coding.
3437    */
3438   (void)blk_rq_map_sg(req_q, Command->Request, Command->cmd_sglist);
3439
3440   (void)pci_map_sg(Controller->PCIDevice, Command->cmd_sglist, 1, Command->DmaDirection);
3441   /*
3442    * Resubmitting the request sector at a time is really tedious.
3443    * But, this should almost never happen.  So, we're willing to pay
3444    * this price so that in the end, as much of the transfer is completed
3445    * successfully as possible.
3446    */
3447   Command->SegmentCount = 1;
3448   Command->BlockNumber = Request->sector;
3449   Command->BlockCount = 1;
3450   DAC960_QueueReadWriteCommand(Command);
3451   return;
3452 }
3453
3454 /*
3455   DAC960_RequestFunction is the I/O Request Function for DAC960 Controllers.
3456 */
3457
3458 static void DAC960_RequestFunction(struct request_queue *RequestQueue)
3459 {
3460         DAC960_ProcessRequest(RequestQueue->queuedata);
3461 }
3462
3463 /*
3464   DAC960_ProcessCompletedBuffer performs completion processing for an
3465   individual Buffer.
3466 */
3467
3468 static inline boolean DAC960_ProcessCompletedRequest(DAC960_Command_T *Command,
3469                                                  boolean SuccessfulIO)
3470 {
3471         struct request *Request = Command->Request;
3472         int UpToDate;
3473
3474         UpToDate = 0;
3475         if (SuccessfulIO)
3476                 UpToDate = 1;
3477
3478         pci_unmap_sg(Command->Controller->PCIDevice, Command->cmd_sglist,
3479                 Command->SegmentCount, Command->DmaDirection);
3480
3481          if (!end_that_request_first(Request, UpToDate, Command->BlockCount)) {
3482
3483                 end_that_request_last(Request);
3484
3485                 if (Command->Completion) {
3486                         complete(Command->Completion);
3487                         Command->Completion = NULL;
3488                 }
3489                 return true;
3490         }
3491         return false;
3492 }
3493
3494 /*
3495   DAC960_V1_ReadWriteError prints an appropriate error message for Command
3496   when an error occurs on a Read or Write operation.
3497 */
3498
3499 static void DAC960_V1_ReadWriteError(DAC960_Command_T *Command)
3500 {
3501   DAC960_Controller_T *Controller = Command->Controller;
3502   unsigned char *CommandName = "UNKNOWN";
3503   switch (Command->CommandType)
3504     {
3505     case DAC960_ReadCommand:
3506     case DAC960_ReadRetryCommand:
3507       CommandName = "READ";
3508       break;
3509     case DAC960_WriteCommand:
3510     case DAC960_WriteRetryCommand:
3511       CommandName = "WRITE";
3512       break;
3513     case DAC960_MonitoringCommand:
3514     case DAC960_ImmediateCommand:
3515     case DAC960_QueuedCommand:
3516       break;
3517     }
3518   switch (Command->V1.CommandStatus)
3519     {
3520     case DAC960_V1_IrrecoverableDataError:
3521       DAC960_Error("Irrecoverable Data Error on %s:\n",
3522                    Controller, CommandName);
3523       break;
3524     case DAC960_V1_LogicalDriveNonexistentOrOffline:
3525       DAC960_Error("Logical Drive Nonexistent or Offline on %s:\n",
3526                    Controller, CommandName);
3527       break;
3528     case DAC960_V1_AccessBeyondEndOfLogicalDrive:
3529       DAC960_Error("Attempt to Access Beyond End of Logical Drive "
3530                    "on %s:\n", Controller, CommandName);
3531       break;
3532     case DAC960_V1_BadDataEncountered:
3533       DAC960_Error("Bad Data Encountered on %s:\n", Controller, CommandName);
3534       break;
3535     default:
3536       DAC960_Error("Unexpected Error Status %04X on %s:\n",
3537                    Controller, Command->V1.CommandStatus, CommandName);
3538       break;
3539     }
3540   DAC960_Error("  /dev/rd/c%dd%d:   absolute blocks %u..%u\n",
3541                Controller, Controller->ControllerNumber,
3542                Command->LogicalDriveNumber, Command->BlockNumber,
3543                Command->BlockNumber + Command->BlockCount - 1);
3544 }
3545
3546
3547 /*
3548   DAC960_V1_ProcessCompletedCommand performs completion processing for Command
3549   for DAC960 V1 Firmware Controllers.
3550 */
3551
3552 static void DAC960_V1_ProcessCompletedCommand(DAC960_Command_T *Command)
3553 {
3554   DAC960_Controller_T *Controller = Command->Controller;
3555   DAC960_CommandType_T CommandType = Command->CommandType;
3556   DAC960_V1_CommandOpcode_T CommandOpcode =
3557     Command->V1.CommandMailbox.Common.CommandOpcode;
3558   DAC960_V1_CommandStatus_T CommandStatus = Command->V1.CommandStatus;
3559
3560   if (CommandType == DAC960_ReadCommand ||
3561       CommandType == DAC960_WriteCommand)
3562     {
3563
3564 #ifdef FORCE_RETRY_DEBUG
3565       CommandStatus = DAC960_V1_IrrecoverableDataError;
3566 #endif
3567
3568       if (CommandStatus == DAC960_V1_NormalCompletion) {
3569
3570                 if (!DAC960_ProcessCompletedRequest(Command, true))
3571                         BUG();
3572
3573       } else if (CommandStatus == DAC960_V1_IrrecoverableDataError ||
3574                 CommandStatus == DAC960_V1_BadDataEncountered)
3575         {
3576           /*
3577            * break the command down into pieces and resubmit each
3578            * piece, hoping that some of them will succeed.
3579            */
3580            DAC960_queue_partial_rw(Command);
3581            return;
3582         }
3583       else
3584         {
3585           if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
3586             DAC960_V1_ReadWriteError(Command);
3587
3588          if (!DAC960_ProcessCompletedRequest(Command, false))
3589                 BUG();
3590         }
3591     }
3592   else if (CommandType == DAC960_ReadRetryCommand ||
3593            CommandType == DAC960_WriteRetryCommand)
3594     {
3595       boolean normal_completion;
3596 #ifdef FORCE_RETRY_FAILURE_DEBUG
3597       static int retry_count = 1;
3598 #endif
3599       /*
3600         Perform completion processing for the portion that was
3601         retried, and submit the next portion, if any.
3602       */
3603       normal_completion = true;
3604       if (CommandStatus != DAC960_V1_NormalCompletion) {
3605         normal_completion = false;
3606         if (CommandStatus != DAC960_V1_LogicalDriveNonexistentOrOffline)
3607             DAC960_V1_ReadWriteError(Command);
3608       }
3609
3610 #ifdef FORCE_RETRY_FAILURE_DEBUG
3611       if (!(++retry_count % 10000)) {
3612               printk("V1 error retry failure test\n");
3613               normal_completion = false;
3614               DAC960_V1_ReadWriteError(Command);
3615       }
3616 #endif
3617
3618       if (!DAC960_ProcessCompletedRequest(Command, normal_completion)) {
3619         DAC960_queue_partial_rw(Command);
3620         return;
3621       }
3622     }
3623
3624   else if (CommandType == DAC960_MonitoringCommand)
3625     {
3626       if (Controller->ShutdownMonitoringTimer)
3627               return;
3628       if (CommandOpcode == DAC960_V1_Enquiry)
3629         {
3630           DAC960_V1_Enquiry_T *OldEnquiry = &Controller->V1.Enquiry;
3631           DAC960_V1_Enquiry_T *NewEnquiry = Controller->V1.NewEnquiry;
3632           unsigned int OldCriticalLogicalDriveCount =
3633             OldEnquiry->CriticalLogicalDriveCount;
3634           unsigned int NewCriticalLogicalDriveCount =
3635             NewEnquiry->CriticalLogicalDriveCount;
3636           if (NewEnquiry->NumberOfLogicalDrives > Controller->LogicalDriveCount)
3637             {
3638               int LogicalDriveNumber = Controller->LogicalDriveCount - 1;
3639               while (++LogicalDriveNumber < NewEnquiry->NumberOfLogicalDrives)
3640                 DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3641                                 "Now Exists\n", Controller,
3642                                 LogicalDriveNumber,
3643                                 Controller->ControllerNumber,
3644                                 LogicalDriveNumber);
3645               Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
3646               DAC960_ComputeGenericDiskInfo(Controller);
3647             }
3648           if (NewEnquiry->NumberOfLogicalDrives < Controller->LogicalDriveCount)
3649             {
3650               int LogicalDriveNumber = NewEnquiry->NumberOfLogicalDrives - 1;
3651               while (++LogicalDriveNumber < Controller->LogicalDriveCount)
3652                 DAC960_Critical("Logical Drive %d (/dev/rd/c%dd%d) "
3653                                 "No Longer Exists\n", Controller,
3654                                 LogicalDriveNumber,
3655                                 Controller->ControllerNumber,
3656                                 LogicalDriveNumber);
3657               Controller->LogicalDriveCount = NewEnquiry->NumberOfLogicalDrives;
3658               DAC960_ComputeGenericDiskInfo(Controller);
3659             }
3660           if (NewEnquiry->StatusFlags.DeferredWriteError !=
3661               OldEnquiry->StatusFlags.DeferredWriteError)
3662             DAC960_Critical("Deferred Write Error Flag is now %s\n", Controller,
3663                             (NewEnquiry->StatusFlags.DeferredWriteError
3664                              ? "TRUE" : "FALSE"));
3665           if ((NewCriticalLogicalDriveCount > 0 ||
3666                NewCriticalLogicalDriveCount != OldCriticalLogicalDriveCount) ||
3667               (NewEnquiry->OfflineLogicalDriveCount > 0 ||
3668                NewEnquiry->OfflineLogicalDriveCount !=
3669                OldEnquiry->OfflineLogicalDriveCount) ||
3670               (NewEnquiry->DeadDriveCount > 0 ||
3671                NewEnquiry->DeadDriveCount !=
3672                OldEnquiry->DeadDriveCount) ||
3673               (NewEnquiry->EventLogSequenceNumber !=
3674                OldEnquiry->EventLogSequenceNumber) ||
3675               Controller->MonitoringTimerCount == 0 ||
3676               (jiffies - Controller->SecondaryMonitoringTime
3677                >= DAC960_SecondaryMonitoringInterval))
3678             {
3679               Controller->V1.NeedLogicalDriveInformation = true;
3680               Controller->V1.NewEventLogSequenceNumber =
3681                 NewEnquiry->EventLogSequenceNumber;
3682               Controller->V1.NeedErrorTableInformation = true;
3683               Controller->V1.NeedDeviceStateInformation = true;
3684               Controller->V1.StartDeviceStateScan = true;
3685               Controller->V1.NeedBackgroundInitializationStatus =
3686                 Controller->V1.BackgroundInitializationStatusSupported;
3687               Controller->SecondaryMonitoringTime = jiffies;
3688             }
3689           if (NewEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
3690               NewEnquiry->RebuildFlag
3691               == DAC960_V1_BackgroundRebuildInProgress ||
3692               OldEnquiry->RebuildFlag == DAC960_V1_StandbyRebuildInProgress ||
3693               OldEnquiry->RebuildFlag == DAC960_V1_BackgroundRebuildInProgress)
3694             {
3695               Controller->V1.NeedRebuildProgress = true;
3696               Controller->V1.RebuildProgressFirst =
3697                 (NewEnquiry->CriticalLogicalDriveCount <
3698                  OldEnquiry->CriticalLogicalDriveCount);
3699             }
3700           if (OldEnquiry->RebuildFlag == DAC960_V1_BackgroundCheckInProgress)
3701             switch (NewEnquiry->RebuildFlag)
3702               {
3703               case DAC960_V1_NoStandbyRebuildOrCheckInProgress:
3704                 DAC960_Progress("Consistency Check Completed Successfully\n",
3705                                 Controller);
3706                 break;
3707               case DAC960_V1_StandbyRebuildInProgress:
3708               case DAC960_V1_BackgroundRebuildInProgress:
3709                 break;
3710               case DAC960_V1_BackgroundCheckInProgress:
3711                 Controller->V1.NeedConsistencyCheckProgress = true;
3712                 break;
3713               case DAC960_V1_StandbyRebuildCompletedWithError:
3714                 DAC960_Progress("Consistency Check Completed with Error\n",
3715                                 Controller);
3716                 break;
3717               case DAC960_V1_BackgroundRebuildOrCheckFailed_DriveFailed:
3718                 DAC960_Progress("Consistency Check Failed - "
3719                                 "Physical Device Failed\n", Controller);
3720                 break;
3721               case DAC960_V1_BackgroundRebuildOrCheckFailed_LogicalDriveFailed:
3722                 DAC960_Progress("Consistency Check Failed - "
3723                                 "Logical Drive Failed\n", Controller);
3724                 break;
3725               case DAC960_V1_BackgroundRebuildOrCheckFailed_OtherCauses:
3726                 DAC960_Progress("Consistency Check Failed - Other Causes\n",
3727                                 Controller);
3728                 break;
3729               case DAC960_V1_BackgroundRebuildOrCheckSuccessfullyTerminated:
3730                 DAC960_Progress("Consistency Check Successfully Terminated\n",
3731                                 Controller);
3732                 break;
3733               }
3734           else if (NewEnquiry->RebuildFlag
3735                    == DAC960_V1_BackgroundCheckInProgress)
3736             Controller->V1.NeedConsistencyCheckProgress = true;
3737           Controller->MonitoringAlertMode =
3738             (NewEnquiry->CriticalLogicalDriveCount > 0 ||
3739              NewEnquiry->OfflineLogicalDriveCount > 0 ||
3740              NewEnquiry->DeadDriveCount > 0);
3741           if (NewEnquiry->RebuildFlag > DAC960_V1_BackgroundCheckInProgress)
3742             {
3743               Controller->V1.PendingRebuildFlag = NewEnquiry->RebuildFlag;
3744               Controller->V1.RebuildFlagPending = true;
3745             }
3746           memcpy(&Controller->V1.Enquiry, &Controller->V1.NewEnquiry,
3747                  sizeof(DAC960_V1_Enquiry_T));
3748         }
3749       else if (CommandOpcode == DAC960_V1_PerformEventLogOperation)
3750         {
3751           static char
3752             *DAC960_EventMessages[] =
3753                { "killed because write recovery failed",
3754                  "killed because of SCSI bus reset failure",
3755                  "killed because of double check condition",
3756                  "killed because it was removed",
3757                  "killed because of gross error on SCSI chip",
3758                  "killed because of bad tag returned from drive",
3759                  "killed because of timeout on SCSI command",
3760                  "killed because of reset SCSI command issued from system",
3761                  "killed because busy or parity error count exceeded limit",
3762                  "killed because of 'kill drive' command from system",
3763                  "killed because of selection timeout",
3764                  "killed due to SCSI phase sequence error",
3765                  "killed due to unknown status" };
3766           DAC960_V1_EventLogEntry_T *EventLogEntry =
3767                 Controller->V1.EventLogEntry;
3768           if (EventLogEntry->SequenceNumber ==
3769               Controller->V1.OldEventLogSequenceNumber)
3770             {
3771               unsigned char SenseKey = EventLogEntry->SenseKey;
3772               unsigned char AdditionalSenseCode =
3773                 EventLogEntry->AdditionalSenseCode;
3774               unsigned char AdditionalSenseCodeQualifier =
3775                 EventLogEntry->AdditionalSenseCodeQualifier;
3776               if (SenseKey == DAC960_SenseKey_VendorSpecific &&
3777                   AdditionalSenseCode == 0x80 &&
3778                   AdditionalSenseCodeQualifier <
3779                   sizeof(DAC960_EventMessages) / sizeof(char *))
3780                 DAC960_Critical("Physical Device %d:%d %s\n", Controller,
3781                                 EventLogEntry->Channel,
3782                                 EventLogEntry->TargetID,
3783                                 DAC960_EventMessages[
3784                                   AdditionalSenseCodeQualifier]);
3785               else if (SenseKey == DAC960_SenseKey_UnitAttention &&
3786                        AdditionalSenseCode == 0x29)
3787                 {
3788                   if (Controller->MonitoringTimerCount > 0)
3789                     Controller->V1.DeviceResetCount[EventLogEntry->Channel]
3790                                                    [EventLogEntry->TargetID]++;
3791                 }
3792               else if (!(SenseKey == DAC960_SenseKey_NoSense ||
3793                          (SenseKey == DAC960_SenseKey_NotReady &&
3794                           AdditionalSenseCode == 0x04 &&
3795                           (AdditionalSenseCodeQualifier == 0x01 ||
3796                            AdditionalSenseCodeQualifier == 0x02))))
3797                 {
3798                   DAC960_Critical("Physical Device %d:%d Error Log: "
3799                                   "Sense Key = %X, ASC = %02X, ASCQ = %02X\n",
3800                                   Controller,
3801                                   EventLogEntry->Channel,
3802                                   EventLogEntry->TargetID,
3803                                   SenseKey,
3804                                   AdditionalSenseCode,
3805                                   AdditionalSenseCodeQualifier);
3806                   DAC960_Critical("Physical Device %d:%d Error Log: "
3807                                   "Information = %02X%02X%02X%02X "
3808                                   "%02X%02X%02X%02X\n",
3809                                   Controller,
3810                                   EventLogEntry->Channel,
3811                                   EventLogEntry->TargetID,
3812                                   EventLogEntry->Information[0],
3813                                   EventLogEntry->Information[1],
3814                                   EventLogEntry->Information[2],
3815                                   EventLogEntry->Information[3],
3816                                   EventLogEntry->CommandSpecificInformation[0],
3817                                   EventLogEntry->CommandSpecificInformation[1],
3818                                   EventLogEntry->CommandSpecificInformation[2],
3819                                   EventLogEntry->CommandSpecificInformation[3]);
3820                 }
3821             }
3822           Controller->V1.OldEventLogSequenceNumber++;
3823         }
3824       else if (CommandOpcode == DAC960_V1_GetErrorTable)
3825         {
3826           DAC960_V1_ErrorTable_T *OldErrorTable = &Controller->V1.ErrorTable;
3827           DAC960_V1_ErrorTable_T *NewErrorTable = Controller->V1.NewErrorTable;
3828           int Channel, TargetID;
3829           for (Channel = 0; Channel < Controller->Channels; Channel++)
3830             for (TargetID = 0; TargetID < Controller->Targets; TargetID++)
3831               {
3832                 DAC960_V1_ErrorTableEntry_T *NewErrorEntry =
3833                   &NewErrorTable->ErrorTableEntries[Channel][TargetID];
3834                 DAC960_V1_ErrorTableEntry_T *OldErrorEntry =
3835                   &OldErrorTable->ErrorTableEntries[Channel][TargetID];
3836                 if ((NewErrorEntry->ParityErrorCount !=
3837                      OldErrorEntry->ParityErrorCount) ||
3838                     (NewErrorEntry->SoftErrorCount !=
3839                      OldErrorEntry->SoftErrorCount) ||
3840                     (NewErrorEntry->HardErrorCount !=
3841                      OldErrorEntry->HardErrorCount) ||
3842                     (NewErrorEntry->MiscErrorCount !=
3843                      OldErrorEntry->MiscErrorCount))
3844                   DAC960_Critical("Physical Device %d:%d Errors: "
3845                                   "Parity = %d, Soft = %d, "
3846                                   "Hard = %d, Misc = %d\n",
3847                                   Controller, Channel, TargetID,
3848                                   NewErrorEntry->ParityErrorCount,
3849                                   NewErrorEntry->SoftErrorCount,
3850                                   NewErrorEntry->HardErrorCount,
3851                                   NewErrorEntry->MiscErrorCount);
3852               }
3853           memcpy(&Controller->V1.ErrorTable, Controller->V1.NewErrorTable,
3854                  sizeof(DAC960_V1_ErrorTable_T));
3855         }
3856       else if (CommandOpcode == DAC960_V1_GetDeviceState)
3857         {
3858           DAC960_V1_DeviceState_T *OldDeviceState =
3859             &Controller->V1.DeviceState[Controller->V1.DeviceStateChannel]
3860                                        [Controller->V1.DeviceStateTargetID];
3861           DAC960_V1_DeviceState_T *NewDeviceState =
3862             Controller->V1.NewDeviceState;
3863           if (NewDeviceState->DeviceState != OldDeviceState->DeviceState)
3864             DAC960_Critical("Physical Device %d:%d is now %s\n", Controller,
3865                             Controller->V1.DeviceStateChannel,
3866                             Controller->V1.DeviceStateTargetID,
3867                             (NewDeviceState->DeviceState
3868                              == DAC960_V1_Device_Dead
3869                              ? "DEAD"
3870                              : NewDeviceState->DeviceState
3871                                == DAC960_V1_Device_WriteOnly
3872                                ? "WRITE-ONLY"
3873                                : NewDeviceState->DeviceState
3874                                  == DAC960_V1_Device_Online
3875                                  ? "ONLINE" : "STANDBY"));
3876           if (OldDeviceState->DeviceState == DAC960_V1_Device_Dead &&
3877               NewDeviceState->DeviceState != DAC960_V1_Device_Dead)
3878             {
3879               Controller->V1.NeedDeviceInquiryInformation = true;
3880               Controller->V1.NeedDeviceSerialNumberInformation = true;
3881               Controller->V1.DeviceResetCount
3882                              [Controller->V1.DeviceStateChannel]
3883                              [Controller->V1.DeviceStateTargetID] = 0;
3884             }
3885           memcpy(OldDeviceState, NewDeviceState,
3886                  sizeof(DAC960_V1_DeviceState_T));
3887         }
3888       else if (CommandOpcode == DAC960_V1_GetLogicalDriveInformation)
3889         {
3890           int LogicalDriveNumber;