Merge master.kernel.org:/home/rmk/linux-2.6-arm
[linux-2.6] / drivers / scsi / BusLogic.c
1
2 /*
3
4   Linux Driver for BusLogic MultiMaster and FlashPoint SCSI Host Adapters
5
6   Copyright 1995-1998 by Leonard N. Zubkoff <lnz@dandelion.com>
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   The author respectfully requests that any modifications to this software be
18   sent directly to him for evaluation and testing.
19
20   Special thanks to Wayne Yen, Jin-Lon Hon, and Alex Win of BusLogic, whose
21   advice has been invaluable, to David Gentzel, for writing the original Linux
22   BusLogic driver, and to Paul Gortmaker, for being such a dedicated test site.
23
24   Finally, special thanks to Mylex/BusLogic for making the FlashPoint SCCB
25   Manager available as freely redistributable source code.
26
27 */
28
29 #define BusLogic_DriverVersion          "2.1.16"
30 #define BusLogic_DriverDate             "18 July 2002"
31
32 #include <linux/config.h>
33 #include <linux/module.h>
34 #include <linux/init.h>
35 #include <linux/interrupt.h>
36 #include <linux/types.h>
37 #include <linux/blkdev.h>
38 #include <linux/delay.h>
39 #include <linux/ioport.h>
40 #include <linux/mm.h>
41 #include <linux/stat.h>
42 #include <linux/pci.h>
43 #include <linux/spinlock.h>
44 #include <scsi/scsicam.h>
45
46 #include <asm/dma.h>
47 #include <asm/io.h>
48 #include <asm/system.h>
49
50 #include <scsi/scsi.h>
51 #include <scsi/scsi_cmnd.h>
52 #include <scsi/scsi_device.h>
53 #include <scsi/scsi_host.h>
54 #include <scsi/scsi_tcq.h>
55 #include "BusLogic.h"
56 #include "FlashPoint.c"
57
58 #ifndef FAILURE
59 #define FAILURE (-1)
60 #endif
61
62 static struct scsi_host_template Bus_Logic_template;
63
64 /*
65   BusLogic_DriverOptionsCount is a count of the number of BusLogic Driver
66   Options specifications provided via the Linux Kernel Command Line or via
67   the Loadable Kernel Module Installation Facility.
68 */
69
70 static int BusLogic_DriverOptionsCount;
71
72
73 /*
74   BusLogic_DriverOptions is an array of Driver Options structures representing
75   BusLogic Driver Options specifications provided via the Linux Kernel Command
76   Line or via the Loadable Kernel Module Installation Facility.
77 */
78
79 static struct BusLogic_DriverOptions BusLogic_DriverOptions[BusLogic_MaxHostAdapters];
80
81
82 /*
83   BusLogic can be assigned a string by insmod.
84 */
85
86 MODULE_LICENSE("GPL");
87 #ifdef MODULE
88 static char *BusLogic;
89 module_param(BusLogic, charp, 0);
90 #endif
91
92
93 /*
94   BusLogic_ProbeOptions is a set of Probe Options to be applied across
95   all BusLogic Host Adapters.
96 */
97
98 static struct BusLogic_ProbeOptions BusLogic_ProbeOptions;
99
100
101 /*
102   BusLogic_GlobalOptions is a set of Global Options to be applied across
103   all BusLogic Host Adapters.
104 */
105
106 static struct BusLogic_GlobalOptions BusLogic_GlobalOptions;
107
108 static LIST_HEAD(BusLogic_host_list);
109
110 /*
111   BusLogic_ProbeInfoCount is the number of entries in BusLogic_ProbeInfoList.
112 */
113
114 static int BusLogic_ProbeInfoCount;
115
116
117 /*
118   BusLogic_ProbeInfoList is the list of I/O Addresses and Bus Probe Information
119   to be checked for potential BusLogic Host Adapters.  It is initialized by
120   interrogating the PCI Configuration Space on PCI machines as well as from the
121   list of standard BusLogic I/O Addresses.
122 */
123
124 static struct BusLogic_ProbeInfo *BusLogic_ProbeInfoList;
125
126
127 /*
128   BusLogic_CommandFailureReason holds a string identifying the reason why a
129   call to BusLogic_Command failed.  It is only non-NULL when BusLogic_Command
130   returns a failure code.
131 */
132
133 static char *BusLogic_CommandFailureReason;
134
135 /*
136   BusLogic_AnnounceDriver announces the Driver Version and Date, Author's
137   Name, Copyright Notice, and Electronic Mail Address.
138 */
139
140 static void BusLogic_AnnounceDriver(struct BusLogic_HostAdapter *HostAdapter)
141 {
142         BusLogic_Announce("***** BusLogic SCSI Driver Version " BusLogic_DriverVersion " of " BusLogic_DriverDate " *****\n", HostAdapter);
143         BusLogic_Announce("Copyright 1995-1998 by Leonard N. Zubkoff " "<lnz@dandelion.com>\n", HostAdapter);
144 }
145
146
147 /*
148   BusLogic_DriverInfo returns the Host Adapter Name to identify this SCSI
149   Driver and Host Adapter.
150 */
151
152 static const char *BusLogic_DriverInfo(struct Scsi_Host *Host)
153 {
154         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) Host->hostdata;
155         return HostAdapter->FullModelName;
156 }
157
158 /*
159   BusLogic_InitializeCCBs initializes a group of Command Control Blocks (CCBs)
160   for Host Adapter from the BlockSize bytes located at BlockPointer.  The newly
161   created CCBs are added to Host Adapter's free list.
162 */
163
164 static void BusLogic_InitializeCCBs(struct BusLogic_HostAdapter *HostAdapter, void *BlockPointer, int BlockSize, dma_addr_t BlockPointerHandle)
165 {
166         struct BusLogic_CCB *CCB = (struct BusLogic_CCB *) BlockPointer;
167         unsigned int offset = 0;
168         memset(BlockPointer, 0, BlockSize);
169         CCB->AllocationGroupHead = BlockPointerHandle;
170         CCB->AllocationGroupSize = BlockSize;
171         while ((BlockSize -= sizeof(struct BusLogic_CCB)) >= 0) {
172                 CCB->Status = BusLogic_CCB_Free;
173                 CCB->HostAdapter = HostAdapter;
174                 CCB->DMA_Handle = (u32) BlockPointerHandle + offset;
175                 if (BusLogic_FlashPointHostAdapterP(HostAdapter)) {
176                         CCB->CallbackFunction = BusLogic_QueueCompletedCCB;
177                         CCB->BaseAddress = HostAdapter->FlashPointInfo.BaseAddress;
178                 }
179                 CCB->Next = HostAdapter->Free_CCBs;
180                 CCB->NextAll = HostAdapter->All_CCBs;
181                 HostAdapter->Free_CCBs = CCB;
182                 HostAdapter->All_CCBs = CCB;
183                 HostAdapter->AllocatedCCBs++;
184                 CCB++;
185                 offset += sizeof(struct BusLogic_CCB);
186         }
187 }
188
189
190 /*
191   BusLogic_CreateInitialCCBs allocates the initial CCBs for Host Adapter.
192 */
193
194 static boolean __init BusLogic_CreateInitialCCBs(struct BusLogic_HostAdapter *HostAdapter)
195 {
196         int BlockSize = BusLogic_CCB_AllocationGroupSize * sizeof(struct BusLogic_CCB);
197         void *BlockPointer;
198         dma_addr_t BlockPointerHandle;
199         while (HostAdapter->AllocatedCCBs < HostAdapter->InitialCCBs) {
200                 BlockPointer = pci_alloc_consistent(HostAdapter->PCI_Device, BlockSize, &BlockPointerHandle);
201                 if (BlockPointer == NULL) {
202                         BusLogic_Error("UNABLE TO ALLOCATE CCB GROUP - DETACHING\n", HostAdapter);
203                         return false;
204                 }
205                 BusLogic_InitializeCCBs(HostAdapter, BlockPointer, BlockSize, BlockPointerHandle);
206         }
207         return true;
208 }
209
210
211 /*
212   BusLogic_DestroyCCBs deallocates the CCBs for Host Adapter.
213 */
214
215 static void BusLogic_DestroyCCBs(struct BusLogic_HostAdapter *HostAdapter)
216 {
217         struct BusLogic_CCB *NextCCB = HostAdapter->All_CCBs, *CCB, *Last_CCB = NULL;
218         HostAdapter->All_CCBs = NULL;
219         HostAdapter->Free_CCBs = NULL;
220         while ((CCB = NextCCB) != NULL) {
221                 NextCCB = CCB->NextAll;
222                 if (CCB->AllocationGroupHead) {
223                         if (Last_CCB)
224                                 pci_free_consistent(HostAdapter->PCI_Device, Last_CCB->AllocationGroupSize, Last_CCB, Last_CCB->AllocationGroupHead);
225                         Last_CCB = CCB;
226                 }
227         }
228         if (Last_CCB)
229                 pci_free_consistent(HostAdapter->PCI_Device, Last_CCB->AllocationGroupSize, Last_CCB, Last_CCB->AllocationGroupHead);
230 }
231
232
233 /*
234   BusLogic_CreateAdditionalCCBs allocates Additional CCBs for Host Adapter.  If
235   allocation fails and there are no remaining CCBs available, the Driver Queue
236   Depth is decreased to a known safe value to avoid potential deadlocks when
237   multiple host adapters share the same IRQ Channel.
238 */
239
240 static void BusLogic_CreateAdditionalCCBs(struct BusLogic_HostAdapter *HostAdapter, int AdditionalCCBs, boolean SuccessMessageP)
241 {
242         int BlockSize = BusLogic_CCB_AllocationGroupSize * sizeof(struct BusLogic_CCB);
243         int PreviouslyAllocated = HostAdapter->AllocatedCCBs;
244         void *BlockPointer;
245         dma_addr_t BlockPointerHandle;
246         if (AdditionalCCBs <= 0)
247                 return;
248         while (HostAdapter->AllocatedCCBs - PreviouslyAllocated < AdditionalCCBs) {
249                 BlockPointer = pci_alloc_consistent(HostAdapter->PCI_Device, BlockSize, &BlockPointerHandle);
250                 if (BlockPointer == NULL)
251                         break;
252                 BusLogic_InitializeCCBs(HostAdapter, BlockPointer, BlockSize, BlockPointerHandle);
253         }
254         if (HostAdapter->AllocatedCCBs > PreviouslyAllocated) {
255                 if (SuccessMessageP)
256                         BusLogic_Notice("Allocated %d additional CCBs (total now %d)\n", HostAdapter, HostAdapter->AllocatedCCBs - PreviouslyAllocated, HostAdapter->AllocatedCCBs);
257                 return;
258         }
259         BusLogic_Notice("Failed to allocate additional CCBs\n", HostAdapter);
260         if (HostAdapter->DriverQueueDepth > HostAdapter->AllocatedCCBs - HostAdapter->TargetDeviceCount) {
261                 HostAdapter->DriverQueueDepth = HostAdapter->AllocatedCCBs - HostAdapter->TargetDeviceCount;
262                 HostAdapter->SCSI_Host->can_queue = HostAdapter->DriverQueueDepth;
263         }
264 }
265
266 /*
267   BusLogic_AllocateCCB allocates a CCB from Host Adapter's free list,
268   allocating more memory from the Kernel if necessary.  The Host Adapter's
269   Lock should already have been acquired by the caller.
270 */
271
272 static struct BusLogic_CCB *BusLogic_AllocateCCB(struct BusLogic_HostAdapter
273                                                  *HostAdapter)
274 {
275         static unsigned long SerialNumber = 0;
276         struct BusLogic_CCB *CCB;
277         CCB = HostAdapter->Free_CCBs;
278         if (CCB != NULL) {
279                 CCB->SerialNumber = ++SerialNumber;
280                 HostAdapter->Free_CCBs = CCB->Next;
281                 CCB->Next = NULL;
282                 if (HostAdapter->Free_CCBs == NULL)
283                         BusLogic_CreateAdditionalCCBs(HostAdapter, HostAdapter->IncrementalCCBs, true);
284                 return CCB;
285         }
286         BusLogic_CreateAdditionalCCBs(HostAdapter, HostAdapter->IncrementalCCBs, true);
287         CCB = HostAdapter->Free_CCBs;
288         if (CCB == NULL)
289                 return NULL;
290         CCB->SerialNumber = ++SerialNumber;
291         HostAdapter->Free_CCBs = CCB->Next;
292         CCB->Next = NULL;
293         return CCB;
294 }
295
296
297 /*
298   BusLogic_DeallocateCCB deallocates a CCB, returning it to the Host Adapter's
299   free list.  The Host Adapter's Lock should already have been acquired by the
300   caller.
301 */
302
303 static void BusLogic_DeallocateCCB(struct BusLogic_CCB *CCB)
304 {
305         struct BusLogic_HostAdapter *HostAdapter = CCB->HostAdapter;
306         struct scsi_cmnd *cmd = CCB->Command;
307
308         if (cmd->use_sg != 0) {
309                 pci_unmap_sg(HostAdapter->PCI_Device,
310                                 (struct scatterlist *)cmd->request_buffer,
311                                 cmd->use_sg, cmd->sc_data_direction);
312         } else if (cmd->request_bufflen != 0) {
313                 pci_unmap_single(HostAdapter->PCI_Device, CCB->DataPointer,
314                                 CCB->DataLength, cmd->sc_data_direction);
315         }
316         pci_unmap_single(HostAdapter->PCI_Device, CCB->SenseDataPointer,
317                         CCB->SenseDataLength, PCI_DMA_FROMDEVICE);
318
319         CCB->Command = NULL;
320         CCB->Status = BusLogic_CCB_Free;
321         CCB->Next = HostAdapter->Free_CCBs;
322         HostAdapter->Free_CCBs = CCB;
323 }
324
325
326 /*
327   BusLogic_Command sends the command OperationCode to HostAdapter, optionally
328   providing ParameterLength bytes of ParameterData and receiving at most
329   ReplyLength bytes of ReplyData; any excess reply data is received but
330   discarded.
331
332   On success, this function returns the number of reply bytes read from
333   the Host Adapter (including any discarded data); on failure, it returns
334   -1 if the command was invalid, or -2 if a timeout occurred.
335
336   BusLogic_Command is called exclusively during host adapter detection and
337   initialization, so performance and latency are not critical, and exclusive
338   access to the Host Adapter hardware is assumed.  Once the host adapter and
339   driver are initialized, the only Host Adapter command that is issued is the
340   single byte Execute Mailbox Command operation code, which does not require
341   waiting for the Host Adapter Ready bit to be set in the Status Register.
342 */
343
344 static int BusLogic_Command(struct BusLogic_HostAdapter *HostAdapter, enum BusLogic_OperationCode OperationCode, void *ParameterData, int ParameterLength, void *ReplyData, int ReplyLength)
345 {
346         unsigned char *ParameterPointer = (unsigned char *) ParameterData;
347         unsigned char *ReplyPointer = (unsigned char *) ReplyData;
348         union BusLogic_StatusRegister StatusRegister;
349         union BusLogic_InterruptRegister InterruptRegister;
350         unsigned long ProcessorFlags = 0;
351         int ReplyBytes = 0, Result;
352         long TimeoutCounter;
353         /*
354            Clear out the Reply Data if provided.
355          */
356         if (ReplyLength > 0)
357                 memset(ReplyData, 0, ReplyLength);
358         /*
359            If the IRQ Channel has not yet been acquired, then interrupts must be
360            disabled while issuing host adapter commands since a Command Complete
361            interrupt could occur if the IRQ Channel was previously enabled by another
362            BusLogic Host Adapter or another driver sharing the same IRQ Channel.
363          */
364         if (!HostAdapter->IRQ_ChannelAcquired) {
365                 local_irq_save(ProcessorFlags);
366                 local_irq_disable();
367         }
368         /*
369            Wait for the Host Adapter Ready bit to be set and the Command/Parameter
370            Register Busy bit to be reset in the Status Register.
371          */
372         TimeoutCounter = 10000;
373         while (--TimeoutCounter >= 0) {
374                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
375                 if (StatusRegister.sr.HostAdapterReady && !StatusRegister.sr.CommandParameterRegisterBusy)
376                         break;
377                 udelay(100);
378         }
379         if (TimeoutCounter < 0) {
380                 BusLogic_CommandFailureReason = "Timeout waiting for Host Adapter Ready";
381                 Result = -2;
382                 goto Done;
383         }
384         /*
385            Write the OperationCode to the Command/Parameter Register.
386          */
387         HostAdapter->HostAdapterCommandCompleted = false;
388         BusLogic_WriteCommandParameterRegister(HostAdapter, OperationCode);
389         /*
390            Write any additional Parameter Bytes.
391          */
392         TimeoutCounter = 10000;
393         while (ParameterLength > 0 && --TimeoutCounter >= 0) {
394                 /*
395                    Wait 100 microseconds to give the Host Adapter enough time to determine
396                    whether the last value written to the Command/Parameter Register was
397                    valid or not.  If the Command Complete bit is set in the Interrupt
398                    Register, then the Command Invalid bit in the Status Register will be
399                    reset if the Operation Code or Parameter was valid and the command
400                    has completed, or set if the Operation Code or Parameter was invalid.
401                    If the Data In Register Ready bit is set in the Status Register, then
402                    the Operation Code was valid, and data is waiting to be read back
403                    from the Host Adapter.  Otherwise, wait for the Command/Parameter
404                    Register Busy bit in the Status Register to be reset.
405                  */
406                 udelay(100);
407                 InterruptRegister.All = BusLogic_ReadInterruptRegister(HostAdapter);
408                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
409                 if (InterruptRegister.ir.CommandComplete)
410                         break;
411                 if (HostAdapter->HostAdapterCommandCompleted)
412                         break;
413                 if (StatusRegister.sr.DataInRegisterReady)
414                         break;
415                 if (StatusRegister.sr.CommandParameterRegisterBusy)
416                         continue;
417                 BusLogic_WriteCommandParameterRegister(HostAdapter, *ParameterPointer++);
418                 ParameterLength--;
419         }
420         if (TimeoutCounter < 0) {
421                 BusLogic_CommandFailureReason = "Timeout waiting for Parameter Acceptance";
422                 Result = -2;
423                 goto Done;
424         }
425         /*
426            The Modify I/O Address command does not cause a Command Complete Interrupt.
427          */
428         if (OperationCode == BusLogic_ModifyIOAddress) {
429                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
430                 if (StatusRegister.sr.CommandInvalid) {
431                         BusLogic_CommandFailureReason = "Modify I/O Address Invalid";
432                         Result = -1;
433                         goto Done;
434                 }
435                 if (BusLogic_GlobalOptions.TraceConfiguration)
436                         BusLogic_Notice("BusLogic_Command(%02X) Status = %02X: " "(Modify I/O Address)\n", HostAdapter, OperationCode, StatusRegister.All);
437                 Result = 0;
438                 goto Done;
439         }
440         /*
441            Select an appropriate timeout value for awaiting command completion.
442          */
443         switch (OperationCode) {
444         case BusLogic_InquireInstalledDevicesID0to7:
445         case BusLogic_InquireInstalledDevicesID8to15:
446         case BusLogic_InquireTargetDevices:
447                 /* Approximately 60 seconds. */
448                 TimeoutCounter = 60 * 10000;
449                 break;
450         default:
451                 /* Approximately 1 second. */
452                 TimeoutCounter = 10000;
453                 break;
454         }
455         /*
456            Receive any Reply Bytes, waiting for either the Command Complete bit to
457            be set in the Interrupt Register, or for the Interrupt Handler to set the
458            Host Adapter Command Completed bit in the Host Adapter structure.
459          */
460         while (--TimeoutCounter >= 0) {
461                 InterruptRegister.All = BusLogic_ReadInterruptRegister(HostAdapter);
462                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
463                 if (InterruptRegister.ir.CommandComplete)
464                         break;
465                 if (HostAdapter->HostAdapterCommandCompleted)
466                         break;
467                 if (StatusRegister.sr.DataInRegisterReady) {
468                         if (++ReplyBytes <= ReplyLength)
469                                 *ReplyPointer++ = BusLogic_ReadDataInRegister(HostAdapter);
470                         else
471                                 BusLogic_ReadDataInRegister(HostAdapter);
472                 }
473                 if (OperationCode == BusLogic_FetchHostAdapterLocalRAM && StatusRegister.sr.HostAdapterReady)
474                         break;
475                 udelay(100);
476         }
477         if (TimeoutCounter < 0) {
478                 BusLogic_CommandFailureReason = "Timeout waiting for Command Complete";
479                 Result = -2;
480                 goto Done;
481         }
482         /*
483            Clear any pending Command Complete Interrupt.
484          */
485         BusLogic_InterruptReset(HostAdapter);
486         /*
487            Provide tracing information if requested.
488          */
489         if (BusLogic_GlobalOptions.TraceConfiguration) {
490                 int i;
491                 BusLogic_Notice("BusLogic_Command(%02X) Status = %02X: %2d ==> %2d:", HostAdapter, OperationCode, StatusRegister.All, ReplyLength, ReplyBytes);
492                 if (ReplyLength > ReplyBytes)
493                         ReplyLength = ReplyBytes;
494                 for (i = 0; i < ReplyLength; i++)
495                         BusLogic_Notice(" %02X", HostAdapter, ((unsigned char *) ReplyData)[i]);
496                 BusLogic_Notice("\n", HostAdapter);
497         }
498         /*
499            Process Command Invalid conditions.
500          */
501         if (StatusRegister.sr.CommandInvalid) {
502                 /*
503                    Some early BusLogic Host Adapters may not recover properly from
504                    a Command Invalid condition, so if this appears to be the case,
505                    a Soft Reset is issued to the Host Adapter.  Potentially invalid
506                    commands are never attempted after Mailbox Initialization is
507                    performed, so there should be no Host Adapter state lost by a
508                    Soft Reset in response to a Command Invalid condition.
509                  */
510                 udelay(1000);
511                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
512                 if (StatusRegister.sr.CommandInvalid ||
513                     StatusRegister.sr.Reserved ||
514                     StatusRegister.sr.DataInRegisterReady ||
515                     StatusRegister.sr.CommandParameterRegisterBusy || !StatusRegister.sr.HostAdapterReady || !StatusRegister.sr.InitializationRequired || StatusRegister.sr.DiagnosticActive || StatusRegister.sr.DiagnosticFailure) {
516                         BusLogic_SoftReset(HostAdapter);
517                         udelay(1000);
518                 }
519                 BusLogic_CommandFailureReason = "Command Invalid";
520                 Result = -1;
521                 goto Done;
522         }
523         /*
524            Handle Excess Parameters Supplied conditions.
525          */
526         if (ParameterLength > 0) {
527                 BusLogic_CommandFailureReason = "Excess Parameters Supplied";
528                 Result = -1;
529                 goto Done;
530         }
531         /*
532            Indicate the command completed successfully.
533          */
534         BusLogic_CommandFailureReason = NULL;
535         Result = ReplyBytes;
536         /*
537            Restore the interrupt status if necessary and return.
538          */
539       Done:
540         if (!HostAdapter->IRQ_ChannelAcquired)
541                 local_irq_restore(ProcessorFlags);
542         return Result;
543 }
544
545
546 /*
547   BusLogic_AppendProbeAddressISA appends a single ISA I/O Address to the list
548   of I/O Address and Bus Probe Information to be checked for potential BusLogic
549   Host Adapters.
550 */
551
552 static void __init BusLogic_AppendProbeAddressISA(unsigned long IO_Address)
553 {
554         struct BusLogic_ProbeInfo *ProbeInfo;
555         if (BusLogic_ProbeInfoCount >= BusLogic_MaxHostAdapters)
556                 return;
557         ProbeInfo = &BusLogic_ProbeInfoList[BusLogic_ProbeInfoCount++];
558         ProbeInfo->HostAdapterType = BusLogic_MultiMaster;
559         ProbeInfo->HostAdapterBusType = BusLogic_ISA_Bus;
560         ProbeInfo->IO_Address = IO_Address;
561         ProbeInfo->PCI_Device = NULL;
562 }
563
564
565 /*
566   BusLogic_InitializeProbeInfoListISA initializes the list of I/O Address and
567   Bus Probe Information to be checked for potential BusLogic SCSI Host Adapters
568   only from the list of standard BusLogic MultiMaster ISA I/O Addresses.
569 */
570
571 static void __init BusLogic_InitializeProbeInfoListISA(struct BusLogic_HostAdapter
572                                                        *PrototypeHostAdapter)
573 {
574         /*
575            If BusLogic Driver Options specifications requested that ISA Bus Probes
576            be inhibited, do not proceed further.
577          */
578         if (BusLogic_ProbeOptions.NoProbeISA)
579                 return;
580         /*
581            Append the list of standard BusLogic MultiMaster ISA I/O Addresses.
582          */
583         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe330 : check_region(0x330, BusLogic_MultiMasterAddressCount) == 0)
584                 BusLogic_AppendProbeAddressISA(0x330);
585         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe334 : check_region(0x334, BusLogic_MultiMasterAddressCount) == 0)
586                 BusLogic_AppendProbeAddressISA(0x334);
587         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe230 : check_region(0x230, BusLogic_MultiMasterAddressCount) == 0)
588                 BusLogic_AppendProbeAddressISA(0x230);
589         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe234 : check_region(0x234, BusLogic_MultiMasterAddressCount) == 0)
590                 BusLogic_AppendProbeAddressISA(0x234);
591         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe130 : check_region(0x130, BusLogic_MultiMasterAddressCount) == 0)
592                 BusLogic_AppendProbeAddressISA(0x130);
593         if (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe134 : check_region(0x134, BusLogic_MultiMasterAddressCount) == 0)
594                 BusLogic_AppendProbeAddressISA(0x134);
595 }
596
597
598 #ifdef CONFIG_PCI
599
600
601 /*
602   BusLogic_SortProbeInfo sorts a section of BusLogic_ProbeInfoList in order
603   of increasing PCI Bus and Device Number.
604 */
605
606 static void __init BusLogic_SortProbeInfo(struct BusLogic_ProbeInfo *ProbeInfoList, int ProbeInfoCount)
607 {
608         int LastInterchange = ProbeInfoCount - 1, Bound, j;
609         while (LastInterchange > 0) {
610                 Bound = LastInterchange;
611                 LastInterchange = 0;
612                 for (j = 0; j < Bound; j++) {
613                         struct BusLogic_ProbeInfo *ProbeInfo1 = &ProbeInfoList[j];
614                         struct BusLogic_ProbeInfo *ProbeInfo2 = &ProbeInfoList[j + 1];
615                         if (ProbeInfo1->Bus > ProbeInfo2->Bus || (ProbeInfo1->Bus == ProbeInfo2->Bus && (ProbeInfo1->Device > ProbeInfo2->Device))) {
616                                 struct BusLogic_ProbeInfo TempProbeInfo;
617                                 memcpy(&TempProbeInfo, ProbeInfo1, sizeof(struct BusLogic_ProbeInfo));
618                                 memcpy(ProbeInfo1, ProbeInfo2, sizeof(struct BusLogic_ProbeInfo));
619                                 memcpy(ProbeInfo2, &TempProbeInfo, sizeof(struct BusLogic_ProbeInfo));
620                                 LastInterchange = j;
621                         }
622                 }
623         }
624 }
625
626
627 /*
628   BusLogic_InitializeMultiMasterProbeInfo initializes the list of I/O Address
629   and Bus Probe Information to be checked for potential BusLogic MultiMaster
630   SCSI Host Adapters by interrogating the PCI Configuration Space on PCI
631   machines as well as from the list of standard BusLogic MultiMaster ISA
632   I/O Addresses.  It returns the number of PCI MultiMaster Host Adapters found.
633 */
634
635 static int __init BusLogic_InitializeMultiMasterProbeInfo(struct BusLogic_HostAdapter
636                                                           *PrototypeHostAdapter)
637 {
638         struct BusLogic_ProbeInfo *PrimaryProbeInfo = &BusLogic_ProbeInfoList[BusLogic_ProbeInfoCount];
639         int NonPrimaryPCIMultiMasterIndex = BusLogic_ProbeInfoCount + 1;
640         int NonPrimaryPCIMultiMasterCount = 0, PCIMultiMasterCount = 0;
641         boolean ForceBusDeviceScanningOrder = false;
642         boolean ForceBusDeviceScanningOrderChecked = false;
643         boolean StandardAddressSeen[6];
644         struct pci_dev *PCI_Device = NULL;
645         int i;
646         if (BusLogic_ProbeInfoCount >= BusLogic_MaxHostAdapters)
647                 return 0;
648         BusLogic_ProbeInfoCount++;
649         for (i = 0; i < 6; i++)
650                 StandardAddressSeen[i] = false;
651         /*
652            Iterate over the MultiMaster PCI Host Adapters.  For each enumerated host
653            adapter, determine whether its ISA Compatible I/O Port is enabled and if
654            so, whether it is assigned the Primary I/O Address.  A host adapter that is
655            assigned the Primary I/O Address will always be the preferred boot device.
656            The MultiMaster BIOS will first recognize a host adapter at the Primary I/O
657            Address, then any other PCI host adapters, and finally any host adapters
658            located at the remaining standard ISA I/O Addresses.  When a PCI host
659            adapter is found with its ISA Compatible I/O Port enabled, a command is
660            issued to disable the ISA Compatible I/O Port, and it is noted that the
661            particular standard ISA I/O Address need not be probed.
662          */
663         PrimaryProbeInfo->IO_Address = 0;
664         while ((PCI_Device = pci_find_device(PCI_VENDOR_ID_BUSLOGIC, PCI_DEVICE_ID_BUSLOGIC_MULTIMASTER, PCI_Device)) != NULL) {
665                 struct BusLogic_HostAdapter *HostAdapter = PrototypeHostAdapter;
666                 struct BusLogic_PCIHostAdapterInformation PCIHostAdapterInformation;
667                 enum BusLogic_ISACompatibleIOPort ModifyIOAddressRequest;
668                 unsigned char Bus;
669                 unsigned char Device;
670                 unsigned int IRQ_Channel;
671                 unsigned long BaseAddress0;
672                 unsigned long BaseAddress1;
673                 unsigned long IO_Address;
674                 unsigned long PCI_Address;
675
676                 if (pci_enable_device(PCI_Device))
677                         continue;
678
679                 if (pci_set_dma_mask(PCI_Device, (u64) 0xffffffff))
680                         continue;
681
682                 Bus = PCI_Device->bus->number;
683                 Device = PCI_Device->devfn >> 3;
684                 IRQ_Channel = PCI_Device->irq;
685                 IO_Address = BaseAddress0 = pci_resource_start(PCI_Device, 0);
686                 PCI_Address = BaseAddress1 = pci_resource_start(PCI_Device, 1);
687
688                 if (pci_resource_flags(PCI_Device, 0) & IORESOURCE_MEM) {
689                         BusLogic_Error("BusLogic: Base Address0 0x%X not I/O for " "MultiMaster Host Adapter\n", NULL, BaseAddress0);
690                         BusLogic_Error("at PCI Bus %d Device %d I/O Address 0x%X\n", NULL, Bus, Device, IO_Address);
691                         continue;
692                 }
693                 if (pci_resource_flags(PCI_Device, 1) & IORESOURCE_IO) {
694                         BusLogic_Error("BusLogic: Base Address1 0x%X not Memory for " "MultiMaster Host Adapter\n", NULL, BaseAddress1);
695                         BusLogic_Error("at PCI Bus %d Device %d PCI Address 0x%X\n", NULL, Bus, Device, PCI_Address);
696                         continue;
697                 }
698                 if (IRQ_Channel == 0) {
699                         BusLogic_Error("BusLogic: IRQ Channel %d invalid for " "MultiMaster Host Adapter\n", NULL, IRQ_Channel);
700                         BusLogic_Error("at PCI Bus %d Device %d I/O Address 0x%X\n", NULL, Bus, Device, IO_Address);
701                         continue;
702                 }
703                 if (BusLogic_GlobalOptions.TraceProbe) {
704                         BusLogic_Notice("BusLogic: PCI MultiMaster Host Adapter " "detected at\n", NULL);
705                         BusLogic_Notice("BusLogic: PCI Bus %d Device %d I/O Address " "0x%X PCI Address 0x%X\n", NULL, Bus, Device, IO_Address, PCI_Address);
706                 }
707                 /*
708                    Issue the Inquire PCI Host Adapter Information command to determine
709                    the ISA Compatible I/O Port.  If the ISA Compatible I/O Port is
710                    known and enabled, note that the particular Standard ISA I/O
711                    Address should not be probed.
712                  */
713                 HostAdapter->IO_Address = IO_Address;
714                 BusLogic_InterruptReset(HostAdapter);
715                 if (BusLogic_Command(HostAdapter, BusLogic_InquirePCIHostAdapterInformation, NULL, 0, &PCIHostAdapterInformation, sizeof(PCIHostAdapterInformation))
716                     == sizeof(PCIHostAdapterInformation)) {
717                         if (PCIHostAdapterInformation.ISACompatibleIOPort < 6)
718                                 StandardAddressSeen[PCIHostAdapterInformation.ISACompatibleIOPort] = true;
719                 } else
720                         PCIHostAdapterInformation.ISACompatibleIOPort = BusLogic_IO_Disable;
721                 /*
722                  * Issue the Modify I/O Address command to disable the ISA Compatible
723                  * I/O Port.  On PCI Host Adapters, the Modify I/O Address command
724                  * allows modification of the ISA compatible I/O Address that the Host
725                  * Adapter responds to; it does not affect the PCI compliant I/O Address
726                  * assigned at system initialization.
727                  */
728                 ModifyIOAddressRequest = BusLogic_IO_Disable;
729                 BusLogic_Command(HostAdapter, BusLogic_ModifyIOAddress, &ModifyIOAddressRequest, sizeof(ModifyIOAddressRequest), NULL, 0);
730                 /*
731                    For the first MultiMaster Host Adapter enumerated, issue the Fetch
732                    Host Adapter Local RAM command to read byte 45 of the AutoSCSI area,
733                    for the setting of the "Use Bus And Device # For PCI Scanning Seq."
734                    option.  Issue the Inquire Board ID command since this option is
735                    only valid for the BT-948/958/958D.
736                  */
737                 if (!ForceBusDeviceScanningOrderChecked) {
738                         struct BusLogic_FetchHostAdapterLocalRAMRequest FetchHostAdapterLocalRAMRequest;
739                         struct BusLogic_AutoSCSIByte45 AutoSCSIByte45;
740                         struct BusLogic_BoardID BoardID;
741                         FetchHostAdapterLocalRAMRequest.ByteOffset = BusLogic_AutoSCSI_BaseOffset + 45;
742                         FetchHostAdapterLocalRAMRequest.ByteCount = sizeof(AutoSCSIByte45);
743                         BusLogic_Command(HostAdapter, BusLogic_FetchHostAdapterLocalRAM, &FetchHostAdapterLocalRAMRequest, sizeof(FetchHostAdapterLocalRAMRequest), &AutoSCSIByte45, sizeof(AutoSCSIByte45));
744                         BusLogic_Command(HostAdapter, BusLogic_InquireBoardID, NULL, 0, &BoardID, sizeof(BoardID));
745                         if (BoardID.FirmwareVersion1stDigit == '5')
746                                 ForceBusDeviceScanningOrder = AutoSCSIByte45.ForceBusDeviceScanningOrder;
747                         ForceBusDeviceScanningOrderChecked = true;
748                 }
749                 /*
750                    Determine whether this MultiMaster Host Adapter has its ISA
751                    Compatible I/O Port enabled and is assigned the Primary I/O Address.
752                    If it does, then it is the Primary MultiMaster Host Adapter and must
753                    be recognized first.  If it does not, then it is added to the list
754                    for probing after any Primary MultiMaster Host Adapter is probed.
755                  */
756                 if (PCIHostAdapterInformation.ISACompatibleIOPort == BusLogic_IO_330) {
757                         PrimaryProbeInfo->HostAdapterType = BusLogic_MultiMaster;
758                         PrimaryProbeInfo->HostAdapterBusType = BusLogic_PCI_Bus;
759                         PrimaryProbeInfo->IO_Address = IO_Address;
760                         PrimaryProbeInfo->PCI_Address = PCI_Address;
761                         PrimaryProbeInfo->Bus = Bus;
762                         PrimaryProbeInfo->Device = Device;
763                         PrimaryProbeInfo->IRQ_Channel = IRQ_Channel;
764                         PrimaryProbeInfo->PCI_Device = PCI_Device;
765                         PCIMultiMasterCount++;
766                 } else if (BusLogic_ProbeInfoCount < BusLogic_MaxHostAdapters) {
767                         struct BusLogic_ProbeInfo *ProbeInfo = &BusLogic_ProbeInfoList[BusLogic_ProbeInfoCount++];
768                         ProbeInfo->HostAdapterType = BusLogic_MultiMaster;
769                         ProbeInfo->HostAdapterBusType = BusLogic_PCI_Bus;
770                         ProbeInfo->IO_Address = IO_Address;
771                         ProbeInfo->PCI_Address = PCI_Address;
772                         ProbeInfo->Bus = Bus;
773                         ProbeInfo->Device = Device;
774                         ProbeInfo->IRQ_Channel = IRQ_Channel;
775                         ProbeInfo->PCI_Device = PCI_Device;
776                         NonPrimaryPCIMultiMasterCount++;
777                         PCIMultiMasterCount++;
778                 } else
779                         BusLogic_Warning("BusLogic: Too many Host Adapters " "detected\n", NULL);
780         }
781         /*
782            If the AutoSCSI "Use Bus And Device # For PCI Scanning Seq." option is ON
783            for the first enumerated MultiMaster Host Adapter, and if that host adapter
784            is a BT-948/958/958D, then the MultiMaster BIOS will recognize MultiMaster
785            Host Adapters in the order of increasing PCI Bus and Device Number.  In
786            that case, sort the probe information into the same order the BIOS uses.
787            If this option is OFF, then the MultiMaster BIOS will recognize MultiMaster
788            Host Adapters in the order they are enumerated by the PCI BIOS, and hence
789            no sorting is necessary.
790          */
791         if (ForceBusDeviceScanningOrder)
792                 BusLogic_SortProbeInfo(&BusLogic_ProbeInfoList[NonPrimaryPCIMultiMasterIndex], NonPrimaryPCIMultiMasterCount);
793         /*
794            If no PCI MultiMaster Host Adapter is assigned the Primary I/O Address,
795            then the Primary I/O Address must be probed explicitly before any PCI
796            host adapters are probed.
797          */
798         if (!BusLogic_ProbeOptions.NoProbeISA)
799                 if (PrimaryProbeInfo->IO_Address == 0 && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe330 : check_region(0x330, BusLogic_MultiMasterAddressCount) == 0)) {
800                         PrimaryProbeInfo->HostAdapterType = BusLogic_MultiMaster;
801                         PrimaryProbeInfo->HostAdapterBusType = BusLogic_ISA_Bus;
802                         PrimaryProbeInfo->IO_Address = 0x330;
803                 }
804         /*
805            Append the list of standard BusLogic MultiMaster ISA I/O Addresses,
806            omitting the Primary I/O Address which has already been handled.
807          */
808         if (!BusLogic_ProbeOptions.NoProbeISA) {
809                 if (!StandardAddressSeen[1] && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe334 : check_region(0x334, BusLogic_MultiMasterAddressCount) == 0))
810                         BusLogic_AppendProbeAddressISA(0x334);
811                 if (!StandardAddressSeen[2] && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe230 : check_region(0x230, BusLogic_MultiMasterAddressCount) == 0))
812                         BusLogic_AppendProbeAddressISA(0x230);
813                 if (!StandardAddressSeen[3] && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe234 : check_region(0x234, BusLogic_MultiMasterAddressCount) == 0))
814                         BusLogic_AppendProbeAddressISA(0x234);
815                 if (!StandardAddressSeen[4] && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe130 : check_region(0x130, BusLogic_MultiMasterAddressCount) == 0))
816                         BusLogic_AppendProbeAddressISA(0x130);
817                 if (!StandardAddressSeen[5] && (BusLogic_ProbeOptions.LimitedProbeISA ? BusLogic_ProbeOptions.Probe134 : check_region(0x134, BusLogic_MultiMasterAddressCount) == 0))
818                         BusLogic_AppendProbeAddressISA(0x134);
819         }
820         /*
821            Iterate over the older non-compliant MultiMaster PCI Host Adapters,
822            noting the PCI bus location and assigned IRQ Channel.
823          */
824         PCI_Device = NULL;
825         while ((PCI_Device = pci_find_device(PCI_VENDOR_ID_BUSLOGIC, PCI_DEVICE_ID_BUSLOGIC_MULTIMASTER_NC, PCI_Device)) != NULL) {
826                 unsigned char Bus;
827                 unsigned char Device;
828                 unsigned int IRQ_Channel;
829                 unsigned long IO_Address;
830
831                 if (pci_enable_device(PCI_Device))
832                         continue;
833
834                 if (pci_set_dma_mask(PCI_Device, (u64) 0xffffffff))
835                         continue;
836
837                 Bus = PCI_Device->bus->number;
838                 Device = PCI_Device->devfn >> 3;
839                 IRQ_Channel = PCI_Device->irq;
840                 IO_Address = pci_resource_start(PCI_Device, 0);
841
842                 if (IO_Address == 0 || IRQ_Channel == 0)
843                         continue;
844                 for (i = 0; i < BusLogic_ProbeInfoCount; i++) {
845                         struct BusLogic_ProbeInfo *ProbeInfo = &BusLogic_ProbeInfoList[i];
846                         if (ProbeInfo->IO_Address == IO_Address && ProbeInfo->HostAdapterType == BusLogic_MultiMaster) {
847                                 ProbeInfo->HostAdapterBusType = BusLogic_PCI_Bus;
848                                 ProbeInfo->PCI_Address = 0;
849                                 ProbeInfo->Bus = Bus;
850                                 ProbeInfo->Device = Device;
851                                 ProbeInfo->IRQ_Channel = IRQ_Channel;
852                                 ProbeInfo->PCI_Device = PCI_Device;
853                                 break;
854                         }
855                 }
856         }
857         return PCIMultiMasterCount;
858 }
859
860
861 /*
862   BusLogic_InitializeFlashPointProbeInfo initializes the list of I/O Address
863   and Bus Probe Information to be checked for potential BusLogic FlashPoint
864   Host Adapters by interrogating the PCI Configuration Space.  It returns the
865   number of FlashPoint Host Adapters found.
866 */
867
868 static int __init BusLogic_InitializeFlashPointProbeInfo(struct BusLogic_HostAdapter
869                                                          *PrototypeHostAdapter)
870 {
871         int FlashPointIndex = BusLogic_ProbeInfoCount, FlashPointCount = 0;
872         struct pci_dev *PCI_Device = NULL;
873         /*
874            Interrogate PCI Configuration Space for any FlashPoint Host Adapters.
875          */
876         while ((PCI_Device = pci_find_device(PCI_VENDOR_ID_BUSLOGIC, PCI_DEVICE_ID_BUSLOGIC_FLASHPOINT, PCI_Device)) != NULL) {
877                 unsigned char Bus;
878                 unsigned char Device;
879                 unsigned int IRQ_Channel;
880                 unsigned long BaseAddress0;
881                 unsigned long BaseAddress1;
882                 unsigned long IO_Address;
883                 unsigned long PCI_Address;
884
885                 if (pci_enable_device(PCI_Device))
886                         continue;
887
888                 if (pci_set_dma_mask(PCI_Device, (u64) 0xffffffff))
889                         continue;
890
891                 Bus = PCI_Device->bus->number;
892                 Device = PCI_Device->devfn >> 3;
893                 IRQ_Channel = PCI_Device->irq;
894                 IO_Address = BaseAddress0 = pci_resource_start(PCI_Device, 0);
895                 PCI_Address = BaseAddress1 = pci_resource_start(PCI_Device, 1);
896 #ifndef CONFIG_SCSI_OMIT_FLASHPOINT
897                 if (pci_resource_flags(PCI_Device, 0) & IORESOURCE_MEM) {
898                         BusLogic_Error("BusLogic: Base Address0 0x%X not I/O for " "FlashPoint Host Adapter\n", NULL, BaseAddress0);
899                         BusLogic_Error("at PCI Bus %d Device %d I/O Address 0x%X\n", NULL, Bus, Device, IO_Address);
900                         continue;
901                 }
902                 if (pci_resource_flags(PCI_Device, 1) & IORESOURCE_IO) {
903                         BusLogic_Error("BusLogic: Base Address1 0x%X not Memory for " "FlashPoint Host Adapter\n", NULL, BaseAddress1);
904                         BusLogic_Error("at PCI Bus %d Device %d PCI Address 0x%X\n", NULL, Bus, Device, PCI_Address);
905                         continue;
906                 }
907                 if (IRQ_Channel == 0) {
908                         BusLogic_Error("BusLogic: IRQ Channel %d invalid for " "FlashPoint Host Adapter\n", NULL, IRQ_Channel);
909                         BusLogic_Error("at PCI Bus %d Device %d I/O Address 0x%X\n", NULL, Bus, Device, IO_Address);
910                         continue;
911                 }
912                 if (BusLogic_GlobalOptions.TraceProbe) {
913                         BusLogic_Notice("BusLogic: FlashPoint Host Adapter " "detected at\n", NULL);
914                         BusLogic_Notice("BusLogic: PCI Bus %d Device %d I/O Address " "0x%X PCI Address 0x%X\n", NULL, Bus, Device, IO_Address, PCI_Address);
915                 }
916                 if (BusLogic_ProbeInfoCount < BusLogic_MaxHostAdapters) {
917                         struct BusLogic_ProbeInfo *ProbeInfo = &BusLogic_ProbeInfoList[BusLogic_ProbeInfoCount++];
918                         ProbeInfo->HostAdapterType = BusLogic_FlashPoint;
919                         ProbeInfo->HostAdapterBusType = BusLogic_PCI_Bus;
920                         ProbeInfo->IO_Address = IO_Address;
921                         ProbeInfo->PCI_Address = PCI_Address;
922                         ProbeInfo->Bus = Bus;
923                         ProbeInfo->Device = Device;
924                         ProbeInfo->IRQ_Channel = IRQ_Channel;
925                         ProbeInfo->PCI_Device = PCI_Device;
926                         FlashPointCount++;
927                 } else
928                         BusLogic_Warning("BusLogic: Too many Host Adapters " "detected\n", NULL);
929 #else
930                 BusLogic_Error("BusLogic: FlashPoint Host Adapter detected at " "PCI Bus %d Device %d\n", NULL, Bus, Device);
931                 BusLogic_Error("BusLogic: I/O Address 0x%X PCI Address 0x%X, irq %d, " "but FlashPoint\n", NULL, IO_Address, PCI_Address, IRQ_Channel);
932                 BusLogic_Error("BusLogic: support was omitted in this kernel " "configuration.\n", NULL);
933 #endif
934         }
935         /*
936            The FlashPoint BIOS will scan for FlashPoint Host Adapters in the order of
937            increasing PCI Bus and Device Number, so sort the probe information into
938            the same order the BIOS uses.
939          */
940         BusLogic_SortProbeInfo(&BusLogic_ProbeInfoList[FlashPointIndex], FlashPointCount);
941         return FlashPointCount;
942 }
943
944
945 /*
946   BusLogic_InitializeProbeInfoList initializes the list of I/O Address and Bus
947   Probe Information to be checked for potential BusLogic SCSI Host Adapters by
948   interrogating the PCI Configuration Space on PCI machines as well as from the
949   list of standard BusLogic MultiMaster ISA I/O Addresses.  By default, if both
950   FlashPoint and PCI MultiMaster Host Adapters are present, this driver will
951   probe for FlashPoint Host Adapters first unless the BIOS primary disk is
952   controlled by the first PCI MultiMaster Host Adapter, in which case
953   MultiMaster Host Adapters will be probed first.  The BusLogic Driver Options
954   specifications "MultiMasterFirst" and "FlashPointFirst" can be used to force
955   a particular probe order.
956 */
957
958 static void __init BusLogic_InitializeProbeInfoList(struct BusLogic_HostAdapter
959                                                     *PrototypeHostAdapter)
960 {
961         /*
962            If a PCI BIOS is present, interrogate it for MultiMaster and FlashPoint
963            Host Adapters; otherwise, default to the standard ISA MultiMaster probe.
964          */
965         if (!BusLogic_ProbeOptions.NoProbePCI) {
966                 if (BusLogic_ProbeOptions.MultiMasterFirst) {
967                         BusLogic_InitializeMultiMasterProbeInfo(PrototypeHostAdapter);
968                         BusLogic_InitializeFlashPointProbeInfo(PrototypeHostAdapter);
969                 } else if (BusLogic_ProbeOptions.FlashPointFirst) {
970                         BusLogic_InitializeFlashPointProbeInfo(PrototypeHostAdapter);
971                         BusLogic_InitializeMultiMasterProbeInfo(PrototypeHostAdapter);
972                 } else {
973                         int FlashPointCount = BusLogic_InitializeFlashPointProbeInfo(PrototypeHostAdapter);
974                         int PCIMultiMasterCount = BusLogic_InitializeMultiMasterProbeInfo(PrototypeHostAdapter);
975                         if (FlashPointCount > 0 && PCIMultiMasterCount > 0) {
976                                 struct BusLogic_ProbeInfo *ProbeInfo = &BusLogic_ProbeInfoList[FlashPointCount];
977                                 struct BusLogic_HostAdapter *HostAdapter = PrototypeHostAdapter;
978                                 struct BusLogic_FetchHostAdapterLocalRAMRequest FetchHostAdapterLocalRAMRequest;
979                                 struct BusLogic_BIOSDriveMapByte Drive0MapByte;
980                                 while (ProbeInfo->HostAdapterBusType != BusLogic_PCI_Bus)
981                                         ProbeInfo++;
982                                 HostAdapter->IO_Address = ProbeInfo->IO_Address;
983                                 FetchHostAdapterLocalRAMRequest.ByteOffset = BusLogic_BIOS_BaseOffset + BusLogic_BIOS_DriveMapOffset + 0;
984                                 FetchHostAdapterLocalRAMRequest.ByteCount = sizeof(Drive0MapByte);
985                                 BusLogic_Command(HostAdapter, BusLogic_FetchHostAdapterLocalRAM, &FetchHostAdapterLocalRAMRequest, sizeof(FetchHostAdapterLocalRAMRequest), &Drive0MapByte, sizeof(Drive0MapByte));
986                                 /*
987                                    If the Map Byte for BIOS Drive 0 indicates that BIOS Drive 0
988                                    is controlled by this PCI MultiMaster Host Adapter, then
989                                    reverse the probe order so that MultiMaster Host Adapters are
990                                    probed before FlashPoint Host Adapters.
991                                  */
992                                 if (Drive0MapByte.DiskGeometry != BusLogic_BIOS_Disk_Not_Installed) {
993                                         struct BusLogic_ProbeInfo SavedProbeInfo[BusLogic_MaxHostAdapters];
994                                         int MultiMasterCount = BusLogic_ProbeInfoCount - FlashPointCount;
995                                         memcpy(SavedProbeInfo, BusLogic_ProbeInfoList, BusLogic_ProbeInfoCount * sizeof(struct BusLogic_ProbeInfo));
996                                         memcpy(&BusLogic_ProbeInfoList[0], &SavedProbeInfo[FlashPointCount], MultiMasterCount * sizeof(struct BusLogic_ProbeInfo));
997                                         memcpy(&BusLogic_ProbeInfoList[MultiMasterCount], &SavedProbeInfo[0], FlashPointCount * sizeof(struct BusLogic_ProbeInfo));
998                                 }
999                         }
1000                 }
1001         } else
1002                 BusLogic_InitializeProbeInfoListISA(PrototypeHostAdapter);
1003 }
1004
1005
1006 #endif                          /* CONFIG_PCI */
1007
1008
1009 /*
1010   BusLogic_Failure prints a standardized error message, and then returns false.
1011 */
1012
1013 static boolean BusLogic_Failure(struct BusLogic_HostAdapter *HostAdapter, char *ErrorMessage)
1014 {
1015         BusLogic_AnnounceDriver(HostAdapter);
1016         if (HostAdapter->HostAdapterBusType == BusLogic_PCI_Bus) {
1017                 BusLogic_Error("While configuring BusLogic PCI Host Adapter at\n", HostAdapter);
1018                 BusLogic_Error("Bus %d Device %d I/O Address 0x%X PCI Address 0x%X:\n", HostAdapter, HostAdapter->Bus, HostAdapter->Device, HostAdapter->IO_Address, HostAdapter->PCI_Address);
1019         } else
1020                 BusLogic_Error("While configuring BusLogic Host Adapter at " "I/O Address 0x%X:\n", HostAdapter, HostAdapter->IO_Address);
1021         BusLogic_Error("%s FAILED - DETACHING\n", HostAdapter, ErrorMessage);
1022         if (BusLogic_CommandFailureReason != NULL)
1023                 BusLogic_Error("ADDITIONAL FAILURE INFO - %s\n", HostAdapter, BusLogic_CommandFailureReason);
1024         return false;
1025 }
1026
1027
1028 /*
1029   BusLogic_ProbeHostAdapter probes for a BusLogic Host Adapter.
1030 */
1031
1032 static boolean __init BusLogic_ProbeHostAdapter(struct BusLogic_HostAdapter *HostAdapter)
1033 {
1034         union BusLogic_StatusRegister StatusRegister;
1035         union BusLogic_InterruptRegister InterruptRegister;
1036         union BusLogic_GeometryRegister GeometryRegister;
1037         /*
1038            FlashPoint Host Adapters are Probed by the FlashPoint SCCB Manager.
1039          */
1040         if (BusLogic_FlashPointHostAdapterP(HostAdapter)) {
1041                 struct FlashPoint_Info *FlashPointInfo = &HostAdapter->FlashPointInfo;
1042                 FlashPointInfo->BaseAddress = (u32) HostAdapter->IO_Address;
1043                 FlashPointInfo->IRQ_Channel = HostAdapter->IRQ_Channel;
1044                 FlashPointInfo->Present = false;
1045                 if (!(FlashPoint_ProbeHostAdapter(FlashPointInfo) == 0 && FlashPointInfo->Present)) {
1046                         BusLogic_Error("BusLogic: FlashPoint Host Adapter detected at " "PCI Bus %d Device %d\n", HostAdapter, HostAdapter->Bus, HostAdapter->Device);
1047                         BusLogic_Error("BusLogic: I/O Address 0x%X PCI Address 0x%X, " "but FlashPoint\n", HostAdapter, HostAdapter->IO_Address, HostAdapter->PCI_Address);
1048                         BusLogic_Error("BusLogic: Probe Function failed to validate it.\n", HostAdapter);
1049                         return false;
1050                 }
1051                 if (BusLogic_GlobalOptions.TraceProbe)
1052                         BusLogic_Notice("BusLogic_Probe(0x%X): FlashPoint Found\n", HostAdapter, HostAdapter->IO_Address);
1053                 /*
1054                    Indicate the Host Adapter Probe completed successfully.
1055                  */
1056                 return true;
1057         }
1058         /*
1059            Read the Status, Interrupt, and Geometry Registers to test if there are I/O
1060            ports that respond, and to check the values to determine if they are from a
1061            BusLogic Host Adapter.  A nonexistent I/O port will return 0xFF, in which
1062            case there is definitely no BusLogic Host Adapter at this base I/O Address.
1063            The test here is a subset of that used by the BusLogic Host Adapter BIOS.
1064          */
1065         StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
1066         InterruptRegister.All = BusLogic_ReadInterruptRegister(HostAdapter);
1067         GeometryRegister.All = BusLogic_ReadGeometryRegister(HostAdapter);
1068         if (BusLogic_GlobalOptions.TraceProbe)
1069                 BusLogic_Notice("BusLogic_Probe(0x%X): Status 0x%02X, Interrupt 0x%02X, " "Geometry 0x%02X\n", HostAdapter, HostAdapter->IO_Address, StatusRegister.All, InterruptRegister.All, GeometryRegister.All);
1070         if (StatusRegister.All == 0 || StatusRegister.sr.DiagnosticActive || StatusRegister.sr.CommandParameterRegisterBusy || StatusRegister.sr.Reserved || StatusRegister.sr.CommandInvalid || InterruptRegister.ir.Reserved != 0)
1071                 return false;
1072         /*
1073            Check the undocumented Geometry Register to test if there is an I/O port
1074            that responded.  Adaptec Host Adapters do not implement the Geometry
1075            Register, so this test helps serve to avoid incorrectly recognizing an
1076            Adaptec 1542A or 1542B as a BusLogic.  Unfortunately, the Adaptec 1542C
1077            series does respond to the Geometry Register I/O port, but it will be
1078            rejected later when the Inquire Extended Setup Information command is
1079            issued in BusLogic_CheckHostAdapter.  The AMI FastDisk Host Adapter is a
1080            BusLogic clone that implements the same interface as earlier BusLogic
1081            Host Adapters, including the undocumented commands, and is therefore
1082            supported by this driver.  However, the AMI FastDisk always returns 0x00
1083            upon reading the Geometry Register, so the extended translation option
1084            should always be left disabled on the AMI FastDisk.
1085          */
1086         if (GeometryRegister.All == 0xFF)
1087                 return false;
1088         /*
1089            Indicate the Host Adapter Probe completed successfully.
1090          */
1091         return true;
1092 }
1093
1094
1095 /*
1096   BusLogic_HardwareResetHostAdapter issues a Hardware Reset to the Host Adapter
1097   and waits for Host Adapter Diagnostics to complete.  If HardReset is true, a
1098   Hard Reset is performed which also initiates a SCSI Bus Reset.  Otherwise, a
1099   Soft Reset is performed which only resets the Host Adapter without forcing a
1100   SCSI Bus Reset.
1101 */
1102
1103 static boolean BusLogic_HardwareResetHostAdapter(struct BusLogic_HostAdapter
1104                                                  *HostAdapter, boolean HardReset)
1105 {
1106         union BusLogic_StatusRegister StatusRegister;
1107         int TimeoutCounter;
1108         /*
1109            FlashPoint Host Adapters are Hard Reset by the FlashPoint SCCB Manager.
1110          */
1111         if (BusLogic_FlashPointHostAdapterP(HostAdapter)) {
1112                 struct FlashPoint_Info *FlashPointInfo = &HostAdapter->FlashPointInfo;
1113                 FlashPointInfo->HostSoftReset = !HardReset;
1114                 FlashPointInfo->ReportDataUnderrun = true;
1115                 HostAdapter->CardHandle = FlashPoint_HardwareResetHostAdapter(FlashPointInfo);
1116                 if (HostAdapter->CardHandle == FlashPoint_BadCardHandle)
1117                         return false;
1118                 /*
1119                    Indicate the Host Adapter Hard Reset completed successfully.
1120                  */
1121                 return true;
1122         }
1123         /*
1124            Issue a Hard Reset or Soft Reset Command to the Host Adapter.  The Host
1125            Adapter should respond by setting Diagnostic Active in the Status Register.
1126          */
1127         if (HardReset)
1128                 BusLogic_HardReset(HostAdapter);
1129         else
1130                 BusLogic_SoftReset(HostAdapter);
1131         /*
1132            Wait until Diagnostic Active is set in the Status Register.
1133          */
1134         TimeoutCounter = 5 * 10000;
1135         while (--TimeoutCounter >= 0) {
1136                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
1137                 if (StatusRegister.sr.DiagnosticActive)
1138                         break;
1139                 udelay(100);
1140         }
1141         if (BusLogic_GlobalOptions.TraceHardwareReset)
1142                 BusLogic_Notice("BusLogic_HardwareReset(0x%X): Diagnostic Active, " "Status 0x%02X\n", HostAdapter, HostAdapter->IO_Address, StatusRegister.All);
1143         if (TimeoutCounter < 0)
1144                 return false;
1145         /*
1146            Wait 100 microseconds to allow completion of any initial diagnostic
1147            activity which might leave the contents of the Status Register
1148            unpredictable.
1149          */
1150         udelay(100);
1151         /*
1152            Wait until Diagnostic Active is reset in the Status Register.
1153          */
1154         TimeoutCounter = 10 * 10000;
1155         while (--TimeoutCounter >= 0) {
1156                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
1157                 if (!StatusRegister.sr.DiagnosticActive)
1158                         break;
1159                 udelay(100);
1160         }
1161         if (BusLogic_GlobalOptions.TraceHardwareReset)
1162                 BusLogic_Notice("BusLogic_HardwareReset(0x%X): Diagnostic Completed, " "Status 0x%02X\n", HostAdapter, HostAdapter->IO_Address, StatusRegister.All);
1163         if (TimeoutCounter < 0)
1164                 return false;
1165         /*
1166            Wait until at least one of the Diagnostic Failure, Host Adapter Ready,
1167            or Data In Register Ready bits is set in the Status Register.
1168          */
1169         TimeoutCounter = 10000;
1170         while (--TimeoutCounter >= 0) {
1171                 StatusRegister.All = BusLogic_ReadStatusRegister(HostAdapter);
1172                 if (StatusRegister.sr.DiagnosticFailure || StatusRegister.sr.HostAdapterReady || StatusRegister.sr.DataInRegisterReady)
1173                         break;
1174                 udelay(100);
1175         }
1176         if (BusLogic_GlobalOptions.TraceHardwareReset)
1177                 BusLogic_Notice("BusLogic_HardwareReset(0x%X): Host Adapter Ready, " "Status 0x%02X\n", HostAdapter, HostAdapter->IO_Address, StatusRegister.All);
1178         if (TimeoutCounter < 0)
1179                 return false;
1180         /*
1181            If Diagnostic Failure is set or Host Adapter Ready is reset, then an
1182            error occurred during the Host Adapter diagnostics.  If Data In Register
1183            Ready is set, then there is an Error Code available.
1184          */
1185         if (StatusRegister.sr.DiagnosticFailure || !StatusRegister.sr.HostAdapterReady) {
1186                 BusLogic_CommandFailureReason = NULL;
1187                 BusLogic_Failure(HostAdapter, "HARD RESET DIAGNOSTICS");
1188                 BusLogic_Error("HOST ADAPTER STATUS REGISTER = %02X\n", HostAdapter, StatusRegister.All);
1189                 if (StatusRegister.sr.DataInRegisterReady) {
1190                         unsigned char ErrorCode = BusLogic_ReadDataInRegister(HostAdapter);
1191                         BusLogic_Error("HOST ADAPTER ERROR CODE = %d\n", HostAdapter, ErrorCode);
1192                 }
1193                 return false;
1194         }
1195         /*
1196            Indicate the Host Adapter Hard Reset completed successfully.
1197          */
1198         return true;
1199 }
1200
1201
1202 /*
1203   BusLogic_CheckHostAdapter checks to be sure this really is a BusLogic
1204   Host Adapter.
1205 */
1206
1207 static boolean __init BusLogic_CheckHostAdapter(struct BusLogic_HostAdapter *HostAdapter)
1208 {
1209         struct BusLogic_ExtendedSetupInformation ExtendedSetupInformation;
1210         unsigned char RequestedReplyLength;
1211         boolean Result = true;
1212         /*
1213            FlashPoint Host Adapters do not require this protection.
1214          */
1215         if (BusLogic_FlashPointHostAdapterP(HostAdapter))
1216                 return true;
1217         /*
1218            Issue the Inquire Extended Setup Information command.  Only genuine
1219            BusLogic Host Adapters and true clones support this command.  Adaptec 1542C
1220            series Host Adapters that respond to the Geometry Register I/O port will
1221            fail this command.
1222          */
1223         RequestedReplyLength = sizeof(ExtendedSetupInformation);
1224         if (BusLogic_Command(HostAdapter, BusLogic_InquireExtendedSetupInformation, &RequestedReplyLength, sizeof(RequestedReplyLength), &ExtendedSetupInformation, sizeof(ExtendedSetupInformation))
1225             != sizeof(ExtendedSetupInformation))
1226                 Result = false;
1227         /*
1228            Provide tracing information if requested and return.
1229          */
1230         if (BusLogic_GlobalOptions.TraceProbe)
1231                 BusLogic_Notice("BusLogic_Check(0x%X): MultiMaster %s\n", HostAdapter, HostAdapter->IO_Address, (Result ? "Found" : "Not Found"));
1232         return Result;
1233 }
1234
1235
1236 /*
1237   BusLogic_ReadHostAdapterConfiguration reads the Configuration Information
1238   from Host Adapter and initializes the Host Adapter structure.
1239 */
1240
1241 static boolean __init BusLogic_ReadHostAdapterConfiguration(struct BusLogic_HostAdapter
1242                                                             *HostAdapter)
1243 {
1244         struct BusLogic_BoardID BoardID;
1245         struct BusLogic_Configuration Configuration;
1246         struct BusLogic_SetupInformation SetupInformation;
1247         struct BusLogic_ExtendedSetupInformation ExtendedSetupInformation;
1248         unsigned char HostAdapterModelNumber[5];
1249         unsigned char FirmwareVersion3rdDigit;
1250         unsigned char FirmwareVersionLetter;
1251         struct BusLogic_PCIHostAdapterInformation PCIHostAdapterInformation;
1252         struct BusLogic_FetchHostAdapterLocalRAMRequest FetchHostAdapterLocalRAMRequest;
1253         struct BusLogic_AutoSCSIData AutoSCSIData;
1254         union BusLogic_GeometryRegister GeometryRegister;
1255         unsigned char RequestedReplyLength;
1256         unsigned char *TargetPointer, Character;
1257         int TargetID, i;
1258         /*
1259            Configuration Information for FlashPoint Host Adapters is provided in the
1260            FlashPoint_Info structure by the FlashPoint SCCB Manager's Probe Function.
1261            Initialize fields in the Host Adapter structure from the FlashPoint_Info
1262            structure.
1263          */
1264         if (BusLogic_FlashPointHostAdapterP(HostAdapter)) {
1265                 struct FlashPoint_Info *FlashPointInfo = &HostAdapter->FlashPointInfo;
1266                 TargetPointer = HostAdapter->ModelName;
1267                 *TargetPointer++ = 'B';
1268                 *TargetPointer++ = 'T';
1269                 *TargetPointer++ = '-';
1270                 for (i = 0; i < sizeof(FlashPointInfo->ModelNumber); i++)
1271                         *TargetPointer++ = FlashPointInfo->ModelNumber[i];
1272                 *TargetPointer++ = '\0';
1273                 strcpy(HostAdapter->FirmwareVersion, FlashPoint_FirmwareVersion);
1274                 HostAdapter->SCSI_ID = FlashPointInfo->SCSI_ID;
1275                 HostAdapter->ExtendedTranslationEnabled = FlashPointInfo->ExtendedTranslationEnabled;
1276                 HostAdapter->ParityCheckingEnabled = FlashPointInfo->ParityCheckingEnabled;
1277                 HostAdapter->BusResetEnabled = !FlashPointInfo->HostSoftReset;
1278                 HostAdapter->LevelSensitiveInterrupt = true;
1279                 HostAdapter->HostWideSCSI = FlashPointInfo->HostWideSCSI;
1280                 HostAdapter->HostDifferentialSCSI = false;
1281                 HostAdapter->HostSupportsSCAM = true;
1282                 HostAdapter->HostUltraSCSI = true;
1283                 HostAdapter->ExtendedLUNSupport = true;
1284                 HostAdapter->TerminationInfoValid = true;
1285                 HostAdapter->LowByteTerminated = FlashPointInfo->LowByteTerminated;
1286                 HostAdapter->HighByteTerminated = FlashPointInfo->HighByteTerminated;
1287                 HostAdapter->SCAM_Enabled = FlashPointInfo->SCAM_Enabled;
1288                 HostAdapter->SCAM_Level2 = FlashPointInfo->SCAM_Level2;
1289                 HostAdapter->DriverScatterGatherLimit = BusLogic_ScatterGatherLimit;
1290                 HostAdapter->MaxTargetDevices = (HostAdapter->HostWideSCSI ? 16 : 8);
1291                 HostAdapter->MaxLogicalUnits = 32;
1292                 HostAdapter->InitialCCBs = 4 * BusLogic_CCB_AllocationGroupSize;
1293                 HostAdapter->IncrementalCCBs = BusLogic_CCB_AllocationGroupSize;
1294                 HostAdapter->DriverQueueDepth = 255;
1295                 HostAdapter->HostAdapterQueueDepth = HostAdapter->DriverQueueDepth;
1296                 HostAdapter->SynchronousPermitted = FlashPointInfo->SynchronousPermitted;
1297                 HostAdapter->FastPermitted = FlashPointInfo->FastPermitted;
1298                 HostAdapter->UltraPermitted = FlashPointInfo->UltraPermitted;
1299                 HostAdapter->WidePermitted = FlashPointInfo->WidePermitted;
1300                 HostAdapter->DisconnectPermitted = FlashPointInfo->DisconnectPermitted;
1301                 HostAdapter->TaggedQueuingPermitted = 0xFFFF;
1302                 goto Common;
1303         }
1304         /*
1305            Issue the Inquire Board ID command.
1306          */
1307         if (BusLogic_Command(HostAdapter, BusLogic_InquireBoardID, NULL, 0, &BoardID, sizeof(BoardID)) != sizeof(BoardID))
1308                 return BusLogic_Failure(HostAdapter, "INQUIRE BOARD ID");
1309         /*
1310            Issue the Inquire Configuration command.
1311          */
1312         if (BusLogic_Command(HostAdapter, BusLogic_InquireConfiguration, NULL, 0, &Configuration, sizeof(Configuration))
1313             != sizeof(Configuration))
1314                 return BusLogic_Failure(HostAdapter, "INQUIRE CONFIGURATION");
1315         /*
1316            Issue the Inquire Setup Information command.
1317          */
1318         RequestedReplyLength = sizeof(SetupInformation);
1319         if (BusLogic_Command(HostAdapter, BusLogic_InquireSetupInformation, &RequestedReplyLength, sizeof(RequestedReplyLength), &SetupInformation, sizeof(SetupInformation))
1320             != sizeof(SetupInformation))
1321                 return BusLogic_Failure(HostAdapter, "INQUIRE SETUP INFORMATION");
1322         /*
1323            Issue the Inquire Extended Setup Information command.
1324          */
1325         RequestedReplyLength = sizeof(ExtendedSetupInformation);
1326         if (BusLogic_Command(HostAdapter, BusLogic_InquireExtendedSetupInformation, &RequestedReplyLength, sizeof(RequestedReplyLength), &ExtendedSetupInformation, sizeof(ExtendedSetupInformation))
1327             != sizeof(ExtendedSetupInformation))
1328                 return BusLogic_Failure(HostAdapter, "INQUIRE EXTENDED SETUP INFORMATION");
1329         /*
1330            Issue the Inquire Firmware Version 3rd Digit command.
1331          */
1332         FirmwareVersion3rdDigit = '\0';
1333         if (BoardID.FirmwareVersion1stDigit > '0')
1334                 if (BusLogic_Command(HostAdapter, BusLogic_InquireFirmwareVersion3rdDigit, NULL, 0, &FirmwareVersion3rdDigit, sizeof(FirmwareVersion3rdDigit))
1335                     != sizeof(FirmwareVersion3rdDigit))
1336                         return BusLogic_Failure(HostAdapter, "INQUIRE FIRMWARE 3RD DIGIT");
1337         /*
1338            Issue the Inquire Host Adapter Model Number command.
1339          */
1340         if (ExtendedSetupInformation.BusType == 'A' && BoardID.FirmwareVersion1stDigit == '2')
1341                 /* BusLogic BT-542B ISA 2.xx */
1342                 strcpy(HostAdapterModelNumber, "542B");
1343         else if (ExtendedSetupInformation.BusType == 'E' && BoardID.FirmwareVersion1stDigit == '2' && (BoardID.FirmwareVersion2ndDigit <= '1' || (BoardID.FirmwareVersion2ndDigit == '2' && FirmwareVersion3rdDigit == '0')))
1344                 /* BusLogic BT-742A EISA 2.1x or 2.20 */
1345                 strcpy(HostAdapterModelNumber, "742A");
1346         else if (ExtendedSetupInformation.BusType == 'E' && BoardID.FirmwareVersion1stDigit == '0')
1347                 /* AMI FastDisk EISA Series 441 0.x */
1348                 strcpy(HostAdapterModelNumber, "747A");
1349         else {
1350                 RequestedReplyLength = sizeof(HostAdapterModelNumber);
1351                 if (BusLogic_Command(HostAdapter, BusLogic_InquireHostAdapterModelNumber, &RequestedReplyLength, sizeof(RequestedReplyLength), &HostAdapterModelNumber, sizeof(HostAdapterModelNumber))
1352                     != sizeof(HostAdapterModelNumber))
1353                         return BusLogic_Failure(HostAdapter, "INQUIRE HOST ADAPTER MODEL NUMBER");
1354         }
1355         /*
1356            BusLogic MultiMaster Host Adapters can be identified by their model number
1357            and the major version number of their firmware as follows:
1358
1359            5.xx       BusLogic "W" Series Host Adapters:
1360            BT-948/958/958D
1361            4.xx       BusLogic "C" Series Host Adapters:
1362            BT-946C/956C/956CD/747C/757C/757CD/445C/545C/540CF
1363            3.xx       BusLogic "S" Series Host Adapters:
1364            BT-747S/747D/757S/757D/445S/545S/542D
1365            BT-542B/742A (revision H)
1366            2.xx       BusLogic "A" Series Host Adapters:
1367            BT-542B/742A (revision G and below)
1368            0.xx       AMI FastDisk VLB/EISA BusLogic Clone Host Adapter
1369          */
1370         /*
1371            Save the Model Name and Host Adapter Name in the Host Adapter structure.
1372          */
1373         TargetPointer = HostAdapter->ModelName;
1374         *TargetPointer++ = 'B';
1375         *TargetPointer++ = 'T';
1376         *TargetPointer++ = '-';
1377         for (i = 0; i < sizeof(HostAdapterModelNumber); i++) {
1378                 Character = HostAdapterModelNumber[i];
1379                 if (Character == ' ' || Character == '\0')
1380                         break;
1381                 *TargetPointer++ = Character;
1382         }
1383         *TargetPointer++ = '\0';
1384         /*
1385            Save the Firmware Version in the Host Adapter structure.
1386          */
1387         TargetPointer = HostAdapter->FirmwareVersion;
1388         *TargetPointer++ = BoardID.FirmwareVersion1stDigit;
1389         *TargetPointer++ = '.';
1390         *TargetPointer++ = BoardID.FirmwareVersion2ndDigit;
1391         if (FirmwareVersion3rdDigit != ' ' && FirmwareVersion3rdDigit != '\0')
1392                 *TargetPointer++ = FirmwareVersion3rdDigit;
1393         *TargetPointer = '\0';
1394         /*
1395            Issue the Inquire Firmware Version Letter command.
1396          */
1397         if (strcmp(HostAdapter->FirmwareVersion, "3.3") >= 0) {
1398                 if (BusLogic_Command(HostAdapter, BusLogic_InquireFirmwareVersionLetter, NULL, 0, &FirmwareVersionLetter, sizeof(FirmwareVersionLetter))
1399                     != sizeof(FirmwareVersionLetter))
1400                         return BusLogic_Failure(HostAdapter, "INQUIRE FIRMWARE VERSION LETTER");
1401                 if (FirmwareVersionLetter != ' ' && FirmwareVersionLetter != '\0')
1402                         *TargetPointer++ = FirmwareVersionLetter;
1403                 *TargetPointer = '\0';
1404         }
1405         /*
1406            Save the Host Adapter SCSI ID in the Host Adapter structure.
1407          */
1408         HostAdapter->SCSI_ID = Configuration.HostAdapterID;
1409         /*
1410            Determine the Bus Type and save it in the Host Adapter structure, determine
1411            and save the IRQ Channel if necessary, and determine and save the DMA
1412            Channel for ISA Host Adapters.
1413          */
1414         HostAdapter->HostAdapterBusType = BusLogic_HostAdapterBusTypes[HostAdapter->ModelName[3] - '4'];
1415         if (HostAdapter->IRQ_Channel == 0) {
1416                 if (Configuration.IRQ_Channel9)
1417                         HostAdapter->IRQ_Channel = 9;
1418                 else if (Configuration.IRQ_Channel10)
1419                         HostAdapter->IRQ_Channel = 10;
1420                 else if (Configuration.IRQ_Channel11)
1421                         HostAdapter->IRQ_Channel = 11;
1422                 else if (Configuration.IRQ_Channel12)
1423                         HostAdapter->IRQ_Channel = 12;
1424                 else if (Configuration.IRQ_Channel14)
1425                         HostAdapter->IRQ_Channel = 14;
1426                 else if (Configuration.IRQ_Channel15)
1427                         HostAdapter->IRQ_Channel = 15;
1428         }
1429         if (HostAdapter->HostAdapterBusType == BusLogic_ISA_Bus) {
1430                 if (Configuration.DMA_Channel5)
1431                         HostAdapter->DMA_Channel = 5;
1432                 else if (Configuration.DMA_Channel6)
1433                         HostAdapter->DMA_Channel = 6;
1434                 else if (Configuration.DMA_Channel7)
1435                         HostAdapter->DMA_Channel = 7;
1436         }
1437         /*
1438            Determine whether Extended Translation is enabled and save it in
1439            the Host Adapter structure.
1440          */
1441         GeometryRegister.All = BusLogic_ReadGeometryRegister(HostAdapter);
1442         HostAdapter->ExtendedTranslationEnabled = GeometryRegister.gr.ExtendedTranslationEnabled;
1443         /*
1444            Save the Scatter Gather Limits, Level Sensitive Interrupt flag, Wide
1445            SCSI flag, Differential SCSI flag, SCAM Supported flag, and
1446            Ultra SCSI flag in the Host Adapter structure.
1447          */
1448         HostAdapter->HostAdapterScatterGatherLimit = ExtendedSetupInformation.ScatterGatherLimit;
1449         HostAdapter->DriverScatterGatherLimit = HostAdapter->HostAdapterScatterGatherLimit;
1450         if (HostAdapter->HostAdapterScatterGatherLimit > BusLogic_ScatterGatherLimit)
1451                 HostAdapter->DriverScatterGatherLimit = BusLogic_ScatterGatherLimit;
1452         if (ExtendedSetupInformation.Misc.LevelSensitiveInterrupt)
1453                 HostAdapter->LevelSensitiveInterrupt = true;
1454         HostAdapter->HostWideSCSI = ExtendedSetupInformation.HostWideSCSI;
1455         HostAdapter->HostDifferentialSCSI = ExtendedSetupInformation.HostDifferentialSCSI;
1456         HostAdapter->HostSupportsSCAM = ExtendedSetupInformation.HostSupportsSCAM;
1457         HostAdapter->HostUltraSCSI = ExtendedSetupInformation.HostUltraSCSI;
1458         /*
1459            Determine whether Extended LUN Format CCBs are supported and save the
1460            information in the Host Adapter structure.
1461          */
1462         if (HostAdapter->FirmwareVersion[0] == '5' || (HostAdapter->FirmwareVersion[0] == '4' && HostAdapter->HostWideSCSI))
1463                 HostAdapter->ExtendedLUNSupport = true;
1464         /*
1465            Issue the Inquire PCI Host Adapter Information command to read the
1466            Termination Information from "W" series MultiMaster Host Adapters.
1467          */
1468         if (HostAdapter->FirmwareVersion[0] == '5') {
1469                 if (BusLogic_Command(HostAdapter, BusLogic_InquirePCIHostAdapterInformation, NULL, 0, &PCIHostAdapterInformation, sizeof(PCIHostAdapterInformation))
1470                     != sizeof(PCIHostAdapterInformation))
1471                         return BusLogic_Failure(HostAdapter, "INQUIRE PCI HOST ADAPTER INFORMATION");
1472                 /*
1473                    Save the Termination Information in the Host Adapter structure.
1474                  */
1475                 if (PCIHostAdapterInformation.GenericInfoValid) {
1476                         HostAdapter->TerminationInfoValid = true;
1477                         HostAdapter->LowByteTerminated = PCIHostAdapterInformation.LowByteTerminated;
1478                         HostAdapter->HighByteTerminated = PCIHostAdapterInformation.HighByteTerminated;
1479                 }
1480         }
1481         /*
1482            Issue the Fetch Host Adapter Local RAM command to read the AutoSCSI data
1483            from "W" and "C" series MultiMaster Host Adapters.
1484          */
1485         if (HostAdapter->FirmwareVersion[0] >= '4') {
1486                 FetchHostAdapterLocalRAMRequest.ByteOffset = BusLogic_AutoSCSI_BaseOffset;
1487                 FetchHostAdapterLocalRAMRequest.ByteCount = sizeof(AutoSCSIData);
1488                 if (BusLogic_Command(HostAdapter, BusLogic_FetchHostAdapterLocalRAM, &FetchHostAdapterLocalRAMRequest, sizeof(FetchHostAdapterLocalRAMRequest), &AutoSCSIData, sizeof(AutoSCSIData))
1489                     != sizeof(AutoSCSIData))
1490                         return BusLogic_Failure(HostAdapter, "FETCH HOST ADAPTER LOCAL RAM");
1491                 /*
1492                    Save the Parity Checking Enabled, Bus Reset Enabled, and Termination
1493                    Information in the Host Adapter structure.
1494                  */
1495                 HostAdapter->ParityCheckingEnabled = AutoSCSIData.ParityCheckingEnabled;
1496                 HostAdapter->BusResetEnabled = AutoSCSIData.BusResetEnabled;
1497                 if (HostAdapter->FirmwareVersion[0] == '4') {
1498                         HostAdapter->TerminationInfoValid = true;
1499                         HostAdapter->LowByteTerminated = AutoSCSIData.LowByteTerminated;
1500                         HostAdapter->HighByteTerminated = AutoSCSIData.HighByteTerminated;
1501                 }
1502                 /*
1503                    Save the Wide Permitted, Fast Permitted, Synchronous Permitted,
1504                    Disconnect Permitted, Ultra Permitted, and SCAM Information in the
1505                    Host Adapter structure.
1506                  */
1507                 HostAdapter->WidePermitted = AutoSCSIData.WidePermitted;
1508                 HostAdapter->FastPermitted = AutoSCSIData.FastPermitted;
1509                 HostAdapter->SynchronousPermitted = AutoSCSIData.SynchronousPermitted;
1510                 HostAdapter->DisconnectPermitted = AutoSCSIData.DisconnectPermitted;
1511                 if (HostAdapter->HostUltraSCSI)
1512                         HostAdapter->UltraPermitted = AutoSCSIData.UltraPermitted;
1513                 if (HostAdapter->HostSupportsSCAM) {
1514                         HostAdapter->SCAM_Enabled = AutoSCSIData.SCAM_Enabled;
1515                         HostAdapter->SCAM_Level2 = AutoSCSIData.SCAM_Level2;
1516                 }
1517         }
1518         /*
1519            Initialize fields in the Host Adapter structure for "S" and "A" series
1520            MultiMaster Host Adapters.
1521          */
1522         if (HostAdapter->FirmwareVersion[0] < '4') {
1523                 if (SetupInformation.SynchronousInitiationEnabled) {
1524                         HostAdapter->SynchronousPermitted = 0xFF;
1525                         if (HostAdapter->HostAdapterBusType == BusLogic_EISA_Bus) {
1526                                 if (ExtendedSetupInformation.Misc.FastOnEISA)
1527                                         HostAdapter->FastPermitted = 0xFF;
1528                                 if (strcmp(HostAdapter->ModelName, "BT-757") == 0)
1529                                         HostAdapter->WidePermitted = 0xFF;
1530                         }
1531                 }
1532                 HostAdapter->DisconnectPermitted = 0xFF;
1533                 HostAdapter->ParityCheckingEnabled = SetupInformation.ParityCheckingEnabled;
1534                 HostAdapter->BusResetEnabled = true;
1535         }
1536         /*
1537            Determine the maximum number of Target IDs and Logical Units supported by
1538            this driver for Wide and Narrow Host Adapters.
1539          */
1540         HostAdapter->MaxTargetDevices = (HostAdapter->HostWideSCSI ? 16 : 8);
1541         HostAdapter->MaxLogicalUnits = (HostAdapter->ExtendedLUNSupport ? 32 : 8);
1542         /*
1543            Select appropriate values for the Mailbox Count, Driver Queue Depth,
1544            Initial CCBs, and Incremental CCBs variables based on whether or not Strict
1545            Round Robin Mode is supported.  If Strict Round Robin Mode is supported,
1546            then there is no performance degradation in using the maximum possible
1547            number of Outgoing and Incoming Mailboxes and allowing the Tagged and
1548            Untagged Queue Depths to determine the actual utilization.  If Strict Round
1549            Robin Mode is not supported, then the Host Adapter must scan all the
1550            Outgoing Mailboxes whenever an Outgoing Mailbox entry is made, which can
1551            cause a substantial performance penalty.  The host adapters actually have
1552            room to store the following number of CCBs internally; that is, they can
1553            internally queue and manage this many active commands on the SCSI bus
1554            simultaneously.  Performance measurements demonstrate that the Driver Queue
1555            Depth should be set to the Mailbox Count, rather than the Host Adapter
1556            Queue Depth (internal CCB capacity), as it is more efficient to have the
1557            queued commands waiting in Outgoing Mailboxes if necessary than to block
1558            the process in the higher levels of the SCSI Subsystem.
1559
1560            192          BT-948/958/958D
1561            100          BT-946C/956C/956CD/747C/757C/757CD/445C
1562            50   BT-545C/540CF
1563            30   BT-747S/747D/757S/757D/445S/545S/542D/542B/742A
1564          */
1565         if (HostAdapter->FirmwareVersion[0] == '5')
1566                 HostAdapter->HostAdapterQueueDepth = 192;
1567         else if (HostAdapter->FirmwareVersion[0] == '4')
1568                 HostAdapter->HostAdapterQueueDepth = (HostAdapter->HostAdapterBusType != BusLogic_ISA_Bus ? 100 : 50);
1569         else
1570                 HostAdapter->HostAdapterQueueDepth = 30;
1571         if (strcmp(HostAdapter->FirmwareVersion, "3.31") >= 0) {
1572                 HostAdapter->StrictRoundRobinModeSupport = true;
1573                 HostAdapter->MailboxCount = BusLogic_MaxMailboxes;
1574         } else {
1575                 HostAdapter->StrictRoundRobinModeSupport = false;
1576                 HostAdapter->MailboxCount = 32;
1577         }
1578         HostAdapter->DriverQueueDepth = HostAdapter->MailboxCount;
1579         HostAdapter->InitialCCBs = 4 * BusLogic_CCB_AllocationGroupSize;
1580         HostAdapter->IncrementalCCBs = BusLogic_CCB_AllocationGroupSize;
1581         /*
1582            Tagged Queuing support is available and operates properly on all "W" series
1583            MultiMaster Host Adapters, on "C" series MultiMaster Host Adapters with
1584            firmware version 4.22 and above, and on "S" series MultiMaster Host
1585            Adapters with firmware version 3.35 and above.
1586          */
1587         HostAdapter->TaggedQueuingPermitted = 0;
1588         switch (HostAdapter->FirmwareVersion[0]) {
1589         case '5':
1590                 HostAdapter->TaggedQueuingPermitted = 0xFFFF;
1591                 break;
1592         case '4':
1593                 if (strcmp(HostAdapter->FirmwareVersion, "4.22") >= 0)
1594                         HostAdapter->TaggedQueuingPermitted = 0xFFFF;
1595                 break;
1596         case '3':
1597                 if (strcmp(HostAdapter->FirmwareVersion, "3.35") >= 0)
1598                         HostAdapter->TaggedQueuingPermitted = 0xFFFF;
1599                 break;
1600         }
1601         /*
1602            Determine the Host Adapter BIOS Address if the BIOS is enabled and
1603            save it in the Host Adapter structure.  The BIOS is disabled if the
1604            BIOS_Address is 0.
1605          */
1606         HostAdapter->BIOS_Address = ExtendedSetupInformation.BIOS_Address << 12;
1607         /*
1608            ISA Host Adapters require Bounce Buffers if there is more than 16MB memory.
1609          */
1610         if (HostAdapter->HostAdapterBusType == BusLogic_ISA_Bus && (void *) high_memory > (void *) MAX_DMA_ADDRESS)
1611                 HostAdapter->BounceBuffersRequired = true;
1612         /*
1613            BusLogic BT-445S Host Adapters prior to board revision E have a hardware
1614            bug whereby when the BIOS is enabled, transfers to/from the same address
1615            range the BIOS occupies modulo 16MB are handled incorrectly.  Only properly
1616            functioning BT-445S Host Adapters have firmware version 3.37, so require
1617            that ISA Bounce Buffers be used for the buggy BT-445S models if there is
1618            more than 16MB memory.
1619          */
1620         if (HostAdapter->BIOS_Address > 0 && strcmp(HostAdapter->ModelName, "BT-445S") == 0 && strcmp(HostAdapter->FirmwareVersion, "3.37") < 0 && (void *) high_memory > (void *) MAX_DMA_ADDRESS)
1621                 HostAdapter->BounceBuffersRequired = true;
1622         /*
1623            Initialize parameters common to MultiMaster and FlashPoint Host Adapters.
1624          */
1625       Common:
1626         /*
1627            Initialize the Host Adapter Full Model Name from the Model Name.
1628          */
1629         strcpy(HostAdapter->FullModelName, "BusLogic ");
1630         strcat(HostAdapter->FullModelName, HostAdapter->ModelName);
1631         /*
1632            Select an appropriate value for the Tagged Queue Depth either from a
1633            BusLogic Driver Options specification, or based on whether this Host
1634            Adapter requires that ISA Bounce Buffers be used.  The Tagged Queue Depth
1635            is left at 0 for automatic determination in BusLogic_SelectQueueDepths.
1636            Initialize the Untagged Queue Depth.
1637          */
1638         for (TargetID = 0; TargetID < BusLogic_MaxTargetDevices; TargetID++) {
1639                 unsigned char QueueDepth = 0;
1640                 if (HostAdapter->DriverOptions != NULL && HostAdapter->DriverOptions->QueueDepth[TargetID] > 0)
1641                         QueueDepth = HostAdapter->DriverOptions->QueueDepth[TargetID];
1642                 else if (HostAdapter->BounceBuffersRequired)
1643                         QueueDepth = BusLogic_TaggedQueueDepthBB;
1644                 HostAdapter->QueueDepth[TargetID] = QueueDepth;
1645         }
1646         if (HostAdapter->BounceBuffersRequired)
1647                 HostAdapter->UntaggedQueueDepth = BusLogic_UntaggedQueueDepthBB;
1648         else
1649                 HostAdapter->UntaggedQueueDepth = BusLogic_UntaggedQueueDepth;
1650         if (HostAdapter->DriverOptions != NULL)
1651                 HostAdapter->CommonQueueDepth = HostAdapter->DriverOptions->CommonQueueDepth;
1652         if (HostAdapter->CommonQueueDepth > 0 && HostAdapter->CommonQueueDepth < HostAdapter->UntaggedQueueDepth)
1653                 HostAdapter->UntaggedQueueDepth = HostAdapter->CommonQueueDepth;
1654         /*
1655            Tagged Queuing is only allowed if Disconnect/Reconnect is permitted.
1656            Therefore, mask the Tagged Queuing Permitted Default bits with the
1657            Disconnect/Reconnect Permitted bits.
1658          */
1659         HostAdapter->TaggedQueuingPermitted &= HostAdapter->DisconnectPermitted;
1660         /*
1661            Combine the default Tagged Queuing Permitted bits with any BusLogic Driver
1662            Options Tagged Queuing specification.
1663          */
1664         if (HostAdapter->DriverOptions != NULL)
1665                 HostAdapter->TaggedQueuingPermitted =
1666                     (HostAdapter->DriverOptions->TaggedQueuingPermitted & HostAdapter->DriverOptions->TaggedQueuingPermittedMask) | (HostAdapter->TaggedQueuingPermitted & ~HostAdapter->DriverOptions->TaggedQueuingPermittedMask);
1667
1668         /*
1669            Select an appropriate value for Bus Settle Time either from a BusLogic
1670            Driver Options specification, or from BusLogic_DefaultBusSettleTime.
1671          */
1672         if (HostAdapter->DriverOptions != NULL && HostAdapter->DriverOptions->BusSettleTime > 0)
1673                 HostAdapter->BusSettleTime = HostAdapter->DriverOptions->BusSettleTime;
1674         else
1675                 HostAdapter->BusSettleTime = BusLogic_DefaultBusSettleTime;
1676         /*
1677            Indicate reading the Host Adapter Configuration completed successfully.
1678          */
1679         return true;
1680 }
1681
1682
1683 /*
1684   BusLogic_ReportHostAdapterConfiguration reports the configuration of
1685   Host Adapter.
1686 */
1687
1688 static boolean __init BusLogic_ReportHostAdapterConfiguration(struct BusLogic_HostAdapter
1689                                                               *HostAdapter)
1690 {
1691         unsigned short AllTargetsMask = (1 << HostAdapter->MaxTargetDevices) - 1;
1692         unsigned short SynchronousPermitted, FastPermitted;
1693         unsigned short UltraPermitted, WidePermitted;
1694         unsigned short DisconnectPermitted, TaggedQueuingPermitted;
1695         boolean CommonSynchronousNegotiation, CommonTaggedQueueDepth;
1696         char SynchronousString[BusLogic_MaxTargetDevices + 1];
1697         char WideString[BusLogic_MaxTargetDevices + 1];
1698         char DisconnectString[BusLogic_MaxTargetDevices + 1];
1699         char TaggedQueuingString[BusLogic_MaxTargetDevices + 1];
1700         char *SynchronousMessage = SynchronousString;
1701         char *WideMessage = WideString;
1702         char *DisconnectMessage = DisconnectString;
1703         char *TaggedQueuingMessage = TaggedQueuingString;
1704         int TargetID;
1705         BusLogic_Info("Configuring BusLogic Model %s %s%s%s%s SCSI Host Adapter\n",
1706                       HostAdapter, HostAdapter->ModelName,
1707                       BusLogic_HostAdapterBusNames[HostAdapter->HostAdapterBusType], (HostAdapter->HostWideSCSI ? " Wide" : ""), (HostAdapter->HostDifferentialSCSI ? " Differential" : ""), (HostAdapter->HostUltraSCSI ? " Ultra" : ""));
1708         BusLogic_Info("  Firmware Version: %s, I/O Address: 0x%X, " "IRQ Channel: %d/%s\n", HostAdapter, HostAdapter->FirmwareVersion, HostAdapter->IO_Address, HostAdapter->IRQ_Channel, (HostAdapter->LevelSensitiveInterrupt ? "Level" : "Edge"));
1709         if (HostAdapter->HostAdapterBusType != BusLogic_PCI_Bus) {
1710                 BusLogic_Info("  DMA Channel: ", HostAdapter);
1711                 if (HostAdapter->DMA_Channel > 0)
1712                         BusLogic_Info("%d, ", HostAdapter, HostAdapter->DMA_Channel);
1713                 else
1714                         BusLogic_Info("None, ", HostAdapter);
1715                 if (HostAdapter->BIOS_Address > 0)
1716                         BusLogic_Info("BIOS Address: 0x%X, ", HostAdapter, HostAdapter->BIOS_Address);
1717                 else
1718                         BusLogic_Info("BIOS Address: None, ", HostAdapter);
1719         } else {
1720                 BusLogic_Info("  PCI Bus: %d, Device: %d, Address: ", HostAdapter, HostAdapter->Bus, HostAdapter->Device);
1721                 if (HostAdapter->PCI_Address > 0)
1722                         BusLogic_Info("0x%X, ", HostAdapter, HostAdapter->PCI_Address);
1723                 else
1724                         BusLogic_Info("Unassigned, ", HostAdapter);
1725         }
1726         BusLogic_Info("Host Adapter SCSI ID: %d\n", HostAdapter, HostAdapter->SCSI_ID);
1727         BusLogic_Info("  Parity Checking: %s, Extended Translation: %s\n", HostAdapter, (HostAdapter->ParityCheckingEnabled ? "Enabled" : "Disabled"), (HostAdapter->ExtendedTranslationEnabled ? "Enabled" : "Disabled"));
1728         AllTargetsMask &= ~(1 << HostAdapter->SCSI_ID);
1729         SynchronousPermitted = HostAdapter->SynchronousPermitted & AllTargetsMask;
1730         FastPermitted = HostAdapter->FastPermitted & AllTargetsMask;
1731         UltraPermitted = HostAdapter->UltraPermitted & AllTargetsMask;
1732         if ((BusLogic_MultiMasterHostAdapterP(HostAdapter) && (HostAdapter->FirmwareVersion[0] >= '4' || HostAdapter->HostAdapterBusType == BusLogic_EISA_Bus)) || BusLogic_FlashPointHostAdapterP(HostAdapter)) {
1733                 CommonSynchronousNegotiation = false;
1734                 if (SynchronousPermitted == 0) {
1735                         SynchronousMessage = "Disabled";
1736                         CommonSynchronousNegotiation = true;
1737                 } else if (SynchronousPermitted == AllTargetsMask) {
1738                         if (FastPermitted == 0) {
1739                                 SynchronousMessage = "Slow";
1740                                 CommonSynchronousNegotiation = true;
1741                         } else if (FastPermitted == AllTargetsMask) {
1742                                 if (UltraPermitted == 0) {
1743                                         SynchronousMessage = "Fast";
1744                                         CommonSynchronousNegotiation = true;
1745                                 } else if (UltraPermitted == AllTargetsMask) {
1746                                         SynchronousMessage = "Ultra";
1747                                         CommonSynchronousNegotiation = true;
1748                                 }
1749                         }
1750                 }
1751                 if (!CommonSynchronousNegotiation) {
1752                         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
1753                                 SynchronousString[TargetID] = ((!(SynchronousPermitted & (1 << TargetID))) ? 'N' : (!(FastPermitted & (1 << TargetID)) ? 'S' : (!(UltraPermitted & (1 << TargetID)) ? 'F' : 'U')));
1754                         SynchronousString[HostAdapter->SCSI_ID] = '#';
1755                         SynchronousString[HostAdapter->MaxTargetDevices] = '\0';
1756                 }
1757         } else
1758                 SynchronousMessage = (SynchronousPermitted == 0 ? "Disabled" : "Enabled");
1759         WidePermitted = HostAdapter->WidePermitted & AllTargetsMask;
1760         if (WidePermitted == 0)
1761                 WideMessage = "Disabled";
1762         else if (WidePermitted == AllTargetsMask)
1763                 WideMessage = "Enabled";
1764         else {
1765                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
1766                         WideString[TargetID] = ((WidePermitted & (1 << TargetID)) ? 'Y' : 'N');
1767                 WideString[HostAdapter->SCSI_ID] = '#';
1768                 WideString[HostAdapter->MaxTargetDevices] = '\0';
1769         }
1770         DisconnectPermitted = HostAdapter->DisconnectPermitted & AllTargetsMask;
1771         if (DisconnectPermitted == 0)
1772                 DisconnectMessage = "Disabled";
1773         else if (DisconnectPermitted == AllTargetsMask)
1774                 DisconnectMessage = "Enabled";
1775         else {
1776                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
1777                         DisconnectString[TargetID] = ((DisconnectPermitted & (1 << TargetID)) ? 'Y' : 'N');
1778                 DisconnectString[HostAdapter->SCSI_ID] = '#';
1779                 DisconnectString[HostAdapter->MaxTargetDevices] = '\0';
1780         }
1781         TaggedQueuingPermitted = HostAdapter->TaggedQueuingPermitted & AllTargetsMask;
1782         if (TaggedQueuingPermitted == 0)
1783                 TaggedQueuingMessage = "Disabled";
1784         else if (TaggedQueuingPermitted == AllTargetsMask)
1785                 TaggedQueuingMessage = "Enabled";
1786         else {
1787                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
1788                         TaggedQueuingString[TargetID] = ((TaggedQueuingPermitted & (1 << TargetID)) ? 'Y' : 'N');
1789                 TaggedQueuingString[HostAdapter->SCSI_ID] = '#';
1790                 TaggedQueuingString[HostAdapter->MaxTargetDevices] = '\0';
1791         }
1792         BusLogic_Info("  Synchronous Negotiation: %s, Wide Negotiation: %s\n", HostAdapter, SynchronousMessage, WideMessage);
1793         BusLogic_Info("  Disconnect/Reconnect: %s, Tagged Queuing: %s\n", HostAdapter, DisconnectMessage, TaggedQueuingMessage);
1794         if (BusLogic_MultiMasterHostAdapterP(HostAdapter)) {
1795                 BusLogic_Info("  Scatter/Gather Limit: %d of %d segments, " "Mailboxes: %d\n", HostAdapter, HostAdapter->DriverScatterGatherLimit, HostAdapter->HostAdapterScatterGatherLimit, HostAdapter->MailboxCount);
1796                 BusLogic_Info("  Driver Queue Depth: %d, " "Host Adapter Queue Depth: %d\n", HostAdapter, HostAdapter->DriverQueueDepth, HostAdapter->HostAdapterQueueDepth);
1797         } else
1798                 BusLogic_Info("  Driver Queue Depth: %d, " "Scatter/Gather Limit: %d segments\n", HostAdapter, HostAdapter->DriverQueueDepth, HostAdapter->DriverScatterGatherLimit);
1799         BusLogic_Info("  Tagged Queue Depth: ", HostAdapter);
1800         CommonTaggedQueueDepth = true;
1801         for (TargetID = 1; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
1802                 if (HostAdapter->QueueDepth[TargetID] != HostAdapter->QueueDepth[0]) {
1803                         CommonTaggedQueueDepth = false;
1804                         break;
1805                 }
1806         if (CommonTaggedQueueDepth) {
1807                 if (HostAdapter->QueueDepth[0] > 0)
1808                         BusLogic_Info("%d", HostAdapter, HostAdapter->QueueDepth[0]);
1809                 else
1810                         BusLogic_Info("Automatic", HostAdapter);
1811         } else
1812                 BusLogic_Info("Individual", HostAdapter);
1813         BusLogic_Info(", Untagged Queue Depth: %d\n", HostAdapter, HostAdapter->UntaggedQueueDepth);
1814         if (HostAdapter->TerminationInfoValid) {
1815                 if (HostAdapter->HostWideSCSI)
1816                         BusLogic_Info("  SCSI Bus Termination: %s", HostAdapter, (HostAdapter->LowByteTerminated ? (HostAdapter->HighByteTerminated ? "Both Enabled" : "Low Enabled")
1817                                                                                   : (HostAdapter->HighByteTerminated ? "High Enabled" : "Both Disabled")));
1818                 else
1819                         BusLogic_Info("  SCSI Bus Termination: %s", HostAdapter, (HostAdapter->LowByteTerminated ? "Enabled" : "Disabled"));
1820                 if (HostAdapter->HostSupportsSCAM)
1821                         BusLogic_Info(", SCAM: %s", HostAdapter, (HostAdapter->SCAM_Enabled ? (HostAdapter->SCAM_Level2 ? "Enabled, Level 2" : "Enabled, Level 1")
1822                                                                   : "Disabled"));
1823                 BusLogic_Info("\n", HostAdapter);
1824         }
1825         /*
1826            Indicate reporting the Host Adapter configuration completed successfully.
1827          */
1828         return true;
1829 }
1830
1831
1832 /*
1833   BusLogic_AcquireResources acquires the system resources necessary to use
1834   Host Adapter.
1835 */
1836
1837 static boolean __init BusLogic_AcquireResources(struct BusLogic_HostAdapter *HostAdapter)
1838 {
1839         if (HostAdapter->IRQ_Channel == 0) {
1840                 BusLogic_Error("NO LEGAL INTERRUPT CHANNEL ASSIGNED - DETACHING\n", HostAdapter);
1841                 return false;
1842         }
1843         /*
1844            Acquire shared access to the IRQ Channel.
1845          */
1846         if (request_irq(HostAdapter->IRQ_Channel, BusLogic_InterruptHandler, SA_SHIRQ, HostAdapter->FullModelName, HostAdapter) < 0) {
1847                 BusLogic_Error("UNABLE TO ACQUIRE IRQ CHANNEL %d - DETACHING\n", HostAdapter, HostAdapter->IRQ_Channel);
1848                 return false;
1849         }
1850         HostAdapter->IRQ_ChannelAcquired = true;
1851         /*
1852            Acquire exclusive access to the DMA Channel.
1853          */
1854         if (HostAdapter->DMA_Channel > 0) {
1855                 if (request_dma(HostAdapter->DMA_Channel, HostAdapter->FullModelName) < 0) {
1856                         BusLogic_Error("UNABLE TO ACQUIRE DMA CHANNEL %d - DETACHING\n", HostAdapter, HostAdapter->DMA_Channel);
1857                         return false;
1858                 }
1859                 set_dma_mode(HostAdapter->DMA_Channel, DMA_MODE_CASCADE);
1860                 enable_dma(HostAdapter->DMA_Channel);
1861                 HostAdapter->DMA_ChannelAcquired = true;
1862         }
1863         /*
1864            Indicate the System Resource Acquisition completed successfully,
1865          */
1866         return true;
1867 }
1868
1869
1870 /*
1871   BusLogic_ReleaseResources releases any system resources previously acquired
1872   by BusLogic_AcquireResources.
1873 */
1874
1875 static void BusLogic_ReleaseResources(struct BusLogic_HostAdapter *HostAdapter)
1876 {
1877         /*
1878            Release shared access to the IRQ Channel.
1879          */
1880         if (HostAdapter->IRQ_ChannelAcquired)
1881                 free_irq(HostAdapter->IRQ_Channel, HostAdapter);
1882         /*
1883            Release exclusive access to the DMA Channel.
1884          */
1885         if (HostAdapter->DMA_ChannelAcquired)
1886                 free_dma(HostAdapter->DMA_Channel);
1887         /*
1888            Release any allocated memory structs not released elsewhere
1889          */
1890         if (HostAdapter->MailboxSpace)
1891                 pci_free_consistent(HostAdapter->PCI_Device, HostAdapter->MailboxSize, HostAdapter->MailboxSpace, HostAdapter->MailboxSpaceHandle);
1892         HostAdapter->MailboxSpace = NULL;
1893         HostAdapter->MailboxSpaceHandle = 0;
1894         HostAdapter->MailboxSize = 0;
1895 }
1896
1897
1898 /*
1899   BusLogic_InitializeHostAdapter initializes Host Adapter.  This is the only
1900   function called during SCSI Host Adapter detection which modifies the state
1901   of the Host Adapter from its initial power on or hard reset state.
1902 */
1903
1904 static boolean BusLogic_InitializeHostAdapter(struct BusLogic_HostAdapter
1905                                               *HostAdapter)
1906 {
1907         struct BusLogic_ExtendedMailboxRequest ExtendedMailboxRequest;
1908         enum BusLogic_RoundRobinModeRequest RoundRobinModeRequest;
1909         enum BusLogic_SetCCBFormatRequest SetCCBFormatRequest;
1910         int TargetID;
1911         /*
1912            Initialize the pointers to the first and last CCBs that are queued for
1913            completion processing.
1914          */
1915         HostAdapter->FirstCompletedCCB = NULL;
1916         HostAdapter->LastCompletedCCB = NULL;
1917         /*
1918            Initialize the Bus Device Reset Pending CCB, Tagged Queuing Active,
1919            Command Successful Flag, Active Commands, and Commands Since Reset
1920            for each Target Device.
1921          */
1922         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
1923                 HostAdapter->BusDeviceResetPendingCCB[TargetID] = NULL;
1924                 HostAdapter->TargetFlags[TargetID].TaggedQueuingActive = false;
1925                 HostAdapter->TargetFlags[TargetID].CommandSuccessfulFlag = false;
1926                 HostAdapter->ActiveCommands[TargetID] = 0;
1927                 HostAdapter->CommandsSinceReset[TargetID] = 0;
1928         }
1929         /*
1930            FlashPoint Host Adapters do not use Outgoing and Incoming Mailboxes.
1931          */
1932         if (BusLogic_FlashPointHostAdapterP(HostAdapter))
1933                 goto Done;
1934         /*
1935            Initialize the Outgoing and Incoming Mailbox pointers.
1936          */
1937         HostAdapter->MailboxSize = HostAdapter->MailboxCount * (sizeof(struct BusLogic_OutgoingMailbox) + sizeof(struct BusLogic_IncomingMailbox));
1938         HostAdapter->MailboxSpace = pci_alloc_consistent(HostAdapter->PCI_Device, HostAdapter->MailboxSize, &HostAdapter->MailboxSpaceHandle);
1939         if (HostAdapter->MailboxSpace == NULL)
1940                 return BusLogic_Failure(HostAdapter, "MAILBOX ALLOCATION");
1941         HostAdapter->FirstOutgoingMailbox = (struct BusLogic_OutgoingMailbox *) HostAdapter->MailboxSpace;
1942         HostAdapter->LastOutgoingMailbox = HostAdapter->FirstOutgoingMailbox + HostAdapter->MailboxCount - 1;
1943         HostAdapter->NextOutgoingMailbox = HostAdapter->FirstOutgoingMailbox;
1944         HostAdapter->FirstIncomingMailbox = (struct BusLogic_IncomingMailbox *) (HostAdapter->LastOutgoingMailbox + 1);
1945         HostAdapter->LastIncomingMailbox = HostAdapter->FirstIncomingMailbox + HostAdapter->MailboxCount - 1;
1946         HostAdapter->NextIncomingMailbox = HostAdapter->FirstIncomingMailbox;
1947
1948         /*
1949            Initialize the Outgoing and Incoming Mailbox structures.
1950          */
1951         memset(HostAdapter->FirstOutgoingMailbox, 0, HostAdapter->MailboxCount * sizeof(struct BusLogic_OutgoingMailbox));
1952         memset(HostAdapter->FirstIncomingMailbox, 0, HostAdapter->MailboxCount * sizeof(struct BusLogic_IncomingMailbox));
1953         /*
1954            Initialize the Host Adapter's Pointer to the Outgoing/Incoming Mailboxes.
1955          */
1956         ExtendedMailboxRequest.MailboxCount = HostAdapter->MailboxCount;
1957         ExtendedMailboxRequest.BaseMailboxAddress = (u32) HostAdapter->MailboxSpaceHandle;
1958         if (BusLogic_Command(HostAdapter, BusLogic_InitializeExtendedMailbox, &ExtendedMailboxRequest, sizeof(ExtendedMailboxRequest), NULL, 0) < 0)
1959                 return BusLogic_Failure(HostAdapter, "MAILBOX INITIALIZATION");
1960         /*
1961            Enable Strict Round Robin Mode if supported by the Host Adapter.  In
1962            Strict Round Robin Mode, the Host Adapter only looks at the next Outgoing
1963            Mailbox for each new command, rather than scanning through all the
1964            Outgoing Mailboxes to find any that have new commands in them.  Strict
1965            Round Robin Mode is significantly more efficient.
1966          */
1967         if (HostAdapter->StrictRoundRobinModeSupport) {
1968                 RoundRobinModeRequest = BusLogic_StrictRoundRobinMode;
1969                 if (BusLogic_Command(HostAdapter, BusLogic_EnableStrictRoundRobinMode, &RoundRobinModeRequest, sizeof(RoundRobinModeRequest), NULL, 0) < 0)
1970                         return BusLogic_Failure(HostAdapter, "ENABLE STRICT ROUND ROBIN MODE");
1971         }
1972         /*
1973            For Host Adapters that support Extended LUN Format CCBs, issue the Set CCB
1974            Format command to allow 32 Logical Units per Target Device.
1975          */
1976         if (HostAdapter->ExtendedLUNSupport) {
1977                 SetCCBFormatRequest = BusLogic_ExtendedLUNFormatCCB;
1978                 if (BusLogic_Command(HostAdapter, BusLogic_SetCCBFormat, &SetCCBFormatRequest, sizeof(SetCCBFormatRequest), NULL, 0) < 0)
1979                         return BusLogic_Failure(HostAdapter, "SET CCB FORMAT");
1980         }
1981         /*
1982            Announce Successful Initialization.
1983          */
1984       Done:
1985         if (!HostAdapter->HostAdapterInitialized) {
1986                 BusLogic_Info("*** %s Initialized Successfully ***\n", HostAdapter, HostAdapter->FullModelName);
1987                 BusLogic_Info("\n", HostAdapter);
1988         } else
1989                 BusLogic_Warning("*** %s Initialized Successfully ***\n", HostAdapter, HostAdapter->FullModelName);
1990         HostAdapter->HostAdapterInitialized = true;
1991         /*
1992            Indicate the Host Adapter Initialization completed successfully.
1993          */
1994         return true;
1995 }
1996
1997
1998 /*
1999   BusLogic_TargetDeviceInquiry inquires about the Target Devices accessible
2000   through Host Adapter.
2001 */
2002
2003 static boolean __init BusLogic_TargetDeviceInquiry(struct BusLogic_HostAdapter
2004                                                    *HostAdapter)
2005 {
2006         u16 InstalledDevices;
2007         u8 InstalledDevicesID0to7[8];
2008         struct BusLogic_SetupInformation SetupInformation;
2009         u8 SynchronousPeriod[BusLogic_MaxTargetDevices];
2010         unsigned char RequestedReplyLength;
2011         int TargetID;
2012         /*
2013            Wait a few seconds between the Host Adapter Hard Reset which initiates
2014            a SCSI Bus Reset and issuing any SCSI Commands.  Some SCSI devices get
2015            confused if they receive SCSI Commands too soon after a SCSI Bus Reset.
2016          */
2017         BusLogic_Delay(HostAdapter->BusSettleTime);
2018         /*
2019            FlashPoint Host Adapters do not provide for Target Device Inquiry.
2020          */
2021         if (BusLogic_FlashPointHostAdapterP(HostAdapter))
2022                 return true;
2023         /*
2024            Inhibit the Target Device Inquiry if requested.
2025          */
2026         if (HostAdapter->DriverOptions != NULL && HostAdapter->DriverOptions->LocalOptions.InhibitTargetInquiry)
2027                 return true;
2028         /*
2029            Issue the Inquire Target Devices command for host adapters with firmware
2030            version 4.25 or later, or the Inquire Installed Devices ID 0 to 7 command
2031            for older host adapters.  This is necessary to force Synchronous Transfer
2032            Negotiation so that the Inquire Setup Information and Inquire Synchronous
2033            Period commands will return valid data.  The Inquire Target Devices command
2034            is preferable to Inquire Installed Devices ID 0 to 7 since it only probes
2035            Logical Unit 0 of each Target Device.
2036          */
2037         if (strcmp(HostAdapter->FirmwareVersion, "4.25") >= 0) {
2038
2039                 /*
2040                  * Issue a Inquire Target Devices command.  Inquire Target Devices only
2041                  * tests Logical Unit 0 of each Target Device unlike the Inquire Installed
2042                  * Devices commands which test Logical Units 0 - 7.  Two bytes are
2043                  * returned, where byte 0 bit 0 set indicates that Target Device 0 exists,
2044                  * and so on.
2045                  */
2046
2047                 if (BusLogic_Command(HostAdapter, BusLogic_InquireTargetDevices, NULL, 0, &InstalledDevices, sizeof(InstalledDevices))
2048                     != sizeof(InstalledDevices))
2049                         return BusLogic_Failure(HostAdapter, "INQUIRE TARGET DEVICES");
2050                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2051                         HostAdapter->TargetFlags[TargetID].TargetExists = (InstalledDevices & (1 << TargetID) ? true : false);
2052         } else {
2053
2054                 /*
2055                  * Issue an Inquire Installed Devices command.  For each Target Device,
2056                  * a byte is returned where bit 0 set indicates that Logical Unit 0
2057                  * exists, bit 1 set indicates that Logical Unit 1 exists, and so on.
2058                  */
2059
2060                 if (BusLogic_Command(HostAdapter, BusLogic_InquireInstalledDevicesID0to7, NULL, 0, &InstalledDevicesID0to7, sizeof(InstalledDevicesID0to7))
2061                     != sizeof(InstalledDevicesID0to7))
2062                         return BusLogic_Failure(HostAdapter, "INQUIRE INSTALLED DEVICES ID 0 TO 7");
2063                 for (TargetID = 0; TargetID < 8; TargetID++)
2064                         HostAdapter->TargetFlags[TargetID].TargetExists = (InstalledDevicesID0to7[TargetID] != 0 ? true : false);
2065         }
2066         /*
2067            Issue the Inquire Setup Information command.
2068          */
2069         RequestedReplyLength = sizeof(SetupInformation);
2070         if (BusLogic_Command(HostAdapter, BusLogic_InquireSetupInformation, &RequestedReplyLength, sizeof(RequestedReplyLength), &SetupInformation, sizeof(SetupInformation))
2071             != sizeof(SetupInformation))
2072                 return BusLogic_Failure(HostAdapter, "INQUIRE SETUP INFORMATION");
2073         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2074                 HostAdapter->SynchronousOffset[TargetID] = (TargetID < 8 ? SetupInformation.SynchronousValuesID0to7[TargetID].Offset : SetupInformation.SynchronousValuesID8to15[TargetID - 8].Offset);
2075         if (strcmp(HostAdapter->FirmwareVersion, "5.06L") >= 0)
2076                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2077                         HostAdapter->TargetFlags[TargetID].WideTransfersActive = (TargetID < 8 ? (SetupInformation.WideTransfersActiveID0to7 & (1 << TargetID)
2078                                                                                                   ? true : false)
2079                                                                                   : (SetupInformation.WideTransfersActiveID8to15 & (1 << (TargetID - 8))
2080                                                                                      ? true : false));
2081         /*
2082            Issue the Inquire Synchronous Period command.
2083          */
2084         if (HostAdapter->FirmwareVersion[0] >= '3') {
2085
2086                 /* Issue a Inquire Synchronous Period command.  For each Target Device,
2087                  * a byte is returned which represents the Synchronous Transfer Period
2088                  * in units of 10 nanoseconds.
2089                  */
2090
2091                 RequestedReplyLength = sizeof(SynchronousPeriod);
2092                 if (BusLogic_Command(HostAdapter, BusLogic_InquireSynchronousPeriod, &RequestedReplyLength, sizeof(RequestedReplyLength), &SynchronousPeriod, sizeof(SynchronousPeriod))
2093                     != sizeof(SynchronousPeriod))
2094                         return BusLogic_Failure(HostAdapter, "INQUIRE SYNCHRONOUS PERIOD");
2095                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2096                         HostAdapter->SynchronousPeriod[TargetID] = SynchronousPeriod[TargetID];
2097         } else
2098                 for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2099                         if (SetupInformation.SynchronousValuesID0to7[TargetID].Offset > 0)
2100                                 HostAdapter->SynchronousPeriod[TargetID] = 20 + 5 * SetupInformation.SynchronousValuesID0to7[TargetID]
2101                                     .TransferPeriod;
2102         /*
2103            Indicate the Target Device Inquiry completed successfully.
2104          */
2105         return true;
2106 }
2107
2108 /*
2109   BusLogic_InitializeHostStructure initializes the fields in the SCSI Host
2110   structure.  The base, io_port, n_io_ports, irq, and dma_channel fields in the
2111   SCSI Host structure are intentionally left uninitialized, as this driver
2112   handles acquisition and release of these resources explicitly, as well as
2113   ensuring exclusive access to the Host Adapter hardware and data structures
2114   through explicit acquisition and release of the Host Adapter's Lock.
2115 */
2116
2117 static void __init BusLogic_InitializeHostStructure(struct BusLogic_HostAdapter
2118                                                     *HostAdapter, struct Scsi_Host *Host)
2119 {
2120         Host->max_id = HostAdapter->MaxTargetDevices;
2121         Host->max_lun = HostAdapter->MaxLogicalUnits;
2122         Host->max_channel = 0;
2123         Host->unique_id = HostAdapter->IO_Address;
2124         Host->this_id = HostAdapter->SCSI_ID;
2125         Host->can_queue = HostAdapter->DriverQueueDepth;
2126         Host->sg_tablesize = HostAdapter->DriverScatterGatherLimit;
2127         Host->unchecked_isa_dma = HostAdapter->BounceBuffersRequired;
2128         Host->cmd_per_lun = HostAdapter->UntaggedQueueDepth;
2129 }
2130
2131 /*
2132   BusLogic_SlaveConfigure will actually set the queue depth on individual
2133   scsi devices as they are permanently added to the device chain.  We
2134   shamelessly rip off the SelectQueueDepths code to make this work mostly
2135   like it used to.  Since we don't get called once at the end of the scan
2136   but instead get called for each device, we have to do things a bit
2137   differently.
2138 */
2139 static int BusLogic_SlaveConfigure(struct scsi_device *Device)
2140 {
2141         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) Device->host->hostdata;
2142         int TargetID = Device->id;
2143         int QueueDepth = HostAdapter->QueueDepth[TargetID];
2144
2145         if (HostAdapter->TargetFlags[TargetID].TaggedQueuingSupported && (HostAdapter->TaggedQueuingPermitted & (1 << TargetID))) {
2146                 if (QueueDepth == 0)
2147                         QueueDepth = BusLogic_MaxAutomaticTaggedQueueDepth;
2148                 HostAdapter->QueueDepth[TargetID] = QueueDepth;
2149                 scsi_adjust_queue_depth(Device, MSG_SIMPLE_TAG, QueueDepth);
2150         } else {
2151                 HostAdapter->TaggedQueuingPermitted &= ~(1 << TargetID);
2152                 QueueDepth = HostAdapter->UntaggedQueueDepth;
2153                 HostAdapter->QueueDepth[TargetID] = QueueDepth;
2154                 scsi_adjust_queue_depth(Device, 0, QueueDepth);
2155         }
2156         QueueDepth = 0;
2157         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++)
2158                 if (HostAdapter->TargetFlags[TargetID].TargetExists) {
2159                         QueueDepth += HostAdapter->QueueDepth[TargetID];
2160                 }
2161         if (QueueDepth > HostAdapter->AllocatedCCBs)
2162                 BusLogic_CreateAdditionalCCBs(HostAdapter, QueueDepth - HostAdapter->AllocatedCCBs, false);
2163         return 0;
2164 }
2165
2166 /*
2167   BusLogic_DetectHostAdapter probes for BusLogic Host Adapters at the standard
2168   I/O Addresses where they may be located, initializing, registering, and
2169   reporting the configuration of each BusLogic Host Adapter it finds.  It
2170   returns the number of BusLogic Host Adapters successfully initialized and
2171   registered.
2172 */
2173
2174 static int __init BusLogic_init(void)
2175 {
2176         int BusLogicHostAdapterCount = 0, DriverOptionsIndex = 0, ProbeIndex;
2177         struct BusLogic_HostAdapter *PrototypeHostAdapter;
2178
2179 #ifdef MODULE
2180         if (BusLogic)
2181                 BusLogic_Setup(BusLogic);
2182 #endif
2183
2184         if (BusLogic_ProbeOptions.NoProbe)
2185                 return -ENODEV;
2186         BusLogic_ProbeInfoList = (struct BusLogic_ProbeInfo *)
2187             kmalloc(BusLogic_MaxHostAdapters * sizeof(struct BusLogic_ProbeInfo), GFP_ATOMIC);
2188         if (BusLogic_ProbeInfoList == NULL) {
2189                 BusLogic_Error("BusLogic: Unable to allocate Probe Info List\n", NULL);
2190                 return -ENOMEM;
2191         }
2192         memset(BusLogic_ProbeInfoList, 0, BusLogic_MaxHostAdapters * sizeof(struct BusLogic_ProbeInfo));
2193         PrototypeHostAdapter = (struct BusLogic_HostAdapter *)
2194             kmalloc(sizeof(struct BusLogic_HostAdapter), GFP_ATOMIC);
2195         if (PrototypeHostAdapter == NULL) {
2196                 kfree(BusLogic_ProbeInfoList);
2197                 BusLogic_Error("BusLogic: Unable to allocate Prototype " "Host Adapter\n", NULL);
2198                 return -ENOMEM;
2199         }
2200         memset(PrototypeHostAdapter, 0, sizeof(struct BusLogic_HostAdapter));
2201 #ifdef MODULE
2202         if (BusLogic != NULL)
2203                 BusLogic_Setup(BusLogic);
2204 #endif
2205         BusLogic_InitializeProbeInfoList(PrototypeHostAdapter);
2206         for (ProbeIndex = 0; ProbeIndex < BusLogic_ProbeInfoCount; ProbeIndex++) {
2207                 struct BusLogic_ProbeInfo *ProbeInfo = &BusLogic_ProbeInfoList[ProbeIndex];
2208                 struct BusLogic_HostAdapter *HostAdapter = PrototypeHostAdapter;
2209                 struct Scsi_Host *Host;
2210                 if (ProbeInfo->IO_Address == 0)
2211                         continue;
2212                 memset(HostAdapter, 0, sizeof(struct BusLogic_HostAdapter));
2213                 HostAdapter->HostAdapterType = ProbeInfo->HostAdapterType;
2214                 HostAdapter->HostAdapterBusType = ProbeInfo->HostAdapterBusType;
2215                 HostAdapter->IO_Address = ProbeInfo->IO_Address;
2216                 HostAdapter->PCI_Address = ProbeInfo->PCI_Address;
2217                 HostAdapter->Bus = ProbeInfo->Bus;
2218                 HostAdapter->Device = ProbeInfo->Device;
2219                 HostAdapter->IRQ_Channel = ProbeInfo->IRQ_Channel;
2220                 HostAdapter->AddressCount = BusLogic_HostAdapterAddressCount[HostAdapter->HostAdapterType];
2221                 /*
2222                    Probe the Host Adapter.  If unsuccessful, abort further initialization.
2223                  */
2224                 if (!BusLogic_ProbeHostAdapter(HostAdapter))
2225                         continue;
2226                 /*
2227                    Hard Reset the Host Adapter.  If unsuccessful, abort further
2228                    initialization.
2229                  */
2230                 if (!BusLogic_HardwareResetHostAdapter(HostAdapter, true))
2231                         continue;
2232                 /*
2233                    Check the Host Adapter.  If unsuccessful, abort further initialization.
2234                  */
2235                 if (!BusLogic_CheckHostAdapter(HostAdapter))
2236                         continue;
2237                 /*
2238                    Initialize the Driver Options field if provided.
2239                  */
2240                 if (DriverOptionsIndex < BusLogic_DriverOptionsCount)
2241                         HostAdapter->DriverOptions = &BusLogic_DriverOptions[DriverOptionsIndex++];
2242                 /*
2243                    Announce the Driver Version and Date, Author's Name, Copyright Notice,
2244                    and Electronic Mail Address.
2245                  */
2246                 BusLogic_AnnounceDriver(HostAdapter);
2247                 /*
2248                    Register usage of the I/O Address range.  From this point onward, any
2249                    failure will be assumed to be due to a problem with the Host Adapter,
2250                    rather than due to having mistakenly identified this port as belonging
2251                    to a BusLogic Host Adapter.  The I/O Address range will not be
2252                    released, thereby preventing it from being incorrectly identified as
2253                    any other type of Host Adapter.
2254                  */
2255                 if (!request_region(HostAdapter->IO_Address, HostAdapter->AddressCount, "BusLogic"))
2256                         continue;
2257                 /*
2258                    Register the SCSI Host structure.
2259                  */
2260
2261                 Host = scsi_host_alloc(&Bus_Logic_template, sizeof(struct BusLogic_HostAdapter));
2262                 if (Host == NULL) {
2263                         release_region(HostAdapter->IO_Address, HostAdapter->AddressCount);
2264                         continue;
2265                 }
2266                 HostAdapter = (struct BusLogic_HostAdapter *) Host->hostdata;
2267                 memcpy(HostAdapter, PrototypeHostAdapter, sizeof(struct BusLogic_HostAdapter));
2268                 HostAdapter->SCSI_Host = Host;
2269                 HostAdapter->HostNumber = Host->host_no;
2270                 /*
2271                    Add Host Adapter to the end of the list of registered BusLogic
2272                    Host Adapters.
2273                  */
2274                 list_add_tail(&HostAdapter->host_list, &BusLogic_host_list);
2275
2276                 /*
2277                    Read the Host Adapter Configuration, Configure the Host Adapter,
2278                    Acquire the System Resources necessary to use the Host Adapter, then
2279                    Create the Initial CCBs, Initialize the Host Adapter, and finally
2280                    perform Target Device Inquiry.
2281                  */
2282                 if (BusLogic_ReadHostAdapterConfiguration(HostAdapter) &&
2283                     BusLogic_ReportHostAdapterConfiguration(HostAdapter) && BusLogic_AcquireResources(HostAdapter) && BusLogic_CreateInitialCCBs(HostAdapter) && BusLogic_InitializeHostAdapter(HostAdapter) && BusLogic_TargetDeviceInquiry(HostAdapter)) {
2284                         /*
2285                            Initialization has been completed successfully.  Release and
2286                            re-register usage of the I/O Address range so that the Model
2287                            Name of the Host Adapter will appear, and initialize the SCSI
2288                            Host structure.
2289                          */
2290                         release_region(HostAdapter->IO_Address, HostAdapter->AddressCount);
2291                         if (!request_region(HostAdapter->IO_Address, HostAdapter->AddressCount, HostAdapter->FullModelName)) {
2292                                 printk(KERN_WARNING "BusLogic: Release and re-register of " "port 0x%04lx failed \n", (unsigned long) HostAdapter->IO_Address);
2293                                 BusLogic_DestroyCCBs(HostAdapter);
2294                                 BusLogic_ReleaseResources(HostAdapter);
2295                                 list_del(&HostAdapter->host_list);
2296                                 scsi_host_put(Host);
2297                         } else {
2298                                 BusLogic_InitializeHostStructure(HostAdapter, Host);
2299                                 scsi_add_host(Host, NULL);
2300                                 scsi_scan_host(Host);
2301                                 BusLogicHostAdapterCount++;
2302                         }
2303                 } else {
2304                         /*
2305                            An error occurred during Host Adapter Configuration Querying, Host
2306                            Adapter Configuration, Resource Acquisition, CCB Creation, Host
2307                            Adapter Initialization, or Target Device Inquiry, so remove Host
2308                            Adapter from the list of registered BusLogic Host Adapters, destroy
2309                            the CCBs, Release the System Resources, and Unregister the SCSI
2310                            Host.
2311                          */
2312                         BusLogic_DestroyCCBs(HostAdapter);
2313                         BusLogic_ReleaseResources(HostAdapter);
2314                         list_del(&HostAdapter->host_list);
2315                         scsi_host_put(Host);
2316                 }
2317         }
2318         kfree(PrototypeHostAdapter);
2319         kfree(BusLogic_ProbeInfoList);
2320         BusLogic_ProbeInfoList = NULL;
2321         return 0;
2322 }
2323
2324
2325 /*
2326   BusLogic_ReleaseHostAdapter releases all resources previously acquired to
2327   support a specific Host Adapter, including the I/O Address range, and
2328   unregisters the BusLogic Host Adapter.
2329 */
2330
2331 static int __exit BusLogic_ReleaseHostAdapter(struct BusLogic_HostAdapter *HostAdapter)
2332 {
2333         struct Scsi_Host *Host = HostAdapter->SCSI_Host;
2334
2335         scsi_remove_host(Host);
2336
2337         /*
2338            FlashPoint Host Adapters must first be released by the FlashPoint
2339            SCCB Manager.
2340          */
2341         if (BusLogic_FlashPointHostAdapterP(HostAdapter))
2342                 FlashPoint_ReleaseHostAdapter(HostAdapter->CardHandle);
2343         /*
2344            Destroy the CCBs and release any system resources acquired to
2345            support Host Adapter.
2346          */
2347         BusLogic_DestroyCCBs(HostAdapter);
2348         BusLogic_ReleaseResources(HostAdapter);
2349         /*
2350            Release usage of the I/O Address range.
2351          */
2352         release_region(HostAdapter->IO_Address, HostAdapter->AddressCount);
2353         /*
2354            Remove Host Adapter from the list of registered BusLogic Host Adapters.
2355          */
2356         list_del(&HostAdapter->host_list);
2357
2358         scsi_host_put(Host);
2359         return 0;
2360 }
2361
2362
2363 /*
2364   BusLogic_QueueCompletedCCB queues CCB for completion processing.
2365 */
2366
2367 static void BusLogic_QueueCompletedCCB(struct BusLogic_CCB *CCB)
2368 {
2369         struct BusLogic_HostAdapter *HostAdapter = CCB->HostAdapter;
2370         CCB->Status = BusLogic_CCB_Completed;
2371         CCB->Next = NULL;
2372         if (HostAdapter->FirstCompletedCCB == NULL) {
2373                 HostAdapter->FirstCompletedCCB = CCB;
2374                 HostAdapter->LastCompletedCCB = CCB;
2375         } else {
2376                 HostAdapter->LastCompletedCCB->Next = CCB;
2377                 HostAdapter->LastCompletedCCB = CCB;
2378         }
2379         HostAdapter->ActiveCommands[CCB->TargetID]--;
2380 }
2381
2382
2383 /*
2384   BusLogic_ComputeResultCode computes a SCSI Subsystem Result Code from
2385   the Host Adapter Status and Target Device Status.
2386 */
2387
2388 static int BusLogic_ComputeResultCode(struct BusLogic_HostAdapter *HostAdapter, enum BusLogic_HostAdapterStatus HostAdapterStatus, enum BusLogic_TargetDeviceStatus TargetDeviceStatus)
2389 {
2390         int HostStatus;
2391         switch (HostAdapterStatus) {
2392         case BusLogic_CommandCompletedNormally:
2393         case BusLogic_LinkedCommandCompleted:
2394         case BusLogic_LinkedCommandCompletedWithFlag:
2395                 HostStatus = DID_OK;
2396                 break;
2397         case BusLogic_SCSISelectionTimeout:
2398                 HostStatus = DID_TIME_OUT;
2399                 break;
2400         case BusLogic_InvalidOutgoingMailboxActionCode:
2401         case BusLogic_InvalidCommandOperationCode:
2402         case BusLogic_InvalidCommandParameter:
2403                 BusLogic_Warning("BusLogic Driver Protocol Error 0x%02X\n", HostAdapter, HostAdapterStatus);
2404         case BusLogic_DataUnderRun:
2405         case BusLogic_DataOverRun:
2406         case BusLogic_UnexpectedBusFree:
2407         case BusLogic_LinkedCCBhasInvalidLUN:
2408         case BusLogic_AutoRequestSenseFailed:
2409         case BusLogic_TaggedQueuingMessageRejected:
2410         case BusLogic_UnsupportedMessageReceived:
2411         case BusLogic_HostAdapterHardwareFailed:
2412         case BusLogic_TargetDeviceReconnectedImproperly:
2413         case BusLogic_AbortQueueGenerated:
2414         case BusLogic_HostAdapterSoftwareError:
2415         case BusLogic_HostAdapterHardwareTimeoutError:
2416         case BusLogic_SCSIParityErrorDetected:
2417                 HostStatus = DID_ERROR;
2418                 break;
2419         case BusLogic_InvalidBusPhaseRequested:
2420         case BusLogic_TargetFailedResponseToATN:
2421         case BusLogic_HostAdapterAssertedRST:
2422         case BusLogic_OtherDeviceAssertedRST:
2423         case BusLogic_HostAdapterAssertedBusDeviceReset:
2424                 HostStatus = DID_RESET;
2425                 break;
2426         default:
2427                 BusLogic_Warning("Unknown Host Adapter Status 0x%02X\n", HostAdapter, HostAdapterStatus);
2428                 HostStatus = DID_ERROR;
2429                 break;
2430         }
2431         return (HostStatus << 16) | TargetDeviceStatus;
2432 }
2433
2434
2435 /*
2436   BusLogic_ScanIncomingMailboxes scans the Incoming Mailboxes saving any
2437   Incoming Mailbox entries for completion processing.
2438 */
2439
2440 static void BusLogic_ScanIncomingMailboxes(struct BusLogic_HostAdapter *HostAdapter)
2441 {
2442         /*
2443            Scan through the Incoming Mailboxes in Strict Round Robin fashion, saving
2444            any completed CCBs for further processing.  It is essential that for each
2445            CCB and SCSI Command issued, command completion processing is performed
2446            exactly once.  Therefore, only Incoming Mailboxes with completion code
2447            Command Completed Without Error, Command Completed With Error, or Command
2448            Aborted At Host Request are saved for completion processing.  When an
2449            Incoming Mailbox has a completion code of Aborted Command Not Found, the
2450            CCB had already completed or been aborted before the current Abort request
2451            was processed, and so completion processing has already occurred and no
2452            further action should be taken.
2453          */
2454         struct BusLogic_IncomingMailbox *NextIncomingMailbox = HostAdapter->NextIncomingMailbox;
2455         enum BusLogic_CompletionCode CompletionCode;
2456         while ((CompletionCode = NextIncomingMailbox->CompletionCode) != BusLogic_IncomingMailboxFree) {
2457                 /*
2458                    We are only allowed to do this because we limit our architectures we
2459                    run on to machines where bus_to_virt() actually works.  There *needs*
2460                    to be a dma_addr_to_virt() in the new PCI DMA mapping interface to
2461                    replace bus_to_virt() or else this code is going to become very
2462                    innefficient.
2463                  */
2464                 struct BusLogic_CCB *CCB = (struct BusLogic_CCB *) Bus_to_Virtual(NextIncomingMailbox->CCB);
2465                 if (CompletionCode != BusLogic_AbortedCommandNotFound) {
2466                         if (CCB->Status == BusLogic_CCB_Active || CCB->Status == BusLogic_CCB_Reset) {
2467                                 /*
2468                                    Save the Completion Code for this CCB and queue the CCB
2469                                    for completion processing.
2470                                  */
2471                                 CCB->CompletionCode = CompletionCode;
2472                                 BusLogic_QueueCompletedCCB(CCB);
2473                         } else {
2474                                 /*
2475                                    If a CCB ever appears in an Incoming Mailbox and is not marked
2476                                    as status Active or Reset, then there is most likely a bug in
2477                                    the Host Adapter firmware.
2478                                  */
2479                                 BusLogic_Warning("Illegal CCB #%ld status %d in " "Incoming Mailbox\n", HostAdapter, CCB->SerialNumber, CCB->Status);
2480                         }
2481                 }
2482                 NextIncomingMailbox->CompletionCode = BusLogic_IncomingMailboxFree;
2483                 if (++NextIncomingMailbox > HostAdapter->LastIncomingMailbox)
2484                         NextIncomingMailbox = HostAdapter->FirstIncomingMailbox;
2485         }
2486         HostAdapter->NextIncomingMailbox = NextIncomingMailbox;
2487 }
2488
2489
2490 /*
2491   BusLogic_ProcessCompletedCCBs iterates over the completed CCBs for Host
2492   Adapter setting the SCSI Command Result Codes, deallocating the CCBs, and
2493   calling the SCSI Subsystem Completion Routines.  The Host Adapter's Lock
2494   should already have been acquired by the caller.
2495 */
2496
2497 static void BusLogic_ProcessCompletedCCBs(struct BusLogic_HostAdapter *HostAdapter)
2498 {
2499         if (HostAdapter->ProcessCompletedCCBsActive)
2500                 return;
2501         HostAdapter->ProcessCompletedCCBsActive = true;
2502         while (HostAdapter->FirstCompletedCCB != NULL) {
2503                 struct BusLogic_CCB *CCB = HostAdapter->FirstCompletedCCB;
2504                 struct scsi_cmnd *Command = CCB->Command;
2505                 HostAdapter->FirstCompletedCCB = CCB->Next;
2506                 if (HostAdapter->FirstCompletedCCB == NULL)
2507                         HostAdapter->LastCompletedCCB = NULL;
2508                 /*
2509                    Process the Completed CCB.
2510                  */
2511                 if (CCB->Opcode == BusLogic_BusDeviceReset) {
2512                         int TargetID = CCB->TargetID;
2513                         BusLogic_Warning("Bus Device Reset CCB #%ld to Target " "%d Completed\n", HostAdapter, CCB->SerialNumber, TargetID);
2514                         BusLogic_IncrementErrorCounter(&HostAdapter->TargetStatistics[TargetID].BusDeviceResetsCompleted);
2515                         HostAdapter->TargetFlags[TargetID].TaggedQueuingActive = false;
2516                         HostAdapter->CommandsSinceReset[TargetID] = 0;
2517                         HostAdapter->LastResetCompleted[TargetID] = jiffies;
2518                         /*
2519                            Place CCB back on the Host Adapter's free list.
2520                          */
2521                         BusLogic_DeallocateCCB(CCB);
2522 #if 0                           /* this needs to be redone different for new EH */
2523                         /*
2524                            Bus Device Reset CCBs have the Command field non-NULL only when a
2525                            Bus Device Reset was requested for a Command that did not have a
2526                            currently active CCB in the Host Adapter (i.e., a Synchronous
2527                            Bus Device Reset), and hence would not have its Completion Routine
2528                            called otherwise.
2529                          */
2530                         while (Command != NULL) {
2531                                 struct scsi_cmnd *NextCommand = Command->reset_chain;
2532                                 Command->reset_chain = NULL;
2533                                 Command->result = DID_RESET << 16;
2534                                 Command->scsi_done(Command);
2535                                 Command = NextCommand;
2536                         }
2537 #endif
2538                         /*
2539                            Iterate over the CCBs for this Host Adapter performing completion
2540                            processing for any CCBs marked as Reset for this Target.
2541                          */
2542                         for (CCB = HostAdapter->All_CCBs; CCB != NULL; CCB = CCB->NextAll)
2543                                 if (CCB->Status == BusLogic_CCB_Reset && CCB->TargetID == TargetID) {
2544                                         Command = CCB->Command;
2545                                         BusLogic_DeallocateCCB(CCB);
2546                                         HostAdapter->ActiveCommands[TargetID]--;
2547                                         Command->result = DID_RESET << 16;
2548                                         Command->scsi_done(Command);
2549                                 }
2550                         HostAdapter->BusDeviceResetPendingCCB[TargetID] = NULL;
2551                 } else {
2552                         /*
2553                            Translate the Completion Code, Host Adapter Status, and Target
2554                            Device Status into a SCSI Subsystem Result Code.
2555                          */
2556                         switch (CCB->CompletionCode) {
2557                         case BusLogic_IncomingMailboxFree:
2558                         case BusLogic_AbortedCommandNotFound:
2559                         case BusLogic_InvalidCCB:
2560                                 BusLogic_Warning("CCB #%ld to Target %d Impossible State\n", HostAdapter, CCB->SerialNumber, CCB->TargetID);
2561                                 break;
2562                         case BusLogic_CommandCompletedWithoutError:
2563                                 HostAdapter->TargetStatistics[CCB->TargetID]
2564                                     .CommandsCompleted++;
2565                                 HostAdapter->TargetFlags[CCB->TargetID]
2566                                     .CommandSuccessfulFlag = true;
2567                                 Command->result = DID_OK << 16;
2568                                 break;
2569                         case BusLogic_CommandAbortedAtHostRequest:
2570                                 BusLogic_Warning("CCB #%ld to Target %d Aborted\n", HostAdapter, CCB->SerialNumber, CCB->TargetID);
2571                                 BusLogic_IncrementErrorCounter(&HostAdapter->TargetStatistics[CCB->TargetID]
2572                                                                .CommandAbortsCompleted);
2573                                 Command->result = DID_ABORT << 16;
2574                                 break;
2575                         case BusLogic_CommandCompletedWithError:
2576                                 Command->result = BusLogic_ComputeResultCode(HostAdapter, CCB->HostAdapterStatus, CCB->TargetDeviceStatus);
2577                                 if (CCB->HostAdapterStatus != BusLogic_SCSISelectionTimeout) {
2578                                         HostAdapter->TargetStatistics[CCB->TargetID]
2579                                             .CommandsCompleted++;
2580                                         if (BusLogic_GlobalOptions.TraceErrors) {
2581                                                 int i;
2582                                                 BusLogic_Notice("CCB #%ld Target %d: Result %X Host "
2583                                                                 "Adapter Status %02X " "Target Status %02X\n", HostAdapter, CCB->SerialNumber, CCB->TargetID, Command->result, CCB->HostAdapterStatus, CCB->TargetDeviceStatus);
2584                                                 BusLogic_Notice("CDB   ", HostAdapter);
2585                                                 for (i = 0; i < CCB->CDB_Length; i++)
2586                                                         BusLogic_Notice(" %02X", HostAdapter, CCB->CDB[i]);
2587                                                 BusLogic_Notice("\n", HostAdapter);
2588                                                 BusLogic_Notice("Sense ", HostAdapter);
2589                                                 for (i = 0; i < CCB->SenseDataLength; i++)
2590                                                         BusLogic_Notice(" %02X", HostAdapter, Command->sense_buffer[i]);
2591                                                 BusLogic_Notice("\n", HostAdapter);
2592                                         }
2593                                 }
2594                                 break;
2595                         }
2596                         /*
2597                            When an INQUIRY command completes normally, save the
2598                            CmdQue (Tagged Queuing Supported) and WBus16 (16 Bit
2599                            Wide Data Transfers Supported) bits.
2600                          */
2601                         if (CCB->CDB[0] == INQUIRY && CCB->CDB[1] == 0 && CCB->HostAdapterStatus == BusLogic_CommandCompletedNormally) {
2602                                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[CCB->TargetID];
2603                                 struct SCSI_Inquiry *InquiryResult = (struct SCSI_Inquiry *) Command->request_buffer;
2604                                 TargetFlags->TargetExists = true;
2605                                 TargetFlags->TaggedQueuingSupported = InquiryResult->CmdQue;
2606                                 TargetFlags->WideTransfersSupported = InquiryResult->WBus16;
2607                         }
2608                         /*
2609                            Place CCB back on the Host Adapter's free list.
2610                          */
2611                         BusLogic_DeallocateCCB(CCB);
2612                         /*
2613                            Call the SCSI Command Completion Routine.
2614                          */
2615                         Command->scsi_done(Command);
2616                 }
2617         }
2618         HostAdapter->ProcessCompletedCCBsActive = false;
2619 }
2620
2621
2622 /*
2623   BusLogic_InterruptHandler handles hardware interrupts from BusLogic Host
2624   Adapters.
2625 */
2626
2627 static irqreturn_t BusLogic_InterruptHandler(int IRQ_Channel, void *DeviceIdentifier, struct pt_regs *InterruptRegisters)
2628 {
2629         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) DeviceIdentifier;
2630         unsigned long ProcessorFlags;
2631         /*
2632            Acquire exclusive access to Host Adapter.
2633          */
2634         spin_lock_irqsave(HostAdapter->SCSI_Host->host_lock, ProcessorFlags);
2635         /*
2636            Handle Interrupts appropriately for each Host Adapter type.
2637          */
2638         if (BusLogic_MultiMasterHostAdapterP(HostAdapter)) {
2639                 union BusLogic_InterruptRegister InterruptRegister;
2640                 /*
2641                    Read the Host Adapter Interrupt Register.
2642                  */
2643                 InterruptRegister.All = BusLogic_ReadInterruptRegister(HostAdapter);
2644                 if (InterruptRegister.ir.InterruptValid) {
2645                         /*
2646                            Acknowledge the interrupt and reset the Host Adapter
2647                            Interrupt Register.
2648                          */
2649                         BusLogic_InterruptReset(HostAdapter);
2650                         /*
2651                            Process valid External SCSI Bus Reset and Incoming Mailbox
2652                            Loaded Interrupts.  Command Complete Interrupts are noted,
2653                            and Outgoing Mailbox Available Interrupts are ignored, as
2654                            they are never enabled.
2655                          */
2656                         if (InterruptRegister.ir.ExternalBusReset)
2657                                 HostAdapter->HostAdapterExternalReset = true;
2658                         else if (InterruptRegister.ir.IncomingMailboxLoaded)
2659                                 BusLogic_ScanIncomingMailboxes(HostAdapter);
2660                         else if (InterruptRegister.ir.CommandComplete)
2661                                 HostAdapter->HostAdapterCommandCompleted = true;
2662                 }
2663         } else {
2664                 /*
2665                    Check if there is a pending interrupt for this Host Adapter.
2666                  */
2667                 if (FlashPoint_InterruptPending(HostAdapter->CardHandle))
2668                         switch (FlashPoint_HandleInterrupt(HostAdapter->CardHandle)) {
2669                         case FlashPoint_NormalInterrupt:
2670                                 break;
2671                         case FlashPoint_ExternalBusReset:
2672                                 HostAdapter->HostAdapterExternalReset = true;
2673                                 break;
2674                         case FlashPoint_InternalError:
2675                                 BusLogic_Warning("Internal FlashPoint Error detected" " - Resetting Host Adapter\n", HostAdapter);
2676                                 HostAdapter->HostAdapterInternalError = true;
2677                                 break;
2678                         }
2679         }
2680         /*
2681            Process any completed CCBs.
2682          */
2683         if (HostAdapter->FirstCompletedCCB != NULL)
2684                 BusLogic_ProcessCompletedCCBs(HostAdapter);
2685         /*
2686            Reset the Host Adapter if requested.
2687          */
2688         if (HostAdapter->HostAdapterExternalReset) {
2689                 BusLogic_Warning("Resetting %s due to External SCSI Bus Reset\n", HostAdapter, HostAdapter->FullModelName);
2690                 BusLogic_IncrementErrorCounter(&HostAdapter->ExternalHostAdapterResets);
2691                 BusLogic_ResetHostAdapter(HostAdapter, false);
2692                 HostAdapter->HostAdapterExternalReset = false;
2693         } else if (HostAdapter->HostAdapterInternalError) {
2694                 BusLogic_Warning("Resetting %s due to Host Adapter Internal Error\n", HostAdapter, HostAdapter->FullModelName);
2695                 BusLogic_IncrementErrorCounter(&HostAdapter->HostAdapterInternalErrors);
2696                 BusLogic_ResetHostAdapter(HostAdapter, true);
2697                 HostAdapter->HostAdapterInternalError = false;
2698         }
2699         /*
2700            Release exclusive access to Host Adapter.
2701          */
2702         spin_unlock_irqrestore(HostAdapter->SCSI_Host->host_lock, ProcessorFlags);
2703         return IRQ_HANDLED;
2704 }
2705
2706
2707 /*
2708   BusLogic_WriteOutgoingMailbox places CCB and Action Code into an Outgoing
2709   Mailbox for execution by Host Adapter.  The Host Adapter's Lock should
2710   already have been acquired by the caller.
2711 */
2712
2713 static boolean BusLogic_WriteOutgoingMailbox(struct BusLogic_HostAdapter
2714                                              *HostAdapter, enum BusLogic_ActionCode ActionCode, struct BusLogic_CCB *CCB)
2715 {
2716         struct BusLogic_OutgoingMailbox *NextOutgoingMailbox;
2717         NextOutgoingMailbox = HostAdapter->NextOutgoingMailbox;
2718         if (NextOutgoingMailbox->ActionCode == BusLogic_OutgoingMailboxFree) {
2719                 CCB->Status = BusLogic_CCB_Active;
2720                 /*
2721                    The CCB field must be written before the Action Code field since
2722                    the Host Adapter is operating asynchronously and the locking code
2723                    does not protect against simultaneous access by the Host Adapter.
2724                  */
2725                 NextOutgoingMailbox->CCB = CCB->DMA_Handle;
2726                 NextOutgoingMailbox->ActionCode = ActionCode;
2727                 BusLogic_StartMailboxCommand(HostAdapter);
2728                 if (++NextOutgoingMailbox > HostAdapter->LastOutgoingMailbox)
2729                         NextOutgoingMailbox = HostAdapter->FirstOutgoingMailbox;
2730                 HostAdapter->NextOutgoingMailbox = NextOutgoingMailbox;
2731                 if (ActionCode == BusLogic_MailboxStartCommand) {
2732                         HostAdapter->ActiveCommands[CCB->TargetID]++;
2733                         if (CCB->Opcode != BusLogic_BusDeviceReset)
2734                                 HostAdapter->TargetStatistics[CCB->TargetID].CommandsAttempted++;
2735                 }
2736                 return true;
2737         }
2738         return false;
2739 }
2740
2741 /* Error Handling (EH) support */
2742
2743 static int BusLogic_host_reset(struct scsi_cmnd * SCpnt)
2744 {
2745         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) SCpnt->device->host->hostdata;
2746
2747         unsigned int id = SCpnt->device->id;
2748         struct BusLogic_TargetStatistics *stats = &HostAdapter->TargetStatistics[id];
2749         int rc;
2750
2751         spin_lock_irq(SCpnt->device->host->host_lock);
2752
2753         BusLogic_IncrementErrorCounter(&stats->HostAdapterResetsRequested);
2754
2755         rc = BusLogic_ResetHostAdapter(HostAdapter, false);
2756         spin_unlock_irq(SCpnt->device->host->host_lock);
2757         return rc;
2758 }
2759
2760 /*
2761   BusLogic_QueueCommand creates a CCB for Command and places it into an
2762   Outgoing Mailbox for execution by the associated Host Adapter.
2763 */
2764
2765 static int BusLogic_QueueCommand(struct scsi_cmnd *Command, void (*CompletionRoutine) (struct scsi_cmnd *))
2766 {
2767         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) Command->device->host->hostdata;
2768         struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[Command->device->id];
2769         struct BusLogic_TargetStatistics *TargetStatistics = HostAdapter->TargetStatistics;
2770         unsigned char *CDB = Command->cmnd;
2771         int CDB_Length = Command->cmd_len;
2772         int TargetID = Command->device->id;
2773         int LogicalUnit = Command->device->lun;
2774         void *BufferPointer = Command->request_buffer;
2775         int BufferLength = Command->request_bufflen;
2776         int SegmentCount = Command->use_sg;
2777         struct BusLogic_CCB *CCB;
2778         /*
2779            SCSI REQUEST_SENSE commands will be executed automatically by the Host
2780            Adapter for any errors, so they should not be executed explicitly unless
2781            the Sense Data is zero indicating that no error occurred.
2782          */
2783         if (CDB[0] == REQUEST_SENSE && Command->sense_buffer[0] != 0) {
2784                 Command->result = DID_OK << 16;
2785                 CompletionRoutine(Command);
2786                 return 0;
2787         }
2788         /*
2789            Allocate a CCB from the Host Adapter's free list.  In the unlikely event
2790            that there are none available and memory allocation fails, wait 1 second
2791            and try again.  If that fails, the Host Adapter is probably hung so signal
2792            an error as a Host Adapter Hard Reset should be initiated soon.
2793          */
2794         CCB = BusLogic_AllocateCCB(HostAdapter);
2795         if (CCB == NULL) {
2796                 spin_unlock_irq(HostAdapter->SCSI_Host->host_lock);
2797                 BusLogic_Delay(1);
2798                 spin_lock_irq(HostAdapter->SCSI_Host->host_lock);
2799                 CCB = BusLogic_AllocateCCB(HostAdapter);
2800                 if (CCB == NULL) {
2801                         Command->result = DID_ERROR << 16;
2802                         CompletionRoutine(Command);
2803                         return 0;
2804                 }
2805         }
2806         /*
2807            Initialize the fields in the BusLogic Command Control Block (CCB).
2808          */
2809         if (SegmentCount == 0 && BufferLength != 0) {
2810                 CCB->Opcode = BusLogic_InitiatorCCB;
2811                 CCB->DataLength = BufferLength;
2812                 CCB->DataPointer = pci_map_single(HostAdapter->PCI_Device,
2813                                 BufferPointer, BufferLength,
2814                                 Command->sc_data_direction);
2815         } else if (SegmentCount != 0) {
2816                 struct scatterlist *ScatterList = (struct scatterlist *) BufferPointer;
2817                 int Segment, Count;
2818
2819                 Count = pci_map_sg(HostAdapter->PCI_Device, ScatterList, SegmentCount,
2820                                 Command->sc_data_direction);
2821                 CCB->Opcode = BusLogic_InitiatorCCB_ScatterGather;
2822                 CCB->DataLength = Count * sizeof(struct BusLogic_ScatterGatherSegment);
2823                 if (BusLogic_MultiMasterHostAdapterP(HostAdapter))
2824                         CCB->DataPointer = (unsigned int) CCB->DMA_Handle + ((unsigned long) &CCB->ScatterGatherList - (unsigned long) CCB);
2825                 else
2826                         CCB->DataPointer = Virtual_to_32Bit_Virtual(CCB->ScatterGatherList);
2827                 for (Segment = 0; Segment < Count; Segment++) {
2828                         CCB->ScatterGatherList[Segment].SegmentByteCount = sg_dma_len(ScatterList + Segment);
2829                         CCB->ScatterGatherList[Segment].SegmentDataPointer = sg_dma_address(ScatterList + Segment);
2830                 }
2831         } else {
2832                 CCB->Opcode = BusLogic_InitiatorCCB;
2833                 CCB->DataLength = BufferLength;
2834                 CCB->DataPointer = 0;
2835         }
2836         switch (CDB[0]) {
2837         case READ_6:
2838         case READ_10:
2839                 CCB->DataDirection = BusLogic_DataInLengthChecked;
2840                 TargetStatistics[TargetID].ReadCommands++;
2841                 BusLogic_IncrementByteCounter(&TargetStatistics[TargetID].TotalBytesRead, BufferLength);
2842                 BusLogic_IncrementSizeBucket(TargetStatistics[TargetID].ReadCommandSizeBuckets, BufferLength);
2843                 break;
2844         case WRITE_6:
2845         case WRITE_10:
2846                 CCB->DataDirection = BusLogic_DataOutLengthChecked;
2847                 TargetStatistics[TargetID].WriteCommands++;
2848                 BusLogic_IncrementByteCounter(&TargetStatistics[TargetID].TotalBytesWritten, BufferLength);
2849                 BusLogic_IncrementSizeBucket(TargetStatistics[TargetID].WriteCommandSizeBuckets, BufferLength);
2850                 break;
2851         default:
2852                 CCB->DataDirection = BusLogic_UncheckedDataTransfer;
2853                 break;
2854         }
2855         CCB->CDB_Length = CDB_Length;
2856         CCB->HostAdapterStatus = 0;
2857         CCB->TargetDeviceStatus = 0;
2858         CCB->TargetID = TargetID;
2859         CCB->LogicalUnit = LogicalUnit;
2860         CCB->TagEnable = false;
2861         CCB->LegacyTagEnable = false;
2862         /*
2863            BusLogic recommends that after a Reset the first couple of commands that
2864            are sent to a Target Device be sent in a non Tagged Queue fashion so that
2865            the Host Adapter and Target Device can establish Synchronous and Wide
2866            Transfer before Queue Tag messages can interfere with the Synchronous and
2867            Wide Negotiation messages.  By waiting to enable Tagged Queuing until after
2868            the first BusLogic_MaxTaggedQueueDepth commands have been queued, it is
2869            assured that after a Reset any pending commands are requeued before Tagged
2870            Queuing is enabled and that the Tagged Queuing message will not occur while
2871            the partition table is being printed.  In addition, some devices do not
2872            properly handle the transition from non-tagged to tagged commands, so it is
2873            necessary to wait until there are no pending commands for a target device
2874            before queuing tagged commands.
2875          */
2876         if (HostAdapter->CommandsSinceReset[TargetID]++ >=
2877             BusLogic_MaxTaggedQueueDepth && !TargetFlags->TaggedQueuingActive && HostAdapter->ActiveCommands[TargetID] == 0 && TargetFlags->TaggedQueuingSupported && (HostAdapter->TaggedQueuingPermitted & (1 << TargetID))) {
2878                 TargetFlags->TaggedQueuingActive = true;
2879                 BusLogic_Notice("Tagged Queuing now active for Target %d\n", HostAdapter, TargetID);
2880         }
2881         if (TargetFlags->TaggedQueuingActive) {
2882                 enum BusLogic_QueueTag QueueTag = BusLogic_SimpleQueueTag;
2883                 /*
2884                    When using Tagged Queuing with Simple Queue Tags, it appears that disk
2885                    drive controllers do not guarantee that a queued command will not
2886                    remain in a disconnected state indefinitely if commands that read or
2887                    write nearer the head position continue to arrive without interruption.
2888                    Therefore, for each Target Device this driver keeps track of the last
2889                    time either the queue was empty or an Ordered Queue Tag was issued.  If
2890                    more than 4 seconds (one fifth of the 20 second disk timeout) have
2891                    elapsed since this last sequence point, this command will be issued
2892                    with an Ordered Queue Tag rather than a Simple Queue Tag, which forces
2893                    the Target Device to complete all previously queued commands before
2894                    this command may be executed.
2895                  */
2896                 if (HostAdapter->ActiveCommands[TargetID] == 0)
2897                         HostAdapter->LastSequencePoint[TargetID] = jiffies;
2898                 else if (jiffies - HostAdapter->LastSequencePoint[TargetID] > 4 * HZ) {
2899                         HostAdapter->LastSequencePoint[TargetID] = jiffies;
2900                         QueueTag = BusLogic_OrderedQueueTag;
2901                 }
2902                 if (HostAdapter->ExtendedLUNSupport) {
2903                         CCB->TagEnable = true;
2904                         CCB->QueueTag = QueueTag;
2905                 } else {
2906                         CCB->LegacyTagEnable = true;
2907                         CCB->LegacyQueueTag = QueueTag;
2908                 }
2909         }
2910         memcpy(CCB->CDB, CDB, CDB_Length);
2911         CCB->SenseDataLength = sizeof(Command->sense_buffer);
2912         CCB->SenseDataPointer = pci_map_single(HostAdapter->PCI_Device, Command->sense_buffer, CCB->SenseDataLength, PCI_DMA_FROMDEVICE);
2913         CCB->Command = Command;
2914         Command->scsi_done = CompletionRoutine;
2915         if (BusLogic_MultiMasterHostAdapterP(HostAdapter)) {
2916                 /*
2917                    Place the CCB in an Outgoing Mailbox.  The higher levels of the SCSI
2918                    Subsystem should not attempt to queue more commands than can be placed
2919                    in Outgoing Mailboxes, so there should always be one free.  In the
2920                    unlikely event that there are none available, wait 1 second and try
2921                    again.  If that fails, the Host Adapter is probably hung so signal an
2922                    error as a Host Adapter Hard Reset should be initiated soon.
2923                  */
2924                 if (!BusLogic_WriteOutgoingMailbox(HostAdapter, BusLogic_MailboxStartCommand, CCB)) {
2925                         spin_unlock_irq(HostAdapter->SCSI_Host->host_lock);
2926                         BusLogic_Warning("Unable to write Outgoing Mailbox - " "Pausing for 1 second\n", HostAdapter);
2927                         BusLogic_Delay(1);
2928                         spin_lock_irq(HostAdapter->SCSI_Host->host_lock);
2929                         if (!BusLogic_WriteOutgoingMailbox(HostAdapter, BusLogic_MailboxStartCommand, CCB)) {
2930                                 BusLogic_Warning("Still unable to write Outgoing Mailbox - " "Host Adapter Dead?\n", HostAdapter);
2931                                 BusLogic_DeallocateCCB(CCB);
2932                                 Command->result = DID_ERROR << 16;
2933                                 Command->scsi_done(Command);
2934                         }
2935                 }
2936         } else {
2937                 /*
2938                    Call the FlashPoint SCCB Manager to start execution of the CCB.
2939                  */
2940                 CCB->Status = BusLogic_CCB_Active;
2941                 HostAdapter->ActiveCommands[TargetID]++;
2942                 TargetStatistics[TargetID].CommandsAttempted++;
2943                 FlashPoint_StartCCB(HostAdapter->CardHandle, CCB);
2944                 /*
2945                    The Command may have already completed and BusLogic_QueueCompletedCCB
2946                    been called, or it may still be pending.
2947                  */
2948                 if (CCB->Status == BusLogic_CCB_Completed)
2949                         BusLogic_ProcessCompletedCCBs(HostAdapter);
2950         }
2951         return 0;
2952 }
2953
2954
2955 /*
2956   BusLogic_AbortCommand aborts Command if possible.
2957 */
2958
2959 static int BusLogic_AbortCommand(struct scsi_cmnd *Command)
2960 {
2961         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) Command->device->host->hostdata;
2962
2963         int TargetID = Command->device->id;
2964         struct BusLogic_CCB *CCB;
2965         BusLogic_IncrementErrorCounter(&HostAdapter->TargetStatistics[TargetID].CommandAbortsRequested);
2966         /*
2967            Attempt to find an Active CCB for this Command.  If no Active CCB for this
2968            Command is found, then no Abort is necessary.
2969          */
2970         for (CCB = HostAdapter->All_CCBs; CCB != NULL; CCB = CCB->NextAll)
2971                 if (CCB->Command == Command)
2972                         break;
2973         if (CCB == NULL) {
2974                 BusLogic_Warning("Unable to Abort Command to Target %d - " "No CCB Found\n", HostAdapter, TargetID);
2975                 return SUCCESS;
2976         } else if (CCB->Status == BusLogic_CCB_Completed) {
2977                 BusLogic_Warning("Unable to Abort Command to Target %d - " "CCB Completed\n", HostAdapter, TargetID);
2978                 return SUCCESS;
2979         } else if (CCB->Status == BusLogic_CCB_Reset) {
2980                 BusLogic_Warning("Unable to Abort Command to Target %d - " "CCB Reset\n", HostAdapter, TargetID);
2981                 return SUCCESS;
2982         }
2983         if (BusLogic_MultiMasterHostAdapterP(HostAdapter)) {
2984                 /*
2985                    Attempt to Abort this CCB.  MultiMaster Firmware versions prior to 5.xx
2986                    do not generate Abort Tag messages, but only generate the non-tagged
2987                    Abort message.  Since non-tagged commands are not sent by the Host
2988                    Adapter until the queue of outstanding tagged commands has completed,
2989                    and the Abort message is treated as a non-tagged command, it is
2990                    effectively impossible to abort commands when Tagged Queuing is active.
2991                    Firmware version 5.xx does generate Abort Tag messages, so it is
2992                    possible to abort commands when Tagged Queuing is active.
2993                  */
2994                 if (HostAdapter->TargetFlags[TargetID].TaggedQueuingActive && HostAdapter->FirmwareVersion[0] < '5') {
2995                         BusLogic_Warning("Unable to Abort CCB #%ld to Target %d - " "Abort Tag Not Supported\n", HostAdapter, CCB->SerialNumber, TargetID);
2996                         return FAILURE;
2997                 } else if (BusLogic_WriteOutgoingMailbox(HostAdapter, BusLogic_MailboxAbortCommand, CCB)) {
2998                         BusLogic_Warning("Aborting CCB #%ld to Target %d\n", HostAdapter, CCB->SerialNumber, TargetID);
2999                         BusLogic_IncrementErrorCounter(&HostAdapter->TargetStatistics[TargetID].CommandAbortsAttempted);
3000                         return SUCCESS;
3001                 } else {
3002                         BusLogic_Warning("Unable to Abort CCB #%ld to Target %d - " "No Outgoing Mailboxes\n", HostAdapter, CCB->SerialNumber, TargetID);
3003                         return FAILURE;
3004                 }
3005         } else {
3006                 /*
3007                    Call the FlashPoint SCCB Manager to abort execution of the CCB.
3008                  */
3009                 BusLogic_Warning("Aborting CCB #%ld to Target %d\n", HostAdapter, CCB->SerialNumber, TargetID);
3010                 BusLogic_IncrementErrorCounter(&HostAdapter->TargetStatistics[TargetID].CommandAbortsAttempted);
3011                 FlashPoint_AbortCCB(HostAdapter->CardHandle, CCB);
3012                 /*
3013                    The Abort may have already been completed and
3014                    BusLogic_QueueCompletedCCB been called, or it
3015                    may still be pending.
3016                  */
3017                 if (CCB->Status == BusLogic_CCB_Completed) {
3018                         BusLogic_ProcessCompletedCCBs(HostAdapter);
3019                 }
3020                 return SUCCESS;
3021         }
3022         return SUCCESS;
3023 }
3024
3025 /*
3026   BusLogic_ResetHostAdapter resets Host Adapter if possible, marking all
3027   currently executing SCSI Commands as having been Reset.
3028 */
3029
3030 static int BusLogic_ResetHostAdapter(struct BusLogic_HostAdapter *HostAdapter, boolean HardReset)
3031 {
3032         struct BusLogic_CCB *CCB;
3033         int TargetID;
3034
3035         /*
3036          * Attempt to Reset and Reinitialize the Host Adapter.
3037          */
3038
3039         if (!(BusLogic_HardwareResetHostAdapter(HostAdapter, HardReset) && BusLogic_InitializeHostAdapter(HostAdapter))) {
3040                 BusLogic_Error("Resetting %s Failed\n", HostAdapter, HostAdapter->FullModelName);
3041                 return FAILURE;
3042         }
3043
3044         /*
3045          * Deallocate all currently executing CCBs.
3046          */
3047
3048         for (CCB = HostAdapter->All_CCBs; CCB != NULL; CCB = CCB->NextAll)
3049                 if (CCB->Status == BusLogic_CCB_Active)
3050                         BusLogic_DeallocateCCB(CCB);
3051         /*
3052          * Wait a few seconds between the Host Adapter Hard Reset which
3053          * initiates a SCSI Bus Reset and issuing any SCSI Commands.  Some
3054          * SCSI devices get confused if they receive SCSI Commands too soon
3055          * after a SCSI Bus Reset.
3056          */
3057
3058         if (HardReset) {
3059                 spin_unlock_irq(HostAdapter->SCSI_Host->host_lock);
3060                 BusLogic_Delay(HostAdapter->BusSettleTime);
3061                 spin_lock_irq(HostAdapter->SCSI_Host->host_lock);
3062         }
3063
3064         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3065                 HostAdapter->LastResetAttempted[TargetID] = jiffies;
3066                 HostAdapter->LastResetCompleted[TargetID] = jiffies;
3067         }
3068         return SUCCESS;
3069 }
3070
3071 /*
3072   BusLogic_BIOSDiskParameters returns the Heads/Sectors/Cylinders BIOS Disk
3073   Parameters for Disk.  The default disk geometry is 64 heads, 32 sectors, and
3074   the appropriate number of cylinders so as not to exceed drive capacity.  In
3075   order for disks equal to or larger than 1 GB to be addressable by the BIOS
3076   without exceeding the BIOS limitation of 1024 cylinders, Extended Translation
3077   may be enabled in AutoSCSI on FlashPoint Host Adapters and on "W" and "C"
3078   series MultiMaster Host Adapters, or by a dip switch setting on "S" and "A"
3079   series MultiMaster Host Adapters.  With Extended Translation enabled, drives
3080   between 1 GB inclusive and 2 GB exclusive are given a disk geometry of 128
3081   heads and 32 sectors, and drives above 2 GB inclusive are given a disk
3082   geometry of 255 heads and 63 sectors.  However, if the BIOS detects that the
3083   Extended Translation setting does not match the geometry in the partition
3084   table, then the translation inferred from the partition table will be used by
3085   the BIOS, and a warning may be displayed.
3086 */
3087
3088 static int BusLogic_BIOSDiskParameters(struct scsi_device *sdev, struct block_device *Device, sector_t capacity, int *Parameters)
3089 {
3090         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) sdev->host->hostdata;
3091         struct BIOS_DiskParameters *DiskParameters = (struct BIOS_DiskParameters *) Parameters;
3092         unsigned char *buf;
3093         if (HostAdapter->ExtendedTranslationEnabled && capacity >= 2 * 1024 * 1024 /* 1 GB in 512 byte sectors */ ) {
3094                 if (capacity >= 4 * 1024 * 1024 /* 2 GB in 512 byte sectors */ ) {
3095                         DiskParameters->Heads = 255;
3096                         DiskParameters->Sectors = 63;
3097                 } else {
3098                         DiskParameters->Heads = 128;
3099                         DiskParameters->Sectors = 32;
3100                 }
3101         } else {
3102                 DiskParameters->Heads = 64;
3103                 DiskParameters->Sectors = 32;
3104         }
3105         DiskParameters->Cylinders = (unsigned long) capacity / (DiskParameters->Heads * DiskParameters->Sectors);
3106         buf = scsi_bios_ptable(Device);
3107         if (buf == NULL)
3108                 return 0;
3109         /*
3110            If the boot sector partition table flag is valid, search for a partition
3111            table entry whose end_head matches one of the standard BusLogic geometry
3112            translations (64/32, 128/32, or 255/63).
3113          */
3114         if (*(unsigned short *) (buf + 64) == 0xAA55) {
3115                 struct partition *FirstPartitionEntry = (struct partition *) buf;
3116                 struct partition *PartitionEntry = FirstPartitionEntry;
3117                 int SavedCylinders = DiskParameters->Cylinders, PartitionNumber;
3118                 unsigned char PartitionEntryEndHead = 0, PartitionEntryEndSector = 0;
3119                 for (PartitionNumber = 0; PartitionNumber < 4; PartitionNumber++) {
3120                         PartitionEntryEndHead = PartitionEntry->end_head;
3121                         PartitionEntryEndSector = PartitionEntry->end_sector & 0x3F;
3122                         if (PartitionEntryEndHead == 64 - 1) {
3123                                 DiskParameters->Heads = 64;
3124                                 DiskParameters->Sectors = 32;
3125                                 break;
3126                         } else if (PartitionEntryEndHead == 128 - 1) {
3127                                 DiskParameters->Heads = 128;
3128                                 DiskParameters->Sectors = 32;
3129                                 break;
3130                         } else if (PartitionEntryEndHead == 255 - 1) {
3131                                 DiskParameters->Heads = 255;
3132                                 DiskParameters->Sectors = 63;
3133                                 break;
3134                         }
3135                         PartitionEntry++;
3136                 }
3137                 if (PartitionNumber == 4) {
3138                         PartitionEntryEndHead = FirstPartitionEntry->end_head;
3139                         PartitionEntryEndSector = FirstPartitionEntry->end_sector & 0x3F;
3140                 }
3141                 DiskParameters->Cylinders = (unsigned long) capacity / (DiskParameters->Heads * DiskParameters->Sectors);
3142                 if (PartitionNumber < 4 && PartitionEntryEndSector == DiskParameters->Sectors) {
3143                         if (DiskParameters->Cylinders != SavedCylinders)
3144                                 BusLogic_Warning("Adopting Geometry %d/%d from Partition Table\n", HostAdapter, DiskParameters->Heads, DiskParameters->Sectors);
3145                 } else if (PartitionEntryEndHead > 0 || PartitionEntryEndSector > 0) {
3146                         BusLogic_Warning("Warning: Partition Table appears to " "have Geometry %d/%d which is\n", HostAdapter, PartitionEntryEndHead + 1, PartitionEntryEndSector);
3147                         BusLogic_Warning("not compatible with current BusLogic " "Host Adapter Geometry %d/%d\n", HostAdapter, DiskParameters->Heads, DiskParameters->Sectors);
3148                 }
3149         }
3150         kfree(buf);
3151         return 0;
3152 }
3153
3154
3155 /*
3156   BugLogic_ProcDirectoryInfo implements /proc/scsi/BusLogic/<N>.
3157 */
3158
3159 static int BusLogic_ProcDirectoryInfo(struct Scsi_Host *shost, char *ProcBuffer, char **StartPointer, off_t Offset, int BytesAvailable, int WriteFlag)
3160 {
3161         struct BusLogic_HostAdapter *HostAdapter = (struct BusLogic_HostAdapter *) shost->hostdata;
3162         struct BusLogic_TargetStatistics *TargetStatistics;
3163         int TargetID, Length;
3164         char *Buffer;
3165
3166         TargetStatistics = HostAdapter->TargetStatistics;
3167         if (WriteFlag) {
3168                 HostAdapter->ExternalHostAdapterResets = 0;
3169                 HostAdapter->HostAdapterInternalErrors = 0;
3170                 memset(TargetStatistics, 0, BusLogic_MaxTargetDevices * sizeof(struct BusLogic_TargetStatistics));
3171                 return 0;
3172         }
3173         Buffer = HostAdapter->MessageBuffer;
3174         Length = HostAdapter->MessageBufferLength;
3175         Length += sprintf(&Buffer[Length], "\n\
3176 Current Driver Queue Depth:     %d\n\
3177 Currently Allocated CCBs:       %d\n", HostAdapter->DriverQueueDepth, HostAdapter->AllocatedCCBs);
3178         Length += sprintf(&Buffer[Length], "\n\n\
3179                            DATA TRANSFER STATISTICS\n\
3180 \n\
3181 Target  Tagged Queuing  Queue Depth  Active  Attempted  Completed\n\
3182 ======  ==============  ===========  ======  =========  =========\n");
3183         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3184                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[TargetID];
3185                 if (!TargetFlags->TargetExists)
3186                         continue;
3187                 Length += sprintf(&Buffer[Length], "  %2d       %s", TargetID, (TargetFlags->TaggedQueuingSupported ? (TargetFlags->TaggedQueuingActive ? "    Active" : (HostAdapter->TaggedQueuingPermitted & (1 << TargetID)
3188                                                                                                                                                                     ? "  Permitted" : "   Disabled"))
3189                                                                           : "Not Supported"));
3190                 Length += sprintf(&Buffer[Length],
3191                                   "         %3d       %3u    %9u        %9u\n", HostAdapter->QueueDepth[TargetID], HostAdapter->ActiveCommands[TargetID], TargetStatistics[TargetID].CommandsAttempted, TargetStatistics[TargetID].CommandsCompleted);
3192         }
3193         Length += sprintf(&Buffer[Length], "\n\
3194 Target  Read Commands  Write Commands   Total Bytes Read    Total Bytes Written\n\
3195 ======  =============  ==============  ===================  ===================\n");
3196         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3197                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[TargetID];
3198                 if (!TargetFlags->TargetExists)
3199                         continue;
3200                 Length += sprintf(&Buffer[Length], "  %2d         %9u    %9u", TargetID, TargetStatistics[TargetID].ReadCommands, TargetStatistics[TargetID].WriteCommands);
3201                 if (TargetStatistics[TargetID].TotalBytesRead.Billions > 0)
3202                         Length += sprintf(&Buffer[Length], "     %9u%09u", TargetStatistics[TargetID].TotalBytesRead.Billions, TargetStatistics[TargetID].TotalBytesRead.Units);
3203                 else
3204                         Length += sprintf(&Buffer[Length], "            %9u", TargetStatistics[TargetID].TotalBytesRead.Units);
3205                 if (TargetStatistics[TargetID].TotalBytesWritten.Billions > 0)
3206                         Length += sprintf(&Buffer[Length], "   %9u%09u\n", TargetStatistics[TargetID].TotalBytesWritten.Billions, TargetStatistics[TargetID].TotalBytesWritten.Units);
3207                 else
3208                         Length += sprintf(&Buffer[Length], "         %9u\n", TargetStatistics[TargetID].TotalBytesWritten.Units);
3209         }
3210         Length += sprintf(&Buffer[Length], "\n\
3211 Target  Command    0-1KB      1-2KB      2-4KB      4-8KB     8-16KB\n\
3212 ======  =======  =========  =========  =========  =========  =========\n");
3213         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3214                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[TargetID];
3215                 if (!TargetFlags->TargetExists)
3216                         continue;
3217                 Length +=
3218                     sprintf(&Buffer[Length],
3219                             "  %2d       Read    %9u  %9u  %9u  %9u  %9u\n", TargetID,
3220                             TargetStatistics[TargetID].ReadCommandSizeBuckets[0],
3221                             TargetStatistics[TargetID].ReadCommandSizeBuckets[1], TargetStatistics[TargetID].ReadCommandSizeBuckets[2], TargetStatistics[TargetID].ReadCommandSizeBuckets[3], TargetStatistics[TargetID].ReadCommandSizeBuckets[4]);
3222                 Length +=
3223                     sprintf(&Buffer[Length],
3224                             "  %2d       Write   %9u  %9u  %9u  %9u  %9u\n", TargetID,
3225                             TargetStatistics[TargetID].WriteCommandSizeBuckets[0],
3226                             TargetStatistics[TargetID].WriteCommandSizeBuckets[1], TargetStatistics[TargetID].WriteCommandSizeBuckets[2], TargetStatistics[TargetID].WriteCommandSizeBuckets[3], TargetStatistics[TargetID].WriteCommandSizeBuckets[4]);
3227         }
3228         Length += sprintf(&Buffer[Length], "\n\
3229 Target  Command   16-32KB    32-64KB   64-128KB   128-256KB   256KB+\n\
3230 ======  =======  =========  =========  =========  =========  =========\n");
3231         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3232                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[TargetID];
3233                 if (!TargetFlags->TargetExists)
3234                         continue;
3235                 Length +=
3236                     sprintf(&Buffer[Length],
3237                             "  %2d       Read    %9u  %9u  %9u  %9u  %9u\n", TargetID,
3238                             TargetStatistics[TargetID].ReadCommandSizeBuckets[5],
3239                             TargetStatistics[TargetID].ReadCommandSizeBuckets[6], TargetStatistics[TargetID].ReadCommandSizeBuckets[7], TargetStatistics[TargetID].ReadCommandSizeBuckets[8], TargetStatistics[TargetID].ReadCommandSizeBuckets[9]);
3240                 Length +=
3241                     sprintf(&Buffer[Length],
3242                             "  %2d       Write   %9u  %9u  %9u  %9u  %9u\n", TargetID,
3243                             TargetStatistics[TargetID].WriteCommandSizeBuckets[5],
3244                             TargetStatistics[TargetID].WriteCommandSizeBuckets[6], TargetStatistics[TargetID].WriteCommandSizeBuckets[7], TargetStatistics[TargetID].WriteCommandSizeBuckets[8], TargetStatistics[TargetID].WriteCommandSizeBuckets[9]);
3245         }
3246         Length += sprintf(&Buffer[Length], "\n\n\
3247                            ERROR RECOVERY STATISTICS\n\
3248 \n\
3249           Command Aborts      Bus Device Resets   Host Adapter Resets\n\
3250 Target  Requested Completed  Requested Completed  Requested Completed\n\
3251   ID    \\\\\\\\ Attempted ////  \\\\\\\\ Attempted ////  \\\\\\\\ Attempted ////\n\
3252 ======   ===== ===== =====    ===== ===== =====    ===== ===== =====\n");
3253         for (TargetID = 0; TargetID < HostAdapter->MaxTargetDevices; TargetID++) {
3254                 struct BusLogic_TargetFlags *TargetFlags = &HostAdapter->TargetFlags[TargetID];
3255                 if (!TargetFlags->TargetExists)
3256                         continue;
3257                 Length += sprintf(&Buffer[Length], "\
3258   %2d    %5d %5d %5d    %5d %5d %5d        %5d %5d %5d\n", TargetID, TargetStatistics[TargetID].CommandAbortsRequested, TargetStatistics[TargetID].CommandAbortsAttempted, TargetStatistics[TargetID].CommandAbortsCompleted, TargetStatistics[TargetID].BusDeviceResetsRequested, TargetStatistics[TargetID].BusDeviceResetsAttempted, TargetStatistics[TargetID].BusDeviceResetsCompleted, TargetStatistics[TargetID].HostAdapterResetsRequested, TargetStatistics[TargetID].HostAdapterResetsAttempted, TargetStatistics[TargetID].HostAdapterResetsCompleted);
3259         }
3260         Length += sprintf(&Buffer[Length], "\nExternal Host Adapter Resets: %d\n", HostAdapter->ExternalHostAdapterResets);
3261         Length += sprintf(&Buffer[Length], "Host Adapter Internal Errors: %d\n", HostAdapter->HostAdapterInternalErrors);
3262         if (Length >= BusLogic_MessageBufferSize)
3263                 BusLogic_Error("Message Buffer length %d exceeds size %d\n", HostAdapter, Length, BusLogic_MessageBufferSize);
3264         if ((Length -= Offset) <= 0)
3265                 return 0;
3266         if (Length >= BytesAvailable)
3267                 Length = BytesAvailable;
3268         memcpy(ProcBuffer, HostAdapter->MessageBuffer + Offset, Length);
3269         *StartPointer = ProcBuffer;
3270         return Length;
3271 }
3272
3273
3274 /*
3275   BusLogic_Message prints Driver Messages.
3276 */
3277
3278 static void BusLogic_Message(enum BusLogic_MessageLevel MessageLevel, char *Format, struct BusLogic_HostAdapter *HostAdapter, ...)
3279 {
3280         static char Buffer[BusLogic_LineBufferSize];
3281         static boolean BeginningOfLine = true;
3282         va_list Arguments;
3283         int Length = 0;
3284         va_start(Arguments, HostAdapter);
3285         Length = vsprintf(Buffer, Format, Arguments);
3286         va_end(Arguments);
3287         if (MessageLevel == BusLogic_AnnounceLevel) {
3288                 static int AnnouncementLines = 0;
3289                 strcpy(&HostAdapter->MessageBuffer[HostAdapter->MessageBufferLength], Buffer);
3290                 HostAdapter->MessageBufferLength += Length;
3291                 if (++AnnouncementLines <= 2)
3292                         printk("%sscsi: %s", BusLogic_MessageLevelMap[MessageLevel], Buffer);
3293         } else if (MessageLevel == BusLogic_InfoLevel) {
3294                 strcpy(&HostAdapter->MessageBuffer[HostAdapter->MessageBufferLength], Buffer);
3295                 HostAdapter->MessageBufferLength += Length;
3296                 if (BeginningOfLine) {
3297                         if (Buffer[0] != '\n' || Length > 1)
3298                                 printk("%sscsi%d: %s", BusLogic_MessageLevelMap[MessageLevel], HostAdapter->HostNumber, Buffer);
3299                 } else
3300                         printk("%s", Buffer);
3301         } else {
3302                 if (BeginningOfLine) {
3303                         if (HostAdapter != NULL && HostAdapter->HostAdapterInitialized)
3304                                 printk("%sscsi%d: %s", BusLogic_MessageLevelMap[MessageLevel], HostAdapter->HostNumber, Buffer);
3305                         else
3306                                 printk("%s%s", BusLogic_MessageLevelMap[MessageLevel], Buffer);
3307                 } else
3308                         printk("%s", Buffer);
3309         }
3310         BeginningOfLine = (Buffer[Length - 1] == '\n');
3311 }
3312
3313
3314 /*
3315   BusLogic_ParseKeyword parses an individual option keyword.  It returns true
3316   and updates the pointer if the keyword is recognized and false otherwise.
3317 */
3318
3319 static boolean __init BusLogic_ParseKeyword(char **StringPointer, char *Keyword)
3320 {
3321         char *Pointer = *StringPointer;
3322         while (*Keyword != '\0') {
3323                 char StringChar = *Pointer++;
3324                 char KeywordChar = *Keyword++;
3325                 if (StringChar >= 'A' && StringChar <= 'Z')
3326                         StringChar += 'a' - 'Z';
3327                 if (KeywordChar >= 'A' && KeywordChar <= 'Z')
3328                         KeywordChar += 'a' - 'Z';
3329                 if (StringChar != KeywordChar)
3330                         return false;
3331         }
3332         *StringPointer = Pointer;
3333         return true;
3334 }
3335
3336
3337 /*
3338   BusLogic_ParseDriverOptions handles processing of BusLogic Driver Options
3339   specifications.
3340
3341   BusLogic Driver Options may be specified either via the Linux Kernel Command
3342   Line or via the Loadable Kernel Module Installation Facility.  Driver Options
3343   for multiple host adapters may be specified either by separating the option
3344   strings by a semicolon, or by specifying multiple "BusLogic=" strings on the
3345   command line.  Individual option specifications for a single host adapter are
3346   separated by commas.  The Probing and Debugging Options apply to all host
3347   adapters whereas the remaining options apply individually only to the
3348   selected host adapter.
3349
3350   The BusLogic Driver Probing Options are described in
3351   <file:Documentation/scsi/BusLogic.txt>.
3352 */
3353
3354 static int __init BusLogic_ParseDriverOptions(char *OptionsString)
3355 {
3356         while (true) {
3357                 struct BusLogic_DriverOptions *DriverOptions = &BusLogic_DriverOptions[BusLogic_DriverOptionsCount++];
3358                 int TargetID;
3359                 memset(DriverOptions, 0, sizeof(struct BusLogic_DriverOptions));
3360                 while (*OptionsString != '\0' && *OptionsString != ';') {
3361                         /* Probing Options. */
3362                         if (BusLogic_ParseKeyword(&OptionsString, "IO:")) {
3363                                 unsigned long IO_Address = simple_strtoul(OptionsString, &OptionsString, 0);
3364                                 BusLogic_ProbeOptions.LimitedProbeISA = true;
3365                                 switch (IO_Address) {
3366                                 case 0x330:
3367                                         BusLogic_ProbeOptions.Probe330 = true;
3368                                         break;
3369                                 case 0x334:
3370                                         BusLogic_ProbeOptions.Probe334 = true;
3371                                         break;
3372                                 case 0x230:
3373                                         BusLogic_ProbeOptions.Probe230 = true;
3374                                         break;
3375                                 case 0x234:
3376                                         BusLogic_ProbeOptions.Probe234 = true;
3377                                         break;
3378                                 case 0x130:
3379                                         BusLogic_ProbeOptions.Probe130 = true;
3380                                         break;
3381                                 case 0x134:
3382                                         BusLogic_ProbeOptions.Probe134 = true;
3383                                         break;
3384                                 default:
3385                                         BusLogic_Error("BusLogic: Invalid Driver Options " "(invalid I/O Address 0x%X)\n", NULL, IO_Address);
3386                                         return 0;
3387                                 }
3388                         } else if (BusLogic_ParseKeyword(&OptionsString, "NoProbeISA"))
3389                                 BusLogic_ProbeOptions.NoProbeISA = true;
3390                         else if (BusLogic_ParseKeyword(&OptionsString, "NoProbePCI"))
3391                                 BusLogic_ProbeOptions.NoProbePCI = true;
3392                         else if (BusLogic_ParseKeyword(&OptionsString, "NoProbe"))
3393                                 BusLogic_ProbeOptions.NoProbe = true;
3394                         else if (BusLogic_ParseKeyword(&OptionsString, "NoSortPCI"))
3395                                 BusLogic_ProbeOptions.NoSortPCI = true;
3396                         else if (BusLogic_ParseKeyword(&OptionsString, "MultiMasterFirst"))
3397                                 BusLogic_ProbeOptions.MultiMasterFirst = true;
3398                         else if (BusLogic_ParseKeyword(&OptionsString, "FlashPointFirst"))
3399                                 BusLogic_ProbeOptions.FlashPointFirst = true;
3400                         /* Tagged Queuing Options. */
3401                         else if (BusLogic_ParseKeyword(&OptionsString, "QueueDepth:[") || BusLogic_ParseKeyword(&OptionsString, "QD:[")) {
3402                                 for (TargetID = 0; TargetID < BusLogic_MaxTargetDevices; TargetID++) {
3403                                         unsigned short QueueDepth = simple_strtoul(OptionsString, &OptionsString, 0);
3404                                         if (QueueDepth > BusLogic_MaxTaggedQueueDepth) {
3405                                                 BusLogic_Error("BusLogic: Invalid Driver Options " "(invalid Queue Depth %d)\n", NULL, QueueDepth);
3406                                                 return 0;
3407                                         }
3408                                         DriverOptions->QueueDepth[TargetID] = QueueDepth;
3409                                         if (*OptionsString == ',')
3410                                                 OptionsString++;
3411                                         else if (*OptionsString == ']')
3412                                                 break;
3413                                         else {
3414                                                 BusLogic_Error("BusLogic: Invalid Driver Options " "(',' or ']' expected at '%s')\n", NULL, OptionsString);
3415                                                 return 0;
3416                                         }
3417                                 }
3418                                 if (*OptionsString != ']') {
3419                                         BusLogic_Error("BusLogic: Invalid Driver Options " "(']' expected at '%s')\n", NULL, OptionsString);
3420                                         return 0;
3421                                 } else
3422                                         OptionsString++;
3423                         } else if (BusLogic_ParseKeyword(&OptionsString, "QueueDepth:") || BusLogic_ParseKeyword(&OptionsString, "QD:")) {
3424                                 unsigned short QueueDepth = simple_strtoul(OptionsString, &OptionsString, 0);
3425                                 if (QueueDepth == 0 || QueueDepth > BusLogic_MaxTaggedQueueDepth) {
3426                                         BusLogic_Error("BusLogic: Invalid Driver Options " "(invalid Queue Depth %d)\n", NULL, QueueDepth);
3427                                         return 0;
3428                                 }
3429                                 DriverOptions->CommonQueueDepth = QueueDepth;
3430                                 for (TargetID = 0; TargetID < BusLogic_MaxTargetDevices; TargetID++)
3431                                         DriverOptions->QueueDepth[TargetID] = QueueDepth;
3432                         } else if (BusLogic_ParseKeyword(&OptionsString, "TaggedQueuing:") || BusLogic_ParseKeyword(&OptionsString, "TQ:")) {
3433                                 if (BusLogic_ParseKeyword(&OptionsString, "Default")) {
3434                                         DriverOptions->TaggedQueuingPermitted = 0x0000;
3435                                         DriverOptions->TaggedQueuingPermittedMask = 0x0000;
3436                                 } else if (BusLogic_ParseKeyword(&OptionsString, "Enable")) {
3437                                         DriverOptions->TaggedQueuingPermitted = 0xFFFF;
3438                                         DriverOptions->TaggedQueuingPermittedMask = 0xFFFF;
3439                                 } else if (BusLogic_ParseKeyword(&OptionsString, "Disable")) {
3440                                         DriverOptions->TaggedQueuingPermitted = 0x0000;
3441                                         DriverOptions->TaggedQueuingPermittedMask = 0xFFFF;
3442                                 } else {
3443                                         unsigned short TargetBit;
3444                                         for (TargetID = 0, TargetBit = 1; TargetID < BusLogic_MaxTargetDevices; TargetID++, TargetBit <<= 1)
3445                                                 switch (*OptionsString++) {
3446                                                 case 'Y':
3447                                                         DriverOptions->TaggedQueuingPermitted |= TargetBit;
3448                                                         DriverOptions->TaggedQueuingPermittedMask |= TargetBit;
3449                                                         break;
3450                                                 case 'N':
3451                                                         DriverOptions->TaggedQueuingPermitted &= ~TargetBit;
3452                                                         DriverOptions->TaggedQueuingPermittedMask |= TargetBit;
3453                                                         break;
3454                                                 case 'X':
3455                                                         break;
3456                                                 default:
3457                                                         OptionsString--;
3458                                                         TargetID = BusLogic_MaxTargetDevices;
3459                                                         break;
3460                                                 }
3461                                 }
3462                         }
3463                         /* Miscellaneous Options. */
3464                         else if (BusLogic_ParseKeyword(&OptionsString, "BusSettleTime:") || BusLogic_ParseKeyword(&OptionsString, "BST:")) {
3465                                 unsigned short BusSettleTime = simple_strtoul(OptionsString, &OptionsString, 0);
3466                                 if (BusSettleTime > 5 * 60) {
3467                                         BusLogic_Error("BusLogic: Invalid Driver Options " "(invalid Bus Settle Time %d)\n", NULL, BusSettleTime);
3468                                         return 0;
3469                                 }
3470                                 DriverOptions->BusSettleTime = BusSettleTime;
3471                         } else if (BusLogic_ParseKeyword(&OptionsString, "InhibitTargetInquiry"))
3472                                 DriverOptions->LocalOptions.InhibitTargetInquiry = true;
3473                         /* Debugging Options. */
3474                         else if (BusLogic_ParseKeyword(&OptionsString, "TraceProbe"))
3475                                 BusLogic_GlobalOptions.TraceProbe = true;
3476                         else if (BusLogic_ParseKeyword(&OptionsString, "TraceHardwareReset"))
3477                                 BusLogic_GlobalOptions.TraceHardwareReset = true;
3478                         else if (BusLogic_ParseKeyword(&OptionsString, "TraceConfiguration"))
3479                                 BusLogic_GlobalOptions.TraceConfiguration = true;
3480                         else if (BusLogic_ParseKeyword(&OptionsString, "TraceErrors"))
3481                                 BusLogic_GlobalOptions.TraceErrors = true;
3482                         else if (BusLogic_ParseKeyword(&OptionsString, "Debug")) {
3483                                 BusLogic_GlobalOptions.TraceProbe = true;
3484                                 BusLogic_GlobalOptions.TraceHardwareReset = true;
3485                                 BusLogic_GlobalOptions.TraceConfiguration = true;
3486                                 BusLogic_GlobalOptions.TraceErrors = true;
3487                         }
3488                         if (*OptionsString == ',')
3489                                 OptionsString++;
3490                         else if (*OptionsString != ';' && *OptionsString != '\0') {
3491                                 BusLogic_Error("BusLogic: Unexpected Driver Option '%s' " "ignored\n", NULL, OptionsString);
3492                                 *OptionsString = '\0';
3493                         }
3494                 }
3495                 if (!(BusLogic_DriverOptionsCount == 0 || BusLogic_ProbeInfoCount == 0 || BusLogic_DriverOptionsCount == BusLogic_ProbeInfoCount)) {
3496                         BusLogic_Error("BusLogic: Invalid Driver Options " "(all or no I/O Addresses must be specified)\n", NULL);
3497                         return 0;
3498                 }
3499                 /*
3500                    Tagged Queuing is disabled when the Queue Depth is 1 since queuing
3501                    multiple commands is not possible.
3502                  */
3503                 for (TargetID = 0; TargetID < BusLogic_MaxTargetDevices; TargetID++)
3504                         if (DriverOptions->QueueDepth[TargetID] == 1) {
3505                                 unsigned short TargetBit = 1 << TargetID;
3506                                 DriverOptions->TaggedQueuingPermitted &= ~TargetBit;
3507                                 DriverOptions->TaggedQueuingPermittedMask |= TargetBit;
3508                         }
3509                 if (*OptionsString == ';')
3510                         OptionsString++;
3511                 if (*OptionsString == '\0')
3512                         return 0;
3513         }
3514         return 1;
3515 }
3516
3517 /*
3518   Get it all started
3519 */
3520
3521 static struct scsi_host_template Bus_Logic_template = {
3522         .module = THIS_MODULE,
3523         .proc_name = "BusLogic",
3524         .proc_info = BusLogic_ProcDirectoryInfo,
3525         .name = "BusLogic",
3526         .info = BusLogic_DriverInfo,
3527         .queuecommand = BusLogic_QueueCommand,
3528         .slave_configure = BusLogic_SlaveConfigure,
3529         .bios_param = BusLogic_BIOSDiskParameters,
3530         .eh_host_reset_handler = BusLogic_host_reset,
3531 #if 0
3532         .eh_abort_handler = BusLogic_AbortCommand,
3533 #endif
3534         .unchecked_isa_dma = 1,
3535         .max_sectors = 128,
3536         .use_clustering = ENABLE_CLUSTERING,
3537 };
3538
3539 /*
3540   BusLogic_Setup handles processing of Kernel Command Line Arguments.
3541 */
3542
3543 static int __init BusLogic_Setup(char *str)
3544 {
3545         int ints[3];
3546
3547         (void) get_options(str, ARRAY_SIZE(ints), ints);
3548
3549         if (ints[0] != 0) {
3550                 BusLogic_Error("BusLogic: Obsolete Command Line Entry " "Format Ignored\n", NULL);
3551                 return 0;
3552         }
3553         if (str == NULL || *str == '\0')
3554                 return 0;
3555         return BusLogic_ParseDriverOptions(str);
3556 }
3557
3558 /*
3559  * Exit function.  Deletes all hosts associated with this driver.
3560  */
3561
3562 static void __exit BusLogic_exit(void)
3563 {
3564         struct BusLogic_HostAdapter *ha, *next;
3565
3566         list_for_each_entry_safe(ha, next, &BusLogic_host_list, host_list)
3567                 BusLogic_ReleaseHostAdapter(ha);
3568 }
3569
3570 __setup("BusLogic=", BusLogic_Setup);
3571
3572 module_init(BusLogic_init);
3573 module_exit(BusLogic_exit);