ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[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  ***********************************************************************/
172
173 /* Uncomment SA_INTERRUPT, if the driver refuses to share its IRQ with other devices */
174 #define DC390_IRQ SA_SHIRQ /* | SA_INTERRUPT */
175
176 /* DEBUG options */
177 //#define DC390_DEBUG0
178 //#define DC390_DEBUG1
179 //#define DC390_DCBDEBUG
180 //#define DC390_PARSEDEBUG
181 //#define DC390_REMOVABLEDEBUG
182 //#define DC390_LOCKDEBUG
183
184 //#define NOP do{}while(0)
185 #define C_NOP
186
187 /* Debug definitions */
188 #ifdef DC390_DEBUG0
189 # define DEBUG0(x) x
190 #else
191 # define DEBUG0(x) C_NOP
192 #endif
193 #ifdef DC390_DEBUG1
194 # define DEBUG1(x) x
195 #else
196 # define DEBUG1(x) C_NOP
197 #endif
198 #ifdef DC390_DCBDEBUG
199 # define DCBDEBUG(x) x
200 #else
201 # define DCBDEBUG(x) C_NOP
202 #endif
203 #ifdef DC390_PARSEDEBUG
204 # define PARSEDEBUG(x) x
205 #else
206 # define PARSEDEBUG(x) C_NOP
207 #endif
208 #ifdef DC390_REMOVABLEDEBUG
209 # define REMOVABLEDEBUG(x) x
210 #else
211 # define REMOVABLEDEBUG(x) C_NOP
212 #endif
213 #define DCBDEBUG1(x) C_NOP
214
215 /* Includes */
216 #include <linux/module.h>
217 #include <asm/dma.h>
218 #include <asm/io.h>
219 #include <asm/system.h>
220 #include <linux/delay.h>
221 #include <linux/signal.h>
222 #include <linux/sched.h>
223 #include <linux/errno.h>
224 #include <linux/kernel.h>
225 #include <linux/ioport.h>
226 #include <linux/pci.h>
227 #include <linux/proc_fs.h>
228 #include <linux/string.h>
229 #include <linux/ctype.h>
230 #include <linux/mm.h>
231 #include <linux/config.h>
232 #include <linux/version.h>
233 #include <linux/blkdev.h>
234 #include <linux/timer.h>
235 #include <linux/interrupt.h>
236
237 #include "scsi.h"
238 #include "hosts.h"
239 #include <linux/stat.h>
240 #include <scsi/scsicam.h>
241
242 #include "dc390.h"
243
244 #define PCI_DEVICE_ID_AMD53C974         PCI_DEVICE_ID_AMD_SCSI
245
246 /* Locking */
247
248 /* Note: Starting from 2.1.9x, the mid-level scsi code issues a 
249  * spinlock_irqsave (&io_request_lock) before calling the driver's 
250  * routines, so we don't need to lock, except in the IRQ handler.
251  * The policy 3, let the midlevel scsi code do the io_request_locks
252  * and us locking on a driver specific lock, shouldn't hurt anybody; it
253  * just causes a minor performance degradation for setting the locks.
254  */
255
256 /* spinlock things
257  * level 3: lock on both adapter specific locks and (global) io_request_lock
258  * level 2: lock on adapter specific locks only
259  * level 1: rely on the locking of the mid level code (io_request_lock)
260  * undef  : traditional save_flags; cli; restore_flags;
261  */
262
263 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,30)
264 # include <linux/init.h>
265 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,30)
266 # include <linux/spinlock.h>
267 #else
268 # include <asm/spinlock.h>
269 #endif
270 #endif
271
272 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,99) && defined(MODULE)
273 static struct pci_device_id tmscsim_pci_tbl[] = {
274         {
275                 .vendor         = PCI_VENDOR_ID_AMD,
276                 .device         = PCI_DEVICE_ID_AMD53C974,
277                 .subvendor      = PCI_ANY_ID,
278                 .subdevice      = PCI_ANY_ID,
279         },
280         { }             /* Terminating entry */
281 };
282 MODULE_DEVICE_TABLE(pci, tmscsim_pci_tbl);
283 #endif
284         
285 #define USE_SPINLOCKS 1
286 #define NEW_PCI 1
287
288 #define DC390_AFLAGS 
289 #define DC390_IFLAGS unsigned long iflags
290 #define DC390_DFLAGS unsigned long dflags
291 spinlock_t dc390_drvlock = SPIN_LOCK_UNLOCKED;
292 #define DC390_LOCK_IO(dev) spin_lock_irqsave (((struct Scsi_Host *)dev)->host_lock, iflags)
293 #define DC390_UNLOCK_IO(dev) spin_unlock_irqrestore (((struct Scsi_Host *)dev)->host_lock, iflags)
294 #define DC390_LOCK_DRV spin_lock_irqsave (&dc390_drvlock, dflags)
295 #define DC390_UNLOCK_DRV spin_unlock_irqrestore (&dc390_drvlock, dflags)
296 #define DC390_LOCK_DRV_NI spin_lock (&dc390_drvlock)
297 #define DC390_UNLOCK_DRV_NI spin_unlock (&dc390_drvlock)
298 #define DC390_LOCK_ACB /* DC390_LOCK_IO */
299 #define DC390_UNLOCK_ACB /* DC390_UNLOCK_IO */
300 #define DC390_LOCK_ACB_NI /* spin_lock (&(pACB->lock)) */
301 #define DC390_UNLOCK_ACB_NI /* spin_unlock (&(pACB->lock)) */
302 #define DC390_LOCKA_INIT /* DC390_LOCKA_INIT */
303
304 /* These macros are used for uniform access to 2.0.x and 2.1.x PCI config space*/
305
306 #define PDEV pdev
307 #define PDEVDECL struct pci_dev *pdev
308 #define PDEVDECL0 struct pci_dev *pdev = NULL
309 #define PDEVDECL1 struct pci_dev *pdev
310 #define PDEVSET pACB->pdev=pdev
311 #define PDEVSET1 pdev=pACB->pdev
312 #define PCI_WRITE_CONFIG_BYTE(pd, rv, bv) pci_write_config_byte (pd, rv, bv)
313 #define PCI_READ_CONFIG_BYTE(pd, rv, bv) pci_read_config_byte (pd, rv, bv)
314 #define PCI_WRITE_CONFIG_WORD(pd, rv, bv) pci_write_config_word (pd, rv, bv)
315 #define PCI_READ_CONFIG_WORD(pd, rv, bv) pci_read_config_word (pd, rv, bv)
316 #define PCI_BUS_DEV pdev->bus->number, pdev->devfn
317 #define PCI_PRESENT (1)
318 #define PCI_SET_MASTER pci_set_master (pdev)
319 #define PCI_FIND_DEVICE(vend, id) (pdev = pci_find_device (vend, id, pdev))
320 #define PCI_GET_IO_AND_IRQ do{io_port = pci_resource_start (pdev, 0); irq = pdev->irq;} while(0)
321
322 #include "tmscsim.h"
323
324 #ifndef __init
325 # define __init
326 #endif
327
328 UCHAR dc390_StartSCSI( PACB pACB, PDCB pDCB, PSRB pSRB );
329 void dc390_DataOut_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
330 void dc390_DataIn_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
331 static void dc390_Command_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
332 static void dc390_Status_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
333 static void dc390_MsgOut_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
334 void dc390_MsgIn_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
335 static void dc390_DataOutPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
336 static void dc390_DataInPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
337 void dc390_CommandPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
338 static void dc390_StatusPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
339 void dc390_MsgOutPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
340 static void dc390_MsgInPhase( PACB pACB, PSRB pSRB, PUCHAR psstatus);
341 static void dc390_Nop_0( PACB pACB, PSRB pSRB, PUCHAR psstatus);
342 static void dc390_Nop_1( PACB pACB, PSRB pSRB, PUCHAR psstatus);
343
344 static void dc390_SetXferRate( PACB pACB, PDCB pDCB );
345 void dc390_Disconnect( PACB pACB );
346 void dc390_Reselect( PACB pACB );
347 void dc390_SRBdone( PACB pACB, PDCB pDCB, PSRB pSRB );
348 void dc390_DoingSRB_Done( PACB pACB, PSCSICMD cmd );
349 static void dc390_ScsiRstDetect( PACB pACB );
350 static void dc390_ResetSCSIBus( PACB pACB );
351 static void __inline__ dc390_RequestSense( PACB pACB, PDCB pDCB, PSRB pSRB );
352 static void __inline__ dc390_InvalidCmd( PACB pACB );
353 static void __inline__ dc390_EnableMsgOut_Abort (PACB, PSRB);
354 static void dc390_remove_dev (PACB pACB, PDCB pDCB);
355 irqreturn_t do_DC390_Interrupt( int, void *, struct pt_regs *);
356
357 int    dc390_initAdapter( PSH psh, ULONG io_port, UCHAR Irq, UCHAR index );
358 void   dc390_initDCB( PACB pACB, PDCB *ppDCB, UCHAR id, UCHAR lun);
359 void   dc390_updateDCB (PACB pACB, PDCB pDCB);
360
361 static int DC390_release(struct Scsi_Host *host);
362 static int dc390_shutdown (struct Scsi_Host *host);
363
364
365 //static PSHT   dc390_pSHT_start = NULL;
366 //static PSH    dc390_pSH_start = NULL;
367 //static PSH    dc390_pSH_current = NULL;
368 static PACB     dc390_pACB_start= NULL;
369 static PACB     dc390_pACB_current = NULL;
370 static ULONG    dc390_lastabortedpid = 0;
371 static UINT     dc390_laststatus = 0;
372 static UCHAR    dc390_adapterCnt = 0;
373
374 /* Startup values, to be overriden on the commandline */
375 int tmscsim[] = {-2, -2, -2, -2, -2, -2};
376
377 # if defined(MODULE) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,30)
378 MODULE_PARM(tmscsim, "1-6i");
379 MODULE_PARM_DESC(tmscsim, "Host SCSI ID, Speed (0=10MHz), Device Flags, Adapter Flags, Max Tags (log2(tags)-1), DelayReset (s)");
380 # endif
381
382 #if defined(MODULE) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,30)
383 MODULE_AUTHOR("C.L. Huang / Kurt Garloff");
384 MODULE_DESCRIPTION("SCSI host adapter driver for Tekram DC390 and other AMD53C974A based PCI SCSI adapters");
385 MODULE_LICENSE("GPL");
386
387 MODULE_SUPPORTED_DEVICE("sd,sr,sg,st");
388 #endif
389
390 static PVOID dc390_phase0[]={
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 PVOID dc390_phase1[]={
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
414 #ifdef DC390_DEBUG1
415 static char* dc390_p0_str[] = {
416        "dc390_DataOut_0",
417        "dc390_DataIn_0",
418        "dc390_Command_0",
419        "dc390_Status_0",
420        "dc390_Nop_0",
421        "dc390_Nop_0",
422        "dc390_MsgOut_0",
423        "dc390_MsgIn_0",
424        "dc390_Nop_1"
425        };
426      
427 static char* dc390_p1_str[] = {
428        "dc390_DataOutPhase",
429        "dc390_DataInPhase",
430        "dc390_CommandPhase",
431        "dc390_StatusPhase",
432        "dc390_Nop_0",
433        "dc390_Nop_0",
434        "dc390_MsgOutPhase",
435        "dc390_MsgInPhase",
436        "dc390_Nop_1"
437        };
438 #endif   
439
440 /* Devices erroneously pretending to be able to do TagQ */
441 UCHAR  dc390_baddevname1[2][28] ={
442        "SEAGATE ST3390N         9546",
443        "HP      C3323-300       4269"};
444 #define BADDEVCNT       2
445
446 static char*  dc390_adapname = "DC390";
447 UCHAR  dc390_eepromBuf[MAX_ADAPTER_NUM][EE_LEN];
448 UCHAR  dc390_clock_period1[] = {4, 5, 6, 7, 8, 10, 13, 20};
449 UCHAR  dc390_clock_speed[] = {100,80,67,57,50, 40, 31, 20};
450
451 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,3,30)
452 struct proc_dir_entry   DC390_proc_scsi_tmscsim ={
453        PROC_SCSI_DC390T, 7 ,"tmscsim",
454        S_IFDIR | S_IRUGO | S_IXUGO, 2
455        };
456 #endif
457
458 /***********************************************************************
459  * Functions for access to DC390 EEPROM
460  * and some to emulate it
461  *
462  **********************************************************************/
463
464
465 static void __init dc390_EnDisableCE( UCHAR mode, PDEVDECL, PUCHAR regval )
466 {
467     UCHAR bval;
468
469     bval = 0;
470     if(mode == ENABLE_CE)
471         *regval = 0xc0;
472     else
473         *regval = 0x80;
474     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
475     if(mode == DISABLE_CE)
476         PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
477     udelay(160);
478 }
479
480
481 /* Override EEprom values with explicitly set values */
482 static void __init dc390_EEprom_Override (UCHAR index)
483 {
484     PUCHAR ptr;
485     UCHAR  id;
486     ptr = (PUCHAR) dc390_eepromBuf[index];
487     
488     /* Adapter Settings */
489     if (tmscsim[0] != -2)
490         ptr[EE_ADAPT_SCSI_ID] = (UCHAR)tmscsim[0];      /* Adapter ID */
491     if (tmscsim[3] != -2)
492         ptr[EE_MODE2] = (UCHAR)tmscsim[3];
493     if (tmscsim[5] != -2)
494         ptr[EE_DELAY] = tmscsim[5];                     /* Reset delay */
495     if (tmscsim[4] != -2)
496         ptr[EE_TAG_CMD_NUM] = (UCHAR)tmscsim[4];        /* Tagged Cmds */
497     
498     /* Device Settings */
499     for (id = 0; id < MAX_SCSI_ID; id++)
500     {
501         if (tmscsim[2] != -2)
502                 ptr[id<<2] = (UCHAR)tmscsim[2];         /* EE_MODE1 */
503         if (tmscsim[1] != -2)
504                 ptr[(id<<2) + 1] = (UCHAR)tmscsim[1];   /* EE_Speed */
505     }
506 }
507
508 /* Handle "-1" case */
509 static void __init dc390_check_for_safe_settings (void)
510 {
511         if (tmscsim[0] == -1 || tmscsim[0] > 15) /* modules-2.0.0 passes -1 as string */
512         {
513                 tmscsim[0] = 7; tmscsim[1] = 4;
514                 tmscsim[2] = 0x09; tmscsim[3] = 0x0f;
515                 tmscsim[4] = 2; tmscsim[5] = 10;
516                 printk (KERN_INFO "DC390: Using safe settings.\n");
517         }
518 }
519
520
521 int __initdata tmscsim_def[] = {7, 0 /* 10MHz */,
522                 PARITY_CHK_ | SEND_START_ | EN_DISCONNECT_
523                 | SYNC_NEGO_ | TAG_QUEUEING_,
524                 MORE2_DRV | GREATER_1G | RST_SCSI_BUS | ACTIVE_NEGATION
525                 /* | NO_SEEK */
526 # ifdef CONFIG_SCSI_MULTI_LUN
527                 | LUN_CHECK
528 # endif
529                 , 3 /* 16 Tags per LUN */, 1 /* s delay after Reset */ };
530
531 /* Copy defaults over set values where missing */
532 static void __init dc390_fill_with_defaults (void)
533 {
534         int i;
535         PARSEDEBUG(printk(KERN_INFO "DC390: setup %08x %08x %08x %08x %08x %08x\n", tmscsim[0],\
536                           tmscsim[1], tmscsim[2], tmscsim[3], tmscsim[4], tmscsim[5]));
537         for (i = 0; i < 6; i++)
538         {
539                 if (tmscsim[i] < 0 || tmscsim[i] > 255)
540                         tmscsim[i] = tmscsim_def[i];
541         }
542         /* Sanity checks */
543         if (tmscsim[0] >   7) tmscsim[0] =   7;
544         if (tmscsim[1] >   7) tmscsim[1] =   4;
545         if (tmscsim[4] >   5) tmscsim[4] =   4;
546         if (tmscsim[5] > 180) tmscsim[5] = 180;
547 }
548
549 /* Override defaults on cmdline:
550  * tmscsim: AdaptID, MaxSpeed (Index), DevMode (Bitmapped), AdaptMode (Bitmapped)
551  */
552 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,13)
553 int __init dc390_setup (char *str)
554 {       
555         int ints[8];
556         int i, im;
557         (void)get_options (str, ARRAY_SIZE(ints), ints);
558         im = ints[0];
559         if (im > 6)
560         {
561                 printk (KERN_NOTICE "DC390: ignore extra params!\n");
562                 im = 6;
563         }
564         for (i = 0; i < im; i++)
565                 tmscsim[i] = ints[i+1];
566         /* dc390_checkparams (); */
567         return 1;
568 }
569 #ifndef MODULE
570 __setup("tmscsim=", dc390_setup);
571 #endif
572
573 #else
574 void __init dc390_setup (char *str, int *ints)
575 {
576         int i, im;
577         im = ints[0];
578         if (im > 6)
579         {
580                 printk (KERN_NOTICE "DC390: ignore extra params!\n");
581                 im = 6;
582         }
583         for (i = 0; i < im; i++)
584                 tmscsim[i] = ints[i+1];
585         /* dc390_checkparams (); */
586 }
587 #endif
588
589
590
591 static void __init dc390_EEpromOutDI( PDEVDECL, PUCHAR regval, UCHAR Carry )
592 {
593     UCHAR bval;
594
595     bval = 0;
596     if(Carry)
597     {
598         bval = 0x40;
599         *regval = 0x80;
600         PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
601     }
602     udelay(160);
603     bval |= 0x80;
604     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
605     udelay(160);
606     bval = 0;
607     PCI_WRITE_CONFIG_BYTE(PDEV, *regval, bval);
608     udelay(160);
609 }
610
611
612 static UCHAR __init dc390_EEpromInDO( PDEVDECL )
613 {
614     UCHAR bval;
615
616     PCI_WRITE_CONFIG_BYTE(PDEV, 0x80, 0x80);
617     udelay(160);
618     PCI_WRITE_CONFIG_BYTE(PDEV, 0x80, 0x40);
619     udelay(160);
620     PCI_READ_CONFIG_BYTE(PDEV, 0x00, &bval);
621     if(bval == 0x22)
622         return(1);
623     else
624         return(0);
625 }
626
627
628 static USHORT __init dc390_EEpromGetData1( PDEVDECL )
629 {
630     UCHAR i;
631     UCHAR carryFlag;
632     USHORT wval;
633
634     wval = 0;
635     for(i=0; i<16; i++)
636     {
637         wval <<= 1;
638         carryFlag = dc390_EEpromInDO(PDEV);
639         wval |= carryFlag;
640     }
641     return(wval);
642 }
643
644
645 static void __init dc390_Prepare( PDEVDECL, PUCHAR regval, UCHAR EEpromCmd )
646 {
647     UCHAR i,j;
648     UCHAR carryFlag;
649
650     carryFlag = 1;
651     j = 0x80;
652     for(i=0; i<9; i++)
653     {
654         dc390_EEpromOutDI(PDEV,regval,carryFlag);
655         carryFlag = (EEpromCmd & j) ? 1 : 0;
656         j >>= 1;
657     }
658 }
659
660
661 static void __init dc390_ReadEEprom( PDEVDECL, PUSHORT ptr)
662 {
663     UCHAR   regval,cmd;
664     UCHAR   i;
665
666     cmd = EEPROM_READ;
667     for(i=0; i<0x40; i++)
668     {
669         dc390_EnDisableCE(ENABLE_CE, PDEV, &regval);
670         dc390_Prepare(PDEV, &regval, cmd++);
671         *ptr++ = dc390_EEpromGetData1(PDEV);
672         dc390_EnDisableCE(DISABLE_CE, PDEV, &regval);
673     }
674 }
675
676
677 static void __init dc390_interpret_delay (UCHAR index)
678 {
679     char interpd [] = {1,3,5,10,16,30,60,120};
680     dc390_eepromBuf[index][EE_DELAY] = interpd [dc390_eepromBuf[index][EE_DELAY]];
681 }
682
683 static UCHAR __init dc390_CheckEEpromCheckSum( PDEVDECL, UCHAR index )
684 {
685     UCHAR  i;
686     char  EEbuf[128];
687     USHORT wval, *ptr = (PUSHORT)EEbuf;
688
689     dc390_ReadEEprom( PDEV, ptr );
690     memcpy (dc390_eepromBuf[index], EEbuf, EE_ADAPT_SCSI_ID);
691     memcpy (&dc390_eepromBuf[index][EE_ADAPT_SCSI_ID], 
692             &EEbuf[REAL_EE_ADAPT_SCSI_ID], EE_LEN - EE_ADAPT_SCSI_ID);
693     dc390_interpret_delay (index);
694     
695     wval = 0;
696     for(i=0; i<0x40; i++, ptr++)
697         wval += *ptr;
698     return (wval == 0x1234 ? 0 : 1);
699 }
700
701
702 /***********************************************************************
703  * Functions for the management of the internal structures 
704  * (DCBs, SRBs, Queueing)
705  *
706  **********************************************************************/
707 static PDCB __inline__ dc390_findDCB ( PACB pACB, UCHAR id, UCHAR lun)
708 {
709    PDCB pDCB = pACB->pLinkDCB; if (!pDCB) return 0;
710    while (pDCB->TargetID != id || pDCB->TargetLUN != lun)
711      {
712         pDCB = pDCB->pNextDCB;
713         if (pDCB == pACB->pLinkDCB)
714           {
715              DCBDEBUG(printk (KERN_WARNING "DC390: DCB not found (DCB=%p, DCBmap[%2x]=%2x)\n",
716                               pDCB, id, pACB->DCBmap[id]));
717              return 0;
718           }
719      }
720    DCBDEBUG1( printk (KERN_DEBUG "DCB %p (%02x,%02x) found.\n", \
721                       pDCB, pDCB->TargetID, pDCB->TargetLUN));
722    return pDCB;
723 }
724
725 /* Queueing philosphy:
726  * There are a couple of lists:
727  * - Query: Contains the Scsi Commands not yet turned into SRBs (per ACB)
728  *   (Note: For new EH, it is unnecessary!)
729  * - Waiting: Contains a list of SRBs not yet sent (per DCB)
730  * - Free: List of free SRB slots
731  * 
732  * If there are no waiting commands for the DCB, the new one is sent to the bus
733  * otherwise the oldest one is taken from the Waiting list and the new one is 
734  * queued to the Waiting List
735  * 
736  * Lists are managed using two pointers and eventually a counter
737  */
738
739
740 #if 0
741 /* Look for a SCSI cmd in a SRB queue */
742 static PSRB dc390_find_cmd_in_SRBq (PSCSICMD cmd, PSRB queue)
743 {
744     PSRB q = queue;
745     while (q)
746     {
747         if (q->pcmd == cmd) return q;
748         q = q->pNextSRB;
749         if (q == queue) return 0;
750     }
751     return q;
752 }
753 #endif
754     
755
756 /* Append to Query List */
757 static void dc390_Query_append( PSCSICMD cmd, PACB pACB )
758 {
759         dc390_cmd_scp_t *cmdq = (dc390_cmd_scp_t *)&cmd->SCp;
760
761         DEBUG0(printk ("DC390: Append cmd %li to Query\n", cmd->pid));
762
763         list_add_tail(&cmdq->list, &pACB->cmdq);
764         pACB->QueryCnt++;
765         pACB->CmdOutOfSRB++;
766 }
767
768
769 /* Return next cmd from Query list */
770 static PSCSICMD dc390_Query_get ( PACB pACB )
771 {
772         PSCSICMD  pcmd;
773         dc390_cmd_scp_t *cmdq;
774         if (list_empty(&pACB->cmdq))
775                 return NULL;
776
777         pcmd = (PSCSICMD) list_entry(pACB->cmdq.next, struct scsi_cmnd_list, scp.list);
778         DEBUG0(printk ("DC390: Get cmd %li from Query\n", pcmd->pid));
779         cmdq = (dc390_cmd_scp_t *)&pcmd->SCp;
780         list_del(&cmdq->list);
781         pACB->QueryCnt--;
782         return pcmd;
783 }
784
785
786 /* Return next free SRB */
787 static __inline__ PSRB dc390_Free_get ( PACB pACB )
788 {
789     PSRB   pSRB;
790
791     pSRB = pACB->pFreeSRB;
792     DEBUG0(printk ("DC390: Get Free SRB %p\n", pSRB));
793     if( pSRB )
794     {
795         pACB->pFreeSRB = pSRB->pNextSRB;
796         pSRB->pNextSRB = NULL;
797     }
798
799     return( pSRB );
800 }
801
802 /* Insert SRB oin top of free list */
803 static __inline__ void dc390_Free_insert (PACB pACB, PSRB pSRB)
804 {
805     DEBUG0(printk ("DC390: Free SRB %p\n", pSRB));
806     pSRB->pNextSRB = pACB->pFreeSRB;
807     pACB->pFreeSRB = pSRB;
808 }
809
810
811 /* Inserts a SRB to the top of the Waiting list */
812 static __inline__ void dc390_Waiting_insert ( PDCB pDCB, PSRB pSRB )
813 {
814     DEBUG0(printk ("DC390: Insert pSRB %p cmd %li to Waiting\n", pSRB, pSRB->pcmd->pid));
815     pSRB->pNextSRB = pDCB->pWaitingSRB;
816     if (!pDCB->pWaitingSRB)
817         pDCB->pWaitLast = pSRB;
818     pDCB->pWaitingSRB = pSRB;
819     pDCB->WaitSRBCnt++;
820 }
821
822
823 /* Queue SRB to waiting list */
824 static __inline__ void dc390_Waiting_append ( PDCB pDCB, PSRB pSRB)
825 {
826         DEBUG0(printk ("DC390: Append pSRB %p cmd %li to Waiting\n", pSRB, pSRB->pcmd->pid));
827     if( pDCB->pWaitingSRB )
828         pDCB->pWaitLast->pNextSRB = pSRB;
829     else
830         pDCB->pWaitingSRB = pSRB;
831
832     pDCB->pWaitLast = pSRB;
833     pSRB->pNextSRB = NULL;
834     pDCB->WaitSRBCnt++;
835     pDCB->pDCBACB->CmdInQ++;
836 }
837
838 static __inline__ void dc390_Going_append (PDCB pDCB, PSRB pSRB)
839 {
840     pDCB->GoingSRBCnt++;
841     DEBUG0(printk("DC390: Append SRB %p to Going\n", pSRB));
842     /* Append to the list of Going commands */
843     if( pDCB->pGoingSRB )
844         pDCB->pGoingLast->pNextSRB = pSRB;
845     else
846         pDCB->pGoingSRB = pSRB;
847
848     pDCB->pGoingLast = pSRB;
849     /* No next one in sent list */
850     pSRB->pNextSRB = NULL;
851 }
852
853 static __inline__ void dc390_Going_remove (PDCB pDCB, PSRB pSRB)
854 {
855         DEBUG0(printk("DC390: Remove SRB %p from Going\n", pSRB));
856    if (pSRB == pDCB->pGoingSRB)
857         pDCB->pGoingSRB = pSRB->pNextSRB;
858    else
859      {
860         PSRB psrb = pDCB->pGoingSRB;
861         while (psrb && psrb->pNextSRB != pSRB)
862           psrb = psrb->pNextSRB;
863         if (!psrb) 
864           { printk (KERN_ERR "DC390: Remove non-ex. SRB %p from Going!\n", pSRB); return; }
865         psrb->pNextSRB = pSRB->pNextSRB;
866         if (pSRB == pDCB->pGoingLast)
867           pDCB->pGoingLast = psrb;
868      }
869    pDCB->GoingSRBCnt--;
870 }
871
872 /* Moves SRB from Going list to the top of Waiting list */
873 static void dc390_Going_to_Waiting ( PDCB pDCB, PSRB pSRB )
874 {
875     DEBUG0(printk(KERN_INFO "DC390: Going_to_Waiting (SRB %p) pid = %li\n", pSRB, pSRB->pcmd->pid));
876     /* Remove SRB from Going */
877     dc390_Going_remove (pDCB, pSRB);
878     /* Insert on top of Waiting */
879     dc390_Waiting_insert (pDCB, pSRB);
880     /* Tag Mask must be freed elsewhere ! (KG, 99/06/18) */
881 }
882
883 /* Moves first SRB from Waiting list to Going list */
884 static __inline__ void dc390_Waiting_to_Going ( PDCB pDCB, PSRB pSRB )
885 {       
886         /* Remove from waiting list */
887         DEBUG0(printk("DC390: Remove SRB %p from head of Waiting\n", pSRB));
888         pDCB->pWaitingSRB = pSRB->pNextSRB;
889         if( !pDCB->pWaitingSRB ) pDCB->pWaitLast = NULL;
890         pDCB->WaitSRBCnt--;
891         dc390_Going_append (pDCB, pSRB);
892 }
893
894 /* 2.0 timer compatibility */
895 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,1,30)
896  static inline int timer_pending(struct timer_list * timer)
897  {
898         return timer->prev != NULL;
899  }
900  #define time_after(a,b)         ((long)(b) - (long)(a) < 0)
901  #define time_before(a,b)        time_after(b,a)
902 #endif
903
904 void DC390_waiting_timed_out (unsigned long ptr);
905 /* Sets the timer to wake us up */
906 static void dc390_waiting_timer (PACB pACB, unsigned long to)
907 {
908         if (timer_pending (&pACB->Waiting_Timer)) return;
909         init_timer (&pACB->Waiting_Timer);
910         pACB->Waiting_Timer.function = DC390_waiting_timed_out;
911         pACB->Waiting_Timer.data = (unsigned long)pACB;
912         if (time_before (jiffies + to, pACB->pScsiHost->last_reset))
913                 pACB->Waiting_Timer.expires = pACB->pScsiHost->last_reset + 1;
914         else
915                 pACB->Waiting_Timer.expires = jiffies + to + 1;
916         add_timer (&pACB->Waiting_Timer);
917 }
918
919
920 /* Send the next command from the waiting list to the bus */
921 static void dc390_Waiting_process ( PACB pACB )
922 {
923     PDCB   ptr, ptr1;
924     PSRB   pSRB;
925
926     if( (pACB->pActiveDCB) || (pACB->ACBFlag & (RESET_DETECT+RESET_DONE+RESET_DEV) ) )
927         return;
928     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
929     ptr = pACB->pDCBRunRobin;
930     if( !ptr )
931       {
932         ptr = pACB->pLinkDCB;
933         pACB->pDCBRunRobin = ptr;
934       }
935     ptr1 = ptr;
936     if (!ptr1) return;
937     do 
938       {
939         pACB->pDCBRunRobin = ptr1->pNextDCB;
940         if( !( pSRB = ptr1->pWaitingSRB ) ||
941             ( ptr1->MaxCommand <= ptr1->GoingSRBCnt ))
942           ptr1 = ptr1->pNextDCB;
943         else
944           {
945             /* Try to send to the bus */
946             if( !dc390_StartSCSI(pACB, ptr1, pSRB) )
947               dc390_Waiting_to_Going (ptr1, pSRB);
948             else
949               dc390_waiting_timer (pACB, HZ/5);
950             break;
951           }
952       } while (ptr1 != ptr);
953     return;
954 }
955
956 /* Wake up waiting queue */
957 void DC390_waiting_timed_out (unsigned long ptr)
958 {
959         PACB pACB = (PACB)ptr;
960         DC390_IFLAGS;
961         DC390_AFLAGS;
962         DEBUG0(printk ("DC390: Debug: Waiting queue woken up by timer!\n"));
963         DC390_LOCK_IO(pACB->pScsiHost);
964         DC390_LOCK_ACB;
965         dc390_Waiting_process (pACB);
966         DC390_UNLOCK_ACB;
967         DC390_UNLOCK_IO(pACB->pScsiHost);
968 }
969
970 /***********************************************************************
971  * Function: static void dc390_SendSRB (PACB pACB, PSRB pSRB)
972  *
973  * Purpose: Send SCSI Request Block (pSRB) to adapter (pACB)
974  *
975  ***********************************************************************/
976
977 static void dc390_SendSRB( PACB pACB, PSRB pSRB )
978 {
979     PDCB   pDCB;
980
981     pDCB = pSRB->pSRBDCB;
982     if( (pDCB->MaxCommand <= pDCB->GoingSRBCnt) || (pACB->pActiveDCB) ||
983         (pACB->ACBFlag & (RESET_DETECT+RESET_DONE+RESET_DEV)) )
984     {
985         dc390_Waiting_append (pDCB, pSRB);
986         dc390_Waiting_process (pACB);
987         return;
988     }
989
990 #if 0
991     if( pDCB->pWaitingSRB )
992     {
993         dc390_Waiting_append (pDCB, pSRB);
994 /*      pSRB = GetWaitingSRB(pDCB); */  /* non-existent */
995         pSRB = pDCB->pWaitingSRB;
996         /* Remove from waiting list */
997         pDCB->pWaitingSRB = pSRB->pNextSRB;
998         pSRB->pNextSRB = NULL;
999         if (!pDCB->pWaitingSRB) pDCB->pWaitLast = NULL;
1000     }
1001 #endif
1002         
1003     if (!dc390_StartSCSI(pACB, pDCB, pSRB))
1004         dc390_Going_append (pDCB, pSRB);
1005     else {
1006         dc390_Waiting_insert (pDCB, pSRB);
1007         dc390_waiting_timer (pACB, HZ/5);
1008     }
1009 }
1010
1011
1012 /* Create pci mapping */
1013 static int dc390_pci_map (PSRB pSRB)
1014 {
1015         int error = 0;
1016         Scsi_Cmnd *pcmd = pSRB->pcmd;
1017         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
1018         dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp));
1019         /* Map sense buffer */
1020         if (pSRB->SRBFlag & AUTO_REQSENSE) {
1021                 sg_dma_address(&pSRB->Segmentx) = cmdp->saved_dma_handle = 
1022                         pci_map_page(pdev, virt_to_page(pcmd->sense_buffer),
1023                                      (unsigned long)pcmd->sense_buffer & ~PAGE_MASK, sizeof(pcmd->sense_buffer),
1024                                      DMA_FROM_DEVICE);
1025                 pSRB->Segmentx.length = sizeof(pcmd->sense_buffer);
1026                 pSRB->SGcount = 1;
1027                 pSRB->pSegmentList = (PSGL) &pSRB->Segmentx;
1028                 DEBUG1(printk("%s(): Mapped sense buffer %p at %x\n", __FUNCTION__, pcmd->sense_buffer, cmdp->saved_dma_handle));
1029         /* Make SG list */      
1030         } else if (pcmd->use_sg) {
1031                 pSRB->pSegmentList = (PSGL) pcmd->request_buffer;
1032                 pSRB->SGcount = pci_map_sg(pdev, pSRB->pSegmentList,
1033                                            pcmd->use_sg,
1034                                            scsi_to_pci_dma_dir(pcmd->sc_data_direction));
1035                 /* TODO: error handling */
1036                 if (!pSRB->SGcount)
1037                         error = 1;
1038                 DEBUG1(printk("%s(): Mapped SG %p with %d (%d) elements\n", __FUNCTION__, pcmd->request_buffer, pSRB->SGcount, pcmd->use_sg));
1039         /* Map single segment */
1040         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
1041                 sg_dma_address(&pSRB->Segmentx) = cmdp->saved_dma_handle =
1042                         pci_map_page(pdev, virt_to_page(pcmd->request_buffer),
1043                                      (unsigned long)pcmd->request_buffer & ~PAGE_MASK,
1044                                      pcmd->request_bufflen, scsi_to_pci_dma_dir(pcmd->sc_data_direction));
1045                 /* TODO: error handling */
1046                 pSRB->Segmentx.length = pcmd->request_bufflen;
1047                 pSRB->SGcount = 1;
1048                 pSRB->pSegmentList = (PSGL) &pSRB->Segmentx;
1049                 DEBUG1(printk("%s(): Mapped request buffer %p at %x\n", __FUNCTION__, pcmd->request_buffer, cmdp->saved_dma_handle));
1050         /* No mapping !? */     
1051         } else
1052                 pSRB->SGcount = 0;
1053         return error;
1054 }
1055
1056 /* Remove pci mapping */
1057 static void dc390_pci_unmap (PSRB pSRB)
1058 {
1059         Scsi_Cmnd* pcmd = pSRB->pcmd;
1060         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
1061         dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp));
1062
1063         if (pSRB->SRBFlag) {
1064                 pci_unmap_page(pdev, cmdp->saved_dma_handle,
1065                                sizeof(pcmd->sense_buffer), DMA_FROM_DEVICE);
1066                 DEBUG1(printk("%s(): Unmapped sense buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
1067         } else if (pcmd->use_sg) {
1068                 pci_unmap_sg(pdev, pcmd->request_buffer, pcmd->use_sg,
1069                              scsi_to_pci_dma_dir(pcmd->sc_data_direction));
1070                 DEBUG1(printk("%s(): Unmapped SG at %p with %d elements\n", __FUNCTION__, pcmd->request_buffer, pcmd->use_sg));
1071         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
1072                 pci_unmap_page(pdev,
1073                                cmdp->saved_dma_handle,
1074                                pcmd->request_bufflen,
1075                                scsi_to_pci_dma_dir(pcmd->sc_data_direction));
1076                 DEBUG1(printk("%s(): Unmapped request buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
1077         }
1078 }
1079
1080
1081 /***********************************************************************
1082  * Function: static void dc390_BuildSRB (Scsi_Cmd *pcmd, PDCB pDCB, 
1083  *                                       PSRB pSRB)
1084  *
1085  * Purpose: Prepare SRB for being sent to Device DCB w/ command *pcmd
1086  *
1087  ***********************************************************************/
1088
1089 static void dc390_BuildSRB (Scsi_Cmnd* pcmd, PDCB pDCB, PSRB pSRB)
1090 {
1091     pSRB->pSRBDCB = pDCB;
1092     pSRB->pcmd = pcmd;
1093     //pSRB->ScsiCmdLen = pcmd->cmd_len;
1094     //memcpy (pSRB->CmdBlock, pcmd->cmnd, pcmd->cmd_len);
1095     
1096     pSRB->SGIndex = 0;
1097     pSRB->AdaptStatus = 0;
1098     pSRB->TargetStatus = 0;
1099     pSRB->MsgCnt = 0;
1100     if( pDCB->DevType != TYPE_TAPE )
1101         pSRB->RetryCnt = 1;
1102     else
1103         pSRB->RetryCnt = 0;
1104     pSRB->SRBStatus = 0;
1105     pSRB->SRBFlag = 0;
1106     pSRB->SRBState = 0;
1107     pSRB->TotalXferredLen = 0;
1108     pSRB->SGBusAddr = 0;
1109     pSRB->SGToBeXferLen = 0;
1110     pSRB->ScsiPhase = 0;
1111     pSRB->EndMessage = 0;
1112     pSRB->TagNumber = 255;
1113     /* KG: deferred PCI mapping to dc390_StartSCSI */
1114 }
1115
1116 /* Put cmnd from Query to Waiting list and send next Waiting cmnd */
1117 static void dc390_Query_to_Waiting (PACB pACB)
1118 {
1119     Scsi_Cmnd *pcmd;
1120     PSRB   pSRB;
1121     PDCB   pDCB;
1122
1123     if( pACB->ACBFlag & (RESET_DETECT+RESET_DONE+RESET_DEV) )
1124         return;
1125
1126     while (pACB->QueryCnt)
1127     {
1128         pSRB = dc390_Free_get ( pACB );
1129         if (!pSRB) return;
1130         pcmd = dc390_Query_get ( pACB );
1131         if (!pcmd) { dc390_Free_insert (pACB, pSRB); return; } /* should not happen */
1132         pDCB = dc390_findDCB (pACB, pcmd->device->id, pcmd->device->lun);
1133         if (!pDCB) 
1134         { 
1135                 dc390_Free_insert (pACB, pSRB);
1136                 printk (KERN_ERR "DC390: Command in queue to non-existing device!\n");
1137                 pcmd->result = MK_RES(DRIVER_ERROR,DID_ERROR,0,0);
1138                 DC390_UNLOCK_ACB_NI;
1139                 pcmd->done (pcmd);
1140                 DC390_LOCK_ACB_NI;
1141         }
1142         dc390_BuildSRB (pcmd, pDCB, pSRB);
1143         dc390_Waiting_append ( pDCB, pSRB );
1144     }
1145 }
1146
1147 /***********************************************************************
1148  * Function : static int DC390_queue_command (Scsi_Cmnd *cmd,
1149  *                                             void (*done)(Scsi_Cmnd *))
1150  *
1151  * Purpose : enqueues a SCSI command
1152  *
1153  * Inputs : cmd - SCSI command, done - callback function called on 
1154  *          completion, with a pointer to the command descriptor.
1155  *
1156  * Returns : (depending on kernel version)
1157  * 2.0.x: always return 0
1158  * 2.1.x: old model: (use_new_eh_code == 0): like 2.0.x
1159  *        TO BE DONE:
1160  *        new model: return 0 if successful
1161  *                   return 1 if command cannot be queued (queue full)
1162  *                   command will be inserted in midlevel queue then ...
1163  *
1164  ***********************************************************************/
1165
1166 int DC390_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *))
1167 {
1168     PDCB   pDCB;
1169     PSRB   pSRB;
1170     PACB   pACB = (PACB) cmd->device->host->hostdata;
1171     DC390_AFLAGS;
1172
1173
1174     DEBUG0(/*  if(pACB->scan_devices) */        \
1175         printk(KERN_INFO "DC390: Queue Cmd=%02x,Tgt=%d,LUN=%d (pid=%li), buffer=%p\n",\
1176                cmd->cmnd[0],cmd->device->id,cmd->device->lun,cmd->pid, cmd->buffer));
1177
1178     DC390_LOCK_ACB;
1179     
1180     /* Assume BAD_TARGET; will be cleared later */
1181     cmd->result = DID_BAD_TARGET << 16;
1182    
1183     /* TODO: Change the policy: Alway accept TEST_UNIT_READY or INQUIRY 
1184      * commands and alloc a DCB for the device if not yet there. DCB will
1185      * be removed in dc390_SRBdone if SEL_TIMEOUT */
1186
1187     if( (pACB->scan_devices == END_SCAN) && (cmd->cmnd[0] != INQUIRY) )
1188         pACB->scan_devices = 0;
1189
1190     else if( (pACB->scan_devices) && (cmd->cmnd[0] == READ_6) )
1191         pACB->scan_devices = 0;
1192
1193     if ( ( cmd->device->id >= pACB->pScsiHost->max_id ) || 
1194          (cmd->device->lun >= pACB->pScsiHost->max_lun) )
1195     {
1196 /*      printk ("DC390: Ignore target %d lun %d\n",
1197                 cmd->device->id, cmd->device->lun); */
1198         DC390_UNLOCK_ACB;
1199         //return (1);
1200         done (cmd);
1201         return (0);
1202     }
1203
1204     if( (pACB->scan_devices || cmd->cmnd[0] == TEST_UNIT_READY || cmd->cmnd[0] == INQUIRY) && 
1205        !(pACB->DCBmap[cmd->device->id] & (1 << cmd->device->lun)) )
1206     {
1207         pACB->scan_devices = 1;
1208
1209         dc390_initDCB( pACB, &pDCB, cmd->device->id, cmd->device->lun );
1210         if (!pDCB)
1211           {
1212             printk (KERN_ERR "DC390: kmalloc for DCB failed, target %02x lun %02x\n", 
1213                     cmd->device->id, cmd->device->lun);
1214             DC390_UNLOCK_ACB;
1215             printk ("DC390: No DCB in queue_command!\n");
1216 #ifdef USE_NEW_EH
1217             return (1);
1218 #else
1219             done (cmd);
1220             return (0);
1221 #endif
1222           }
1223             
1224     }
1225     else if( !(pACB->scan_devices) && !(pACB->DCBmap[cmd->device->id] & (1 << cmd->device->lun)) )
1226     {
1227         printk(KERN_INFO "DC390: Ignore target %02x lun %02x\n",
1228                 cmd->device->id, cmd->device->lun); 
1229         DC390_UNLOCK_ACB;
1230         //return (1);
1231         done (cmd);
1232         return (0);
1233     }
1234     else
1235     {
1236         pDCB = dc390_findDCB (pACB, cmd->device->id, cmd->device->lun);
1237         if (!pDCB)
1238          {  /* should never happen */
1239             printk (KERN_ERR "DC390: no DCB failed, target %02x lun %02x\n", 
1240                     cmd->device->id, cmd->device->lun);
1241             DC390_UNLOCK_ACB;
1242             printk ("DC390: No DCB in queuecommand (2)!\n");
1243 #ifdef USE_NEW_EH
1244             return (1);
1245 #else
1246             done (cmd);
1247             return (0);
1248 #endif
1249          }
1250     }
1251
1252     pACB->Cmds++;
1253     cmd->scsi_done = done;
1254     cmd->result = 0;
1255         
1256     dc390_Query_to_Waiting (pACB);
1257
1258     if( pACB->QueryCnt ) /* Unsent commands ? */
1259     {
1260         DEBUG0(printk ("DC390: QueryCnt != 0\n"));
1261         dc390_Query_append ( cmd, pACB );
1262         dc390_Waiting_process (pACB);
1263     }
1264     else if (pDCB->pWaitingSRB)
1265     {
1266         pSRB = dc390_Free_get ( pACB );
1267         DEBUG0(if (!pSRB) printk ("DC390: No free SRB but Waiting\n"); else printk ("DC390: Free SRB w/ Waiting\n"));
1268         if (!pSRB) dc390_Query_append (cmd, pACB);
1269         else 
1270           {
1271             dc390_BuildSRB (cmd, pDCB, pSRB);
1272             dc390_Waiting_append (pDCB, pSRB);
1273           }
1274         dc390_Waiting_process (pACB);
1275     }
1276     else
1277     {
1278         pSRB = dc390_Free_get ( pACB );
1279         DEBUG0(if (!pSRB) printk ("DC390: No free SRB w/o Waiting\n"); else printk ("DC390: Free SRB w/o Waiting\n"));
1280         if (!pSRB)
1281         {
1282             dc390_Query_append (cmd, pACB);
1283             dc390_Waiting_process (pACB);
1284         }
1285         else 
1286         {
1287             dc390_BuildSRB (cmd, pDCB, pSRB);
1288             dc390_SendSRB (pACB, pSRB);
1289         }
1290     }
1291
1292     DC390_UNLOCK_ACB;
1293     DEBUG1(printk (KERN_DEBUG " ... command (pid %li) queued successfully.\n", cmd->pid));
1294     return(0);
1295 }
1296
1297 /* We ignore mapping problems, as we expect everybody to respect 
1298  * valid partition tables. Waiting for complaints ;-) */
1299
1300 #ifdef CONFIG_SCSI_DC390T_TRADMAP
1301 /* 
1302  * The next function, partsize(), is copied from scsicam.c.
1303  *
1304  * This is ugly code duplication, but I didn't find another way to solve it:
1305  * We want to respect the partition table and if it fails, we apply the 
1306  * DC390 BIOS heuristic. Too bad, just calling scsicam_bios_param() doesn't do
1307  * the job, because we don't know, whether the values returned are from
1308  * the part. table or determined by setsize(). Unfortunately the setsize() 
1309  * values differ from the ones chosen by the DC390 BIOS.
1310  *
1311  * Looking forward to seeing suggestions for a better solution! KG, 98/10/14
1312  */
1313 #include <asm/unaligned.h>
1314
1315 /*
1316  * Function : static int partsize(unsigned char *buf, unsigned long 
1317  *     capacity,unsigned int *cyls, unsigned int *hds, unsigned int *secs);
1318  *
1319  * Purpose : to determine the BIOS mapping used to create the partition
1320  *      table, storing the results in *cyls, *hds, and *secs 
1321  *
1322  * Returns : -1 on failure, 0 on success.
1323  *
1324  */
1325
1326 static int partsize(unsigned char *buf, unsigned long capacity,
1327     unsigned int  *cyls, unsigned int *hds, unsigned int *secs) {
1328     struct partition *p, *largest = NULL;
1329     int i, largest_cyl;
1330     int cyl, ext_cyl, end_head, end_cyl, end_sector;
1331     unsigned int logical_end, physical_end, ext_physical_end;
1332     
1333
1334     if (*(unsigned short *) (buf+64) == 0xAA55) {
1335         for (largest_cyl = -1, p = (struct partition *) buf, 
1336             i = 0; i < 4; ++i, ++p) {
1337             if (!p->sys_ind)
1338                 continue;
1339             cyl = p->cyl + ((p->sector & 0xc0) << 2);
1340             if (cyl > largest_cyl) {
1341                 largest_cyl = cyl;
1342                 largest = p;
1343             }
1344         }
1345     }
1346
1347     if (largest) {
1348         end_cyl = largest->end_cyl + ((largest->end_sector & 0xc0) << 2);
1349         end_head = largest->end_head;
1350         end_sector = largest->end_sector & 0x3f;
1351
1352         physical_end =  end_cyl * (end_head + 1) * end_sector +
1353             end_head * end_sector + end_sector;
1354
1355         /* This is the actual _sector_ number at the end */
1356         logical_end = get_unaligned(&largest->start_sect)
1357                         + get_unaligned(&largest->nr_sects);
1358
1359         /* This is for >1023 cylinders */
1360         ext_cyl= (logical_end-(end_head * end_sector + end_sector))
1361                                         /(end_head + 1) / end_sector;
1362         ext_physical_end = ext_cyl * (end_head + 1) * end_sector +
1363             end_head * end_sector + end_sector;
1364
1365         if ((logical_end == physical_end) ||
1366             (end_cyl==1023 && ext_physical_end==logical_end)) {
1367             *secs = end_sector;
1368             *hds = end_head + 1;
1369             *cyls = capacity / ((end_head + 1) * end_sector);
1370             return 0;
1371         }
1372     }
1373     return -1;
1374 }
1375
1376 /***********************************************************************
1377  * Function:
1378  *   DC390_bios_param
1379  *
1380  * Description:
1381  *   Return the disk geometry for the given SCSI device.
1382  *   Respect the partition table, otherwise try own heuristic
1383  *
1384  * Note:
1385  *   In contrary to other externally callable funcs (DC390_), we don't lock
1386  ***********************************************************************/
1387 int DC390_bios_param (struct scsi_device *sdev, struct block_device *bdev,
1388                 sector_t capacity, int geom[])
1389 {
1390     int heads, sectors, cylinders;
1391     PACB pACB = (PACB) sdev->host->hostdata;
1392     int ret_code = -1;
1393     int size = capacity;
1394     unsigned char *buf;
1395
1396     if ((buf = scsi_bios_ptable(bdev)))
1397     {
1398         /* try to infer mapping from partition table */
1399         ret_code = partsize (buf, (unsigned long) size, (unsigned int *) geom + 2,
1400                              (unsigned int *) geom + 0, (unsigned int *) geom + 1);
1401         kfree (buf);
1402     }
1403     if (ret_code == -1)
1404     {
1405         heads = 64;
1406         sectors = 32;
1407         cylinders = size / (heads * sectors);
1408
1409         if ( (pACB->Gmode2 & GREATER_1G) && (cylinders > 1024) )
1410         {
1411                 heads = 255;
1412                 sectors = 63;
1413                 cylinders = size / (heads * sectors);
1414         }
1415
1416         geom[0] = heads;
1417         geom[1] = sectors;
1418         geom[2] = cylinders;
1419     }
1420
1421     return (0);
1422 }
1423 #else
1424 int DC390_bios_param (struct scsi_device *sdev, struct block_device *bdev,
1425                 sector_t capacity, int geom[])
1426 {
1427     return scsicam_bios_param (bdev, capacity, geom);
1428 }
1429 #endif
1430
1431
1432 void dc390_dumpinfo (PACB pACB, PDCB pDCB, PSRB pSRB)
1433 {
1434     USHORT pstat; PDEVDECL1;
1435     if (!pDCB) pDCB = pACB->pActiveDCB;
1436     if (!pSRB && pDCB) pSRB = pDCB->pActiveSRB;
1437
1438     if (pSRB) 
1439     {
1440         printk ("DC390: SRB: Xferred %08lx, Remain %08lx, State %08x, Phase %02x\n",
1441                 pSRB->TotalXferredLen, pSRB->SGToBeXferLen, pSRB->SRBState,
1442                 pSRB->ScsiPhase);
1443         printk ("DC390: AdpaterStatus: %02x, SRB Status %02x\n", pSRB->AdaptStatus, pSRB->SRBStatus);
1444     }
1445     printk ("DC390: Status of last IRQ (DMA/SC/Int/IRQ): %08x\n", dc390_laststatus);
1446     printk ("DC390: Register dump: SCSI block:\n");
1447     printk ("DC390: XferCnt  Cmd Stat IntS IRQS FFIS Ctl1 Ctl2 Ctl3 Ctl4\n");
1448     printk ("DC390:  %06x   %02x   %02x   %02x",
1449             DC390_read8(CtcReg_Low) + (DC390_read8(CtcReg_Mid) << 8) + (DC390_read8(CtcReg_High) << 16),
1450             DC390_read8(ScsiCmd), DC390_read8(Scsi_Status), DC390_read8(Intern_State));
1451     printk ("   %02x   %02x   %02x   %02x   %02x   %02x\n",
1452             DC390_read8(INT_Status), DC390_read8(Current_Fifo), DC390_read8(CtrlReg1),
1453             DC390_read8(CtrlReg2), DC390_read8(CtrlReg3), DC390_read8(CtrlReg4));
1454     DC390_write32 (DMA_ScsiBusCtrl, WRT_ERASE_DMA_STAT | EN_INT_ON_PCI_ABORT);
1455     if (DC390_read8(Current_Fifo) & 0x1f)
1456       {
1457         printk ("DC390: FIFO:");
1458         while (DC390_read8(Current_Fifo) & 0x1f) printk (" %02x", DC390_read8(ScsiFifo));
1459         printk ("\n");
1460       }
1461     printk ("DC390: Register dump: DMA engine:\n");
1462     printk ("DC390: Cmd   STrCnt    SBusA    WrkBC    WrkAC Stat SBusCtrl\n");
1463     printk ("DC390:  %02x %08x %08x %08x %08x   %02x %08x\n",
1464             DC390_read8(DMA_Cmd), DC390_read32(DMA_XferCnt), DC390_read32(DMA_XferAddr),
1465             DC390_read32(DMA_Wk_ByteCntr), DC390_read32(DMA_Wk_AddrCntr),
1466             DC390_read8(DMA_Status), DC390_read32(DMA_ScsiBusCtrl));
1467     DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
1468     PDEVSET1; PCI_READ_CONFIG_WORD(PDEV, PCI_STATUS, &pstat);
1469     printk ("DC390: Register dump: PCI Status: %04x\n", pstat);
1470     printk ("DC390: In case of driver trouble read linux/Documentation/scsi/tmscsim.txt\n");
1471 }
1472
1473
1474 /***********************************************************************
1475  * Function : int DC390_abort (Scsi_Cmnd *cmd)
1476  *
1477  * Purpose : Abort an errant SCSI command
1478  *
1479  * Inputs : cmd - command to abort
1480  *
1481  * Returns : 0 on success, -1 on failure.
1482  *
1483  * Status: Buggy !
1484  ***********************************************************************/
1485
1486 int DC390_abort (Scsi_Cmnd *cmd)
1487 {
1488     PDCB  pDCB;
1489     PSRB  pSRB, psrb;
1490     UINT  count, i;
1491     int   status;
1492     //ULONG sbac;
1493     PACB  pACB = (PACB) cmd->device->host->hostdata;
1494     DC390_AFLAGS;
1495
1496     DC390_LOCK_ACB;
1497
1498     printk ("DC390: Abort command (pid %li, Device %02i-%02i)\n",
1499             cmd->pid, cmd->device->id, cmd->device->lun);
1500
1501     /* First scan Query list */
1502     if( pACB->QueryCnt )
1503     {
1504         struct scsi_cmnd_list *t, *pcmd_l;
1505         list_for_each_entry_safe(pcmd_l, t, &pACB->cmdq, scp.list)
1506                 if( (struct scsi_cmnd*)pcmd_l == cmd )
1507                 {
1508                         /* Found: Dequeue */
1509                         list_del(&pcmd_l->scp.list);
1510                         pACB->QueryCnt--;
1511                         status = SCSI_ABORT_SUCCESS;
1512                         goto  ABO_X;
1513                 }
1514     }
1515         
1516     pDCB = dc390_findDCB (pACB, cmd->device->id, cmd->device->lun);
1517     if( !pDCB ) goto  NOT_RUN;
1518
1519     /* Added 98/07/02 KG */
1520     /*
1521     pSRB = pDCB->pActiveSRB;
1522     if (pSRB && pSRB->pcmd == cmd )
1523         goto ON_GOING;
1524      */
1525     
1526     pSRB = pDCB->pWaitingSRB;
1527     if( !pSRB )
1528         goto  ON_GOING;
1529
1530     /* Now scan Waiting queue */
1531     if( pSRB->pcmd == cmd )
1532     {
1533         pDCB->pWaitingSRB = pSRB->pNextSRB;
1534         goto  IN_WAIT;
1535     }
1536     else
1537     {
1538         psrb = pSRB;
1539         if( !(psrb->pNextSRB) )
1540             goto ON_GOING;
1541         while( psrb->pNextSRB->pcmd != cmd )
1542         {
1543             psrb = psrb->pNextSRB;
1544             if( !(psrb->pNextSRB) || psrb == pSRB)
1545                 goto ON_GOING;
1546         }
1547         pSRB = psrb->pNextSRB;
1548         psrb->pNextSRB = pSRB->pNextSRB;
1549         if( pSRB == pDCB->pWaitLast )
1550             pDCB->pWaitLast = psrb;
1551 IN_WAIT:
1552         dc390_Free_insert (pACB, pSRB);
1553         pDCB->WaitSRBCnt--;
1554         INIT_LIST_HEAD((struct list_head*)&cmd->SCp);
1555         status = SCSI_ABORT_SUCCESS;
1556         goto  ABO_X;
1557     }
1558
1559     /* SRB has already been sent ! */
1560 ON_GOING:
1561     /* abort() is too stupid for already sent commands at the moment. 
1562      * If it's called we are in trouble anyway, so let's dump some info 
1563      * into the syslog at least. (KG, 98/08/20,99/06/20) */
1564     dc390_dumpinfo (pACB, pDCB, pSRB);
1565     pSRB = pDCB->pGoingSRB;
1566     pDCB->DCBFlag |= ABORT_DEV_;
1567     /* Now for the hard part: The command is currently processed */
1568     for( count = pDCB->GoingSRBCnt, i=0; i<count; i++)
1569     {
1570         if( pSRB->pcmd != cmd )
1571             pSRB = pSRB->pNextSRB;
1572         else
1573         {
1574             if( (pACB->pActiveDCB == pDCB) && (pDCB->pActiveSRB == pSRB) )
1575             {
1576                 status = SCSI_ABORT_BUSY;
1577                 printk ("DC390: Abort current command (pid %li, SRB %p)\n",
1578                         cmd->pid, pSRB);
1579                 goto  ABO_X;
1580             }
1581             else
1582             {
1583                 status = SCSI_ABORT_SNOOZE;
1584                 goto  ABO_X;
1585             }
1586         }
1587     }
1588
1589 NOT_RUN:
1590     status = SCSI_ABORT_NOT_RUNNING;
1591
1592 ABO_X:
1593     cmd->result = DID_ABORT << 16;
1594     printk(KERN_INFO "DC390: Aborted pid %li with status %i\n", cmd->pid, status);
1595 #if 0
1596     if (cmd->pid == dc390_lastabortedpid) /* repeated failure ? */
1597         {
1598                 /* Let's do something to help the bus getting clean again */
1599                 DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1600                 DC390_write8 (ScsiCmd, DMA_COMMAND);
1601                 //DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1602                 //DC390_write8 (ScsiCmd, RESET_ATN_CMD);
1603                 DC390_write8 (ScsiCmd, NOP_CMD);
1604                 //udelay (10000);
1605                 //DC390_read8 (INT_Status);
1606                 //DC390_write8 (ScsiCmd, EN_SEL_RESEL);
1607         }
1608     sbac = DC390_read32 (DMA_ScsiBusCtrl);
1609     if (sbac & SCSI_BUSY)
1610     {   /* clear BSY, SEL and ATN */
1611         printk (KERN_WARNING "DC390: Reset SCSI device: ");
1612         //DC390_write32 (DMA_ScsiBusCtrl, (sbac | SCAM) & ~SCSI_LINES);
1613         //udelay (250);
1614         //sbac = DC390_read32 (DMA_ScsiBusCtrl);
1615         //printk ("%08lx ", sbac);
1616         //DC390_write32 (DMA_ScsiBusCtrl, sbac & ~(SCSI_LINES | SCAM));
1617         //udelay (100);
1618         //sbac = DC390_read32 (DMA_ScsiBusCtrl);
1619         //printk ("%08lx ", sbac);
1620         DC390_write8 (ScsiCmd, RST_DEVICE_CMD);
1621         udelay (250);
1622         DC390_write8 (ScsiCmd, NOP_CMD);
1623         sbac = DC390_read32 (DMA_ScsiBusCtrl);
1624         printk ("%08lx\n", sbac);
1625     }
1626 #endif
1627     dc390_lastabortedpid = cmd->pid;
1628     DC390_UNLOCK_ACB;
1629     //do_DC390_Interrupt (pACB->IRQLevel, 0, 0);
1630 #ifndef USE_NEW_EH      
1631     if (status == SCSI_ABORT_SUCCESS) cmd->scsi_done(cmd);
1632 #endif  
1633     return( status );
1634 }
1635
1636
1637 static void dc390_ResetDevParam( PACB pACB )
1638 {
1639     PDCB   pDCB, pdcb;
1640
1641     pDCB = pACB->pLinkDCB;
1642     if (! pDCB) return;
1643     pdcb = pDCB;
1644     do
1645     {
1646         pDCB->SyncMode &= ~SYNC_NEGO_DONE;
1647         pDCB->SyncPeriod = 0;
1648         pDCB->SyncOffset = 0;
1649         pDCB->TagMask = 0;
1650         pDCB->CtrlR3 = FAST_CLK;
1651         pDCB->CtrlR4 &= NEGATE_REQACKDATA | CTRL4_RESERVED | NEGATE_REQACK;
1652         pDCB->CtrlR4 |= pACB->glitch_cfg;
1653         pDCB = pDCB->pNextDCB;
1654     }
1655     while( pdcb != pDCB );
1656     pACB->ACBFlag &= ~(RESET_DEV | RESET_DONE | RESET_DETECT);
1657
1658 }
1659
1660 #if 0
1661 /* Moves all SRBs from Going to Waiting for all DCBs */
1662 static void dc390_RecoverSRB( PACB pACB )
1663 {
1664     PDCB   pDCB, pdcb;
1665     PSRB   psrb, psrb2;
1666     UINT   cnt, i;
1667
1668     pDCB = pACB->pLinkDCB;
1669     if( !pDCB ) return;
1670     pdcb = pDCB;
1671     do
1672     {
1673         cnt = pdcb->GoingSRBCnt;
1674         psrb = pdcb->pGoingSRB;
1675         for (i=0; i<cnt; i++)
1676         {
1677             psrb2 = psrb;
1678             psrb = psrb->pNextSRB;
1679 /*          dc390_RewaitSRB( pDCB, psrb ); */
1680             if( pdcb->pWaitingSRB )
1681             {
1682                 psrb2->pNextSRB = pdcb->pWaitingSRB;
1683                 pdcb->pWaitingSRB = psrb2;
1684             }
1685             else
1686             {
1687                 pdcb->pWaitingSRB = psrb2;
1688                 pdcb->pWaitLast = psrb2;
1689                 psrb2->pNextSRB = NULL;
1690             }
1691         }
1692         pdcb->GoingSRBCnt = 0;
1693         pdcb->pGoingSRB = NULL;
1694         pdcb->TagMask = 0;
1695         pdcb = pdcb->pNextDCB;
1696     } while( pdcb != pDCB );
1697 }
1698 #endif
1699
1700 /***********************************************************************
1701  * Function : int DC390_reset (Scsi_Cmnd *cmd, ...)
1702  *
1703  * Purpose : perform a hard reset on the SCSI bus
1704  *
1705  * Inputs : cmd - command which caused the SCSI RESET
1706  *          resetFlags - how hard to try
1707  *
1708  * Returns : 0 on success.
1709  ***********************************************************************/
1710
1711 int DC390_reset (Scsi_Cmnd *cmd)
1712 {
1713     UCHAR   bval;
1714     PACB    pACB = (PACB) cmd->device->host->hostdata;
1715     DC390_AFLAGS;
1716
1717     printk(KERN_INFO "DC390: RESET ... ");
1718
1719     DC390_LOCK_ACB;
1720     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
1721     bval = DC390_read8 (CtrlReg1);
1722     bval |= DIS_INT_ON_SCSI_RST;
1723     DC390_write8 (CtrlReg1, bval);      /* disable IRQ on bus reset */
1724
1725     pACB->ACBFlag |= RESET_DEV;
1726     dc390_ResetSCSIBus( pACB );
1727
1728     dc390_ResetDevParam( pACB );
1729     udelay (1000);
1730     pACB->pScsiHost->last_reset = jiffies + 3*HZ/2 
1731                 + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
1732     
1733     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1734     DC390_read8 (INT_Status);           /* Reset Pending INT */
1735
1736     dc390_DoingSRB_Done( pACB, cmd );
1737     /* dc390_RecoverSRB (pACB); */
1738     pACB->pActiveDCB = NULL;
1739
1740     pACB->ACBFlag = 0;
1741     bval = DC390_read8 (CtrlReg1);
1742     bval &= ~DIS_INT_ON_SCSI_RST;
1743     DC390_write8 (CtrlReg1, bval);      /* re-enable interrupt */
1744
1745     dc390_Waiting_process( pACB );
1746
1747     printk("done\n");
1748     DC390_UNLOCK_ACB;
1749     return( SCSI_RESET_SUCCESS );
1750 }
1751
1752 #include "scsiiom.c"
1753
1754
1755 /***********************************************************************
1756  * Function : static void dc390_initDCB()
1757  *
1758  * Purpose :  initialize the internal structures for a DCB (to be malloced)
1759  *
1760  * Inputs : SCSI id and lun
1761  ***********************************************************************/
1762
1763 void dc390_initDCB( PACB pACB, PDCB *ppDCB, UCHAR id, UCHAR lun )
1764 {
1765     PEEprom     prom;
1766     UCHAR       index;
1767     PDCB pDCB, pDCB2;
1768
1769     pDCB = kmalloc (sizeof(DC390_DCB), GFP_ATOMIC);
1770     DCBDEBUG(printk (KERN_INFO "DC390: alloc mem for DCB (ID %i, LUN %i): %p\n" \
1771                      id, lun, pDCB));
1772  
1773     *ppDCB = pDCB;
1774     if (!pDCB) return;
1775     pDCB2 = 0;
1776     if( pACB->DCBCnt == 0 )
1777     {
1778         pACB->pLinkDCB = pDCB;
1779         pACB->pDCBRunRobin = pDCB;
1780     }
1781     else
1782     {
1783         pACB->pLastDCB->pNextDCB = pDCB;
1784     }
1785    
1786     pACB->DCBCnt++;
1787    
1788     pDCB->pNextDCB = pACB->pLinkDCB;
1789     pACB->pLastDCB = pDCB;
1790
1791     pDCB->pDCBACB = pACB;
1792     pDCB->TargetID = id;
1793     pDCB->TargetLUN = lun;
1794     pDCB->pWaitingSRB = NULL;
1795     pDCB->pGoingSRB = NULL;
1796     pDCB->GoingSRBCnt = 0;
1797     pDCB->WaitSRBCnt = 0;
1798     pDCB->pActiveSRB = NULL;
1799     pDCB->TagMask = 0;
1800     pDCB->MaxCommand = 1;
1801     index = pACB->AdapterIndex;
1802     pDCB->DCBFlag = 0;
1803
1804     /* Is there a corresp. LUN==0 device ? */
1805     if (lun != 0)
1806         pDCB2 = dc390_findDCB (pACB, id, 0);
1807     prom = (PEEprom) &dc390_eepromBuf[index][id << 2];
1808     /* Some values are for all LUNs: Copy them */
1809     /* In a clean way: We would have an own structure for a SCSI-ID */
1810     if (pDCB2)
1811     {
1812       pDCB->DevMode = pDCB2->DevMode;
1813       pDCB->SyncMode = pDCB2->SyncMode;
1814       pDCB->SyncPeriod = pDCB2->SyncPeriod;
1815       pDCB->SyncOffset = pDCB2->SyncOffset;
1816       pDCB->NegoPeriod = pDCB2->NegoPeriod;
1817       
1818       pDCB->CtrlR3 = pDCB2->CtrlR3;
1819       pDCB->CtrlR4 = pDCB2->CtrlR4;
1820       pDCB->Inquiry7 = pDCB2->Inquiry7;
1821     }
1822     else
1823     {           
1824       pDCB->DevMode = prom->EE_MODE1;
1825       pDCB->SyncMode = 0;
1826       pDCB->SyncPeriod = 0;
1827       pDCB->SyncOffset = 0;
1828       pDCB->NegoPeriod = (dc390_clock_period1[prom->EE_SPEED] * 25) >> 2;
1829             
1830       pDCB->CtrlR3 = FAST_CLK;
1831       
1832       pDCB->CtrlR4 = pACB->glitch_cfg | CTRL4_RESERVED;
1833       if( dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION)
1834         pDCB->CtrlR4 |= NEGATE_REQACKDATA | NEGATE_REQACK;
1835       pDCB->Inquiry7 = 0;
1836     }
1837
1838     pACB->DCBmap[id] |= (1 << lun);
1839     dc390_updateDCB(pACB, pDCB);
1840 }
1841
1842 /***********************************************************************
1843  * Function : static void dc390_updateDCB()
1844  *
1845  * Purpose :  Set the configuration dependent DCB parameters
1846  ***********************************************************************/
1847
1848 void dc390_updateDCB (PACB pACB, PDCB pDCB)
1849 {
1850   pDCB->SyncMode &= EN_TAG_QUEUEING | SYNC_NEGO_DONE /*| EN_ATN_STOP*/;
1851   if (pDCB->DevMode & TAG_QUEUEING_) {
1852         //if (pDCB->SyncMode & EN_TAG_QUEUEING) pDCB->MaxCommand = pACB->TagMaxNum;
1853   } else {
1854         pDCB->SyncMode &= ~EN_TAG_QUEUEING;
1855         pDCB->MaxCommand = 1;
1856   }
1857
1858   if( pDCB->DevMode & SYNC_NEGO_ )
1859         pDCB->SyncMode |= SYNC_ENABLE;
1860   else {
1861         pDCB->SyncMode &= ~(SYNC_NEGO_DONE | SYNC_ENABLE);
1862         pDCB->SyncOffset &= ~0x0f;
1863   }
1864
1865   //if (! (pDCB->DevMode & EN_DISCONNECT_)) pDCB->SyncMode &= ~EN_ATN_STOP; 
1866
1867   pDCB->CtrlR1 = pACB->pScsiHost->this_id;
1868   if( pDCB->DevMode & PARITY_CHK_ )
1869         pDCB->CtrlR1 |= PARITY_ERR_REPO;
1870 }  
1871
1872
1873 /***********************************************************************
1874  * Function : static void dc390_updateDCBs ()
1875  *
1876  * Purpose :  Set the configuration dependent DCB params for all DCBs
1877  ***********************************************************************/
1878
1879 static void dc390_updateDCBs (PACB pACB)
1880 {
1881   int i;
1882   PDCB pDCB = pACB->pLinkDCB;
1883   for (i = 0; i < pACB->DCBCnt; i++)
1884     {
1885       dc390_updateDCB (pACB, pDCB);
1886       pDCB = pDCB->pNextDCB;
1887     }
1888 }
1889   
1890
1891 /***********************************************************************
1892  * Function : static void dc390_initSRB()
1893  *
1894  * Purpose :  initialize the internal structures for a given SRB
1895  *
1896  * Inputs : psrb - pointer to this scsi request block structure
1897  ***********************************************************************/
1898
1899 static void __inline__ dc390_initSRB( PSRB psrb )
1900 {
1901   /* psrb->PhysSRB = virt_to_phys( psrb ); */
1902 }
1903
1904
1905 void dc390_linkSRB( PACB pACB )
1906 {
1907     UINT   count, i;
1908
1909     count = pACB->SRBCount;
1910     for( i=0; i<count; i++)
1911     {
1912         if( i != count-1 )
1913             pACB->SRB_array[i].pNextSRB = &pACB->SRB_array[i+1];
1914         else
1915             pACB->SRB_array[i].pNextSRB = NULL;
1916         dc390_initSRB( &pACB->SRB_array[i] );
1917     }
1918 }
1919
1920
1921 /***********************************************************************
1922  * Function : static void dc390_initACB ()
1923  *
1924  * Purpose :  initialize the internal structures for a given SCSI host
1925  *
1926  * Inputs : psh - pointer to this host adapter's structure
1927  *          io_port, Irq, index: Resources and adapter index
1928  ***********************************************************************/
1929
1930 void __init dc390_initACB (PSH psh, ULONG io_port, UCHAR Irq, UCHAR index)
1931 {
1932     PACB    pACB;
1933     UCHAR   i;
1934     DC390_AFLAGS;
1935
1936     psh->can_queue = MAX_CMD_QUEUE;
1937     psh->cmd_per_lun = MAX_CMD_PER_LUN;
1938     psh->this_id = (int) dc390_eepromBuf[index][EE_ADAPT_SCSI_ID];
1939     psh->io_port = io_port;
1940     psh->n_io_port = 0x80;
1941     psh->irq = Irq;
1942 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,50)
1943     psh->base = io_port;
1944 #else
1945     psh->base = (char*)io_port;
1946 #endif  
1947     psh->unique_id = io_port;
1948     psh->dma_channel = -1;
1949     psh->last_reset = jiffies;
1950         
1951     pACB = (PACB) psh->hostdata;
1952
1953     pACB->pScsiHost = psh;
1954     pACB->IOPortBase = (USHORT) io_port;
1955     pACB->IRQLevel = Irq;
1956
1957     DEBUG0(printk (KERN_INFO "DC390: Adapter index %i, ID %i, IO 0x%08x, IRQ 0x%02x\n", \
1958                    index, psh->this_id, (int)io_port, Irq));
1959    
1960     psh->max_id = 8;
1961
1962     if( psh->max_id - 1 == dc390_eepromBuf[index][EE_ADAPT_SCSI_ID] )
1963         psh->max_id--;
1964     psh->max_lun = 1;
1965     if( dc390_eepromBuf[index][EE_MODE2] & LUN_CHECK )
1966         psh->max_lun = 8;
1967
1968     pACB->pLinkDCB = NULL;
1969     pACB->pDCBRunRobin = NULL;
1970     pACB->pActiveDCB = NULL;
1971     pACB->pFreeSRB = pACB->SRB_array;
1972     pACB->SRBCount = MAX_SRB_CNT;
1973     pACB->QueryCnt = 0;
1974     INIT_LIST_HEAD(&pACB->cmdq);
1975     pACB->AdapterIndex = index;
1976     pACB->status = 0;
1977     psh->this_id = dc390_eepromBuf[index][EE_ADAPT_SCSI_ID];
1978     pACB->DeviceCnt = 0;
1979     pACB->DCBCnt = 0;
1980     pACB->TagMaxNum = 2 << dc390_eepromBuf[index][EE_TAG_CMD_NUM];
1981     pACB->ACBFlag = 0;
1982     pACB->scan_devices = 1;
1983     pACB->MsgLen = 0;
1984     pACB->Ignore_IRQ = 0;
1985     pACB->Gmode2 = dc390_eepromBuf[index][EE_MODE2];
1986     dc390_linkSRB( pACB );
1987     pACB->pTmpSRB = &pACB->TmpSRB;
1988     dc390_initSRB( pACB->pTmpSRB );
1989     for(i=0; i<MAX_SCSI_ID; i++)
1990         pACB->DCBmap[i] = 0;
1991     pACB->sel_timeout = SEL_TIMEOUT;
1992     pACB->glitch_cfg = EATER_25NS;
1993     pACB->Cmds = pACB->CmdInQ = pACB->CmdOutOfSRB = 0;
1994     pACB->SelLost = pACB->SelConn = 0;
1995     init_timer (&pACB->Waiting_Timer);
1996 }
1997
1998
1999 /***********************************************************************
2000  * Function : static int dc390_initAdapter ()
2001  *
2002  * Purpose :  initialize the SCSI chip ctrl registers
2003  *
2004  * Inputs : psh - pointer to this host adapter's structure
2005  *          io_port, Irq, index: Resources
2006  *
2007  * Outputs: 0 on success, -1 on error
2008  ***********************************************************************/
2009
2010 int __init dc390_initAdapter (PSH psh, ULONG io_port, UCHAR Irq, UCHAR index)
2011 {
2012     PACB   pACB, pACB2;
2013     UCHAR  dstate;
2014     int    i;
2015     
2016     pACB = (PACB) psh->hostdata;
2017
2018     if (request_region (io_port, psh->n_io_port, "tmscsim") == NULL) {
2019         printk(KERN_ERR "DC390: register IO ports error!\n");
2020         return( -1 );
2021     }
2022
2023     DC390_read8_ (INT_Status, io_port);         /* Reset Pending INT */
2024
2025     if( (i = request_irq(Irq, do_DC390_Interrupt, DC390_IRQ, "tmscsim", pACB) ))
2026       {
2027         printk(KERN_ERR "DC390: register IRQ error!\n");
2028         release_region (io_port, psh->n_io_port);
2029         return( -1 );
2030       }
2031
2032     if( !dc390_pACB_start )
2033       {
2034         pACB2 = NULL;
2035         dc390_pACB_start = pACB;
2036         dc390_pACB_current = pACB;
2037         pACB->pNextACB = NULL;
2038       }
2039     else
2040       {
2041         pACB2 = dc390_pACB_current;
2042         dc390_pACB_current->pNextACB = pACB;
2043         dc390_pACB_current = pACB;
2044         pACB->pNextACB = NULL;
2045       }
2046
2047     DC390_write8 (CtrlReg1, DIS_INT_ON_SCSI_RST | psh->this_id);        /* Disable SCSI bus reset interrupt */
2048
2049     if (pACB->Gmode2 & RST_SCSI_BUS)
2050     {
2051         dc390_ResetSCSIBus( pACB );
2052         udelay (1000);
2053         pACB->pScsiHost->last_reset = jiffies + HZ/2
2054                     + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
2055         /*
2056         for( i=0; i<(500 + 1000*dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY]); i++ )
2057                 udelay(1000);
2058          */
2059     }
2060     pACB->ACBFlag = 0;
2061     DC390_read8 (INT_Status);                           /* Reset Pending INT */
2062     
2063     DC390_write8 (Scsi_TimeOut, SEL_TIMEOUT);           /* 250ms selection timeout */
2064     DC390_write8 (Clk_Factor, CLK_FREQ_40MHZ);          /* Conversion factor = 0 , 40MHz clock */
2065     DC390_write8 (ScsiCmd, NOP_CMD);                    /* NOP cmd - clear command register */
2066     DC390_write8 (CtrlReg2, EN_FEATURE+EN_SCSI2_CMD);   /* Enable Feature and SCSI-2 */
2067     DC390_write8 (CtrlReg3, FAST_CLK);                  /* fast clock */
2068     DC390_write8 (CtrlReg4, pACB->glitch_cfg |                  /* glitch eater */
2069                 (dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION) ? NEGATE_REQACKDATA : 0);  /* Negation */
2070     DC390_write8 (CtcReg_High, 0);                      /* Clear Transfer Count High: ID */
2071     DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
2072     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
2073     DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
2074     dstate = DC390_read8 (DMA_Status);
2075     DC390_write8 (DMA_Status, dstate);  /* clear */
2076
2077     return(0);
2078 }
2079
2080
2081 /***********************************************************************
2082  * Function : static int DC390_init (struct Scsi_Host *host, ...)
2083  *
2084  * Purpose :  initialize the internal structures for a given SCSI host
2085  *
2086  * Inputs : host - pointer to this host adapter's structure
2087  *          io_port - IO ports mapped to this adapter
2088  *          Irq - IRQ assigned to this adpater
2089  *          PDEVDECL - PCI access handle
2090  *          index - Adapter index
2091  *
2092  * Outputs: 0 on success, -1 on error
2093  *
2094  * Note: written in capitals, because the locking is only done here,
2095  *      not in DC390_detect, called from outside 
2096  ***********************************************************************/
2097
2098 static int __init DC390_init (PSHT psht, ULONG io_port, UCHAR Irq, PDEVDECL, UCHAR index)
2099 {
2100     PSH   psh;
2101     PACB  pACB;
2102     DC390_AFLAGS;
2103     
2104     if (dc390_CheckEEpromCheckSum (PDEV, index))
2105     {
2106         int speed;
2107         dc390_adapname = "AM53C974";
2108         printk (KERN_INFO "DC390_init: No EEPROM found! Trying default settings ...\n");
2109         dc390_check_for_safe_settings ();
2110         dc390_fill_with_defaults ();
2111         dc390_EEprom_Override (index);
2112         speed = dc390_clock_speed[tmscsim[1]];
2113         printk (KERN_INFO "DC390: Used defaults: AdaptID=%i, SpeedIdx=%i (%i.%i MHz),"
2114                 " DevMode=0x%02x, AdaptMode=0x%02x, TaggedCmnds=%i (%i), DelayReset=%is\n", 
2115                 tmscsim[0], tmscsim[1], speed/10, speed%10,
2116                 (UCHAR)tmscsim[2], (UCHAR)tmscsim[3], tmscsim[4], 2 << (tmscsim[4]), tmscsim[5]);
2117     }
2118     else
2119     {
2120         dc390_check_for_safe_settings ();
2121         dc390_EEprom_Override (index);
2122     }
2123    
2124     psh = scsi_register( psht, sizeof(DC390_ACB) );
2125     if( !psh ) return( -1 );
2126         
2127     scsi_set_device(psh, &pdev->dev);
2128     pACB = (PACB) psh->hostdata;
2129     DC390_LOCKA_INIT;
2130     DC390_LOCK_ACB;
2131
2132 #if 0
2133     if( !dc390_pSH_start )
2134     {
2135         dc390_pSH_start = psh;
2136         dc390_pSH_current = psh;
2137     }
2138     else
2139     {
2140         dc390_pSH_current->next = psh;
2141         dc390_pSH_current = psh;
2142     }
2143 #endif
2144
2145     DEBUG0(printk(KERN_INFO "DC390: pSH = %8x, Index %02i\n", (UINT) psh, index));
2146
2147     dc390_initACB( psh, io_port, Irq, index );
2148         
2149     PDEVSET;
2150
2151     if( !dc390_initAdapter( psh, io_port, Irq, index ) )
2152     {
2153         DEBUG0(printk("DC390: pACB = %8x, pDCBmap = %8x, pSRB_array = %8x\n",\
2154                       (UINT) pACB, (UINT) pACB->DCBmap, (UINT) pACB->SRB_array));
2155         DEBUG0(printk("DC390: ACB size= %4x, DCB size= %4x, SRB size= %4x\n",\
2156                       sizeof(DC390_ACB), sizeof(DC390_DCB), sizeof(DC390_SRB) ));
2157
2158         DC390_UNLOCK_ACB;
2159         return (0);
2160     }
2161     else
2162     {
2163         //dc390_pSH_start = NULL;
2164         scsi_unregister( psh );
2165         DC390_UNLOCK_ACB;
2166         return( -1 );
2167     }
2168 }
2169
2170
2171 /***********************************************************************
2172  * Function : int DC390_detect(Scsi_Host_Template *psht)
2173  *
2174  * Purpose : detects and initializes AMD53C974 SCSI chips
2175  *           that were autoprobed, overridden on the LILO command line,
2176  *           or specified at compile time.
2177  *
2178  * Inputs : psht - template for this SCSI adapter
2179  *
2180  * Returns : number of host adapters detected
2181  *
2182  ***********************************************************************/
2183
2184 #ifndef NEW_PCI
2185 /* Acc. to PCI 2.1 spec it's up to the driver to enable Bus mastering:
2186  * We use pci_set_master () for 2.1.x and this func for 2.0.x:  */
2187 static void __init dc390_set_master (PDEVDECL)
2188 {
2189         USHORT cmd;
2190         UCHAR lat;
2191         
2192         PCI_READ_CONFIG_WORD (PDEV, PCI_COMMAND, &cmd);
2193         
2194         if (! (cmd & PCI_COMMAND_MASTER)) {     
2195                 printk("PCI: Enabling bus mastering for device %02x:%02x\n",
2196                        PCI_BUS_DEV);
2197                 cmd |= PCI_COMMAND_MASTER;
2198                 PCI_WRITE_CONFIG_WORD(PDEV, PCI_COMMAND, cmd);
2199         }
2200         PCI_READ_CONFIG_BYTE (PDEV, PCI_LATENCY_TIMER, &lat);
2201         if (lat < 16 /* || lat == 255 */) {
2202                 printk("PCI: Setting latency timer of device %02x:%02x from %i to 64\n",
2203                        PCI_BUS_DEV, lat);
2204                 PCI_WRITE_CONFIG_BYTE(PDEV, PCI_LATENCY_TIMER, 64);
2205         }
2206         
2207 }
2208 #endif /* ! NEW_PCI */
2209
2210 static void __init dc390_set_pci_cfg (PDEVDECL)
2211 {
2212         USHORT cmd;
2213         PCI_READ_CONFIG_WORD (PDEV, PCI_COMMAND, &cmd);
2214         cmd |= PCI_COMMAND_SERR | PCI_COMMAND_PARITY | PCI_COMMAND_IO;
2215         PCI_WRITE_CONFIG_WORD (PDEV, PCI_COMMAND, cmd);
2216         PCI_WRITE_CONFIG_WORD (PDEV, PCI_STATUS, (PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY));
2217 }
2218         
2219
2220 int __init DC390_detect (Scsi_Host_Template *psht)
2221 {
2222     PDEVDECL0;
2223     UCHAR   irq;
2224     ULONG   io_port;
2225
2226     //dc390_pSHT_start = psht;
2227     dc390_pACB_start = NULL;
2228
2229     if ( PCI_PRESENT )
2230         while (PCI_FIND_DEVICE (PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD53C974))
2231         {
2232 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,30)
2233             if (pci_enable_device (pdev))
2234                 continue;
2235 #endif
2236             PCI_GET_IO_AND_IRQ;
2237             DEBUG0(printk(KERN_INFO "DC390(%i): IO_PORT=%04x,IRQ=%x\n", dc390_adapterCnt, (UINT) io_port, irq));
2238
2239             if( !DC390_init(psht, io_port, irq, PDEV, dc390_adapterCnt))
2240             {
2241                 PCI_SET_MASTER;
2242                 dc390_set_pci_cfg (PDEV);
2243                 dc390_adapterCnt++;
2244             }
2245         }
2246     else
2247         printk (KERN_ERR "DC390: No PCI BIOS found!\n");
2248    
2249     if (dc390_adapterCnt)
2250 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,3,30)
2251         psht->proc_name = "tmscsim";
2252 #else
2253         psht->proc_dir = &DC390_proc_scsi_tmscsim;
2254 #endif
2255     printk(KERN_INFO "DC390: %i adapters found\n", dc390_adapterCnt);
2256     return( dc390_adapterCnt );
2257 }
2258
2259
2260 /***********************************************************************
2261  * Functions: dc390_inquiry(), dc390_inquiry_done()
2262  *
2263  * Purpose: When changing speed etc., we have to issue an INQUIRY
2264  *          command to make sure, we agree upon the nego parameters
2265  *          with the device
2266  ***********************************************************************/
2267
2268 static void dc390_inquiry_done (Scsi_Cmnd* cmd)
2269 {
2270    printk (KERN_INFO "DC390: INQUIRY (ID %02x LUN %02x) returned %08x\n",
2271            cmd->device->id, cmd->device->lun, cmd->result);
2272    if (cmd->result)
2273    {
2274         PACB pACB = (PACB)cmd->device->host->hostdata;
2275         PDCB pDCB = dc390_findDCB (pACB, cmd->device->id, cmd->device->lun);
2276         printk ("DC390: Unsetting DsCn, Sync and TagQ!\n");
2277         if (pDCB)
2278         {
2279                 pDCB->DevMode &= ~(SYNC_NEGO_ | TAG_QUEUEING_ | EN_DISCONNECT_ );
2280                 dc390_updateDCB (pACB, pDCB);
2281         }
2282    }
2283    kfree (cmd);
2284 }
2285
2286 void dc390_inquiry (PACB pACB, PDCB pDCB)
2287 {
2288    char* buffer;
2289    Scsi_Cmnd* cmd;
2290    cmd = kmalloc (sizeof(Scsi_Cmnd) + 256, GFP_ATOMIC);
2291    if (!cmd) { printk ("DC390: kmalloc failed in inquiry!\n"); return; }
2292    buffer = (char*)cmd + sizeof(Scsi_Cmnd);
2293
2294    memset (cmd, 0, sizeof(Scsi_Cmnd) + 256);
2295    cmd->cmnd[0] = INQUIRY;
2296    cmd->cmnd[1] = (pDCB->TargetLUN << 5) & 0xe0;
2297    cmd->cmnd[4] = 0xff;
2298    
2299    cmd->cmd_len = 6; cmd->old_cmd_len = 6;
2300 /* TODO FIXME */
2301 /*    cmd->host = pACB->pScsiHost; */
2302    cmd->device->id = pDCB->TargetID;
2303    cmd->device->lun = pDCB->TargetLUN; 
2304    cmd->serial_number = 1;
2305    cmd->pid = 390;
2306    cmd->bufflen = 128;
2307    cmd->buffer = buffer;
2308    cmd->request_bufflen = 128;
2309    cmd->request_buffer = &buffer[128];
2310    cmd->done = dc390_inquiry_done;
2311    cmd->scsi_done = dc390_inquiry_done;
2312    cmd->timeout_per_command = HZ;
2313
2314    cmd->request->rq_status = RQ_SCSI_BUSY;
2315
2316    pDCB->SyncMode &= ~SYNC_NEGO_DONE;
2317    printk (KERN_INFO "DC390: Queue INQUIRY command to dev ID %02x LUN %02x\n",
2318            pDCB->TargetID, pDCB->TargetLUN);
2319    DC390_queue_command (cmd, dc390_inquiry_done);
2320 }
2321
2322 /***********************************************************************
2323  * Functions: dc390_sendstart(), dc390_sendstart_done()
2324  *
2325  * Purpose: When changing speed etc., we have to issue an INQUIRY
2326  *          command to make sure, we agree upon the nego parameters
2327  *          with the device
2328  ***********************************************************************/
2329
2330 static void dc390_sendstart_done (Scsi_Cmnd* cmd)
2331 {
2332    printk (KERN_INFO "DC390: SENDSTART (ID %02x LUN %02x) returned %08x\n",
2333            cmd->device->id, cmd->device->lun, cmd->result);
2334    kfree (cmd);
2335 }
2336
2337 void dc390_sendstart (PACB pACB, PDCB pDCB)
2338 {
2339    char* buffer;
2340    Scsi_Cmnd* cmd;
2341    cmd = kmalloc (sizeof(Scsi_Cmnd) + 256, GFP_ATOMIC);
2342    if (!cmd) { printk ("DC390: kmalloc failed in sendstart!\n"); return; }
2343    buffer = (char*)cmd + sizeof(Scsi_Cmnd);
2344
2345    memset (cmd, 0, sizeof(Scsi_Cmnd) + 256);
2346    cmd->cmnd[0] = 0x1b; /* START_STOP_UNIT */
2347    cmd->cmnd[1] = (pDCB->TargetLUN << 5) & 0xe0;
2348    cmd->cmnd[4] = 0x01; /* START */
2349    
2350    cmd->cmd_len = 6; cmd->old_cmd_len = 6;
2351 /* TODO FIXME */
2352 /*    cmd->host = pACB->pScsiHost; */
2353    cmd->device->id = pDCB->TargetID;
2354    cmd->device->lun = pDCB->TargetLUN; 
2355    cmd->serial_number = 1;
2356    cmd->pid = 310;
2357    cmd->bufflen = 128;
2358    cmd->buffer = buffer;
2359    cmd->request_bufflen = 128;
2360    cmd->request_buffer = &buffer[128];
2361    cmd->done = dc390_sendstart_done;
2362    cmd->scsi_done = dc390_sendstart_done;
2363    cmd->timeout_per_command = 5*HZ;
2364
2365    cmd->request->rq_status = RQ_SCSI_BUSY;
2366
2367    pDCB->SyncMode &= ~SYNC_NEGO_DONE;
2368    printk (KERN_INFO "DC390: Queue SEND_START command to dev ID %02x LUN %02x\n",
2369            pDCB->TargetID, pDCB->TargetLUN);
2370    DC390_queue_command (cmd, dc390_sendstart_done);
2371 }
2372
2373 /********************************************************************
2374  * Function: dc390_set_info()
2375  *
2376  * Purpose: Change adapter config
2377  *
2378  * Strings are parsed similar to the output of tmscsim_proc_info ()
2379  * '-' means no change
2380  *******************************************************************/
2381
2382 static int dc390_scanf (char** buffer, char** pos, char** p0, int* var)
2383 {
2384    *p0 = *pos;
2385    *var = simple_strtoul (*p0, pos, 10);
2386    if (*p0 == *pos) return -1;
2387    *pos = strsep (buffer, " \t\n:=,;.");
2388    return 0;
2389 }
2390
2391 #define SCANF(buffer, pos, p0, var, min, max)           \
2392 if (dc390_scanf (&buffer, &pos, &p0, &var)) goto einv;  \
2393 else if (var<min || var>max) goto einv2
2394
2395 static int dc390_yesno (char** buffer, char** pos, char* var, char bmask)
2396 {
2397    switch (**pos)
2398      {
2399       case 'Y': *var |= bmask; break;
2400       case 'N': *var &= ~bmask; break;
2401       case '-': break;
2402       default: return -1;
2403      }
2404    *pos = strsep (buffer, " \t\n:=,;");
2405    return 0;
2406 }
2407
2408 #define YESNO(buffer, pos, var, bmask)                                  \
2409         if (dc390_yesno (&buffer, &pos, &var, bmask)) goto einv;        \
2410         else dc390_updateDCB (pACB, pDCB);                              \
2411         if (!pos) goto ok
2412
2413 static int dc390_search (char** buffer, char** pos, char** p0, char* var, char* txt, int max, int scale, char* ign)
2414 {
2415    int dum;
2416    if (! memcmp (*pos, txt, strlen(txt)))
2417      {
2418         *p0 = strsep (buffer, " \t\n:=,;");
2419         if (!*p0) return -1;
2420         dum = simple_strtoul (*p0, pos, 10);
2421         if (*p0 == *pos) return -1;
2422         if (dum >= 0 && dum <= max) 
2423           { *var = (dum * 100) / scale; }
2424         else return -2;
2425         *pos = strsep (buffer, " \t\n:=,;");
2426         if (*ign && *pos && strlen(*pos) >= strlen(ign) && 
2427             !(memcmp (*pos, ign, strlen(ign)))) 
2428                 *pos = strsep (buffer, " \t\n:=,;");
2429
2430      }
2431    return 0;
2432 }
2433
2434 #define SEARCH(buffer, pos, p0, var, txt, max)                                          \
2435 if (dc390_search (&buffer, &pos, &p0, (PUCHAR)(&var), txt, max, 100, "")) goto einv2;   \
2436 else if (!p1) goto ok2
2437
2438 #define SEARCH2(buffer, pos, p0, var, txt, max, scale)                                  \
2439 if (dc390_search (&buffer, &pos, &p0, &var, txt, max, scale, "")) goto einv2;           \
2440 else if (!p1) goto ok2
2441
2442 #define SEARCH3(buffer, pos, p0, var, txt, max, scale, ign)                             \
2443 if (dc390_search (&buffer, &pos, &p0, &var, txt, max, scale, ign)) goto einv2;          \
2444 else if (!p1) goto ok2
2445
2446
2447 #ifdef DC390_PARSEDEBUG
2448 static char _prstr[256];
2449 char* prstr (char* p, char* e)
2450 {
2451    char* c = _prstr;
2452    while (p < e)
2453      if (*p == 0) { *c++ = ':'; p++; }
2454      else if (*p == 10) { *c++ = '\\'; *c++ = 'n'; p++; }
2455      else *c++ = *p++;
2456    *c = 0;
2457    return _prstr;
2458 }
2459 #endif
2460
2461 int dc390_set_info (char *buffer, int length, PACB pACB)
2462 {
2463   char *pos = buffer, *p0 = buffer;
2464   char needs_inquiry = 0; 
2465   int dum = 0;
2466   char dev;
2467   PDCB pDCB = pACB->pLinkDCB;
2468   DC390_IFLAGS;
2469   DC390_AFLAGS;
2470   pos[length] = 0;
2471
2472   DC390_LOCK_IO(pACB->pScsiHost);
2473   DC390_LOCK_ACB;
2474   /* UPPERCASE */ 
2475   /* Don't use kernel toupper, because of 2.0.x bug: ctmp unexported */
2476   while (*pos) 
2477     { if (*pos >='a' && *pos <= 'z') *pos = *pos + 'A' - 'a'; pos++; }
2478   
2479   /* Remove WS */
2480   pos = strsep (&buffer, " \t:\n=,;");
2481   if (!*pos) goto ok;
2482    
2483  next:
2484   if (!memcmp (pos, "RESET", 5)) goto reset;
2485   else if (!memcmp (pos, "INQUIRY", 7)) goto inquiry;
2486   else if (!memcmp (pos, "REMOVE", 6)) goto remove;
2487   else if (!memcmp (pos, "ADD", 3)) goto add;
2488   else if (!memcmp (pos, "START", 5)) goto start;
2489   else if (!memcmp (pos, "DUMP", 4)) goto dump;
2490   
2491   if (isdigit (*pos))
2492     {
2493       /* Device config line */
2494       int dev, id, lun; char* pdec;
2495       char olddevmode;
2496       
2497       SCANF (buffer, pos, p0, dev, 0, pACB->DCBCnt-1);
2498       if (*pos) { SCANF (buffer, pos, p0, id, 0, 7); } else goto einv;
2499       if (*pos) { SCANF (buffer, pos, p0, lun, 0, 7); } else goto einv;
2500       if (!*pos) goto einv;
2501       
2502       PARSEDEBUG(printk (KERN_INFO "DC390: config line %i %i %i:\"%s\"\n", dev, id, lun, prstr (pos, &buffer[length])));
2503       pDCB = pACB->pLinkDCB;
2504       for (dum = 0; dum < dev; dum++) pDCB = pDCB->pNextDCB;
2505       /* Sanity Check */
2506       if (pDCB->TargetID != id || pDCB->TargetLUN != lun) 
2507          {
2508             printk (KERN_ERR "DC390: no such device: Idx=%02i ID=%02i LUN=%02i\n",
2509                     dev, id, lun);
2510             goto einv2;
2511          }
2512
2513       if (pDCB->pWaitingSRB || pDCB->pGoingSRB)
2514       {
2515           printk ("DC390: Cannot change dev (%i-%i) cfg: Pending requests\n",
2516                   pDCB->TargetID, pDCB->TargetLUN);
2517           goto einv;
2518       }
2519           
2520       olddevmode = pDCB->DevMode;
2521       YESNO (buffer, pos, pDCB->DevMode, PARITY_CHK_);
2522       needs_inquiry++;
2523       YESNO (buffer, pos, pDCB->DevMode, SYNC_NEGO_);
2524       if ((olddevmode & SYNC_NEGO_) == (pDCB->DevMode & SYNC_NEGO_)) needs_inquiry--;
2525       needs_inquiry++;
2526       YESNO (buffer, pos, pDCB->DevMode, EN_DISCONNECT_);
2527       if ((olddevmode & EN_DISCONNECT_) == (pDCB->DevMode & EN_DISCONNECT_)) needs_inquiry--;
2528       YESNO (buffer, pos, pDCB->DevMode, SEND_START_);
2529       needs_inquiry++;
2530       YESNO (buffer, pos, pDCB->DevMode, TAG_QUEUEING_);
2531       if ((olddevmode & TAG_QUEUEING_) == (pDCB->DevMode & TAG_QUEUEING_)) needs_inquiry--;
2532
2533       dc390_updateDCB (pACB, pDCB);
2534       if (!*pos) goto ok;
2535        
2536       olddevmode = pDCB->NegoPeriod;
2537       /* Look for decimal point (Speed) */
2538       pdec = pos; 
2539       while (pdec++ < &buffer[length]) if (*pdec == '.') break;
2540       /* NegoPeriod */
2541       if (*pos != '-')
2542         {
2543           SCANF (buffer, pos, p0, dum, 72, 800); 
2544           pDCB->NegoPeriod = dum >> 2;
2545           if (pDCB->NegoPeriod != olddevmode) needs_inquiry++;
2546           if (!pos) goto ok;
2547           if (memcmp (pos, "NS", 2) == 0) pos = strsep (&pos, " \t\n:=,;.");
2548         }
2549       else pos = strsep (&pos, " \t\n:=,;.");
2550       if (!*pos) goto ok;
2551       
2552       /* Sync Speed in MHz */
2553       if (*pos != '-')
2554         {
2555           SCANF (buffer, pos, p0, dum, 1, 13); 
2556           pDCB->NegoPeriod = (1000/dum) >> 2;
2557           if (pDCB->NegoPeriod != olddevmode && !pos) needs_inquiry++;
2558           if (!*pos) goto ok;
2559           /* decimal */
2560           if (pos-1 == pdec)
2561              {
2562                 int dumold = dum;
2563                 dum = simple_strtoul (pos, &p0, 10) * 10;
2564                 for (; p0-pos > 1; p0--) dum /= 10;
2565                 pDCB->NegoPeriod = (100000/(100*dumold + dum)) >> 2;
2566                 if (pDCB->NegoPeriod < 19) pDCB->NegoPeriod = 19;
2567                 pos = strsep (&pos, " \t\n:=,;");
2568                 if (!*pos) goto ok;
2569              }
2570           if (*pos == 'M') pos = strsep (&pos, " \t\n:=,;");
2571           if (pDCB->NegoPeriod != olddevmode) needs_inquiry++;
2572         }
2573       else pos = strsep (&pos, " \t\n:=,;");
2574       /* dc390_updateDCB (pACB, pDCB); */
2575       if (!*pos) goto ok;
2576
2577       olddevmode = pDCB->SyncOffset;
2578       /* SyncOffs */
2579       if (*pos != '-')
2580         {
2581           SCANF (buffer, pos, p0, dum, 0, 0x0f); 
2582           pDCB->SyncOffset = dum;
2583           if (pDCB->SyncOffset > olddevmode) needs_inquiry++;
2584         }
2585       else pos = strsep (&pos, " \t\n:=,;");
2586       if (!*pos) goto ok;
2587       dc390_updateDCB (pACB, pDCB);
2588
2589       //olddevmode = pDCB->MaxCommand;
2590       /* MaxCommand (Tags) */
2591       if (*pos != '-')
2592         {
2593           SCANF (buffer, pos, p0, dum, 1, 32 /*pACB->TagMaxNum*/);
2594           if (pDCB->SyncMode & EN_TAG_QUEUEING)
2595                 pDCB->MaxCommand = dum;
2596           else printk (KERN_INFO "DC390: Can't set MaxCmd larger than one without Tag Queueing!\n");
2597         }
2598       else pos = strsep (&pos, " \t\n:=,;");
2599
2600     }
2601   else
2602     {
2603       char* p1 = pos; UCHAR dum, newadaptid;
2604       PARSEDEBUG(printk (KERN_INFO "DC390: chg adapt cfg \"%s\"\n", prstr (pos, &buffer[length])));
2605       dum = GLITCH_TO_NS (pACB->glitch_cfg);
2606       /* Adapter setting */
2607       SEARCH (buffer, pos, p0, pACB->pScsiHost->max_id, "MAXID", 8); 
2608       SEARCH (buffer, pos, p0, pACB->pScsiHost->max_lun, "MAXLUN", 8); 
2609       SEARCH (buffer, pos, p0, newadaptid, "ADAPTERID", 7);
2610       SEARCH (buffer, pos, p0, pACB->TagMaxNum, "TAGMAXNUM", 32);
2611       SEARCH (buffer, pos, p0, pACB->ACBFlag, "ACBFLAG", 255);
2612       SEARCH3 (buffer, pos, p0, dum, "GLITCHEATER", 40, 1000, "NS");
2613       SEARCH3 (buffer, pos, p0, pACB->sel_timeout, "SELTIMEOUT", 400, 163, "MS");
2614       SEARCH3 (buffer, pos, p0, dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY], "DELAYRESET", 180, 100, "S");
2615     ok2:
2616       pACB->glitch_cfg = NS_TO_GLITCH (dum);
2617       if (pACB->sel_timeout < 60) pACB->sel_timeout = 60;
2618       DC390_write8 (Scsi_TimeOut, pACB->sel_timeout);
2619       if (newadaptid != pACB->pScsiHost->this_id)
2620       {
2621         pACB->pScsiHost->this_id = newadaptid;
2622         dc390_ResetDevParam (pACB);
2623       }     
2624       //dum = 0; while (1 << dum <= pACB->TagMaxNum) dum ++;
2625       //pACB->TagMaxNum &= (1 << --dum);
2626       dc390_updateDCBs (pACB);
2627       // All devs should be INQUIRED now
2628       if (pos == p1) goto einv;
2629     }
2630   if (*pos) goto next;
2631       
2632  ok:
2633   DC390_UNLOCK_ACB;
2634   if (needs_inquiry) 
2635      { dc390_updateDCB (pACB, pDCB); dc390_inquiry (pACB, pDCB); }
2636   DC390_UNLOCK_IO(pACB->pScsiHost);
2637   return (length);
2638
2639  einv2:
2640   pos = p0;
2641  einv:
2642   DC390_UNLOCK_ACB;
2643   DC390_UNLOCK_IO(pACB->pScsiHost);
2644   printk (KERN_WARNING "DC390: parse error near \"%s\"\n", (pos? pos: "NULL"));
2645   return (-EINVAL);
2646    
2647  reset:
2648      {
2649         Scsi_Cmnd cmd;
2650         /* TODO FIXME */
2651         /* cmd.host = pACB->pScsiHost; */
2652         printk (KERN_WARNING "DC390: Driver reset requested!\n");
2653         DC390_UNLOCK_ACB;
2654         DC390_reset (&cmd);
2655         DC390_UNLOCK_IO(pACB->pScsiHost);
2656      }
2657   return (length);
2658
2659  dump:
2660      {
2661         dc390_dumpinfo (pACB, 0, 0);
2662         DC390_UNLOCK_ACB;
2663         DC390_UNLOCK_IO(pACB->pScsiHost);       
2664      }
2665   return (length);
2666         
2667  inquiry:
2668      {
2669         pos = strsep (&pos, " \t\n.:;="); if (!*pos) goto einv;
2670         dev = simple_strtoul (pos, &p0, 10);
2671         if (dev >= pACB->DCBCnt) goto einv_dev;
2672         for (dum = 0; dum < dev; dum++) pDCB = pDCB->pNextDCB;
2673         printk (KERN_NOTICE " DC390: Issue INQUIRY command to Dev(Idx) %i SCSI ID %i LUN %i\n",
2674                 dev, pDCB->TargetID, pDCB->TargetLUN);
2675         DC390_UNLOCK_ACB;
2676         dc390_inquiry (pACB, pDCB);
2677         DC390_UNLOCK_IO(pACB->pScsiHost);
2678      }
2679    return (length);
2680
2681  remove:
2682      {
2683         pos = strsep (&pos, " \t\n.:;="); if (!*pos) goto einv;
2684         dev = simple_strtoul (pos, &p0, 10);
2685         if (dev >= pACB->DCBCnt) goto einv_dev;
2686         for (dum = 0; dum < dev; dum++) pDCB = pDCB->pNextDCB;
2687         printk (KERN_NOTICE " DC390: Remove DCB for Dev(Idx) %i SCSI ID %i LUN %i\n",
2688                 dev, pDCB->TargetID, pDCB->TargetLUN);
2689         /* TO DO: We should make sure no pending commands are left */
2690         dc390_remove_dev (pACB, pDCB);
2691         DC390_UNLOCK_ACB;
2692         DC390_UNLOCK_IO(pACB->pScsiHost);
2693      }
2694    return (length);
2695
2696  add:
2697      {
2698         int id, lun;
2699         pos = strsep (&pos, " \t\n.:;=");
2700         if (*pos) { SCANF (buffer, pos, p0, id, 0, 7); } else goto einv;
2701         if (*pos) { SCANF (buffer, pos, p0, lun, 0, 7); } else goto einv;
2702         pDCB = dc390_findDCB (pACB, id, lun);
2703         if (pDCB) { printk ("DC390: ADD: Device already existing\n"); goto einv; }
2704         dc390_initDCB (pACB, &pDCB, id, lun);
2705         DC390_UNLOCK_ACB;
2706         dc390_inquiry (pACB, pDCB);
2707         DC390_UNLOCK_IO(pACB->pScsiHost);
2708      }
2709    return (length);
2710
2711  start:
2712      {
2713         int id, lun;
2714         pos = strsep (&pos, " \t\n.:;=");
2715         if (*pos) { SCANF (buffer, pos, p0, id, 0, 7); } else goto einv;
2716         if (*pos) { SCANF (buffer, pos, p0, lun, 0, 7); } else goto einv;
2717         pDCB = dc390_findDCB (pACB, id, lun);
2718         if (pDCB) printk ("DC390: SendStart: Device already existing ...\n");
2719         else dc390_initDCB (pACB, &pDCB, id, lun);
2720         DC390_UNLOCK_ACB;
2721         dc390_sendstart (pACB, pDCB);
2722         dc390_inquiry (pACB, pDCB);
2723         DC390_UNLOCK_IO(pACB->pScsiHost);
2724      }
2725    return (length);
2726
2727  einv_dev:
2728    printk (KERN_WARNING "DC390: Ignore cmnd to invalid Dev(Idx) %i. Valid range: 0 - %i.\n", 
2729            dev, pACB->DCBCnt - 1);
2730    DC390_UNLOCK_ACB;
2731    DC390_UNLOCK_IO(pACB->pScsiHost);
2732    return (-EINVAL);
2733 }
2734
2735 #undef SEARCH
2736 #undef YESNO
2737 #undef SCANF
2738
2739 /********************************************************************
2740  * Function: DC390_proc_info(char* buffer, char **start,
2741  *                           off_t offset, int length, int hostno, int inout)
2742  *
2743  * Purpose: return SCSI Adapter/Device Info
2744  *
2745  * Input: buffer: Pointer to a buffer where to write info
2746  *        start :
2747  *        offset:
2748  *        hostno: Host adapter index
2749  *        inout : Read (=0) or set(!=0) info
2750  *
2751  * Output: buffer: contains info
2752  *         length; length of info in buffer
2753  *
2754  * return value: length
2755  *
2756  ********************************************************************/
2757
2758 #undef SPRINTF
2759 #define SPRINTF(args...) pos += sprintf(pos, ## args)
2760
2761 #define YESNO(YN)               \
2762  if (YN) SPRINTF(" Yes ");      \
2763  else SPRINTF(" No  ")
2764
2765
2766 int DC390_proc_info (struct Scsi_Host *shpnt, char *buffer, char **start,
2767                      off_t offset, int length, int inout)
2768 {
2769   int dev, spd, spd1;
2770   char *pos = buffer;
2771   struct scsi_cmnd_list *cl;
2772   PACB pACB;
2773   PDCB pDCB;
2774   DC390_AFLAGS;
2775
2776   pACB = dc390_pACB_start;
2777
2778   while(pACB != (PACB)-1)
2779      {
2780         if (shpnt == pACB->pScsiHost)
2781                 break;
2782         pACB = pACB->pNextACB;
2783      }
2784
2785   if (pACB == (PACB)-1) return(-ESRCH);
2786
2787   if(inout) /* Has data been written to the file ? */
2788       return dc390_set_info(buffer, length, pACB);
2789    
2790   SPRINTF("Tekram DC390/AM53C974 PCI SCSI Host Adapter, ");
2791   SPRINTF("Driver Version %s\n", DC390_VERSION);
2792
2793   DC390_LOCK_ACB;
2794
2795   SPRINTF("SCSI Host Nr %i, ", shpnt->host_no);
2796   SPRINTF("%s Adapter Nr %i\n", dc390_adapname, pACB->AdapterIndex);
2797   SPRINTF("IOPortBase 0x%04x, ", pACB->IOPortBase);
2798   SPRINTF("IRQ %02i\n", pACB->IRQLevel);
2799
2800   SPRINTF("MaxID %i, MaxLUN %i, ", shpnt->max_id, shpnt->max_lun);
2801   SPRINTF("AdapterID %i, SelTimeout %i ms, DelayReset %i s\n", 
2802           shpnt->this_id, (pACB->sel_timeout*164)/100,
2803           dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY]);
2804
2805   SPRINTF("TagMaxNum %i, Status 0x%02x, ACBFlag 0x%02x, GlitchEater %i ns\n",
2806           pACB->TagMaxNum, pACB->status, pACB->ACBFlag, GLITCH_TO_NS(pACB->glitch_cfg)*12);
2807
2808   SPRINTF("Statistics: Cmnds %li, Cmnds not sent directly %i, Out of SRB conds %i\n",
2809           pACB->Cmds, pACB->CmdInQ, pACB->CmdOutOfSRB);
2810   SPRINTF("            Lost arbitrations %i, Sel. connected %i, Connected: %s\n", 
2811           pACB->SelLost, pACB->SelConn, pACB->Connected? "Yes": "No");
2812    
2813   SPRINTF("Nr of attached devices: %i, Nr of DCBs: %i\n", pACB->DeviceCnt, pACB->DCBCnt);
2814   SPRINTF("Map of attached LUNs: %02x %02x %02x %02x %02x %02x %02x %02x\n",
2815           pACB->DCBmap[0], pACB->DCBmap[1], pACB->DCBmap[2], pACB->DCBmap[3], 
2816           pACB->DCBmap[4], pACB->DCBmap[5], pACB->DCBmap[6], pACB->DCBmap[7]);
2817
2818   SPRINTF("Idx ID LUN Prty Sync DsCn SndS TagQ NegoPeriod SyncSpeed SyncOffs MaxCmd\n");
2819
2820   pDCB = pACB->pLinkDCB;
2821   for (dev = 0; dev < pACB->DCBCnt; dev++)
2822      {
2823       SPRINTF("%02i  %02i  %02i ", dev, pDCB->TargetID, pDCB->TargetLUN);
2824       YESNO(pDCB->DevMode & PARITY_CHK_);
2825       YESNO(pDCB->SyncMode & SYNC_NEGO_DONE);
2826       YESNO(pDCB->DevMode & EN_DISCONNECT_);
2827       YESNO(pDCB->DevMode & SEND_START_);
2828       YESNO(pDCB->SyncMode & EN_TAG_QUEUEING);
2829       if (pDCB->SyncOffset & 0x0f)
2830       {
2831          int sp = pDCB->SyncPeriod; if (! (pDCB->CtrlR3 & FAST_SCSI)) sp++;
2832          SPRINTF("  %03i ns ", (pDCB->NegoPeriod) << 2);
2833          spd = 40/(sp); spd1 = 40%(sp);
2834          spd1 = (spd1 * 10 + sp/2) / (sp);
2835          SPRINTF("   %2i.%1i M      %02i", spd, spd1, (pDCB->SyncOffset & 0x0f));
2836       }
2837       else SPRINTF(" (%03i ns)                 ", (pDCB->NegoPeriod) << 2);
2838       /* Add more info ...*/
2839       SPRINTF ("      %02i\n", pDCB->MaxCommand);
2840       pDCB = pDCB->pNextDCB;
2841      }
2842     SPRINTF ("Commands in Queues: Query: %li:", pACB->QueryCnt);
2843     list_for_each_entry(cl, &pACB->cmdq, scp.list)
2844         SPRINTF (" %li", ((struct scsi_cmnd*)cl)->pid);
2845     if (timer_pending(&pACB->Waiting_Timer)) SPRINTF ("Waiting queue timer running\n");
2846     else SPRINTF ("\n");
2847     pDCB = pACB->pLinkDCB;
2848         
2849     for (dev = 0; dev < pACB->DCBCnt; dev++)
2850     {
2851         PSRB pSRB;
2852         if (pDCB->WaitSRBCnt) 
2853                     SPRINTF ("DCB (%02i-%i): Waiting: %i:", pDCB->TargetID, pDCB->TargetLUN,
2854                              pDCB->WaitSRBCnt);
2855         for (pSRB = pDCB->pWaitingSRB; pSRB; pSRB = pSRB->pNextSRB)
2856                 SPRINTF(" %li", pSRB->pcmd->pid);
2857         if (pDCB->GoingSRBCnt) 
2858                     SPRINTF ("\nDCB (%02i-%i): Going  : %i:", pDCB->TargetID, pDCB->TargetLUN,
2859                              pDCB->GoingSRBCnt);
2860         for (pSRB = pDCB->pGoingSRB; pSRB; pSRB = pSRB->pNextSRB)
2861 #if 0 //def DC390_DEBUGTRACE
2862                 SPRINTF(" %s\n  ", pSRB->debugtrace);
2863 #else
2864                 SPRINTF(" %li", pSRB->pcmd->pid);
2865 #endif
2866         if (pDCB->WaitSRBCnt || pDCB->GoingSRBCnt) SPRINTF ("\n");
2867         pDCB = pDCB->pNextDCB;
2868     }
2869         
2870 #ifdef DC390_DEBUGDCB
2871     SPRINTF ("DCB list for ACB %p:\n", pACB);
2872     pDCB = pACB->pLinkDCB;
2873     SPRINTF ("%p", pDCB);
2874     for (dev = 0; dev < pACB->DCBCnt; dev++, pDCB=pDCB->pNextDCB)
2875         SPRINTF ("->%p", pDCB->pNextDCB);
2876     SPRINTF("\n");
2877 #endif
2878   
2879
2880   DC390_UNLOCK_ACB;
2881   *start = buffer + offset;
2882
2883   if (pos - buffer < offset)
2884     return 0;
2885   else if (pos - buffer - offset < length)
2886     return pos - buffer - offset;
2887   else
2888     return length;
2889 }
2890
2891 #undef YESNO
2892 #undef SPRINTF
2893
2894 /***********************************************************************
2895  * Function : static int dc390_shutdown (struct Scsi_Host *host)
2896  *
2897  * Purpose : does a clean (we hope) shutdown of the SCSI chip.
2898  *           Use prior to dumping core, unloading the driver, etc.
2899  *
2900  * Returns : 0 on success
2901  ***********************************************************************/
2902 static int dc390_shutdown (struct Scsi_Host *host)
2903 {
2904     UCHAR    bval;
2905     PACB pACB = (PACB)(host->hostdata);
2906    
2907 /*  pACB->soft_reset(host); */
2908
2909     printk(KERN_INFO "DC390: shutdown\n");
2910
2911     pACB->ACBFlag = RESET_DEV;
2912     bval = DC390_read8 (CtrlReg1);
2913     bval |= DIS_INT_ON_SCSI_RST;
2914     DC390_write8 (CtrlReg1, bval);      /* disable interrupt */
2915     if (pACB->Gmode2 & RST_SCSI_BUS)
2916                 dc390_ResetSCSIBus (pACB);
2917
2918     if (timer_pending (&pACB->Waiting_Timer)) del_timer (&pACB->Waiting_Timer);
2919     return( 0 );
2920 }
2921
2922 void dc390_freeDCBs (struct Scsi_Host *host)
2923 {
2924     PDCB pDCB, nDCB;
2925     PACB pACB = (PACB)(host->hostdata);
2926     
2927     pDCB = pACB->pLinkDCB;
2928     if (!pDCB) return;
2929     do
2930     {
2931         nDCB = pDCB->pNextDCB;
2932         DCBDEBUG(printk (KERN_INFO "DC390: Free DCB (ID %i, LUN %i): %p\n",\
2933                          pDCB->TargetID, pDCB->TargetLUN, pDCB));
2934         //kfree (pDCB);
2935         dc390_remove_dev (pACB, pDCB);
2936         pDCB = nDCB;
2937     } while (pDCB && pACB->pLinkDCB);
2938
2939 }
2940
2941 int DC390_release (struct Scsi_Host *host)
2942 {
2943     DC390_AFLAGS DC390_IFLAGS;
2944     PACB pACB = (PACB)(host->hostdata);
2945
2946     DC390_LOCK_IO(host);
2947     DC390_LOCK_ACB;
2948
2949     /* TO DO: We should check for outstanding commands first. */
2950     dc390_shutdown (host);
2951
2952     if (host->irq != SCSI_IRQ_NONE)
2953     {
2954         DEBUG0(printk(KERN_INFO "DC390: Free IRQ %i\n",host->irq));
2955         free_irq (host->irq, pACB);
2956     }
2957
2958     release_region(host->io_port,host->n_io_port);
2959     dc390_freeDCBs (host);
2960     DC390_UNLOCK_ACB;
2961     DC390_UNLOCK_IO(host);
2962     scsi_unregister(host);
2963     return( 1 );
2964 }
2965
2966 static Scsi_Host_Template driver_template = {
2967    .proc_name      = "tmscsim", 
2968    .proc_info      = DC390_proc_info,
2969    .name           = DC390_BANNER " V" DC390_VERSION,
2970    .detect         = DC390_detect,
2971    .release        = DC390_release,
2972    .queuecommand   = DC390_queue_command,
2973    .eh_abort_handler            = DC390_abort,
2974    .eh_bus_reset_handler        = DC390_reset,
2975    .bios_param     = DC390_bios_param,
2976    .can_queue      = 42,
2977    .this_id        = 7,
2978    .sg_tablesize   = SG_ALL,
2979    .cmd_per_lun    = 16,
2980    .use_clustering = DISABLE_CLUSTERING,
2981 };
2982 #include "scsi_module.c"