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