patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / scsi / tmscsim.c
1 /************************************************************************
2  *      FILE NAME : TMSCSIM.C                                           *
3  *           BY   : C.L. Huang,  ching@tekram.com.tw                    *
4  *      Description: Device Driver for Tekram DC-390(T) PCI SCSI        *
5  *                   Bus Master Host Adapter                            *
6  * (C)Copyright 1995-1996 Tekram Technology Co., Ltd.                   *
7  ************************************************************************
8  * (C) Copyright: put under GNU GPL in 10/96                            *
9  *                              (see Documentation/scsi/tmscsim.txt)    *
10  ************************************************************************
11  * $Id: tmscsim.c,v 2.60.2.30 2000/12/20 01:07:12 garloff Exp $         *
12  *      Enhancements and bugfixes by                                    *
13  *      Kurt Garloff <kurt@garloff.de>  <garloff@suse.de>               *
14  ************************************************************************
15  *      HISTORY:                                                        *
16  *                                                                      *
17  *      REV#    DATE    NAME    DESCRIPTION                             *
18  *      1.00  96/04/24  CLH     First release                           *
19  *      1.01  96/06/12  CLH     Fixed bug of Media Change for Removable *
20  *                              Device, scan all LUN. Support Pre2.0.10 *
21  *      1.02  96/06/18  CLH     Fixed bug of Command timeout ...        *
22  *      1.03  96/09/25  KG      Added tmscsim_proc_info()               *
23  *      1.04  96/10/11  CLH     Updating for support KV 2.0.x           *
24  *      1.05  96/10/18  KG      Fixed bug in DC390_abort(null ptr deref)*
25  *      1.06  96/10/25  KG      Fixed module support                    *
26  *      1.07  96/11/09  KG      Fixed tmscsim_proc_info()               *
27  *      1.08  96/11/18  KG      Fixed null ptr in DC390_Disconnect()    *
28  *      1.09  96/11/30  KG      Added register the allocated IO space   *
29  *      1.10  96/12/05  CLH     Modified tmscsim_proc_info(), and reset *
30  *                              pending interrupt in DC390_detect()     *
31  *      1.11  97/02/05  KG/CLH  Fixeds problem with partitions greater  *
32  *                              than 1GB                                *
33  *      1.12  98/02/15  MJ      Rewritten PCI probing                   *
34  *      1.13  98/04/08  KG      Support for non DC390, __initfunc decls,*
35  *                              changed max devs from 10 to 16          *
36  *      1.14a 98/05/05  KG      Dynamic DCB allocation, add-single-dev  *
37  *                              for LUNs if LUN_SCAN (BIOS) not set     *
38  *                              runtime config using /proc interface    *
39  *      1.14b 98/05/06  KG      eliminated cli (); sti (); spinlocks    *
40  *      1.14c 98/05/07  KG      2.0.x compatibility                     *
41  *      1.20a 98/05/07  KG      changed names of funcs to be consistent *
42  *                              DC390_ (entry points), dc390_ (internal)*
43  *                              reworked locking                        *
44  *      1.20b 98/05/12  KG      bugs: version, kfree, _ctmp             *
45  *                              debug output                            *
46  *      1.20c 98/05/12  KG      bugs: kfree, parsing, EEpromDefaults    *
47  *      1.20d 98/05/14  KG      bugs: list linkage, clear flag after    *
48  *                              reset on startup, code cleanup          *
49  *      1.20e 98/05/15  KG      spinlock comments, name space cleanup   *
50  *                              pLastDCB now part of ACB structure      *
51  *                              added stats, timeout for 2.1, TagQ bug  *
52  *                              RESET and INQUIRY interface commands    *
53  *      1.20f 98/05/18  KG      spinlocks fixes, max_lun fix, free DCBs *
54  *                              for missing LUNs, pending int           *
55  *      1.20g 98/05/19  KG      Clean up: Avoid short                   *
56  *      1.20h 98/05/21  KG      Remove AdaptSCSIID, max_lun ...         *
57  *      1.20i 98/05/21  KG      Aiiie: Bug with TagQMask                *
58  *      1.20j 98/05/24  KG      Handle STAT_BUSY, handle pACB->pLinkDCB *
59  *                              == 0 in remove_dev and DoingSRB_Done    *
60  *      1.20k 98/05/25  KG      DMA_INT (experimental)                  *
61  *      1.20l 98/05/27  KG      remove DMA_INT; DMA_IDLE cmds added;    *
62  *      1.20m 98/06/10  KG      glitch configurable; made some global   *
63  *                              vars part of ACB; use DC390_readX       *
64  *      1.20n 98/06/11  KG      startup params                          *
65  *      1.20o 98/06/15  KG      added TagMaxNum to boot/module params   *
66  *                              Device Nr -> Idx, TagMaxNum power of 2  *
67  *      1.20p 98/06/17  KG      Docu updates. Reset depends on settings *
68  *                              pci_set_master added; 2.0.xx: pcibios_* *
69  *                              used instead of MechNum things ...      *
70  *      1.20q 98/06/23  KG      Changed defaults. Added debug code for  *
71  *                              removable media and fixed it. TagMaxNum *
72  *                              fixed for DC390. Locking: ACB, DRV for  *
73  *                              better IRQ sharing. Spelling: Queueing  *
74  *                              Parsing and glitch_cfg changes. Display *
75  *                              real SyncSpeed value. Made DisConn      *
76  *                              functional (!)                          *
77  *      1.20r 98/06/30  KG      Debug macros, allow disabling DsCn, set *
78  *                              BIT4 in CtrlR4, EN_PAGE_INT, 2.0 module *
79  *                              param -1 fixed.                         *
80  *      1.20s 98/08/20  KG      Debug info on abort(), try to check PCI,*
81  *                              phys_to_bus instead of phys_to_virt,    *
82  *                              fixed sel. process, fixed locking,      *
83  *                              added MODULE_XXX infos, changed IRQ     *
84  *                              request flags, disable DMA_INT          *
85  *      1.20t 98/09/07  KG      TagQ report fixed; Write Erase DMA Stat;*
86  *                              initfunc -> __init; better abort;       *
87  *                              Timeout for XFER_DONE & BLAST_COMPLETE; *
88  *                              Allow up to 33 commands being processed *
89  *      2.0a  98/10/14  KG      Max Cmnds back to 17. DMA_Stat clearing *
90  *                              all flags. Clear within while() loops   *
91  *                              in DataIn_0/Out_0. Null ptr in dumpinfo *
92  *                              for pSRB==0. Better locking during init.*
93  *                              bios_param() now respects part. table.  *
94  *      2.0b  98/10/24  KG      Docu fixes. Timeout Msg in DMA Blast.   *
95  *                              Disallow illegal idx in INQUIRY/REMOVE  *
96  *      2.0c  98/11/19  KG      Cleaned up detect/init for SMP boxes,   *
97  *                              Write Erase DMA (1.20t) caused problems *
98  *      2.0d  98/12/25  KG      Christmas release ;-) Message handling  *
99  *                              completely reworked. Handle target ini- *
100  *                              tiated SDTR correctly.                  *
101  *      2.0d1 99/01/25  KG      Try to handle RESTORE_PTR               *
102  *      2.0d2 99/02/08  KG      Check for failure of kmalloc, correct   *
103  *                              inclusion of scsicam.h, DelayReset      *
104  *      2.0d3 99/05/31  KG      DRIVER_OK -> DID_OK, DID_NO_CONNECT,    *
105  *                              detect Target mode and warn.            *
106  *                              pcmd->result handling cleaned up.       *
107  *      2.0d4 99/06/01  KG      Cleaned selection process. Found bug    *
108  *                              which prevented more than 16 tags. Now: *
109  *                              24. SDTR cleanup. Cleaner multi-LUN     *
110  *                              handling. Don't modify ControlRegs/FIFO *
111  *                              when connected.                         *
112  *      2.0d5 99/06/01  KG      Clear DevID, Fix INQUIRY after cfg chg. *
113  *      2.0d6 99/06/02  KG      Added ADD special command to allow cfg. *
114  *                              before detection. Reset SYNC_NEGO_DONE  *
115  *                              after a bus reset.                      *
116  *      2.0d7 99/06/03  KG      Fixed bugs wrt add,remove commands      *
117  *      2.0d8 99/06/04  KG      Removed copying of cmnd into CmdBlock.  *
118  *                              Fixed Oops in _release().               *
119  *      2.0d9 99/06/06  KG      Also tag queue INQUIRY, T_U_R, ...      *
120  *                              Allow arb. no. of Tagged Cmnds. Max 32  *
121  *      2.0d1099/06/20  KG      TagMaxNo changes now honoured! Queueing *
122  *                              clearified (renamed ..) TagMask handling*
123  *                              cleaned.                                *
124  *      2.0d1199/06/28  KG      cmd->result now identical to 2.0d2      *
125  *      2.0d1299/07/04  KG      Changed order of processing in IRQ      *
126  *      2.0d1399/07/05  KG      Don't update DCB fields if removed      *
127  *      2.0d1499/07/05  KG      remove_dev: Move kfree() to the end     *
128  *      2.0d1599/07/12  KG      use_new_eh_code: 0, ULONG -> UINT where *
129  *                              appropriate                             *
130  *      2.0d1699/07/13  KG      Reenable StartSCSI interrupt, Retry msg *
131  *      2.0d1799/07/15  KG      Remove debug msg. Disable recfg. when   *
132  *                              there are queued cmnds                  *
133  *      2.0d1899/07/18  KG      Selection timeout: Don't requeue        *
134  *      2.0d1999/07/18  KG      Abort: Only call scsi_done if dequeued  *
135  *      2.0d2099/07/19  KG      Rst_Detect: DoingSRB_Done               *
136  *      2.0d2199/08/15  KG      dev_id for request/free_irq, cmnd[0] for*
137  *                              RETRY, SRBdone does DID_ABORT for the   *
138  *                              cmd passed by DC390_reset()             *
139  *      2.0d2299/08/25  KG      dev_id fixed. can_queue: 42             *
140  *      2.0d2399/08/25  KG      Removed some debugging code. dev_id     *
141  *                              now is set to pACB. Use u8,u16,u32.     *
142  *      2.0d2499/11/14  KG      Unreg. I/O if failed IRQ alloc. Call    *
143  *                              done () w/ DID_BAD_TARGET in case of    *
144  *                              missing DCB. We are old EH!!            *
145  *      2.0d2500/01/15  KG      2.3.3x compat from Andreas Schultz      *
146  *                              set unique_id. Disable RETRY message.   *
147  *      2.0d2600/01/29  KG      Go to new EH.                           *
148  *      2.0d2700/01/31  KG      ... but maintain 2.0 compat.            *
149  *                              and fix DCB freeing                     *
150  *      2.0d2800/02/14  KG      Queue statistics fixed, dump special cmd*
151  *                              Waiting_Timer for failed StartSCSI      *
152  *                              New EH: Don't return cmnds to ML on RST *
153  *                              Use old EH (don't have new EH fns yet)  *
154  *                              Reset: Unlock, but refuse to queue      *
155  *                              2.3 __setup function                    *
156  *      2.0e  00/05/22  KG      Return residual for 2.3                 *
157  *      2.0e1 00/05/25  KG      Compile fixes for 2.3.99                *
158  *      2.0e2 00/05/27  KG      Jeff Garzik's pci_enable_device()       *
159  *      2.0e3 00/09/29  KG      Some 2.4 changes. Don't try Sync Nego   *
160  *                              before INQUIRY has reported ability.    *
161  *                              Recognise INQUIRY as scanning command.  *
162  *      2.0e4 00/10/13  KG      Allow compilation into 2.4 kernel       *
163  *      2.0e5 00/11/17  KG      Store Inq.flags in DCB                  *
164  *      2.0e6 00/11/22  KG      2.4 init function (Thx to O.Schumann)   *
165  *                              2.4 PCI device table (Thx to A.Richter) *
166  *      2.0e7 00/11/28  KG      Allow overriding of BIOS settings       *
167  *      2.0f  00/12/20  KG      Handle failed INQUIRYs during scan      *
168  *      2.1a  03/11/29  GL, KG  Initial fixing for 2.6. Convert to      *
169  *                              use the current PCI-mapping API, update *
170  *                              command-queuing.                        *
171  *      2.1b  04/04/13  GL      Fix for 64-bit platforms                *
172  *      2.1b1 04/01/31  GL      (applied 05.04) Remove internal         *
173  *                              command-queuing.                        *
174  *      2.1b2 04/02/01  CH      (applied 05.04) Fix error-handling      *
175  ***********************************************************************/
176
177 /* Uncomment SA_INTERRUPT, if the driver refuses to share its IRQ with other devices */
178 #define DC390_IRQ SA_SHIRQ /* | SA_INTERRUPT */
179
180 /* DEBUG options */
181 //#define DC390_DEBUG0
182 //#define DC390_DEBUG1
183 //#define DC390_DCBDEBUG
184 //#define DC390_PARSEDEBUG
185 //#define DC390_REMOVABLEDEBUG
186 //#define DC390_LOCKDEBUG
187
188 //#define NOP do{}while(0)
189 #define C_NOP
190
191 /* Debug definitions */
192 #ifdef DC390_DEBUG0
193 # define DEBUG0(x) x
194 #else
195 # define DEBUG0(x) C_NOP
196 #endif
197 #ifdef DC390_DEBUG1
198 # define DEBUG1(x) x
199 #else
200 # define DEBUG1(x) C_NOP
201 #endif
202 #ifdef DC390_DCBDEBUG
203 # define DCBDEBUG(x) x
204 #else
205 # define DCBDEBUG(x) C_NOP
206 #endif
207 #ifdef DC390_PARSEDEBUG
208 # define PARSEDEBUG(x) x
209 #else
210 # define PARSEDEBUG(x) C_NOP
211 #endif
212 #ifdef DC390_REMOVABLEDEBUG
213 # define REMOVABLEDEBUG(x) x
214 #else
215 # define REMOVABLEDEBUG(x) C_NOP
216 #endif
217 #define DCBDEBUG1(x) C_NOP
218
219 /* Includes */
220 #include <linux/module.h>
221 #include <asm/dma.h>
222 #include <asm/io.h>
223 #include <asm/system.h>
224 #include <linux/delay.h>
225 #include <linux/signal.h>
226 #include <linux/sched.h>
227 #include <linux/errno.h>
228 #include <linux/kernel.h>
229 #include <linux/ioport.h>
230 #include <linux/pci.h>
231 #include <linux/proc_fs.h>
232 #include <linux/string.h>
233 #include <linux/ctype.h>
234 #include <linux/mm.h>
235 #include <linux/config.h>
236 #include <linux/version.h>
237 #include <linux/blkdev.h>
238 #include <linux/timer.h>
239 #include <linux/interrupt.h>
240
241 #include "scsi.h"
242 #include "hosts.h"
243 #include <linux/stat.h>
244 #include <scsi/scsicam.h>
245
246 #include "dc390.h"
247
248 #define PCI_DEVICE_ID_AMD53C974         PCI_DEVICE_ID_AMD_SCSI
249
250 /* Locking */
251
252 /* Note: Starting from 2.1.9x, the mid-level scsi code issues a 
253  * spinlock_irqsave (&io_request_lock) before calling the driver's 
254  * routines, so we don't need to lock, except in the IRQ handler.
255  * The policy 3, let the midlevel scsi code do the io_request_locks
256  * and us locking on a driver specific lock, shouldn't hurt anybody; it
257  * just causes a minor performance degradation for setting the locks.
258  */
259
260 /* spinlock things
261  * level 3: lock on both adapter specific locks and (global) io_request_lock
262  * level 2: lock on adapter specific locks only
263  * level 1: rely on the locking of the mid level code (io_request_lock)
264  * undef  : traditional save_flags; cli; restore_flags;
265  */
266
267 #include <linux/init.h>
268 #include <linux/spinlock.h>
269
270 #if defined(MODULE)
271 static struct pci_device_id tmscsim_pci_tbl[] = {
272         {
273                 .vendor         = PCI_VENDOR_ID_AMD,
274                 .device         = PCI_DEVICE_ID_AMD53C974,
275                 .subvendor      = PCI_ANY_ID,
276                 .subdevice      = PCI_ANY_ID,
277         },
278         { }             /* Terminating entry */
279 };
280 MODULE_DEVICE_TABLE(pci, tmscsim_pci_tbl);
281 #endif
282         
283 #define USE_SPINLOCKS 1
284
285 #define DC390_IFLAGS unsigned long iflags
286 #define DC390_LOCK_IO(dev) spin_lock_irqsave (((struct Scsi_Host *)dev)->host_lock, iflags)
287 #define DC390_UNLOCK_IO(dev) spin_unlock_irqrestore (((struct Scsi_Host *)dev)->host_lock, iflags)
288
289 /* These macros are used for uniform access to 2.0.x and 2.1.x PCI config space*/
290
291 #define PDEV pdev
292 #define PDEVDECL struct pci_dev *pdev
293 #define PDEVDECL0 struct pci_dev *pdev = NULL
294 #define PDEVDECL1 struct pci_dev *pdev
295 #define PDEVSET pACB->pdev=pdev
296 #define PDEVSET1 pdev=pACB->pdev
297 #define PCI_WRITE_CONFIG_BYTE(pd, rv, bv) pci_write_config_byte (pd, rv, bv)
298 #define PCI_READ_CONFIG_BYTE(pd, rv, bv) pci_read_config_byte (pd, rv, bv)
299 #define PCI_WRITE_CONFIG_WORD(pd, rv, bv) pci_write_config_word (pd, rv, bv)
300 #define PCI_READ_CONFIG_WORD(pd, rv, bv) pci_read_config_word (pd, rv, bv)
301 #define PCI_PRESENT (1)
302 #define PCI_GET_IO_AND_IRQ do{io_port = pci_resource_start (pdev, 0); irq = pdev->irq;} while(0)
303
304 #include "tmscsim.h"
305
306 #ifndef __init
307 # define __init
308 #endif
309
310 static UCHAR dc390_StartSCSI( PACB pACB, PDCB pDCB, PSRB pSRB );
311 static void dc390_DataOut_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
312 static void dc390_DataIn_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
313 static void dc390_Command_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
314 static void dc390_Status_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
315 static void dc390_MsgOut_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
316 static void dc390_MsgIn_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
317 static void dc390_DataOutPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
318 static void dc390_DataInPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
319 static void dc390_CommandPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
320 static void dc390_StatusPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
321 static void dc390_MsgOutPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
322 static void dc390_MsgInPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
323 static void dc390_Nop_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
324 static void dc390_Nop_1( PACB pACB, PSRB pSRB, PUCHAR psstatus);
325
326 static void dc390_SetXferRate( PACB pACB, PDCB pDCB );
327 static void dc390_Disconnect( PACB pACB );
328 static void dc390_Reselect( PACB pACB );
329 static void dc390_SRBdone( PACB pACB, PDCB pDCB, PSRB pSRB );
330 static void dc390_DoingSRB_Done( PACB pACB, PSCSICMD cmd );
331 static void dc390_ScsiRstDetect( PACB pACB );
332 static void dc390_ResetSCSIBus( PACB pACB );
333 static void __inline__ dc390_RequestSense( PACB pACB, PDCB pDCB, PSRB pSRB );
334 static void __inline__ dc390_InvalidCmd( PACB pACB );
335 static void __inline__ dc390_EnableMsgOut_Abort (PACB, PSRB);
336 static void dc390_remove_dev (PACB pACB, PDCB pDCB);
337 static irqreturn_t do_DC390_Interrupt( int, void *, struct pt_regs *);
338
339 static int    dc390_initAdapter( PSH psh, ULONG io_port, UCHAR Irq, UCHAR index );
340 static void   dc390_initDCB( PACB pACB, PDCB *ppDCB, UCHAR id, UCHAR lun);
341 static void   dc390_updateDCB (PACB pACB, PDCB pDCB);
342
343 static int DC390_release(struct Scsi_Host *host);
344 static int dc390_shutdown (struct Scsi_Host *host);
345
346 static PACB     dc390_pACB_start= NULL;
347 static PACB     dc390_pACB_current = NULL;
348 static ULONG    dc390_lastabortedpid = 0;
349 static UINT     dc390_laststatus = 0;
350 static UCHAR    dc390_adapterCnt = 0;
351
352 /* Startup values, to be overriden on the commandline */
353 static int tmscsim[] = {-2, -2, -2, -2, -2, -2};
354
355 #if defined(MODULE)
356 MODULE_PARM(tmscsim, "1-6i");
357 MODULE_PARM_DESC(tmscsim, "Host SCSI ID, Speed (0=10MHz), Device Flags, Adapter Flags, Max Tags (log2(tags)-1), DelayReset (s)");
358 MODULE_AUTHOR("C.L. Huang / Kurt Garloff");
359 MODULE_DESCRIPTION("SCSI host adapter driver for Tekram DC390 and other AMD53C974A based PCI SCSI adapters");
360 MODULE_LICENSE("GPL");
361
362 MODULE_SUPPORTED_DEVICE("sd,sr,sg,st");
363 #endif
364
365 static PVOID dc390_phase0[]={
366        dc390_DataOut_0,
367        dc390_DataIn_0,
368        dc390_Command_0,
369        dc390_Status_0,
370        dc390_Nop_0,
371        dc390_Nop_0,
372        dc390_MsgOut_0,
373        dc390_MsgIn_0,
374        dc390_Nop_1
375        };
376
377 static PVOID dc390_phase1[]={
378        dc390_DataOutPhase,
379        dc390_DataInPhase,
380        dc390_CommandPhase,
381        dc390_StatusPhase,
382        dc390_Nop_0,
383        dc390_Nop_0,
384        dc390_MsgOutPhase,
385        dc390_MsgInPhase,
386        dc390_Nop_1
387        };
388
389 #ifdef DC390_DEBUG1
390 static char* dc390_p0_str[] = {
391        "dc390_DataOut_0",
392        "dc390_DataIn_0",
393        "dc390_Command_0",
394        "dc390_Status_0",
395        "dc390_Nop_0",
396        "dc390_Nop_0",
397        "dc390_MsgOut_0",
398        "dc390_MsgIn_0",
399        "dc390_Nop_1"
400        };
401      
402 static char* dc390_p1_str[] = {
403        "dc390_DataOutPhase",
404        "dc390_DataInPhase",
405        "dc390_CommandPhase",
406        "dc390_StatusPhase",
407        "dc390_Nop_0",
408        "dc390_Nop_0",
409        "dc390_MsgOutPhase",
410        "dc390_MsgInPhase",
411        "dc390_Nop_1"
412        };
413 #endif   
414
415 /* Devices erroneously pretending to be able to do TagQ */
416 static UCHAR  dc390_baddevname1[2][28] ={
417        "SEAGATE ST3390N         9546",
418        "HP      C3323-300       4269"};
419 #define BADDEVCNT       2
420
421 static char*  dc390_adapname = "DC390";
422 static UCHAR  dc390_eepromBuf[MAX_ADAPTER_NUM][EE_LEN];
423 static UCHAR  dc390_clock_period1[] = {4, 5, 6, 7, 8, 10, 13, 20};
424 static UCHAR  dc390_clock_speed[] = {100,80,67,57,50, 40, 31, 20};
425
426 /***********************************************************************
427  * Functions for access to DC390 EEPROM
428  * and some to emulate it
429  *
430  **********************************************************************/
431
432
433 static void __init dc390_EnDisableCE( UCHAR mode, PDEVDECL, PUCHAR regval )
434 {
435     UCHAR bval;
436
437     bval = 0;
438     if(mode == ENABLE_CE)
439         *regval = 0xc0;
440     else
441         *regval = 0x80;
442     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
443     if(mode == DISABLE_CE)
444         PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
445     udelay(160);
446 }
447
448
449 /* Override EEprom values with explicitly set values */
450 static void __init dc390_EEprom_Override (UCHAR index)
451 {
452     PUCHAR ptr;
453     UCHAR  id;
454     ptr = (PUCHAR) dc390_eepromBuf[index];
455     
456     /* Adapter Settings */
457     if (tmscsim[0] != -2)
458         ptr[EE_ADAPT_SCSI_ID] = (UCHAR)tmscsim[0];      /* Adapter ID */
459     if (tmscsim[3] != -2)
460         ptr[EE_MODE2] = (UCHAR)tmscsim[3];
461     if (tmscsim[5] != -2)
462         ptr[EE_DELAY] = tmscsim[5];                     /* Reset delay */
463     if (tmscsim[4] != -2)
464         ptr[EE_TAG_CMD_NUM] = (UCHAR)tmscsim[4];        /* Tagged Cmds */
465     
466     /* Device Settings */
467     for (id = 0; id < MAX_SCSI_ID; id++)
468     {
469         if (tmscsim[2] != -2)
470                 ptr[id<<2] = (UCHAR)tmscsim[2];         /* EE_MODE1 */
471         if (tmscsim[1] != -2)
472                 ptr[(id<<2) + 1] = (UCHAR)tmscsim[1];   /* EE_Speed */
473     }
474 }
475
476 /* Handle "-1" case */
477 static void __init dc390_check_for_safe_settings (void)
478 {
479         if (tmscsim[0] == -1 || tmscsim[0] > 15) /* modules-2.0.0 passes -1 as string */
480         {
481                 tmscsim[0] = 7; tmscsim[1] = 4;
482                 tmscsim[2] = 0x09; tmscsim[3] = 0x0f;
483                 tmscsim[4] = 2; tmscsim[5] = 10;
484                 printk (KERN_INFO "DC390: Using safe settings.\n");
485         }
486 }
487
488
489 static int __initdata tmscsim_def[] = {7, 0 /* 10MHz */,
490                 PARITY_CHK_ | SEND_START_ | EN_DISCONNECT_
491                 | SYNC_NEGO_ | TAG_QUEUEING_,
492                 MORE2_DRV | GREATER_1G | RST_SCSI_BUS | ACTIVE_NEGATION
493                 /* | NO_SEEK */
494 # ifdef CONFIG_SCSI_MULTI_LUN
495                 | LUN_CHECK
496 # endif
497                 , 3 /* 16 Tags per LUN */, 1 /* s delay after Reset */ };
498
499 /* Copy defaults over set values where missing */
500 static void __init dc390_fill_with_defaults (void)
501 {
502         int i;
503         PARSEDEBUG(printk(KERN_INFO "DC390: setup %08x %08x %08x %08x %08x %08x\n", tmscsim[0],\
504                           tmscsim[1], tmscsim[2], tmscsim[3], tmscsim[4], tmscsim[5]));
505         for (i = 0; i < 6; i++)
506         {
507                 if (tmscsim[i] < 0 || tmscsim[i] > 255)
508                         tmscsim[i] = tmscsim_def[i];
509         }
510         /* Sanity checks */
511         if (tmscsim[0] >   7) tmscsim[0] =   7;
512         if (tmscsim[1] >   7) tmscsim[1] =   4;
513         if (tmscsim[4] >   5) tmscsim[4] =   4;
514         if (tmscsim[5] > 180) tmscsim[5] = 180;
515 }
516
517 /* Override defaults on cmdline:
518  * tmscsim: AdaptID, MaxSpeed (Index), DevMode (Bitmapped), AdaptMode (Bitmapped)
519  */
520 static int __init dc390_setup (char *str)
521 {       
522         int ints[8];
523         int i, im;
524         (void)get_options (str, ARRAY_SIZE(ints), ints);
525         im = ints[0];
526         if (im > 6)
527         {
528                 printk (KERN_NOTICE "DC390: ignore extra params!\n");
529                 im = 6;
530         }
531         for (i = 0; i < im; i++)
532                 tmscsim[i] = ints[i+1];
533         /* dc390_checkparams (); */
534         return 1;
535 }
536 #ifndef MODULE
537 __setup("tmscsim=", dc390_setup);
538 #endif
539
540 static void __init dc390_EEpromOutDI( PDEVDECL, PUCHAR regval, UCHAR Carry )
541 {
542     UCHAR bval;
543
544     bval = 0;
545     if(Carry)
546     {
547         bval = 0x40;
548         *regval = 0x80;
549         PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
550     }
551     udelay(160);
552     bval |= 0x80;
553     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
554     udelay(160);
555     bval = 0;
556     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
557     udelay(160);
558 }
559
560
561 static UCHAR __init dc390_EEpromInDO( PDEVDECL )
562 {
563     UCHAR bval;
564
565     PCI_WRITE_CONFIG_BYTE(PDEV, 0x80, 0x80);
566     udelay(160);
567     PCI_WRITE_CONFIG_BYTE(PDEV, 0x80, 0x40);
568     udelay(160);
569     PCI_READ_CONFIG_BYTE(PDEV, 0x00, &bval);
570     if(bval == 0x22)
571         return(1);
572     else
573         return(0);
574 }
575
576
577 static USHORT __init dc390_EEpromGetData1( PDEVDECL )
578 {
579     UCHAR i;
580     UCHAR carryFlag;
581     USHORT wval;
582
583     wval = 0;
584     for(i=0; i<16; i++)
585     {
586         wval <<= 1;
587         carryFlag = dc390_EEpromInDO(PDEV);
588         wval |= carryFlag;
589     }
590     return(wval);
591 }
592
593
594 static void __init dc390_Prepare( PDEVDECL, PUCHAR regval, UCHAR EEpromCmd )
595 {
596     UCHAR i,j;
597     UCHAR carryFlag;
598
599     carryFlag = 1;
600     j = 0x80;
601     for(i=0; i<9; i++)
602     {
603         dc390_EEpromOutDI(PDEV,regval,carryFlag);
604         carryFlag = (EEpromCmd & j) ? 1 : 0;
605         j >>= 1;
606     }
607 }
608
609
610 static void __init dc390_ReadEEprom( PDEVDECL, PUSHORT ptr)
611 {
612     UCHAR   regval,cmd;
613     UCHAR   i;
614
615     cmd = EEPROM_READ;
616     for(i=0; i<0x40; i++)
617     {
618         dc390_EnDisableCE(ENABLE_CE, PDEV, &regval);
619         dc390_Prepare(PDEV, &regval, cmd++);
620         *ptr++ = dc390_EEpromGetData1(PDEV);
621         dc390_EnDisableCE(DISABLE_CE, PDEV, &regval);
622     }
623 }
624
625
626 static void __init dc390_interpret_delay (UCHAR index)
627 {
628     char interpd [] = {1,3,5,10,16,30,60,120};
629     dc390_eepromBuf[index][EE_DELAY] = interpd [dc390_eepromBuf[index][EE_DELAY]];
630 }
631
632 static UCHAR __init dc390_CheckEEpromCheckSum( PDEVDECL, UCHAR index )
633 {
634     UCHAR  i;
635     char  EEbuf[128];
636     USHORT wval, *ptr = (PUSHORT)EEbuf;
637
638     dc390_ReadEEprom( PDEV, ptr );
639     memcpy (dc390_eepromBuf[index], EEbuf, EE_ADAPT_SCSI_ID);
640     memcpy (&dc390_eepromBuf[index][EE_ADAPT_SCSI_ID], 
641             &EEbuf[REAL_EE_ADAPT_SCSI_ID], EE_LEN - EE_ADAPT_SCSI_ID);
642     dc390_interpret_delay (index);
643     
644     wval = 0;
645     for(i=0; i<0x40; i++, ptr++)
646         wval += *ptr;
647     return (wval == 0x1234 ? 0 : 1);
648 }
649
650
651 /***********************************************************************
652  * Functions for the management of the internal structures 
653  * (DCBs, SRBs, Queueing)
654  *
655  **********************************************************************/
656 static PDCB __inline__ dc390_findDCB ( PACB pACB, UCHAR id, UCHAR lun)
657 {
658    PDCB pDCB = pACB->pLinkDCB; if (!pDCB) return 0;
659    while (pDCB->TargetID != id || pDCB->TargetLUN != lun)
660      {
661         pDCB = pDCB->pNextDCB;
662         if (pDCB == pACB->pLinkDCB)
663           {
664              DCBDEBUG(printk (KERN_WARNING "DC390: DCB not found (DCB=%p, DCBmap[%2x]=%2x)\n",
665                               pDCB, id, pACB->DCBmap[id]));
666              return 0;
667           }
668      }
669    DCBDEBUG1( printk (KERN_DEBUG "DCB %p (%02x,%02x) found.\n", \
670                       pDCB, pDCB->TargetID, pDCB->TargetLUN));
671    return pDCB;
672 }
673
674 /* Queueing philosphy:
675  * There are a couple of lists:
676  * - Query: Contains the Scsi Commands not yet turned into SRBs (per ACB)
677  *   (Note: For new EH, it is unnecessary!)
678  * - Waiting: Contains a list of SRBs not yet sent (per DCB)
679  * - Free: List of free SRB slots
680  * 
681  * If there are no waiting commands for the DCB, the new one is sent to the bus
682  * otherwise the oldest one is taken from the Waiting list and the new one is 
683  * queued to the Waiting List
684  * 
685  * Lists are managed using two pointers and eventually a counter
686  */
687
688
689 #if 0
690 /* Look for a SCSI cmd in a SRB queue */
691 static PSRB dc390_find_cmd_in_SRBq (PSCSICMD cmd, PSRB queue)
692 {
693     PSRB q = queue;
694     while (q)
695     {
696         if (q->pcmd == cmd) return q;
697         q = q->pNextSRB;
698         if (q == queue) return 0;
699     }
700     return q;
701 }
702 #endif
703
704 /* Return next free SRB */
705 static __inline__ PSRB dc390_Free_get ( PACB pACB )
706 {
707     PSRB   pSRB;
708
709     pSRB = pACB->pFreeSRB;
710     DEBUG0(printk ("DC390: Get Free SRB %p\n", pSRB));
711     if( pSRB )
712     {
713         pACB->pFreeSRB = pSRB->pNextSRB;
714         pSRB->pNextSRB = NULL;
715     }
716
717     return( pSRB );
718 }
719
720 /* Insert SRB oin top of free list */
721 static __inline__ void dc390_Free_insert (PACB pACB, PSRB pSRB)
722 {
723     DEBUG0(printk ("DC390: Free SRB %p\n", pSRB));
724     pSRB->pNextSRB = pACB->pFreeSRB;
725     pACB->pFreeSRB = pSRB;
726 }
727
728
729 /* Inserts a SRB to the top of the Waiting list */
730 static __inline__ void dc390_Waiting_insert ( PDCB pDCB, PSRB pSRB )
731 {
732     DEBUG0(printk ("DC390: Insert pSRB %p cmd %li to Waiting\n", pSRB, pSRB->pcmd->pid));
733     pSRB->pNextSRB = pDCB->pWaitingSRB;
734     if (!pDCB->pWaitingSRB)
735         pDCB->pWaitLast = pSRB;
736     pDCB->pWaitingSRB = pSRB;
737     pDCB->WaitSRBCnt++;
738 }
739
740
741 /* Queue SRB to waiting list */
742 static __inline__ void dc390_Waiting_append ( PDCB pDCB, PSRB pSRB)
743 {
744         DEBUG0(printk ("DC390: Append pSRB %p cmd %li to Waiting\n", pSRB, pSRB->pcmd->pid));
745     if( pDCB->pWaitingSRB )
746         pDCB->pWaitLast->pNextSRB = pSRB;
747     else
748         pDCB->pWaitingSRB = pSRB;
749
750     pDCB->pWaitLast = pSRB;
751     pSRB->pNextSRB = NULL;
752     pDCB->WaitSRBCnt++;
753     pDCB->pDCBACB->CmdInQ++;
754 }
755
756 static __inline__ void dc390_Going_append (PDCB pDCB, PSRB pSRB)
757 {
758     pDCB->GoingSRBCnt++;
759     DEBUG0(printk("DC390: Append SRB %p to Going\n", pSRB));
760     /* Append to the list of Going commands */
761     if( pDCB->pGoingSRB )
762         pDCB->pGoingLast->pNextSRB = pSRB;
763     else
764         pDCB->pGoingSRB = pSRB;
765
766     pDCB->pGoingLast = pSRB;
767     /* No next one in sent list */
768     pSRB->pNextSRB = NULL;
769 }
770
771 static __inline__ void dc390_Going_remove (PDCB pDCB, PSRB pSRB)
772 {
773         DEBUG0(printk("DC390: Remove SRB %p from Going\n", pSRB));
774    if (pSRB == pDCB->pGoingSRB)
775         pDCB->pGoingSRB = pSRB->pNextSRB;
776    else
777      {
778         PSRB psrb = pDCB->pGoingSRB;
779         while (psrb && psrb->pNextSRB != pSRB)
780           psrb = psrb->pNextSRB;
781         if (!psrb) 
782           { printk (KERN_ERR "DC390: Remove non-ex. SRB %p from Going!\n", pSRB); return; }
783         psrb->pNextSRB = pSRB->pNextSRB;
784         if (pSRB == pDCB->pGoingLast)
785           pDCB->pGoingLast = psrb;
786      }
787    pDCB->GoingSRBCnt--;
788 }
789
790 /* Moves SRB from Going list to the top of Waiting list */
791 static void dc390_Going_to_Waiting ( PDCB pDCB, PSRB pSRB )
792 {
793     DEBUG0(printk(KERN_INFO "DC390: Going_to_Waiting (SRB %p) pid = %li\n", pSRB, pSRB->pcmd->pid));
794     /* Remove SRB from Going */
795     dc390_Going_remove (pDCB, pSRB);
796     /* Insert on top of Waiting */
797     dc390_Waiting_insert (pDCB, pSRB);
798     /* Tag Mask must be freed elsewhere ! (KG, 99/06/18) */
799 }
800
801 /* Moves first SRB from Waiting list to Going list */
802 static __inline__ void dc390_Waiting_to_Going ( PDCB pDCB, PSRB pSRB )
803 {       
804         /* Remove from waiting list */
805         DEBUG0(printk("DC390: Remove SRB %p from head of Waiting\n", pSRB));
806         pDCB->pWaitingSRB = pSRB->pNextSRB;
807         if( !pDCB->pWaitingSRB ) pDCB->pWaitLast = NULL;
808         pDCB->WaitSRBCnt--;
809         dc390_Going_append (pDCB, pSRB);
810 }
811
812 static void DC390_waiting_timed_out (unsigned long ptr);
813 /* Sets the timer to wake us up */
814 static void dc390_waiting_timer (PACB pACB, unsigned long to)
815 {
816         if (timer_pending (&pACB->Waiting_Timer)) return;
817         init_timer (&pACB->Waiting_Timer);
818         pACB->Waiting_Timer.function = DC390_waiting_timed_out;
819         pACB->Waiting_Timer.data = (unsigned long)pACB;
820         if (time_before (jiffies + to, pACB->pScsiHost->last_reset))
821                 pACB->Waiting_Timer.expires = pACB->pScsiHost->last_reset + 1;
822         else
823                 pACB->Waiting_Timer.expires = jiffies + to + 1;
824         add_timer (&pACB->Waiting_Timer);
825 }
826
827
828 /* Send the next command from the waiting list to the bus */
829 static void dc390_Waiting_process ( PACB pACB )
830 {
831     PDCB   ptr, ptr1;
832     PSRB   pSRB;
833
834     if( (pACB->pActiveDCB) || (pACB->ACBFlag & (RESET_DETECT+RESET_DONE+RESET_DEV) ) )
835         return;
836     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
837     ptr = pACB->pDCBRunRobin;
838     if( !ptr )
839       {
840         ptr = pACB->pLinkDCB;
841         pACB->pDCBRunRobin = ptr;
842       }
843     ptr1 = ptr;
844     if (!ptr1) return;
845     do 
846       {
847         pACB->pDCBRunRobin = ptr1->pNextDCB;
848         if( !( pSRB = ptr1->pWaitingSRB ) ||
849             ( ptr1->MaxCommand <= ptr1->GoingSRBCnt ))
850           ptr1 = ptr1->pNextDCB;
851         else
852           {
853             /* Try to send to the bus */
854             if( !dc390_StartSCSI(pACB, ptr1, pSRB) )
855               dc390_Waiting_to_Going (ptr1, pSRB);
856             else
857               dc390_waiting_timer (pACB, HZ/5);
858             break;
859           }
860       } while (ptr1 != ptr);
861     return;
862 }
863
864 /* Wake up waiting queue */
865 static void DC390_waiting_timed_out (unsigned long ptr)
866 {
867         PACB pACB = (PACB)ptr;
868         DC390_IFLAGS;
869         DEBUG0(printk ("DC390: Debug: Waiting queue woken up by timer!\n"));
870         DC390_LOCK_IO(pACB->pScsiHost);
871         dc390_Waiting_process (pACB);
872         DC390_UNLOCK_IO(pACB->pScsiHost);
873 }
874
875 /***********************************************************************
876  * Function: static void dc390_SendSRB (PACB pACB, PSRB pSRB)
877  *
878  * Purpose: Send SCSI Request Block (pSRB) to adapter (pACB)
879  *
880  ***********************************************************************/
881
882 static void dc390_SendSRB( PACB pACB, PSRB pSRB )
883 {
884     PDCB   pDCB;
885
886     pDCB = pSRB->pSRBDCB;
887     if( (pDCB->MaxCommand <= pDCB->GoingSRBCnt) || (pACB->pActiveDCB) ||
888         (pACB->ACBFlag & (RESET_DETECT+RESET_DONE+RESET_DEV)) )
889     {
890         dc390_Waiting_append (pDCB, pSRB);
891         dc390_Waiting_process (pACB);
892         return;
893     }
894
895 #if 0
896     if( pDCB->pWaitingSRB )
897     {
898         dc390_Waiting_append (pDCB, pSRB);
899 /*      pSRB = GetWaitingSRB(pDCB); */  /* non-existent */
900         pSRB = pDCB->pWaitingSRB;
901         /* Remove from waiting list */
902         pDCB->pWaitingSRB = pSRB->pNextSRB;
903         pSRB->pNextSRB = NULL;
904         if (!pDCB->pWaitingSRB) pDCB->pWaitLast = NULL;
905     }
906 #endif
907         
908     if (!dc390_StartSCSI(pACB, pDCB, pSRB))
909         dc390_Going_append (pDCB, pSRB);
910     else {
911         dc390_Waiting_insert (pDCB, pSRB);
912         dc390_waiting_timer (pACB, HZ/5);
913     }
914 }
915
916
917 /* Create pci mapping */
918 static int dc390_pci_map (PSRB pSRB)
919 {
920         int error = 0;
921         Scsi_Cmnd *pcmd = pSRB->pcmd;
922         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
923         dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp));
924         /* Map sense buffer */
925         if (pSRB->SRBFlag & AUTO_REQSENSE) {
926                 sg_dma_address(&pSRB->Segmentx) = cmdp->saved_dma_handle = 
927                         pci_map_page(pdev, virt_to_page(pcmd->sense_buffer),
928                                      (unsigned long)pcmd->sense_buffer & ~PAGE_MASK, sizeof(pcmd->sense_buffer),
929                                      DMA_FROM_DEVICE);
930                 sg_dma_len(&pSRB->Segmentx) = sizeof(pcmd->sense_buffer);
931                 pSRB->SGcount = 1;
932                 pSRB->pSegmentList = (PSGL) &pSRB->Segmentx;
933                 DEBUG1(printk("%s(): Mapped sense buffer %p at %x\n", __FUNCTION__, pcmd->sense_buffer, cmdp->saved_dma_handle));
934         /* Make SG list */      
935         } else if (pcmd->use_sg) {
936                 pSRB->pSegmentList = (PSGL) pcmd->request_buffer;
937                 pSRB->SGcount = pci_map_sg(pdev, pSRB->pSegmentList,
938                                            pcmd->use_sg,
939                                            scsi_to_pci_dma_dir(pcmd->sc_data_direction));
940                 /* TODO: error handling */
941                 if (!pSRB->SGcount)
942                         error = 1;
943                 DEBUG1(printk("%s(): Mapped SG %p with %d (%d) elements\n", __FUNCTION__, pcmd->request_buffer, pSRB->SGcount, pcmd->use_sg));
944         /* Map single segment */
945         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
946                 sg_dma_address(&pSRB->Segmentx) = cmdp->saved_dma_handle =
947                         pci_map_page(pdev, virt_to_page(pcmd->request_buffer),
948                                      (unsigned long)pcmd->request_buffer & ~PAGE_MASK,
949                                      pcmd->request_bufflen, scsi_to_pci_dma_dir(pcmd->sc_data_direction));
950                 /* TODO: error handling */
951                 sg_dma_len(&pSRB->Segmentx) = pcmd->request_bufflen;
952                 pSRB->SGcount = 1;
953                 pSRB->pSegmentList = (PSGL) &pSRB->Segmentx;
954                 DEBUG1(printk("%s(): Mapped request buffer %p at %x\n", __FUNCTION__, pcmd->request_buffer, cmdp->saved_dma_handle));
955         /* No mapping !? */     
956         } else
957                 pSRB->SGcount = 0;
958         return error;
959 }
960
961 /* Remove pci mapping */
962 static void dc390_pci_unmap (PSRB pSRB)
963 {
964         Scsi_Cmnd* pcmd = pSRB->pcmd;
965         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
966         dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp));
967
968         if (pSRB->SRBFlag) {
969                 pci_unmap_page(pdev, cmdp->saved_dma_handle,
970                                sizeof(pcmd->sense_buffer), DMA_FROM_DEVICE);
971                 DEBUG1(printk("%s(): Unmapped sense buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
972         } else if (pcmd->use_sg) {
973                 pci_unmap_sg(pdev, pcmd->request_buffer, pcmd->use_sg,
974                              scsi_to_pci_dma_dir(pcmd->sc_data_direction));
975                 DEBUG1(printk("%s(): Unmapped SG at %p with %d elements\n", __FUNCTION__, pcmd->request_buffer, pcmd->use_sg));
976         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
977                 pci_unmap_page(pdev,
978                                cmdp->saved_dma_handle,
979                                pcmd->request_bufflen,
980                                scsi_to_pci_dma_dir(pcmd->sc_data_direction));
981                 DEBUG1(printk("%s(): Unmapped request buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
982         }
983 }
984
985
986 /***********************************************************************
987  * Function: static void dc390_BuildSRB (Scsi_Cmd *pcmd, PDCB pDCB, 
988  *                                       PSRB pSRB)
989  *
990  * Purpose: Prepare SRB for being sent to Device DCB w/ command *pcmd
991  *
992  ***********************************************************************/
993
994 static void dc390_BuildSRB (Scsi_Cmnd* pcmd, PDCB pDCB, PSRB pSRB)
995 {
996     pSRB->pSRBDCB = pDCB;
997     pSRB->pcmd = pcmd;
998     //pSRB->ScsiCmdLen = pcmd->cmd_len;
999     //memcpy (pSRB->CmdBlock, pcmd->cmnd, pcmd->cmd_len);
1000     
1001     pSRB->SGIndex = 0;
1002     pSRB->AdaptStatus = 0;
1003     pSRB->TargetStatus = 0;
1004     pSRB->MsgCnt = 0;
1005     if( pDCB->DevType != TYPE_TAPE )
1006         pSRB->RetryCnt = 1;
1007     else
1008         pSRB->RetryCnt = 0;
1009     pSRB->SRBStatus = 0;
1010     pSRB->SRBFlag = 0;
1011     pSRB->SRBState = 0;
1012     pSRB->TotalXferredLen = 0;
1013     pSRB->SGBusAddr = 0;
1014     pSRB->SGToBeXferLen = 0;
1015     pSRB->ScsiPhase = 0;
1016     pSRB->EndMessage = 0;
1017     pSRB->TagNumber = 255;
1018     /* KG: deferred PCI mapping to dc390_StartSCSI */
1019 }
1020
1021 /***********************************************************************
1022  * Function : static int DC390_queue_command (Scsi_Cmnd *cmd,
1023  *                                             void (*done)(Scsi_Cmnd *))
1024  *
1025  * Purpose : enqueues a SCSI command
1026  *
1027  * Inputs : cmd - SCSI command, done - callback function called on 
1028  *          completion, with a pointer to the command descriptor.
1029  *
1030  * Returns : (depending on kernel version)
1031  * 2.0.x: always return 0
1032  * 2.1.x: old model: (use_new_eh_code == 0): like 2.0.x
1033  *        TO BE DONE:
1034  *        new model: return 0 if successful
1035  *                   return 1 if command cannot be queued (queue full)
1036  *                   command will be inserted in midlevel queue then ...
1037  *
1038  ***********************************************************************/
1039
1040 static int DC390_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *))
1041 {
1042     PDCB   pDCB;
1043     PSRB   pSRB;
1044     PACB   pACB = (PACB) cmd->device->host->hostdata;
1045
1046     DEBUG0(/*  if(pACB->scan_devices) */        \
1047         printk(KERN_INFO "DC390: Queue Cmd=%02x,Tgt=%d,LUN=%d (pid=%li), buffer=%p\n",\
1048                cmd->cmnd[0],cmd->device->id,cmd->device->lun,cmd->pid, cmd->buffer));
1049
1050     /* TODO: Change the policy: Always accept TEST_UNIT_READY or INQUIRY 
1051      * commands and alloc a DCB for the device if not yet there. DCB will
1052      * be removed in dc390_SRBdone if SEL_TIMEOUT */
1053
1054     if( (pACB->scan_devices == END_SCAN) && (cmd->cmnd[0] != INQUIRY) )
1055         pACB->scan_devices = 0;
1056
1057     else if( (pACB->scan_devices) && (cmd->cmnd[0] == READ_6) )
1058         pACB->scan_devices = 0;
1059
1060     if( (pACB->scan_devices || cmd->cmnd[0] == TEST_UNIT_READY || cmd->cmnd[0] == INQUIRY) && 
1061        !(pACB->DCBmap[cmd->device->id] & (1 << cmd->device->lun)) )
1062     {
1063         pACB->scan_devices = 1;
1064
1065         dc390_initDCB( pACB, &pDCB, cmd->device->id, cmd->device->lun );
1066         if (!pDCB)
1067           {
1068             printk (KERN_ERR "DC390: kmalloc for DCB failed, target %02x lun %02x\n", 
1069                     cmd->device->id, cmd->device->lun);
1070             goto fail;
1071           }
1072             
1073     }
1074     else if( !(pACB->scan_devices) && !(pACB->DCBmap[cmd->device->id] & (1 << cmd->device->lun)) )
1075     {
1076         printk(KERN_INFO "DC390: Ignore target %02x lun %02x\n",
1077                 cmd->device->id, cmd->device->lun); 
1078         goto fail;
1079     }
1080     else
1081     {
1082         pDCB = dc390_findDCB (pACB, cmd->device->id, cmd->device->lun);
1083         if (!pDCB)
1084          {  /* should never happen */
1085             printk (KERN_ERR "DC390: no DCB failed, target %02x lun %02x\n", 
1086                     cmd->device->id, cmd->device->lun);
1087             goto fail;
1088          }
1089     }
1090
1091     pACB->Cmds++;
1092     cmd->scsi_done = done;
1093     cmd->result = 0;
1094
1095     pSRB = dc390_Free_get(pACB);
1096     if (!pSRB)
1097             goto requeue;
1098
1099     dc390_BuildSRB(cmd, pDCB, pSRB);
1100     if (pDCB->pWaitingSRB) {
1101             dc390_Waiting_append(pDCB, pSRB);
1102             dc390_Waiting_process(pACB);
1103     } else
1104             dc390_SendSRB(pACB, pSRB);
1105
1106     DEBUG1(printk (KERN_DEBUG " ... command (pid %li) queued successfully.\n", cmd->pid));
1107     return(0);
1108
1109  requeue:
1110     return 1;
1111  fail:
1112     cmd->result = DID_BAD_TARGET << 16;
1113     done(cmd);
1114     return 0;
1115 }
1116
1117 /* We ignore mapping problems, as we expect everybody to respect 
1118  * valid partition tables. Waiting for complaints ;-) */
1119
1120 #ifdef CONFIG_SCSI_DC390T_TRADMAP
1121 /* 
1122  * The next function, partsize(), is copied from scsicam.c.
1123  *
1124  * This is ugly code duplication, but I didn't find another way to solve it:
1125  * We want to respect the partition table and if it fails, we apply the 
1126  * DC390 BIOS heuristic. Too bad, just calling scsicam_bios_param() doesn't do
1127  * the job, because we don't know, whether the values returned are from
1128  * the part. table or determined by setsize(). Unfortunately the setsize() 
1129  * values differ from the ones chosen by the DC390 BIOS.
1130  *
1131  * Looking forward to seeing suggestions for a better solution! KG, 98/10/14
1132  */
1133 #include <asm/unaligned.h>
1134
1135 /*
1136  * Function : static int partsize(unsigned char *buf, unsigned long 
1137  *     capacity,unsigned int *cyls, unsigned int *hds, unsigned int *secs);
1138  *
1139  * Purpose : to determine the BIOS mapping used to create the partition
1140  *      table, storing the results in *cyls, *hds, and *secs 
1141  *
1142  * Returns : -1 on failure, 0 on success.
1143  *
1144  */
1145
1146 static int partsize(unsigned char *buf, unsigned long capacity,
1147     unsigned int  *cyls, unsigned int *hds, unsigned int *secs) {
1148     struct partition *p, *largest = NULL;
1149     int i, largest_cyl;
1150     int cyl, ext_cyl, end_head, end_cyl, end_sector;
1151     unsigned int logical_end, physical_end, ext_physical_end;
1152     
1153
1154     if (*(unsigned short *) (buf+64) == 0xAA55) {
1155         for (largest_cyl = -1, p = (struct partition *) buf, 
1156             i = 0; i < 4; ++i, ++p) {
1157             if (!p->sys_ind)
1158                 continue;
1159             cyl = p->cyl + ((p->sector & 0xc0) << 2);
1160             if (cyl > largest_cyl) {
1161                 largest_cyl = cyl;
1162                 largest = p;
1163             }
1164         }
1165     }
1166
1167     if (largest) {
1168         end_cyl = largest->end_cyl + ((largest->end_sector & 0xc0) << 2);
1169         end_head = largest->end_head;
1170         end_sector = largest->end_sector & 0x3f;
1171
1172         physical_end =  end_cyl * (end_head + 1) * end_sector +
1173             end_head * end_sector + end_sector;
1174
1175         /* This is the actual _sector_ number at the end */
1176         logical_end = get_unaligned(&largest->start_sect)
1177                         + get_unaligned(&largest->nr_sects);
1178
1179         /* This is for >1023 cylinders */
1180         ext_cyl= (logical_end-(end_head * end_sector + end_sector))
1181                                         /(end_head + 1) / end_sector;
1182         ext_physical_end = ext_cyl * (end_head + 1) * end_sector +
1183             end_head * end_sector + end_sector;
1184
1185         if ((logical_end == physical_end) ||
1186             (end_cyl==1023 && ext_physical_end==logical_end)) {
1187             *secs = end_sector;
1188             *hds = end_head + 1;
1189             *cyls = capacity / ((end_head + 1) * end_sector);
1190             return 0;
1191         }
1192     }
1193     return -1;
1194 }
1195
1196 /***********************************************************************
1197  * Function:
1198  *   DC390_bios_param
1199  *
1200  * Description:
1201  *   Return the disk geometry for the given SCSI device.
1202  *   Respect the partition table, otherwise try own heuristic
1203  *
1204  * Note:
1205  *   In contrary to other externally callable funcs (DC390_), we don't lock
1206  ***********************************************************************/
1207 static int DC390_bios_param (struct scsi_device *sdev, struct block_device *bdev,
1208                              sector_t capacity, int geom[])
1209 {
1210     int heads, sectors, cylinders;
1211     PACB pACB = (PACB) sdev->host->hostdata;
1212     int ret_code = -1;
1213     int size = capacity;
1214     unsigned char *buf;
1215
1216     if ((buf = scsi_bios_ptable(bdev)))
1217     {
1218         /* try to infer mapping from partition table */
1219         ret_code = partsize (buf, (unsigned long) size, (unsigned int *) geom + 2,
1220                              (unsigned int *) geom + 0, (unsigned int *) geom + 1);
1221         kfree (buf);
1222     }
1223     if (ret_code == -1)
1224     {
1225         heads = 64;
1226         sectors = 32;
1227         cylinders = size / (heads * sectors);
1228
1229         if ( (pACB->Gmode2 & GREATER_1G) && (cylinders > 1024) )
1230         {
1231                 heads = 255;
1232                 sectors = 63;
1233                 cylinders = size / (heads * sectors);
1234         }
1235
1236         geom[0] = heads;
1237         geom[1] = sectors;
1238         geom[2] = cylinders;
1239     }
1240
1241     return (0);
1242 }
1243 #else
1244 static int DC390_bios_param (struct scsi_device *sdev, struct block_device *bdev,
1245                              sector_t capacity, int geom[])
1246 {
1247     return scsicam_bios_param (bdev, capacity, geom);
1248 }
1249 #endif
1250
1251 static void dc390_dumpinfo (PACB pACB, PDCB pDCB, PSRB pSRB)
1252 {
1253     USHORT pstat; PDEVDECL1;
1254     if (!pDCB) pDCB = pACB->pActiveDCB;
1255     if (!pSRB && pDCB) pSRB = pDCB->pActiveSRB;
1256
1257     if (pSRB) 
1258     {
1259         printk ("DC390: SRB: Xferred %08lx, Remain %08lx, State %08x, Phase %02x\n",
1260                 pSRB->TotalXferredLen, pSRB->SGToBeXferLen, pSRB->SRBState,
1261                 pSRB->ScsiPhase);
1262         printk ("DC390: AdpaterStatus: %02x, SRB Status %02x\n", pSRB->AdaptStatus, pSRB->SRBStatus);
1263     }
1264     printk ("DC390: Status of last IRQ (DMA/SC/Int/IRQ): %08x\n", dc390_laststatus);
1265     printk ("DC390: Register dump: SCSI block:\n");
1266     printk ("DC390: XferCnt  Cmd Stat IntS IRQS FFIS Ctl1 Ctl2 Ctl3 Ctl4\n");
1267     printk ("DC390:  %06x   %02x   %02x   %02x",
1268             DC390_read8(CtcReg_Low) + (DC390_read8(CtcReg_Mid) << 8) + (DC390_read8(CtcReg_High) << 16),
1269             DC390_read8(ScsiCmd), DC390_read8(Scsi_Status), DC390_read8(Intern_State));
1270     printk ("   %02x   %02x   %02x   %02x   %02x   %02x\n",
1271             DC390_read8(INT_Status), DC390_read8(Current_Fifo), DC390_read8(CtrlReg1),
1272             DC390_read8(CtrlReg2), DC390_read8(CtrlReg3), DC390_read8(CtrlReg4));
1273     DC390_write32 (DMA_ScsiBusCtrl, WRT_ERASE_DMA_STAT | EN_INT_ON_PCI_ABORT);
1274     if (DC390_read8(Current_Fifo) & 0x1f)
1275       {
1276         printk ("DC390: FIFO:");
1277         while (DC390_read8(Current_Fifo) & 0x1f) printk (" %02x", DC390_read8(ScsiFifo));
1278         printk ("\n");
1279       }
1280     printk ("DC390: Register dump: DMA engine:\n");
1281     printk ("DC390: Cmd   STrCnt    SBusA    WrkBC    WrkAC Stat SBusCtrl\n");
1282     printk ("DC390:  %02x %08x %08x %08x %08x   %02x %08x\n",
1283             DC390_read8(DMA_Cmd), DC390_read32(DMA_XferCnt), DC390_read32(DMA_XferAddr),
1284             DC390_read32(DMA_Wk_ByteCntr), DC390_read32(DMA_Wk_AddrCntr),
1285             DC390_read8(DMA_Status), DC390_read32(DMA_ScsiBusCtrl));
1286     DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
1287     PDEVSET1; PCI_READ_CONFIG_WORD(PDEV, PCI_STATUS, &pstat);
1288     printk ("DC390: Register dump: PCI Status: %04x\n", pstat);
1289     printk ("DC390: In case of driver trouble read linux/Documentation/scsi/tmscsim.txt\n");
1290 }
1291
1292
1293 /***********************************************************************
1294  * Function : int DC390_abort (Scsi_Cmnd *cmd)
1295  *
1296  * Purpose : Abort an errant SCSI command
1297  *
1298  * Inputs : cmd - command to abort
1299  *
1300  * Returns : 0 on success, -1 on failure.
1301  *
1302  * Status: Buggy !
1303  ***********************************************************************/
1304
1305 static int DC390_abort (Scsi_Cmnd *cmd)
1306 {
1307     PDCB  pDCB;
1308     PSRB  pSRB, psrb;
1309     UINT  count, i;
1310     int   status;
1311     //ULONG sbac;
1312     PACB  pACB = (PACB) cmd->device->host->hostdata;
1313
1314     printk ("DC390: Abort command (pid %li, Device %02i-%02i)\n",
1315             cmd->pid, cmd->device->id, cmd->device->lun);
1316
1317     pDCB = dc390_findDCB (pACB, cmd->device->id, cmd->device->lun);
1318     if( !pDCB ) goto  NOT_RUN;
1319
1320     /* Added 98/07/02 KG */
1321     /*
1322     pSRB = pDCB->pActiveSRB;
1323     if (pSRB && pSRB->pcmd == cmd )
1324         goto ON_GOING;
1325      */
1326     
1327     pSRB = pDCB->pWaitingSRB;
1328     if( !pSRB )
1329         goto  ON_GOING;
1330
1331     /* Now scan Waiting queue */
1332     if( pSRB->pcmd == cmd )
1333     {
1334         pDCB->pWaitingSRB = pSRB->pNextSRB;
1335         goto  IN_WAIT;
1336     }
1337     else
1338     {
1339         psrb = pSRB;
1340         if( !(psrb->pNextSRB) )
1341             goto ON_GOING;
1342         while( psrb->pNextSRB->pcmd != cmd )
1343         {
1344             psrb = psrb->pNextSRB;
1345             if( !(psrb->pNextSRB) || psrb == pSRB)
1346                 goto ON_GOING;
1347         }
1348         pSRB = psrb->pNextSRB;
1349         psrb->pNextSRB = pSRB->pNextSRB;
1350         if( pSRB == pDCB->pWaitLast )
1351             pDCB->pWaitLast = psrb;
1352 IN_WAIT:
1353         dc390_Free_insert (pACB, pSRB);
1354         pDCB->WaitSRBCnt--;
1355         INIT_LIST_HEAD((struct list_head*)&cmd->SCp);
1356         status = SCSI_ABORT_SUCCESS;
1357         goto  ABO_X;
1358     }
1359
1360     /* SRB has already been sent ! */
1361 ON_GOING:
1362     /* abort() is too stupid for already sent commands at the moment. 
1363      * If it's called we are in trouble anyway, so let's dump some info 
1364      * into the syslog at least. (KG, 98/08/20,99/06/20) */
1365     dc390_dumpinfo (pACB, pDCB, pSRB);
1366     pSRB = pDCB->pGoingSRB;
1367     pDCB->DCBFlag |= ABORT_DEV_;
1368     /* Now for the hard part: The command is currently processed */
1369     for( count = pDCB->GoingSRBCnt, i=0; i<count; i++)
1370     {
1371         if( pSRB->pcmd != cmd )
1372             pSRB = pSRB->pNextSRB;
1373         else
1374         {
1375             if( (pACB->pActiveDCB == pDCB) && (pDCB->pActiveSRB == pSRB) )
1376             {
1377                 status = SCSI_ABORT_BUSY;
1378                 printk ("DC390: Abort current command (pid %li, SRB %p)\n",
1379                         cmd->pid, pSRB);
1380                 goto  ABO_X;
1381             }
1382             else
1383             {
1384                 status = SCSI_ABORT_SNOOZE;
1385                 goto  ABO_X;
1386             }
1387         }
1388     }
1389
1390 NOT_RUN:
1391     status = SCSI_ABORT_NOT_RUNNING;
1392
1393 ABO_X:
1394     cmd->result = DID_ABORT << 16;
1395     printk(KERN_INFO "DC390: Aborted pid %li with status %i\n", cmd->pid, status);
1396 #if 0
1397     if (cmd->pid == dc390_lastabortedpid) /* repeated failure ? */
1398         {
1399                 /* Let's do something to help the bus getting clean again */
1400                 DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1401                 DC390_write8 (ScsiCmd, DMA_COMMAND);
1402                 //DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1403                 //DC390_write8 (ScsiCmd, RESET_ATN_CMD);
1404                 DC390_write8 (ScsiCmd, NOP_CMD);
1405                 //udelay (10000);
1406                 //DC390_read8 (INT_Status);
1407                 //DC390_write8 (ScsiCmd, EN_SEL_RESEL);
1408         }
1409     sbac = DC390_read32 (DMA_ScsiBusCtrl);
1410     if (sbac & SCSI_BUSY)
1411     {   /* clear BSY, SEL and ATN */
1412         printk (KERN_WARNING "DC390: Reset SCSI device: ");
1413         //DC390_write32 (DMA_ScsiBusCtrl, (sbac | SCAM) & ~SCSI_LINES);
1414         //udelay (250);
1415         //sbac = DC390_read32 (DMA_ScsiBusCtrl);
1416         //printk ("%08lx ", sbac);
1417         //DC390_write32 (DMA_ScsiBusCtrl, sbac & ~(SCSI_LINES | SCAM));
1418         //udelay (100);
1419         //sbac = DC390_read32 (DMA_ScsiBusCtrl);
1420         //printk ("%08lx ", sbac);
1421         DC390_write8 (ScsiCmd, RST_DEVICE_CMD);
1422         udelay (250);
1423         DC390_write8 (ScsiCmd, NOP_CMD);
1424         sbac = DC390_read32 (DMA_ScsiBusCtrl);
1425         printk ("%08lx\n", sbac);
1426     }
1427 #endif
1428     dc390_lastabortedpid = cmd->pid;
1429     //do_DC390_Interrupt (pACB->IRQLevel, 0, 0);
1430 #ifndef USE_NEW_EH      
1431     if (status == SCSI_ABORT_SUCCESS) cmd->scsi_done(cmd);
1432 #endif  
1433     return( status );
1434 }
1435
1436
1437 static void dc390_ResetDevParam( PACB pACB )
1438 {
1439     PDCB   pDCB, pdcb;
1440
1441     pDCB = pACB->pLinkDCB;
1442     if (! pDCB) return;
1443     pdcb = pDCB;
1444     do
1445     {
1446         pDCB->SyncMode &= ~SYNC_NEGO_DONE;
1447         pDCB->SyncPeriod = 0;
1448         pDCB->SyncOffset = 0;
1449         pDCB->TagMask = 0;
1450         pDCB->CtrlR3 = FAST_CLK;
1451         pDCB->CtrlR4 &= NEGATE_REQACKDATA | CTRL4_RESERVED | NEGATE_REQACK;
1452         pDCB->CtrlR4 |= pACB->glitch_cfg;
1453         pDCB = pDCB->pNextDCB;
1454     }
1455     while( pdcb != pDCB );
1456     pACB->ACBFlag &= ~(RESET_DEV | RESET_DONE | RESET_DETECT);
1457
1458 }
1459
1460 #if 0
1461 /* Moves all SRBs from Going to Waiting for all DCBs */
1462 static void dc390_RecoverSRB( PACB pACB )
1463 {
1464     PDCB   pDCB, pdcb;
1465     PSRB   psrb, psrb2;
1466     UINT   cnt, i;
1467
1468     pDCB = pACB->pLinkDCB;
1469     if( !pDCB ) return;
1470     pdcb = pDCB;
1471     do
1472     {
1473         cnt = pdcb->GoingSRBCnt;
1474         psrb = pdcb->pGoingSRB;
1475         for (i=0; i<cnt; i++)
1476         {
1477             psrb2 = psrb;
1478             psrb = psrb->pNextSRB;
1479 /*          dc390_RewaitSRB( pDCB, psrb ); */
1480             if( pdcb->pWaitingSRB )
1481             {
1482                 psrb2->pNextSRB = pdcb->pWaitingSRB;
1483                 pdcb->pWaitingSRB = psrb2;
1484             }
1485             else
1486             {
1487                 pdcb->pWaitingSRB = psrb2;
1488                 pdcb->pWaitLast = psrb2;
1489                 psrb2->pNextSRB = NULL;
1490             }
1491         }
1492         pdcb->GoingSRBCnt = 0;
1493         pdcb->pGoingSRB = NULL;
1494         pdcb->TagMask = 0;
1495         pdcb = pdcb->pNextDCB;
1496     } while( pdcb != pDCB );
1497 }
1498 #endif
1499
1500 /***********************************************************************
1501  * Function : int DC390_reset (Scsi_Cmnd *cmd, ...)
1502  *
1503  * Purpose : perform a hard reset on the SCSI bus
1504  *
1505  * Inputs : cmd - command which caused the SCSI RESET
1506  *          resetFlags - how hard to try
1507  *
1508  * Returns : 0 on success.
1509  ***********************************************************************/
1510
1511 static int DC390_reset (Scsi_Cmnd *cmd)
1512 {
1513     UCHAR   bval;
1514     PACB    pACB = (PACB) cmd->device->host->hostdata;
1515
1516     printk(KERN_INFO "DC390: RESET ... ");
1517
1518     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
1519     bval = DC390_read8 (CtrlReg1);
1520     bval |= DIS_INT_ON_SCSI_RST;
1521     DC390_write8 (CtrlReg1, bval);      /* disable IRQ on bus reset */
1522
1523     pACB->ACBFlag |= RESET_DEV;
1524     dc390_ResetSCSIBus( pACB );
1525
1526     dc390_ResetDevParam( pACB );
1527     udelay (1000);
1528     pACB->pScsiHost->last_reset = jiffies + 3*HZ/2 
1529                 + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
1530     
1531     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1532     DC390_read8 (INT_Status);           /* Reset Pending INT */
1533
1534     dc390_DoingSRB_Done( pACB, cmd );
1535     /* dc390_RecoverSRB (pACB); */
1536     pACB->pActiveDCB = NULL;
1537
1538     pACB->ACBFlag = 0;
1539     bval = DC390_read8 (CtrlReg1);
1540     bval &= ~DIS_INT_ON_SCSI_RST;
1541     DC390_write8 (CtrlReg1, bval);      /* re-enable interrupt */
1542
1543     dc390_Waiting_process( pACB );
1544
1545     printk("done\n");
1546     return( SCSI_RESET_SUCCESS );
1547 }
1548
1549 #include "scsiiom.c"
1550
1551
1552 /***********************************************************************
1553  * Function : static void dc390_initDCB()
1554  *
1555  * Purpose :  initialize the internal structures for a DCB (to be malloced)
1556  *
1557  * Inputs : SCSI id and lun
1558  ***********************************************************************/
1559
1560 static void dc390_initDCB( PACB pACB, PDCB *ppDCB, UCHAR id, UCHAR lun )
1561 {
1562     PEEprom     prom;
1563     UCHAR       index;
1564     PDCB pDCB, pDCB2;
1565
1566     pDCB = kmalloc (sizeof(DC390_DCB), GFP_ATOMIC);
1567     DCBDEBUG(printk (KERN_INFO "DC390: alloc mem for DCB (ID %i, LUN %i): %p\n",        \
1568                      id, lun, pDCB));
1569  
1570     *ppDCB = pDCB;
1571     if (!pDCB) return;
1572     pDCB2 = 0;
1573     if( pACB->DCBCnt == 0 )
1574     {
1575         pACB->pLinkDCB = pDCB;
1576         pACB->pDCBRunRobin = pDCB;
1577     }
1578     else
1579     {
1580         pACB->pLastDCB->pNextDCB = pDCB;
1581     }
1582    
1583     pACB->DCBCnt++;
1584    
1585     pDCB->pNextDCB = pACB->pLinkDCB;
1586     pACB->pLastDCB = pDCB;
1587
1588     pDCB->pDCBACB = pACB;
1589     pDCB->TargetID = id;
1590     pDCB->TargetLUN = lun;
1591     pDCB->pWaitingSRB = NULL;
1592     pDCB->pGoingSRB = NULL;
1593     pDCB->GoingSRBCnt = 0;
1594     pDCB->WaitSRBCnt = 0;
1595     pDCB->pActiveSRB = NULL;
1596     pDCB->TagMask = 0;
1597     pDCB->MaxCommand = 1;
1598     index = pACB->AdapterIndex;
1599     pDCB->DCBFlag = 0;
1600
1601     /* Is there a corresp. LUN==0 device ? */
1602     if (lun != 0)
1603         pDCB2 = dc390_findDCB (pACB, id, 0);
1604     prom = (PEEprom) &dc390_eepromBuf[index][id << 2];
1605     /* Some values are for all LUNs: Copy them */
1606     /* In a clean way: We would have an own structure for a SCSI-ID */
1607     if (pDCB2)
1608     {
1609       pDCB->DevMode = pDCB2->DevMode;
1610       pDCB->SyncMode = pDCB2->SyncMode;
1611       pDCB->SyncPeriod = pDCB2->SyncPeriod;
1612       pDCB->SyncOffset = pDCB2->SyncOffset;
1613       pDCB->NegoPeriod = pDCB2->NegoPeriod;
1614       
1615       pDCB->CtrlR3 = pDCB2->CtrlR3;
1616       pDCB->CtrlR4 = pDCB2->CtrlR4;
1617       pDCB->Inquiry7 = pDCB2->Inquiry7;
1618     }
1619     else
1620     {           
1621       pDCB->DevMode = prom->EE_MODE1;
1622       pDCB->SyncMode = 0;
1623       pDCB->SyncPeriod = 0;
1624       pDCB->SyncOffset = 0;
1625       pDCB->NegoPeriod = (dc390_clock_period1[prom->EE_SPEED] * 25) >> 2;
1626             
1627       pDCB->CtrlR3 = FAST_CLK;
1628       
1629       pDCB->CtrlR4 = pACB->glitch_cfg | CTRL4_RESERVED;
1630       if( dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION)
1631         pDCB->CtrlR4 |= NEGATE_REQACKDATA | NEGATE_REQACK;
1632       pDCB->Inquiry7 = 0;
1633     }
1634
1635     pACB->DCBmap[id] |= (1 << lun);
1636     dc390_updateDCB(pACB, pDCB);
1637 }
1638
1639 /***********************************************************************
1640  * Function : static void dc390_updateDCB()
1641  *
1642  * Purpose :  Set the configuration dependent DCB parameters
1643  ***********************************************************************/
1644
1645 static void dc390_updateDCB (PACB pACB, PDCB pDCB)
1646 {
1647   pDCB->SyncMode &= EN_TAG_QUEUEING | SYNC_NEGO_DONE /*| EN_ATN_STOP*/;
1648   if (pDCB->DevMode & TAG_QUEUEING_) {
1649         //if (pDCB->SyncMode & EN_TAG_QUEUEING) pDCB->MaxCommand = pACB->TagMaxNum;
1650   } else {
1651         pDCB->SyncMode &= ~EN_TAG_QUEUEING;
1652         pDCB->MaxCommand = 1;
1653   }
1654
1655   if( pDCB->DevMode & SYNC_NEGO_ )
1656         pDCB->SyncMode |= SYNC_ENABLE;
1657   else {
1658         pDCB->SyncMode &= ~(SYNC_NEGO_DONE | SYNC_ENABLE);
1659         pDCB->SyncOffset &= ~0x0f;
1660   }
1661
1662   //if (! (pDCB->DevMode & EN_DISCONNECT_)) pDCB->SyncMode &= ~EN_ATN_STOP; 
1663
1664   pDCB->CtrlR1 = pACB->pScsiHost->this_id;
1665   if( pDCB->DevMode & PARITY_CHK_ )
1666         pDCB->CtrlR1 |= PARITY_ERR_REPO;
1667 }  
1668
1669 /***********************************************************************
1670  * Function : static void dc390_initSRB()
1671  *
1672  * Purpose :  initialize the internal structures for a given SRB
1673  *
1674  * Inputs : psrb - pointer to this scsi request block structure
1675  ***********************************************************************/
1676
1677 static void __inline__ dc390_initSRB( PSRB psrb )
1678 {
1679   /* psrb->PhysSRB = virt_to_phys( psrb ); */
1680 }
1681
1682
1683 static void dc390_linkSRB( PACB pACB )
1684 {
1685     UINT   count, i;
1686
1687     count = pACB->SRBCount;
1688     for( i=0; i<count; i++)
1689     {
1690         if( i != count-1 )
1691             pACB->SRB_array[i].pNextSRB = &pACB->SRB_array[i+1];
1692         else
1693             pACB->SRB_array[i].pNextSRB = NULL;
1694         dc390_initSRB( &pACB->SRB_array[i] );
1695     }
1696 }
1697
1698
1699 /***********************************************************************
1700  * Function : static void dc390_initACB ()
1701  *
1702  * Purpose :  initialize the internal structures for a given SCSI host
1703  *
1704  * Inputs : psh - pointer to this host adapter's structure
1705  *          io_port, Irq, index: Resources and adapter index
1706  ***********************************************************************/
1707
1708 static void __init dc390_initACB (PSH psh, ULONG io_port, UCHAR Irq, UCHAR index)
1709 {
1710     PACB    pACB;
1711     UCHAR   i;
1712
1713     psh->can_queue = MAX_CMD_QUEUE;
1714     psh->cmd_per_lun = MAX_CMD_PER_LUN;
1715     psh->this_id = (int) dc390_eepromBuf[index][EE_ADAPT_SCSI_ID];
1716     psh->io_port = io_port;
1717     psh->n_io_port = 0x80;
1718     psh->irq = Irq;
1719     psh->base = io_port;
1720     psh->unique_id = io_port;
1721     psh->dma_channel = -1;
1722     psh->last_reset = jiffies;
1723         
1724     pACB = (PACB) psh->hostdata;
1725
1726     pACB->pScsiHost = psh;
1727     pACB->IOPortBase = (USHORT) io_port;
1728     pACB->IRQLevel = Irq;
1729
1730     DEBUG0(printk (KERN_INFO "DC390: Adapter index %i, ID %i, IO 0x%08x, IRQ 0x%02x\n", \
1731                    index, psh->this_id, (int)io_port, Irq));
1732    
1733     psh->max_id = 8;
1734
1735     if( psh->max_id - 1 == dc390_eepromBuf[index][EE_ADAPT_SCSI_ID] )
1736         psh->max_id--;
1737     psh->max_lun = 1;
1738     if( dc390_eepromBuf[index][EE_MODE2] & LUN_CHECK )
1739         psh->max_lun = 8;
1740
1741     pACB->pLinkDCB = NULL;
1742     pACB->pDCBRunRobin = NULL;
1743     pACB->pActiveDCB = NULL;
1744     pACB->pFreeSRB = pACB->SRB_array;
1745     pACB->SRBCount = MAX_SRB_CNT;
1746     pACB->AdapterIndex = index;
1747     pACB->status = 0;
1748     psh->this_id = dc390_eepromBuf[index][EE_ADAPT_SCSI_ID];
1749     pACB->DeviceCnt = 0;
1750     pACB->DCBCnt = 0;
1751     pACB->TagMaxNum = 2 << dc390_eepromBuf[index][EE_TAG_CMD_NUM];
1752     pACB->ACBFlag = 0;
1753     pACB->scan_devices = 1;
1754     pACB->MsgLen = 0;
1755     pACB->Ignore_IRQ = 0;
1756     pACB->Gmode2 = dc390_eepromBuf[index][EE_MODE2];
1757     dc390_linkSRB( pACB );
1758     pACB->pTmpSRB = &pACB->TmpSRB;
1759     dc390_initSRB( pACB->pTmpSRB );
1760     for(i=0; i<MAX_SCSI_ID; i++)
1761         pACB->DCBmap[i] = 0;
1762     pACB->sel_timeout = SEL_TIMEOUT;
1763     pACB->glitch_cfg = EATER_25NS;
1764     pACB->Cmds = pACB->CmdInQ = pACB->CmdOutOfSRB = 0;
1765     pACB->SelLost = pACB->SelConn = 0;
1766     init_timer (&pACB->Waiting_Timer);
1767 }
1768
1769
1770 /***********************************************************************
1771  * Function : static int dc390_initAdapter ()
1772  *
1773  * Purpose :  initialize the SCSI chip ctrl registers
1774  *
1775  * Inputs : psh - pointer to this host adapter's structure
1776  *          io_port, Irq, index: Resources
1777  *
1778  * Outputs: 0 on success, -1 on error
1779  ***********************************************************************/
1780
1781 static int __init dc390_initAdapter (PSH psh, ULONG io_port, UCHAR Irq, UCHAR index)
1782 {
1783     PACB   pACB, pACB2;
1784     UCHAR  dstate;
1785     int    i;
1786     
1787     pACB = (PACB) psh->hostdata;
1788
1789     if (request_region (io_port, psh->n_io_port, "tmscsim") == NULL) {
1790         printk(KERN_ERR "DC390: register IO ports error!\n");
1791         return( -1 );
1792     }
1793
1794     DC390_read8_ (INT_Status, io_port);         /* Reset Pending INT */
1795
1796     if( (i = request_irq(Irq, do_DC390_Interrupt, DC390_IRQ, "tmscsim", pACB) ))
1797       {
1798         printk(KERN_ERR "DC390: register IRQ error!\n");
1799         release_region (io_port, psh->n_io_port);
1800         return( -1 );
1801       }
1802
1803     if( !dc390_pACB_start )
1804       {
1805         pACB2 = NULL;
1806         dc390_pACB_start = pACB;
1807         dc390_pACB_current = pACB;
1808         pACB->pNextACB = NULL;
1809       }
1810     else
1811       {
1812         pACB2 = dc390_pACB_current;
1813         dc390_pACB_current->pNextACB = pACB;
1814         dc390_pACB_current = pACB;
1815         pACB->pNextACB = NULL;
1816       }
1817
1818     DC390_write8 (CtrlReg1, DIS_INT_ON_SCSI_RST | psh->this_id);        /* Disable SCSI bus reset interrupt */
1819
1820     if (pACB->Gmode2 & RST_SCSI_BUS)
1821     {
1822         dc390_ResetSCSIBus( pACB );
1823         udelay (1000);
1824         pACB->pScsiHost->last_reset = jiffies + HZ/2
1825                     + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
1826         /*
1827         for( i=0; i<(500 + 1000*dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY]); i++ )
1828                 udelay(1000);
1829          */
1830     }
1831     pACB->ACBFlag = 0;
1832     DC390_read8 (INT_Status);                           /* Reset Pending INT */
1833     
1834     DC390_write8 (Scsi_TimeOut, SEL_TIMEOUT);           /* 250ms selection timeout */
1835     DC390_write8 (Clk_Factor, CLK_FREQ_40MHZ);          /* Conversion factor = 0 , 40MHz clock */
1836     DC390_write8 (ScsiCmd, NOP_CMD);                    /* NOP cmd - clear command register */
1837     DC390_write8 (CtrlReg2, EN_FEATURE+EN_SCSI2_CMD);   /* Enable Feature and SCSI-2 */
1838     DC390_write8 (CtrlReg3, FAST_CLK);                  /* fast clock */
1839     DC390_write8 (CtrlReg4, pACB->glitch_cfg |                  /* glitch eater */
1840                 (dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION) ? NEGATE_REQACKDATA : 0);  /* Negation */
1841     DC390_write8 (CtcReg_High, 0);                      /* Clear Transfer Count High: ID */
1842     DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1843     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1844     DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
1845     dstate = DC390_read8 (DMA_Status);
1846     DC390_write8 (DMA_Status, dstate);  /* clear */
1847
1848     return(0);
1849 }
1850
1851
1852 /***********************************************************************
1853  * Function : static int DC390_init (struct Scsi_Host *host, ...)
1854  *
1855  * Purpose :  initialize the internal structures for a given SCSI host
1856  *
1857  * Inputs : host - pointer to this host adapter's structure
1858  *          io_port - IO ports mapped to this adapter
1859  *          Irq - IRQ assigned to this adpater
1860  *          struct pci_dev - PCI access handle
1861  *          index - Adapter index
1862  *
1863  * Outputs: 0 on success, -1 on error
1864  *
1865  * Note: written in capitals, because the locking is only done here,
1866  *      not in DC390_detect, called from outside 
1867  ***********************************************************************/
1868
1869 static int __init DC390_init (PSHT psht, ULONG io_port, UCHAR Irq, struct pci_dev *pdev, UCHAR index)
1870 {
1871     PSH   psh;
1872     PACB  pACB;
1873
1874     if (dc390_CheckEEpromCheckSum (PDEV, index))
1875     {
1876         int speed;
1877         dc390_adapname = "AM53C974";
1878         printk (KERN_INFO "DC390_init: No EEPROM found! Trying default settings ...\n");
1879         dc390_check_for_safe_settings ();
1880         dc390_fill_with_defaults ();
1881         dc390_EEprom_Override (index);
1882         speed = dc390_clock_speed[tmscsim[1]];
1883         printk (KERN_INFO "DC390: Used defaults: AdaptID=%i, SpeedIdx=%i (%i.%i MHz),"
1884                 " DevMode=0x%02x, AdaptMode=0x%02x, TaggedCmnds=%i (%i), DelayReset=%is\n", 
1885                 tmscsim[0], tmscsim[1], speed/10, speed%10,
1886                 (UCHAR)tmscsim[2], (UCHAR)tmscsim[3], tmscsim[4], 2 << (tmscsim[4]), tmscsim[5]);
1887     }
1888     else
1889     {
1890         dc390_check_for_safe_settings ();
1891         dc390_EEprom_Override (index);
1892     }
1893    
1894     psh = scsi_register( psht, sizeof(DC390_ACB) );
1895     if( !psh ) return( -1 );
1896         
1897     scsi_set_device(psh, &pdev->dev);
1898     pACB = (PACB) psh->hostdata;
1899
1900     DEBUG0(printk(KERN_INFO "DC390: pSH = %8x, Index %02i\n", (UINT) psh, index));
1901
1902     dc390_initACB( psh, io_port, Irq, index );
1903         
1904     PDEVSET;
1905
1906     if( !dc390_initAdapter( psh, io_port, Irq, index ) )
1907     {
1908         DEBUG0(printk("DC390: pACB = %8x, pDCBmap = %8x, pSRB_array = %8x\n",\
1909                       (UINT) pACB, (UINT) pACB->DCBmap, (UINT) pACB->SRB_array));
1910         DEBUG0(printk("DC390: ACB size= %4x, DCB size= %4x, SRB size= %4x\n",\
1911                       sizeof(DC390_ACB), sizeof(DC390_DCB), sizeof(DC390_SRB) ));
1912         return (0);
1913     }
1914     else
1915     {
1916         scsi_unregister( psh );
1917         return( -1 );
1918     }
1919 }
1920
1921 static void __init dc390_set_pci_cfg (PDEVDECL)
1922 {
1923         USHORT cmd;
1924         PCI_READ_CONFIG_WORD (PDEV, PCI_COMMAND, &cmd);
1925         cmd |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY | PCI_COMMAND_IO;
1926         PCI_WRITE_CONFIG_WORD (PDEV, PCI_COMMAND, cmd);
1927         PCI_WRITE_CONFIG_WORD (PDEV, PCI_STATUS, (PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY));
1928 }
1929
1930 int __init DC390_detect (Scsi_Host_Template *psht)
1931 {
1932     struct pci_dev *pdev = NULL;
1933     UCHAR   irq;
1934     ULONG   io_port;
1935
1936     dc390_pACB_start = NULL;
1937
1938     if ( PCI_PRESENT )
1939             while ((pdev = pci_find_device(PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD53C974, pdev)))
1940         {
1941             if (pci_enable_device (pdev))
1942                 continue;
1943
1944             if (pci_set_dma_mask(pdev, 0xffffffff)) {
1945                     printk(KERN_ERR "DC390(%i): No suitable DMA available.\n", dc390_adapterCnt);
1946                     continue;
1947             }
1948             PCI_GET_IO_AND_IRQ;
1949             DEBUG0(printk(KERN_INFO "DC390(%i): IO_PORT=%04x,IRQ=%x\n", dc390_adapterCnt, (UINT) io_port, irq));
1950
1951             if( !DC390_init(psht, io_port, irq, PDEV, dc390_adapterCnt))
1952             {
1953                 pci_set_master(pdev);
1954                 dc390_set_pci_cfg (PDEV);
1955                 dc390_adapterCnt++;
1956             }
1957         }
1958     else
1959         printk (KERN_ERR "DC390: No PCI BIOS found!\n");
1960    
1961     if (dc390_adapterCnt)
1962         psht->proc_name = "tmscsim";
1963
1964     printk(KERN_INFO "DC390: %i adapters found\n", dc390_adapterCnt);
1965     return( dc390_adapterCnt );
1966 }
1967
1968 /********************************************************************
1969  * Function: DC390_proc_info(char* buffer, char **start,
1970  *                           off_t offset, int length, int hostno, int inout)
1971  *
1972  * Purpose: return SCSI Adapter/Device Info
1973  *
1974  * Input: buffer: Pointer to a buffer where to write info
1975  *        start :
1976  *        offset:
1977  *        hostno: Host adapter index
1978  *        inout : Read (=0) or set(!=0) info
1979  *
1980  * Output: buffer: contains info
1981  *         length; length of info in buffer
1982  *
1983  * return value: length
1984  *
1985  ********************************************************************/
1986
1987 #undef SPRINTF
1988 #define SPRINTF(args...) pos += sprintf(pos, ## args)
1989
1990 #define YESNO(YN)               \
1991  if (YN) SPRINTF(" Yes ");      \
1992  else SPRINTF(" No  ")
1993
1994
1995 static int DC390_proc_info (struct Scsi_Host *shpnt, char *buffer, char **start,
1996                             off_t offset, int length, int inout)
1997 {
1998   int dev, spd, spd1;
1999   char *pos = buffer;
2000   PACB pACB;
2001   PDCB pDCB;
2002
2003   pACB = dc390_pACB_start;
2004
2005   while(pACB != (PACB)-1)
2006      {
2007         if (shpnt == pACB->pScsiHost)
2008                 break;
2009         pACB = pACB->pNextACB;
2010      }
2011
2012   if (pACB == (PACB)-1) return(-ESRCH);
2013
2014   if(inout) /* Has data been written to the file ? */
2015       return -ENOSYS;
2016    
2017   SPRINTF("Tekram DC390/AM53C974 PCI SCSI Host Adapter, ");
2018   SPRINTF("Driver Version %s\n", DC390_VERSION);
2019
2020   SPRINTF("SCSI Host Nr %i, ", shpnt->host_no);
2021   SPRINTF("%s Adapter Nr %i\n", dc390_adapname, pACB->AdapterIndex);
2022   SPRINTF("IOPortBase 0x%04x, ", pACB->IOPortBase);
2023   SPRINTF("IRQ %02i\n", pACB->IRQLevel);
2024
2025   SPRINTF("MaxID %i, MaxLUN %i, ", shpnt->max_id, shpnt->max_lun);
2026   SPRINTF("AdapterID %i, SelTimeout %i ms, DelayReset %i s\n", 
2027           shpnt->this_id, (pACB->sel_timeout*164)/100,
2028           dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY]);
2029
2030   SPRINTF("TagMaxNum %i, Status 0x%02x, ACBFlag 0x%02x, GlitchEater %i ns\n",
2031           pACB->TagMaxNum, pACB->status, pACB->ACBFlag, GLITCH_TO_NS(pACB->glitch_cfg)*12);
2032
2033   SPRINTF("Statistics: Cmnds %li, Cmnds not sent directly %i, Out of SRB conds %i\n",
2034           pACB->Cmds, pACB->CmdInQ, pACB->CmdOutOfSRB);
2035   SPRINTF("            Lost arbitrations %i, Sel. connected %i, Connected: %s\n", 
2036           pACB->SelLost, pACB->SelConn, pACB->Connected? "Yes": "No");
2037    
2038   SPRINTF("Nr of attached devices: %i, Nr of DCBs: %i\n", pACB->DeviceCnt, pACB->DCBCnt);
2039   SPRINTF("Map of attached LUNs: %02x %02x %02x %02x %02x %02x %02x %02x\n",
2040           pACB->DCBmap[0], pACB->DCBmap[1], pACB->DCBmap[2], pACB->DCBmap[3], 
2041           pACB->DCBmap[4], pACB->DCBmap[5], pACB->DCBmap[6], pACB->DCBmap[7]);
2042
2043   SPRINTF("Idx ID LUN Prty Sync DsCn SndS TagQ NegoPeriod SyncSpeed SyncOffs MaxCmd\n");
2044
2045   pDCB = pACB->pLinkDCB;
2046   for (dev = 0; dev < pACB->DCBCnt; dev++)
2047      {
2048       SPRINTF("%02i  %02i  %02i ", dev, pDCB->TargetID, pDCB->TargetLUN);
2049       YESNO(pDCB->DevMode & PARITY_CHK_);
2050       YESNO(pDCB->SyncMode & SYNC_NEGO_DONE);
2051       YESNO(pDCB->DevMode & EN_DISCONNECT_);
2052       YESNO(pDCB->DevMode & SEND_START_);
2053       YESNO(pDCB->SyncMode & EN_TAG_QUEUEING);
2054       if (pDCB->SyncOffset & 0x0f)
2055       {
2056          int sp = pDCB->SyncPeriod; if (! (pDCB->CtrlR3 & FAST_SCSI)) sp++;
2057          SPRINTF("  %03i ns ", (pDCB->NegoPeriod) << 2);
2058          spd = 40/(sp); spd1 = 40%(sp);
2059          spd1 = (spd1 * 10 + sp/2) / (sp);
2060          SPRINTF("   %2i.%1i M      %02i", spd, spd1, (pDCB->SyncOffset & 0x0f));
2061       }
2062       else SPRINTF(" (%03i ns)                 ", (pDCB->NegoPeriod) << 2);
2063       /* Add more info ...*/
2064       SPRINTF ("      %02i\n", pDCB->MaxCommand);
2065       pDCB = pDCB->pNextDCB;
2066      }
2067     if (timer_pending(&pACB->Waiting_Timer)) SPRINTF ("Waiting queue timer running\n");
2068     else SPRINTF ("\n");
2069     pDCB = pACB->pLinkDCB;
2070         
2071     for (dev = 0; dev < pACB->DCBCnt; dev++)
2072     {
2073         PSRB pSRB;
2074         if (pDCB->WaitSRBCnt) 
2075                     SPRINTF ("DCB (%02i-%i): Waiting: %i:", pDCB->TargetID, pDCB->TargetLUN,
2076                              pDCB->WaitSRBCnt);
2077         for (pSRB = pDCB->pWaitingSRB; pSRB; pSRB = pSRB->pNextSRB)
2078                 SPRINTF(" %li", pSRB->pcmd->pid);
2079         if (pDCB->GoingSRBCnt) 
2080                     SPRINTF ("\nDCB (%02i-%i): Going  : %i:", pDCB->TargetID, pDCB->TargetLUN,
2081                              pDCB->GoingSRBCnt);
2082         for (pSRB = pDCB->pGoingSRB; pSRB; pSRB = pSRB->pNextSRB)
2083 #if 0 //def DC390_DEBUGTRACE
2084                 SPRINTF(" %s\n  ", pSRB->debugtrace);
2085 #else
2086                 SPRINTF(" %li", pSRB->pcmd->pid);
2087 #endif
2088         if (pDCB->WaitSRBCnt || pDCB->GoingSRBCnt) SPRINTF ("\n");
2089         pDCB = pDCB->pNextDCB;
2090     }
2091         
2092 #ifdef DC390_DEBUGDCB
2093     SPRINTF ("DCB list for ACB %p:\n", pACB);
2094     pDCB = pACB->pLinkDCB;
2095     SPRINTF ("%p", pDCB);
2096     for (dev = 0; dev < pACB->DCBCnt; dev++, pDCB=pDCB->pNextDCB)
2097         SPRINTF ("->%p", pDCB->pNextDCB);
2098     SPRINTF("\n");
2099 #endif
2100   
2101   *start = buffer + offset;
2102
2103   if (pos - buffer < offset)
2104     return 0;
2105   else if (pos - buffer - offset < length)
2106     return pos - buffer - offset;
2107   else
2108     return length;
2109 }
2110
2111 #undef YESNO
2112 #undef SPRINTF
2113
2114 /***********************************************************************
2115  * Function : static int dc390_shutdown (struct Scsi_Host *host)
2116  *
2117  * Purpose : does a clean (we hope) shutdown of the SCSI chip.
2118  *           Use prior to dumping core, unloading the driver, etc.
2119  *
2120  * Returns : 0 on success
2121  ***********************************************************************/
2122 static int dc390_shutdown (struct Scsi_Host *host)
2123 {
2124     UCHAR    bval;
2125     PACB pACB = (PACB)(host->hostdata);
2126    
2127 /*  pACB->soft_reset(host); */
2128
2129     printk(KERN_INFO "DC390: shutdown\n");
2130
2131     pACB->ACBFlag = RESET_DEV;
2132     bval = DC390_read8 (CtrlReg1);
2133     bval |= DIS_INT_ON_SCSI_RST;
2134     DC390_write8 (CtrlReg1, bval);      /* disable interrupt */
2135     if (pACB->Gmode2 & RST_SCSI_BUS)
2136                 dc390_ResetSCSIBus (pACB);
2137
2138     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
2139     return( 0 );
2140 }
2141
2142 static void dc390_freeDCBs (struct Scsi_Host *host)
2143 {
2144     PDCB pDCB, nDCB;
2145     PACB pACB = (PACB)(host->hostdata);
2146     
2147     pDCB = pACB->pLinkDCB;
2148     if (!pDCB) return;
2149     do
2150     {
2151         nDCB = pDCB->pNextDCB;
2152         DCBDEBUG(printk (KERN_INFO "DC390: Free DCB (ID %i, LUN %i): %p\n",\
2153                          pDCB->TargetID, pDCB->TargetLUN, pDCB));
2154         //kfree (pDCB);
2155         dc390_remove_dev (pACB, pDCB);
2156         pDCB = nDCB;
2157     } while (pDCB && pACB->pLinkDCB);
2158
2159 }
2160
2161 static int DC390_release (struct Scsi_Host *host)
2162 {
2163     DC390_IFLAGS;
2164     PACB pACB = (PACB)(host->hostdata);
2165
2166     DC390_LOCK_IO(host);
2167
2168     /* TO DO: We should check for outstanding commands first. */
2169     dc390_shutdown (host);
2170
2171     if (host->irq != SCSI_IRQ_NONE)
2172     {
2173         DEBUG0(printk(KERN_INFO "DC390: Free IRQ %i\n",host->irq));
2174         free_irq (host->irq, pACB);
2175     }
2176
2177     release_region(host->io_port,host->n_io_port);
2178     dc390_freeDCBs (host);
2179     DC390_UNLOCK_IO(host);
2180     scsi_unregister(host);
2181     return( 1 );
2182 }
2183
2184 static Scsi_Host_Template driver_template = {
2185    .proc_name      = "tmscsim", 
2186    .proc_info      = DC390_proc_info,
2187    .name           = DC390_BANNER " V" DC390_VERSION,
2188    .detect         = DC390_detect,
2189    .release        = DC390_release,
2190    .queuecommand   = DC390_queue_command,
2191    .eh_abort_handler            = DC390_abort,
2192    .eh_bus_reset_handler        = DC390_reset,
2193    .bios_param     = DC390_bios_param,
2194    .can_queue      = 42,
2195    .this_id        = 7,
2196    .sg_tablesize   = SG_ALL,
2197    .cmd_per_lun    = 16,
2198    .use_clustering = DISABLE_CLUSTERING,
2199 };
2200 #include "scsi_module.c"