Merge branch 'forlinus' of git://parisc-linux.org/home/kyle/git/parisc-2.6
[linux-2.6] / drivers / scsi / tmscsim.c
1 /************************************************************************
2  *      FILE NAME : TMSCSIM.C                                           *
3  *           BY   : C.L. Huang,  ching@tekram.com.tw                    *
4  *      Description: Device Driver for Tekram DC-390(T) PCI SCSI        *
5  *                   Bus Master Host Adapter                            *
6  * (C)Copyright 1995-1996 Tekram Technology Co., Ltd.                   *
7  ************************************************************************
8  * (C) Copyright: put under GNU GPL in 10/96                            *
9  *                              (see Documentation/scsi/tmscsim.txt)    *
10  ************************************************************************
11  * $Id: tmscsim.c,v 2.60.2.30 2000/12/20 01:07:12 garloff Exp $         *
12  *      Enhancements and bugfixes by                                    *
13  *      Kurt Garloff <kurt@garloff.de>  <garloff@suse.de>               *
14  ************************************************************************
15  *      HISTORY:                                                        *
16  *                                                                      *
17  *      REV#    DATE    NAME    DESCRIPTION                             *
18  *      1.00  96/04/24  CLH     First release                           *
19  *      1.01  96/06/12  CLH     Fixed bug of Media Change for Removable *
20  *                              Device, scan all LUN. Support Pre2.0.10 *
21  *      1.02  96/06/18  CLH     Fixed bug of Command timeout ...        *
22  *      1.03  96/09/25  KG      Added tmscsim_proc_info()               *
23  *      1.04  96/10/11  CLH     Updating for support KV 2.0.x           *
24  *      1.05  96/10/18  KG      Fixed bug in DC390_abort(null ptr deref)*
25  *      1.06  96/10/25  KG      Fixed module support                    *
26  *      1.07  96/11/09  KG      Fixed tmscsim_proc_info()               *
27  *      1.08  96/11/18  KG      Fixed null ptr in DC390_Disconnect()    *
28  *      1.09  96/11/30  KG      Added register the allocated IO space   *
29  *      1.10  96/12/05  CLH     Modified tmscsim_proc_info(), and reset *
30  *                              pending interrupt in DC390_detect()     *
31  *      1.11  97/02/05  KG/CLH  Fixeds problem with partitions greater  *
32  *                              than 1GB                                *
33  *      1.12  98/02/15  MJ      Rewritten PCI probing                   *
34  *      1.13  98/04/08  KG      Support for non DC390, __initfunc decls,*
35  *                              changed max devs from 10 to 16          *
36  *      1.14a 98/05/05  KG      Dynamic DCB allocation, add-single-dev  *
37  *                              for LUNs if LUN_SCAN (BIOS) not set     *
38  *                              runtime config using /proc interface    *
39  *      1.14b 98/05/06  KG      eliminated cli (); sti (); spinlocks    *
40  *      1.14c 98/05/07  KG      2.0.x compatibility                     *
41  *      1.20a 98/05/07  KG      changed names of funcs to be consistent *
42  *                              DC390_ (entry points), dc390_ (internal)*
43  *                              reworked locking                        *
44  *      1.20b 98/05/12  KG      bugs: version, kfree, _ctmp             *
45  *                              debug output                            *
46  *      1.20c 98/05/12  KG      bugs: kfree, parsing, EEpromDefaults    *
47  *      1.20d 98/05/14  KG      bugs: list linkage, clear flag after    *
48  *                              reset on startup, code cleanup          *
49  *      1.20e 98/05/15  KG      spinlock comments, name space cleanup   *
50  *                              pLastDCB now part of ACB structure      *
51  *                              added stats, timeout for 2.1, TagQ bug  *
52  *                              RESET and INQUIRY interface commands    *
53  *      1.20f 98/05/18  KG      spinlocks fixes, max_lun fix, free DCBs *
54  *                              for missing LUNs, pending int           *
55  *      1.20g 98/05/19  KG      Clean up: Avoid short                   *
56  *      1.20h 98/05/21  KG      Remove AdaptSCSIID, max_lun ...         *
57  *      1.20i 98/05/21  KG      Aiiie: Bug with TagQMask                *
58  *      1.20j 98/05/24  KG      Handle STAT_BUSY, handle pACB->pLinkDCB *
59  *                              == 0 in remove_dev and DoingSRB_Done    *
60  *      1.20k 98/05/25  KG      DMA_INT (experimental)                  *
61  *      1.20l 98/05/27  KG      remove DMA_INT; DMA_IDLE cmds added;    *
62  *      1.20m 98/06/10  KG      glitch configurable; made some global   *
63  *                              vars part of ACB; use DC390_readX       *
64  *      1.20n 98/06/11  KG      startup params                          *
65  *      1.20o 98/06/15  KG      added TagMaxNum to boot/module params   *
66  *                              Device Nr -> Idx, TagMaxNum power of 2  *
67  *      1.20p 98/06/17  KG      Docu updates. Reset depends on settings *
68  *                              pci_set_master added; 2.0.xx: pcibios_* *
69  *                              used instead of MechNum things ...      *
70  *      1.20q 98/06/23  KG      Changed defaults. Added debug code for  *
71  *                              removable media and fixed it. TagMaxNum *
72  *                              fixed for DC390. Locking: ACB, DRV for  *
73  *                              better IRQ sharing. Spelling: Queueing  *
74  *                              Parsing and glitch_cfg changes. Display *
75  *                              real SyncSpeed value. Made DisConn      *
76  *                              functional (!)                          *
77  *      1.20r 98/06/30  KG      Debug macros, allow disabling DsCn, set *
78  *                              BIT4 in CtrlR4, EN_PAGE_INT, 2.0 module *
79  *                              param -1 fixed.                         *
80  *      1.20s 98/08/20  KG      Debug info on abort(), try to check PCI,*
81  *                              phys_to_bus instead of phys_to_virt,    *
82  *                              fixed sel. process, fixed locking,      *
83  *                              added MODULE_XXX infos, changed IRQ     *
84  *                              request flags, disable DMA_INT          *
85  *      1.20t 98/09/07  KG      TagQ report fixed; Write Erase DMA Stat;*
86  *                              initfunc -> __init; better abort;       *
87  *                              Timeout for XFER_DONE & BLAST_COMPLETE; *
88  *                              Allow up to 33 commands being processed *
89  *      2.0a  98/10/14  KG      Max Cmnds back to 17. DMA_Stat clearing *
90  *                              all flags. Clear within while() loops   *
91  *                              in DataIn_0/Out_0. Null ptr in dumpinfo *
92  *                              for pSRB==0. Better locking during init.*
93  *                              bios_param() now respects part. table.  *
94  *      2.0b  98/10/24  KG      Docu fixes. Timeout Msg in DMA Blast.   *
95  *                              Disallow illegal idx in INQUIRY/REMOVE  *
96  *      2.0c  98/11/19  KG      Cleaned up detect/init for SMP boxes,   *
97  *                              Write Erase DMA (1.20t) caused problems *
98  *      2.0d  98/12/25  KG      Christmas release ;-) Message handling  *
99  *                              completely reworked. Handle target ini- *
100  *                              tiated SDTR correctly.                  *
101  *      2.0d1 99/01/25  KG      Try to handle RESTORE_PTR               *
102  *      2.0d2 99/02/08  KG      Check for failure of kmalloc, correct   *
103  *                              inclusion of scsicam.h, DelayReset      *
104  *      2.0d3 99/05/31  KG      DRIVER_OK -> DID_OK, DID_NO_CONNECT,    *
105  *                              detect Target mode and warn.            *
106  *                              pcmd->result handling cleaned up.       *
107  *      2.0d4 99/06/01  KG      Cleaned selection process. Found bug    *
108  *                              which prevented more than 16 tags. Now: *
109  *                              24. SDTR cleanup. Cleaner multi-LUN     *
110  *                              handling. Don't modify ControlRegs/FIFO *
111  *                              when connected.                         *
112  *      2.0d5 99/06/01  KG      Clear DevID, Fix INQUIRY after cfg chg. *
113  *      2.0d6 99/06/02  KG      Added ADD special command to allow cfg. *
114  *                              before detection. Reset SYNC_NEGO_DONE  *
115  *                              after a bus reset.                      *
116  *      2.0d7 99/06/03  KG      Fixed bugs wrt add,remove commands      *
117  *      2.0d8 99/06/04  KG      Removed copying of cmnd into CmdBlock.  *
118  *                              Fixed Oops in _release().               *
119  *      2.0d9 99/06/06  KG      Also tag queue INQUIRY, T_U_R, ...      *
120  *                              Allow arb. no. of Tagged Cmnds. Max 32  *
121  *      2.0d1099/06/20  KG      TagMaxNo changes now honoured! Queueing *
122  *                              clearified (renamed ..) TagMask handling*
123  *                              cleaned.                                *
124  *      2.0d1199/06/28  KG      cmd->result now identical to 2.0d2      *
125  *      2.0d1299/07/04  KG      Changed order of processing in IRQ      *
126  *      2.0d1399/07/05  KG      Don't update DCB fields if removed      *
127  *      2.0d1499/07/05  KG      remove_dev: Move kfree() to the end     *
128  *      2.0d1599/07/12  KG      use_new_eh_code: 0, ULONG -> UINT where *
129  *                              appropriate                             *
130  *      2.0d1699/07/13  KG      Reenable StartSCSI interrupt, Retry msg *
131  *      2.0d1799/07/15  KG      Remove debug msg. Disable recfg. when   *
132  *                              there are queued cmnds                  *
133  *      2.0d1899/07/18  KG      Selection timeout: Don't requeue        *
134  *      2.0d1999/07/18  KG      Abort: Only call scsi_done if dequeued  *
135  *      2.0d2099/07/19  KG      Rst_Detect: DoingSRB_Done               *
136  *      2.0d2199/08/15  KG      dev_id for request/free_irq, cmnd[0] for*
137  *                              RETRY, SRBdone does DID_ABORT for the   *
138  *                              cmd passed by DC390_reset()             *
139  *      2.0d2299/08/25  KG      dev_id fixed. can_queue: 42             *
140  *      2.0d2399/08/25  KG      Removed some debugging code. dev_id     *
141  *                              now is set to pACB. Use u8,u16,u32.     *
142  *      2.0d2499/11/14  KG      Unreg. I/O if failed IRQ alloc. Call    *
143  *                              done () w/ DID_BAD_TARGET in case of    *
144  *                              missing DCB. We are old EH!!            *
145  *      2.0d2500/01/15  KG      2.3.3x compat from Andreas Schultz      *
146  *                              set unique_id. Disable RETRY message.   *
147  *      2.0d2600/01/29  KG      Go to new EH.                           *
148  *      2.0d2700/01/31  KG      ... but maintain 2.0 compat.            *
149  *                              and fix DCB freeing                     *
150  *      2.0d2800/02/14  KG      Queue statistics fixed, dump special cmd*
151  *                              Waiting_Timer for failed StartSCSI      *
152  *                              New EH: Don't return cmnds to ML on RST *
153  *                              Use old EH (don't have new EH fns yet)  *
154  *                              Reset: Unlock, but refuse to queue      *
155  *                              2.3 __setup function                    *
156  *      2.0e  00/05/22  KG      Return residual for 2.3                 *
157  *      2.0e1 00/05/25  KG      Compile fixes for 2.3.99                *
158  *      2.0e2 00/05/27  KG      Jeff Garzik's pci_enable_device()       *
159  *      2.0e3 00/09/29  KG      Some 2.4 changes. Don't try Sync Nego   *
160  *                              before INQUIRY has reported ability.    *
161  *                              Recognise INQUIRY as scanning command.  *
162  *      2.0e4 00/10/13  KG      Allow compilation into 2.4 kernel       *
163  *      2.0e5 00/11/17  KG      Store Inq.flags in DCB                  *
164  *      2.0e6 00/11/22  KG      2.4 init function (Thx to O.Schumann)   *
165  *                              2.4 PCI device table (Thx to A.Richter) *
166  *      2.0e7 00/11/28  KG      Allow overriding of BIOS settings       *
167  *      2.0f  00/12/20  KG      Handle failed INQUIRYs during scan      *
168  *      2.1a  03/11/29  GL, KG  Initial fixing for 2.6. Convert to      *
169  *                              use the current PCI-mapping API, update *
170  *                              command-queuing.                        *
171  *      2.1b  04/04/13  GL      Fix for 64-bit platforms                *
172  *      2.1b1 04/01/31  GL      (applied 05.04) Remove internal         *
173  *                              command-queuing.                        *
174  *      2.1b2 04/02/01  CH      (applied 05.04) Fix error-handling      *
175  *      2.1c  04/05/23  GL      Update to use the new pci_driver API,   *
176  *                              some scsi EH updates, more cleanup.     *
177  *      2.1d  04/05/27  GL      Moved setting of scan_devices to        *
178  *                              slave_alloc/_configure/_destroy, as     *
179  *                              suggested by CH.                        *
180  ***********************************************************************/
181
182 /* DEBUG options */
183 //#define DC390_DEBUG0
184 //#define DC390_DEBUG1
185 //#define DC390_DCBDEBUG
186 //#define DC390_PARSEDEBUG
187 //#define DC390_REMOVABLEDEBUG
188 //#define DC390_LOCKDEBUG
189
190 //#define NOP do{}while(0)
191 #define C_NOP
192
193 /* Debug definitions */
194 #ifdef DC390_DEBUG0
195 # define DEBUG0(x) x
196 #else
197 # define DEBUG0(x) C_NOP
198 #endif
199 #ifdef DC390_DEBUG1
200 # define DEBUG1(x) x
201 #else
202 # define DEBUG1(x) C_NOP
203 #endif
204 #ifdef DC390_DCBDEBUG
205 # define DCBDEBUG(x) x
206 #else
207 # define DCBDEBUG(x) C_NOP
208 #endif
209 #ifdef DC390_PARSEDEBUG
210 # define PARSEDEBUG(x) x
211 #else
212 # define PARSEDEBUG(x) C_NOP
213 #endif
214 #ifdef DC390_REMOVABLEDEBUG
215 # define REMOVABLEDEBUG(x) x
216 #else
217 # define REMOVABLEDEBUG(x) C_NOP
218 #endif
219 #define DCBDEBUG1(x) C_NOP
220
221 #include <linux/config.h>
222 #include <linux/module.h>
223 #include <linux/delay.h>
224 #include <linux/signal.h>
225 #include <linux/sched.h>
226 #include <linux/errno.h>
227 #include <linux/kernel.h>
228 #include <linux/ioport.h>
229 #include <linux/pci.h>
230 #include <linux/proc_fs.h>
231 #include <linux/string.h>
232 #include <linux/mm.h>
233 #include <linux/blkdev.h>
234 #include <linux/timer.h>
235 #include <linux/interrupt.h>
236 #include <linux/init.h>
237 #include <linux/spinlock.h>
238 #include <asm/io.h>
239
240 #include <scsi/scsi.h>
241 #include <scsi/scsi_cmnd.h>
242 #include <scsi/scsi_device.h>
243 #include <scsi/scsi_host.h>
244 #include <scsi/scsicam.h>
245 #include <scsi/scsi_tcq.h>
246
247
248 #define DC390_BANNER "Tekram DC390/AM53C974"
249 #define DC390_VERSION "2.1d 2004-05-27"
250
251 #define PCI_DEVICE_ID_AMD53C974         PCI_DEVICE_ID_AMD_SCSI
252
253 #include "tmscsim.h"
254
255
256 static void dc390_DataOut_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
257 static void dc390_DataIn_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
258 static void dc390_Command_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
259 static void dc390_Status_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
260 static void dc390_MsgOut_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
261 static void dc390_MsgIn_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
262 static void dc390_DataOutPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
263 static void dc390_DataInPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
264 static void dc390_CommandPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
265 static void dc390_StatusPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
266 static void dc390_MsgOutPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
267 static void dc390_MsgInPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
268 static void dc390_Nop_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
269 static void dc390_Nop_1( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus);
270
271 static void dc390_SetXferRate( struct dc390_acb* pACB, struct dc390_dcb* pDCB );
272 static void dc390_Disconnect( struct dc390_acb* pACB );
273 static void dc390_Reselect( struct dc390_acb* pACB );
274 static void dc390_SRBdone( struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB );
275 static void dc390_ScsiRstDetect( struct dc390_acb* pACB );
276 static void dc390_EnableMsgOut_Abort(struct dc390_acb*, struct dc390_srb*);
277 static void dc390_dumpinfo(struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB);
278 static void dc390_ResetDevParam(struct dc390_acb* pACB);
279
280 static u32      dc390_laststatus = 0;
281 static u8       dc390_adapterCnt = 0;
282
283 /* Startup values, to be overriden on the commandline */
284 static int tmscsim[] = {-2, -2, -2, -2, -2, -2};
285
286 module_param_array(tmscsim, int, NULL, 0);
287 MODULE_PARM_DESC(tmscsim, "Host SCSI ID, Speed (0=10MHz), Device Flags, Adapter Flags, Max Tags (log2(tags)-1), DelayReset (s)");
288 MODULE_AUTHOR("C.L. Huang / Kurt Garloff");
289 MODULE_DESCRIPTION("SCSI host adapter driver for Tekram DC390 and other AMD53C974A based PCI SCSI adapters");
290 MODULE_LICENSE("GPL");
291 MODULE_SUPPORTED_DEVICE("sd,sr,sg,st");
292
293 static void *dc390_phase0[]={
294        dc390_DataOut_0,
295        dc390_DataIn_0,
296        dc390_Command_0,
297        dc390_Status_0,
298        dc390_Nop_0,
299        dc390_Nop_0,
300        dc390_MsgOut_0,
301        dc390_MsgIn_0,
302        dc390_Nop_1
303        };
304
305 static void *dc390_phase1[]={
306        dc390_DataOutPhase,
307        dc390_DataInPhase,
308        dc390_CommandPhase,
309        dc390_StatusPhase,
310        dc390_Nop_0,
311        dc390_Nop_0,
312        dc390_MsgOutPhase,
313        dc390_MsgInPhase,
314        dc390_Nop_1
315        };
316
317 #ifdef DC390_DEBUG1
318 static char* dc390_p0_str[] = {
319        "dc390_DataOut_0",
320        "dc390_DataIn_0",
321        "dc390_Command_0",
322        "dc390_Status_0",
323        "dc390_Nop_0",
324        "dc390_Nop_0",
325        "dc390_MsgOut_0",
326        "dc390_MsgIn_0",
327        "dc390_Nop_1"
328        };
329      
330 static char* dc390_p1_str[] = {
331        "dc390_DataOutPhase",
332        "dc390_DataInPhase",
333        "dc390_CommandPhase",
334        "dc390_StatusPhase",
335        "dc390_Nop_0",
336        "dc390_Nop_0",
337        "dc390_MsgOutPhase",
338        "dc390_MsgInPhase",
339        "dc390_Nop_1"
340        };
341 #endif   
342
343 static u8  dc390_eepromBuf[MAX_ADAPTER_NUM][EE_LEN];
344 static u8  dc390_clock_period1[] = {4, 5, 6, 7, 8, 10, 13, 20};
345 static u8  dc390_clock_speed[] = {100,80,67,57,50, 40, 31, 20};
346
347 /***********************************************************************
348  * Functions for the management of the internal structures 
349  * (DCBs, SRBs, Queueing)
350  *
351  **********************************************************************/
352 static struct dc390_dcb __inline__ *dc390_findDCB ( struct dc390_acb* pACB, u8 id, u8 lun)
353 {
354    struct dc390_dcb* pDCB = pACB->pLinkDCB; if (!pDCB) return NULL;
355    while (pDCB->TargetID != id || pDCB->TargetLUN != lun)
356      {
357         pDCB = pDCB->pNextDCB;
358         if (pDCB == pACB->pLinkDCB)
359              return NULL;
360      }
361    DCBDEBUG1( printk (KERN_DEBUG "DCB %p (%02x,%02x) found.\n", \
362                       pDCB, pDCB->TargetID, pDCB->TargetLUN));
363    return pDCB;
364 }
365
366 /* Insert SRB oin top of free list */
367 static __inline__ void dc390_Free_insert (struct dc390_acb* pACB, struct dc390_srb* pSRB)
368 {
369     DEBUG0(printk ("DC390: Free SRB %p\n", pSRB));
370     pSRB->pNextSRB = pACB->pFreeSRB;
371     pACB->pFreeSRB = pSRB;
372 }
373
374 static __inline__ void dc390_Going_append (struct dc390_dcb* pDCB, struct dc390_srb* pSRB)
375 {
376     pDCB->GoingSRBCnt++;
377     DEBUG0(printk("DC390: Append SRB %p to Going\n", pSRB));
378     /* Append to the list of Going commands */
379     if( pDCB->pGoingSRB )
380         pDCB->pGoingLast->pNextSRB = pSRB;
381     else
382         pDCB->pGoingSRB = pSRB;
383
384     pDCB->pGoingLast = pSRB;
385     /* No next one in sent list */
386     pSRB->pNextSRB = NULL;
387 }
388
389 static __inline__ void dc390_Going_remove (struct dc390_dcb* pDCB, struct dc390_srb* pSRB)
390 {
391         DEBUG0(printk("DC390: Remove SRB %p from Going\n", pSRB));
392    if (pSRB == pDCB->pGoingSRB)
393         pDCB->pGoingSRB = pSRB->pNextSRB;
394    else
395      {
396         struct dc390_srb* psrb = pDCB->pGoingSRB;
397         while (psrb && psrb->pNextSRB != pSRB)
398           psrb = psrb->pNextSRB;
399         if (!psrb) 
400           { printk (KERN_ERR "DC390: Remove non-ex. SRB %p from Going!\n", pSRB); return; }
401         psrb->pNextSRB = pSRB->pNextSRB;
402         if (pSRB == pDCB->pGoingLast)
403           pDCB->pGoingLast = psrb;
404      }
405    pDCB->GoingSRBCnt--;
406 }
407
408 static struct scatterlist* dc390_sg_build_single(struct scatterlist *sg, void *addr, unsigned int length)
409 {
410         memset(sg, 0, sizeof(struct scatterlist));
411         sg->page        = virt_to_page(addr);
412         sg->length      = length;
413         sg->offset      = (unsigned long)addr & ~PAGE_MASK;
414         return sg;
415 }
416
417 /* Create pci mapping */
418 static int dc390_pci_map (struct dc390_srb* pSRB)
419 {
420         int error = 0;
421         struct scsi_cmnd *pcmd = pSRB->pcmd;
422         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
423         dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp));
424
425         /* Map sense buffer */
426         if (pSRB->SRBFlag & AUTO_REQSENSE) {
427                 pSRB->pSegmentList      = dc390_sg_build_single(&pSRB->Segmentx, pcmd->sense_buffer, sizeof(pcmd->sense_buffer));
428                 pSRB->SGcount           = pci_map_sg(pdev, pSRB->pSegmentList, 1,
429                                                      DMA_FROM_DEVICE);
430                 cmdp->saved_dma_handle  = sg_dma_address(pSRB->pSegmentList);
431
432                 /* TODO: error handling */
433                 if (pSRB->SGcount != 1)
434                         error = 1;
435                 DEBUG1(printk("%s(): Mapped sense buffer %p at %x\n", __FUNCTION__, pcmd->sense_buffer, cmdp->saved_dma_handle));
436         /* Map SG list */
437         } else if (pcmd->use_sg) {
438                 pSRB->pSegmentList      = (struct scatterlist *) pcmd->request_buffer;
439                 pSRB->SGcount           = pci_map_sg(pdev, pSRB->pSegmentList, pcmd->use_sg,
440                                                      pcmd->sc_data_direction);
441                 /* TODO: error handling */
442                 if (!pSRB->SGcount)
443                         error = 1;
444                 DEBUG1(printk("%s(): Mapped SG %p with %d (%d) elements\n",\
445                               __FUNCTION__, pcmd->request_buffer, pSRB->SGcount, pcmd->use_sg));
446         /* Map single segment */
447         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
448                 pSRB->pSegmentList      = dc390_sg_build_single(&pSRB->Segmentx, pcmd->request_buffer, pcmd->request_bufflen);
449                 pSRB->SGcount           = pci_map_sg(pdev, pSRB->pSegmentList, 1,
450                                                      pcmd->sc_data_direction);
451                 cmdp->saved_dma_handle  = sg_dma_address(pSRB->pSegmentList);
452
453                 /* TODO: error handling */
454                 if (pSRB->SGcount != 1)
455                         error = 1;
456                 DEBUG1(printk("%s(): Mapped request buffer %p at %x\n", __FUNCTION__, pcmd->request_buffer, cmdp->saved_dma_handle));
457         /* No mapping !? */     
458         } else
459                 pSRB->SGcount = 0;
460
461         return error;
462 }
463
464 /* Remove pci mapping */
465 static void dc390_pci_unmap (struct dc390_srb* pSRB)
466 {
467         struct scsi_cmnd *pcmd = pSRB->pcmd;
468         struct pci_dev *pdev = pSRB->pSRBDCB->pDCBACB->pdev;
469         DEBUG1(dc390_cmd_scp_t* cmdp = ((dc390_cmd_scp_t*)(&pcmd->SCp)));
470
471         if (pSRB->SRBFlag) {
472                 pci_unmap_sg(pdev, &pSRB->Segmentx, 1, DMA_FROM_DEVICE);
473                 DEBUG1(printk("%s(): Unmapped sense buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
474         } else if (pcmd->use_sg) {
475                 pci_unmap_sg(pdev, pcmd->request_buffer, pcmd->use_sg, pcmd->sc_data_direction);
476                 DEBUG1(printk("%s(): Unmapped SG at %p with %d elements\n", __FUNCTION__, pcmd->request_buffer, pcmd->use_sg));
477         } else if (pcmd->request_buffer && pcmd->request_bufflen) {
478                 pci_unmap_sg(pdev, &pSRB->Segmentx, 1, pcmd->sc_data_direction);
479                 DEBUG1(printk("%s(): Unmapped request buffer at %x\n", __FUNCTION__, cmdp->saved_dma_handle));
480         }
481 }
482
483 static void __inline__
484 dc390_freetag (struct dc390_dcb* pDCB, struct dc390_srb* pSRB)
485 {
486         if (pSRB->TagNumber != SCSI_NO_TAG) {
487                 pDCB->TagMask &= ~(1 << pSRB->TagNumber);   /* free tag mask */
488                 pSRB->TagNumber = SCSI_NO_TAG;
489         }
490 }
491
492
493 static int
494 dc390_StartSCSI( struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB )
495 {
496     struct scsi_cmnd *scmd = pSRB->pcmd;
497     struct scsi_device *sdev = scmd->device;
498     u8 cmd, disc_allowed, try_sync_nego;
499     char tag[2];
500
501     pSRB->ScsiPhase = SCSI_NOP0;
502
503     if (pACB->Connected)
504     {
505         // Should not happen normally
506         printk (KERN_WARNING "DC390: Can't select when connected! (%08x,%02x)\n",
507                 pSRB->SRBState, pSRB->SRBFlag);
508         pSRB->SRBState = SRB_READY;
509         pACB->SelConn++;
510         return 1;
511     }
512     if (time_before (jiffies, pACB->pScsiHost->last_reset))
513     {
514         DEBUG0(printk ("DC390: We were just reset and don't accept commands yet!\n"));
515         return 1;
516     }
517     /* KG: Moved pci mapping here */
518     dc390_pci_map(pSRB);
519     /* TODO: error handling */
520     DC390_write8 (Scsi_Dest_ID, pDCB->TargetID);
521     DC390_write8 (Sync_Period, pDCB->SyncPeriod);
522     DC390_write8 (Sync_Offset, pDCB->SyncOffset);
523     DC390_write8 (CtrlReg1, pDCB->CtrlR1);
524     DC390_write8 (CtrlReg3, pDCB->CtrlR3);
525     DC390_write8 (CtrlReg4, pDCB->CtrlR4);
526     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);             /* Flush FIFO */
527     DEBUG1(printk (KERN_INFO "DC390: Start SCSI command: %02x (Sync:%02x)\n",\
528             scmd->cmnd[0], pDCB->SyncMode));
529
530     /* Don't disconnect on AUTO_REQSENSE, cause it might be an
531      * Contingent Allegiance Condition (6.6), where no tags should be used.
532      * All other have to be allowed to disconnect to prevent Incorrect 
533      * Initiator Connection (6.8.2/6.5.2) */
534     /* Changed KG, 99/06/06 */
535     if (! (pSRB->SRBFlag & AUTO_REQSENSE))
536         disc_allowed = pDCB->DevMode & EN_DISCONNECT_;
537     else
538         disc_allowed = 0;
539
540     if ((pDCB->SyncMode & SYNC_ENABLE) && pDCB->TargetLUN == 0 && sdev->sdtr &&
541         (((scmd->cmnd[0] == REQUEST_SENSE || (pSRB->SRBFlag & AUTO_REQSENSE)) &&
542           !(pDCB->SyncMode & SYNC_NEGO_DONE)) || scmd->cmnd[0] == INQUIRY))
543       try_sync_nego = 1;
544     else
545       try_sync_nego = 0;
546
547     pSRB->MsgCnt = 0;
548     cmd = SEL_W_ATN;
549     DC390_write8 (ScsiFifo, IDENTIFY(disc_allowed, pDCB->TargetLUN));
550     /* Change 99/05/31: Don't use tags when not disconnecting (BUSY) */
551     if ((pDCB->SyncMode & EN_TAG_QUEUEING) && disc_allowed && scsi_populate_tag_msg(scmd, tag)) {
552         DC390_write8(ScsiFifo, tag[0]);
553         pDCB->TagMask |= 1 << tag[1];
554         pSRB->TagNumber = tag[1];
555         DC390_write8(ScsiFifo, tag[1]);
556         DEBUG1(printk(KERN_INFO "DC390: Select w/DisCn for Cmd %li (SRB %p), block tag %02x\n", scmd->pid, pSRB, tag[1]));
557         cmd = SEL_W_ATN3;
558     } else {
559         /* No TagQ */
560 //no_tag:
561         DEBUG1(printk(KERN_INFO "DC390: Select w%s/DisCn for Cmd %li (SRB %p), No TagQ\n", disc_allowed ? "" : "o", scmd->pid, pSRB));
562     }
563
564     pSRB->SRBState = SRB_START_;
565
566     if (try_sync_nego)
567       { 
568         u8 Sync_Off = pDCB->SyncOffset;
569         DEBUG0(printk (KERN_INFO "DC390: NEW Sync Nego code triggered (%i %i)\n", pDCB->TargetID, pDCB->TargetLUN));
570         pSRB->MsgOutBuf[0] = EXTENDED_MESSAGE;
571         pSRB->MsgOutBuf[1] = 3;
572         pSRB->MsgOutBuf[2] = EXTENDED_SDTR;
573         pSRB->MsgOutBuf[3] = pDCB->NegoPeriod;
574         if (!(Sync_Off & 0x0f)) Sync_Off = SYNC_NEGO_OFFSET;
575         pSRB->MsgOutBuf[4] = Sync_Off;
576         pSRB->MsgCnt = 5;
577         //pSRB->SRBState = SRB_MSGOUT_;
578         pSRB->SRBState |= DO_SYNC_NEGO;
579         cmd = SEL_W_ATN_STOP;
580       }
581
582     /* Command is written in CommandPhase, if SEL_W_ATN_STOP ... */
583     if (cmd != SEL_W_ATN_STOP)
584       {
585         if( pSRB->SRBFlag & AUTO_REQSENSE )
586           {
587             DC390_write8 (ScsiFifo, REQUEST_SENSE);
588             DC390_write8 (ScsiFifo, pDCB->TargetLUN << 5);
589             DC390_write8 (ScsiFifo, 0);
590             DC390_write8 (ScsiFifo, 0);
591             DC390_write8 (ScsiFifo, sizeof(scmd->sense_buffer));
592             DC390_write8 (ScsiFifo, 0);
593             DEBUG1(printk (KERN_DEBUG "DC390: AutoReqSense !\n"));
594           }
595         else    /* write cmnd to bus */ 
596           {
597             u8 *ptr; u8 i;
598             ptr = (u8 *)scmd->cmnd;
599             for (i = 0; i < scmd->cmd_len; i++)
600               DC390_write8 (ScsiFifo, *(ptr++));
601           }
602       }
603     DEBUG0(if (pACB->pActiveDCB)        \
604            printk (KERN_WARNING "DC390: ActiveDCB != 0\n"));
605     DEBUG0(if (pDCB->pActiveSRB)        \
606            printk (KERN_WARNING "DC390: ActiveSRB != 0\n"));
607     //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
608     if (DC390_read8 (Scsi_Status) & INTERRUPT)
609     {
610         dc390_freetag (pDCB, pSRB);
611         DEBUG0(printk ("DC390: Interrupt during Start SCSI (pid %li, target %02i-%02i)\n",
612                 scmd->pid, scmd->device->id, scmd->device->lun));
613         pSRB->SRBState = SRB_READY;
614         //DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
615         pACB->SelLost++;
616         return 1;
617     }
618     DC390_write8 (ScsiCmd, cmd);
619     pACB->pActiveDCB = pDCB;
620     pDCB->pActiveSRB = pSRB;
621     pACB->Connected = 1;
622     pSRB->ScsiPhase = SCSI_NOP1;
623     return 0;
624 }
625
626 //#define DMA_INT EN_DMA_INT /*| EN_PAGE_INT*/
627 #define DMA_INT 0
628
629 #if DMA_INT
630 /* This is similar to AM53C974.c ... */
631 static u8 
632 dc390_dma_intr (struct dc390_acb* pACB)
633 {
634   struct dc390_srb* pSRB;
635   u8 dstate;
636   DEBUG0(u16 pstate; struct pci_dev *pdev = pACB->pdev);
637   
638   DEBUG0(pci_read_config_word(pdev, PCI_STATUS, &pstate));
639   DEBUG0(if (pstate & (PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY))\
640         { printk(KERN_WARNING "DC390: PCI state = %04x!\n", pstate); \
641           pci_write_config_word(pdev, PCI_STATUS, (PCI_STATUS_SIG_SYSTEM_ERROR | PCI_STATUS_DETECTED_PARITY));});
642
643   dstate = DC390_read8 (DMA_Status); 
644
645   if (! pACB->pActiveDCB || ! pACB->pActiveDCB->pActiveSRB) return dstate;
646   else pSRB  = pACB->pActiveDCB->pActiveSRB;
647   
648   if (dstate & (DMA_XFER_ABORT | DMA_XFER_ERROR | POWER_DOWN | PCI_MS_ABORT))
649     {
650         printk (KERN_ERR "DC390: DMA error (%02x)!\n", dstate);
651         return dstate;
652     }
653   if (dstate & DMA_XFER_DONE)
654     {
655         u32 residual, xferCnt; int ctr = 6000000;
656         if (! (DC390_read8 (DMA_Cmd) & READ_DIRECTION))
657           {
658             do
659               {
660                 DEBUG1(printk (KERN_DEBUG "DC390: read residual bytes ... \n"));
661                 dstate = DC390_read8 (DMA_Status);
662                 residual = DC390_read8 (CtcReg_Low) | DC390_read8 (CtcReg_Mid) << 8 |
663                   DC390_read8 (CtcReg_High) << 16;
664                 residual += DC390_read8 (Current_Fifo) & 0x1f;
665               } while (residual && ! (dstate & SCSI_INTERRUPT) && --ctr);
666             if (!ctr) printk (KERN_CRIT "DC390: dma_intr: DMA aborted unfinished: %06x bytes remain!!\n", DC390_read32 (DMA_Wk_ByteCntr));
667             /* residual =  ... */
668           }
669         else
670             residual = 0;
671         
672         /* ??? */
673         
674         xferCnt = pSRB->SGToBeXferLen - residual;
675         pSRB->SGBusAddr += xferCnt;
676         pSRB->TotalXferredLen += xferCnt;
677         pSRB->SGToBeXferLen = residual;
678 # ifdef DC390_DEBUG0
679         printk (KERN_INFO "DC390: DMA: residual = %i, xfer = %i\n", 
680                 (unsigned int)residual, (unsigned int)xferCnt);
681 # endif
682         
683         DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
684     }
685   dc390_laststatus &= ~0xff000000; dc390_laststatus |= dstate << 24;
686   return dstate;
687 }
688 #endif
689
690
691 static void __inline__
692 dc390_InvalidCmd(struct dc390_acb* pACB)
693 {
694         if (pACB->pActiveDCB->pActiveSRB->SRBState & (SRB_START_ | SRB_MSGOUT))
695                 DC390_write8(ScsiCmd, CLEAR_FIFO_CMD);
696 }
697
698
699 static irqreturn_t __inline__
700 DC390_Interrupt(int irq, void *dev_id, struct pt_regs *regs)
701 {
702     struct dc390_acb *pACB = (struct dc390_acb*)dev_id;
703     struct dc390_dcb *pDCB;
704     struct dc390_srb *pSRB;
705     u8  sstatus=0;
706     u8  phase;
707     void   (*stateV)( struct dc390_acb*, struct dc390_srb*, u8 *);
708     u8  istate, istatus;
709 #if DMA_INT
710     u8  dstatus;
711 #endif
712
713     sstatus = DC390_read8 (Scsi_Status);
714     if( !(sstatus & INTERRUPT) )
715         return IRQ_NONE;
716
717     DEBUG1(printk (KERN_DEBUG "sstatus=%02x,", sstatus));
718
719 #if DMA_INT
720     spin_lock_irq(pACB->pScsiHost->host_lock);
721     dstatus = dc390_dma_intr (pACB);
722     spin_unlock_irq(pACB->pScsiHost->host_lock);
723
724     DEBUG1(printk (KERN_DEBUG "dstatus=%02x,", dstatus));
725     if (! (dstatus & SCSI_INTERRUPT))
726       {
727         DEBUG0(printk (KERN_WARNING "DC390 Int w/o SCSI actions (only DMA?)\n"));
728         return IRQ_NONE;
729       }
730 #else
731     //DC390_write32 (DMA_ScsiBusCtrl, WRT_ERASE_DMA_STAT | EN_INT_ON_PCI_ABORT);
732     //dstatus = DC390_read8 (DMA_Status);
733     //DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
734 #endif
735
736     spin_lock_irq(pACB->pScsiHost->host_lock);
737
738     istate = DC390_read8 (Intern_State);
739     istatus = DC390_read8 (INT_Status); /* This clears Scsi_Status, Intern_State and INT_Status ! */
740
741     DEBUG1(printk (KERN_INFO "Istatus(Res,Inv,Dis,Serv,Succ,ReS,SelA,Sel)=%02x,",istatus));
742     dc390_laststatus &= ~0x00ffffff;
743     dc390_laststatus |= /* dstatus<<24 | */ sstatus<<16 | istate<<8 | istatus;
744
745     if (sstatus & ILLEGAL_OP_ERR)
746     {
747         printk ("DC390: Illegal Operation detected (%08x)!\n", dc390_laststatus);
748         dc390_dumpinfo (pACB, pACB->pActiveDCB, pACB->pActiveDCB->pActiveSRB);
749     }
750         
751     else if (istatus &  INVALID_CMD)
752     {
753         printk ("DC390: Invalid Command detected (%08x)!\n", dc390_laststatus);
754         dc390_InvalidCmd( pACB );
755         goto unlock;
756     }
757
758     if (istatus &  SCSI_RESET)
759     {
760         dc390_ScsiRstDetect( pACB );
761         goto unlock;
762     }
763
764     if (istatus &  DISCONNECTED)
765     {
766         dc390_Disconnect( pACB );
767         goto unlock;
768     }
769
770     if (istatus &  RESELECTED)
771     {
772         dc390_Reselect( pACB );
773         goto unlock;
774     }
775
776     else if (istatus & (SELECTED | SEL_ATTENTION))
777     {
778         printk (KERN_ERR "DC390: Target mode not supported!\n");
779         goto unlock;
780     }
781
782     if (istatus & (SUCCESSFUL_OP|SERVICE_REQUEST) )
783     {
784         pDCB = pACB->pActiveDCB;
785         if (!pDCB)
786         {
787                 printk (KERN_ERR "DC390: Suc. op/ Serv. req: pActiveDCB = 0!\n");
788                 goto unlock;
789         }
790         pSRB = pDCB->pActiveSRB;
791         if( pDCB->DCBFlag & ABORT_DEV_ )
792           dc390_EnableMsgOut_Abort (pACB, pSRB);
793
794         phase = pSRB->ScsiPhase;
795         DEBUG1(printk (KERN_INFO "DC390: [%i]%s(0) (%02x)\n", phase, dc390_p0_str[phase], sstatus));
796         stateV = (void *) dc390_phase0[phase];
797         ( *stateV )( pACB, pSRB, &sstatus );
798
799         pSRB->ScsiPhase = sstatus & 7;
800         phase = (u8) sstatus & 7;
801         DEBUG1(printk (KERN_INFO "DC390: [%i]%s(1) (%02x)\n", phase, dc390_p1_str[phase], sstatus));
802         stateV = (void *) dc390_phase1[phase];
803         ( *stateV )( pACB, pSRB, &sstatus );
804     }
805
806  unlock:
807     spin_unlock_irq(pACB->pScsiHost->host_lock);
808     return IRQ_HANDLED;
809 }
810
811 static irqreturn_t do_DC390_Interrupt( int irq, void *dev_id, struct pt_regs *regs)
812 {
813     irqreturn_t ret;
814     DEBUG1(printk (KERN_INFO "DC390: Irq (%i) caught: ", irq));
815     /* Locking is done in DC390_Interrupt */
816     ret = DC390_Interrupt(irq, dev_id, regs);
817     DEBUG1(printk (".. IRQ returned\n"));
818     return ret;
819 }
820
821 static void
822 dc390_DataOut_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
823 {
824     u8   sstatus;
825     struct scatterlist *psgl;
826     u32    ResidCnt, xferCnt;
827     u8   dstate = 0;
828
829     sstatus = *psstatus;
830
831     if( !(pSRB->SRBState & SRB_XFERPAD) )
832     {
833         if( sstatus & (PARITY_ERR | ILLEGAL_OP_ERR) )
834             pSRB->SRBStatus |= PARITY_ERROR;
835
836         if( sstatus & COUNT_2_ZERO )
837         {
838             unsigned long timeout = jiffies + HZ;
839
840             /* Function called from the ISR with the host_lock held and interrupts disabled */
841             if (pSRB->SGToBeXferLen)
842                 while (time_before(jiffies, timeout) && !((dstate = DC390_read8 (DMA_Status)) & DMA_XFER_DONE)) {
843                     spin_unlock_irq(pACB->pScsiHost->host_lock);
844                     udelay(50);
845                     spin_lock_irq(pACB->pScsiHost->host_lock);
846                 }
847             if (!time_before(jiffies, timeout))
848                 printk (KERN_CRIT "DC390: Deadlock in DataOut_0: DMA aborted unfinished: %06x bytes remain!!\n",
849                         DC390_read32 (DMA_Wk_ByteCntr));
850             dc390_laststatus &= ~0xff000000;
851             dc390_laststatus |= dstate << 24;
852             pSRB->TotalXferredLen += pSRB->SGToBeXferLen;
853             pSRB->SGIndex++;
854             if( pSRB->SGIndex < pSRB->SGcount )
855             {
856                 pSRB->pSegmentList++;
857                 psgl = pSRB->pSegmentList;
858
859                 pSRB->SGBusAddr = cpu_to_le32(pci_dma_lo32(sg_dma_address(psgl)));
860                 pSRB->SGToBeXferLen = cpu_to_le32(sg_dma_len(psgl));
861             }
862             else
863                 pSRB->SGToBeXferLen = 0;
864         }
865         else
866         {
867             ResidCnt  = (u32) DC390_read8 (Current_Fifo) & 0x1f;
868             ResidCnt |= (u32) DC390_read8 (CtcReg_High) << 16;
869             ResidCnt |= (u32) DC390_read8 (CtcReg_Mid) << 8; 
870             ResidCnt += (u32) DC390_read8 (CtcReg_Low);
871
872             xferCnt = pSRB->SGToBeXferLen - ResidCnt;
873             pSRB->SGBusAddr += xferCnt;
874             pSRB->TotalXferredLen += xferCnt;
875             pSRB->SGToBeXferLen = ResidCnt;
876         }
877     }
878     if ((*psstatus & 7) != SCSI_DATA_OUT)
879     {
880             DC390_write8 (DMA_Cmd, WRITE_DIRECTION+DMA_IDLE_CMD); /* | DMA_INT */
881             DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
882     }       
883 }
884
885 static void
886 dc390_DataIn_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
887 {
888     u8   sstatus, residual, bval;
889     struct scatterlist *psgl;
890     u32    ResidCnt, i;
891     unsigned long   xferCnt;
892     u8      *ptr;
893
894     sstatus = *psstatus;
895
896     if( !(pSRB->SRBState & SRB_XFERPAD) )
897     {
898         if( sstatus & (PARITY_ERR | ILLEGAL_OP_ERR))
899             pSRB->SRBStatus |= PARITY_ERROR;
900
901         if( sstatus & COUNT_2_ZERO )
902         {
903             int dstate = 0;
904             unsigned long timeout = jiffies + HZ;
905
906             /* Function called from the ISR with the host_lock held and interrupts disabled */
907             if (pSRB->SGToBeXferLen)
908                 while (time_before(jiffies, timeout) && !((dstate = DC390_read8 (DMA_Status)) & DMA_XFER_DONE)) {
909                     spin_unlock_irq(pACB->pScsiHost->host_lock);
910                     udelay(50);
911                     spin_lock_irq(pACB->pScsiHost->host_lock);
912                 }
913             if (!time_before(jiffies, timeout)) {
914                 printk (KERN_CRIT "DC390: Deadlock in DataIn_0: DMA aborted unfinished: %06x bytes remain!!\n",
915                         DC390_read32 (DMA_Wk_ByteCntr));
916                 printk (KERN_CRIT "DC390: DataIn_0: DMA State: %i\n", dstate);
917             }
918             dc390_laststatus &= ~0xff000000;
919             dc390_laststatus |= dstate << 24;
920             DEBUG1(ResidCnt = ((unsigned long) DC390_read8 (CtcReg_High) << 16) \
921                 + ((unsigned long) DC390_read8 (CtcReg_Mid) << 8)               \
922                 + ((unsigned long) DC390_read8 (CtcReg_Low)));
923             DEBUG1(printk (KERN_DEBUG "Count_2_Zero (ResidCnt=%i,ToBeXfer=%li),", ResidCnt, pSRB->SGToBeXferLen));
924
925             DC390_write8 (DMA_Cmd, READ_DIRECTION+DMA_IDLE_CMD); /* | DMA_INT */
926
927             pSRB->TotalXferredLen += pSRB->SGToBeXferLen;
928             pSRB->SGIndex++;
929             if( pSRB->SGIndex < pSRB->SGcount )
930             {
931                 pSRB->pSegmentList++;
932                 psgl = pSRB->pSegmentList;
933
934                 pSRB->SGBusAddr = cpu_to_le32(pci_dma_lo32(sg_dma_address(psgl)));
935                 pSRB->SGToBeXferLen = cpu_to_le32(sg_dma_len(psgl));
936             }
937             else
938                 pSRB->SGToBeXferLen = 0;
939         }
940         else    /* phase changed */
941         {
942             residual = 0;
943             bval = DC390_read8 (Current_Fifo);
944             while( bval & 0x1f )
945             {
946                 DEBUG1(printk (KERN_DEBUG "Check for residuals,"));
947                 if( (bval & 0x1f) == 1 )
948                 {
949                     for(i=0; i < 0x100; i++)
950                     {
951                         bval = DC390_read8 (Current_Fifo);
952                         if( !(bval & 0x1f) )
953                             goto din_1;
954                         else if( i == 0x0ff )
955                         {
956                             residual = 1;   /* ;1 residual byte */
957                             goto din_1;
958                         }
959                     }
960                 }
961                 else
962                     bval = DC390_read8 (Current_Fifo);
963             }
964 din_1:
965             DC390_write8 (DMA_Cmd, READ_DIRECTION+DMA_BLAST_CMD);
966             for (i = 0xa000; i; i--)
967             {
968                 bval = DC390_read8 (DMA_Status);
969                 if (bval & BLAST_COMPLETE)
970                     break;
971             }
972             /* It seems a DMA Blast abort isn't that bad ... */
973             if (!i) printk (KERN_ERR "DC390: DMA Blast aborted unfinished!\n");
974             //DC390_write8 (DMA_Cmd, READ_DIRECTION+DMA_IDLE_CMD); /* | DMA_INT */
975             dc390_laststatus &= ~0xff000000; dc390_laststatus |= bval << 24;
976
977             DEBUG1(printk (KERN_DEBUG "Blast: Read %i times DMA_Status %02x", 0xa000-i, bval));
978             ResidCnt = (u32) DC390_read8 (CtcReg_High);
979             ResidCnt <<= 8;
980             ResidCnt |= (u32) DC390_read8 (CtcReg_Mid);
981             ResidCnt <<= 8;
982             ResidCnt |= (u32) DC390_read8 (CtcReg_Low);
983
984             xferCnt = pSRB->SGToBeXferLen - ResidCnt;
985             pSRB->SGBusAddr += xferCnt;
986             pSRB->TotalXferredLen += xferCnt;
987             pSRB->SGToBeXferLen = ResidCnt;
988
989             if( residual )
990             {
991                 bval = DC390_read8 (ScsiFifo);      /* get one residual byte */
992                 ptr = (u8 *) bus_to_virt( pSRB->SGBusAddr );
993                 *ptr = bval;
994                 pSRB->SGBusAddr++; xferCnt++;
995                 pSRB->TotalXferredLen++;
996                 pSRB->SGToBeXferLen--;
997             }
998             DEBUG1(printk (KERN_DEBUG "Xfered: %li, Total: %li, Remaining: %li\n", xferCnt,\
999                            pSRB->TotalXferredLen, pSRB->SGToBeXferLen));
1000
1001         }
1002     }
1003     if ((*psstatus & 7) != SCSI_DATA_IN)
1004     {
1005             DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1006             DC390_write8 (DMA_Cmd, READ_DIRECTION+DMA_IDLE_CMD); /* | DMA_INT */
1007     }
1008 }
1009
1010 static void
1011 dc390_Command_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1012 {
1013 }
1014
1015 static void
1016 dc390_Status_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1017 {
1018
1019     pSRB->TargetStatus = DC390_read8 (ScsiFifo);
1020     //udelay (1);
1021     pSRB->EndMessage = DC390_read8 (ScsiFifo);  /* get message */
1022
1023     *psstatus = SCSI_NOP0;
1024     pSRB->SRBState = SRB_COMPLETED;
1025     DC390_write8 (ScsiCmd, MSG_ACCEPTED_CMD);
1026 }
1027
1028 static void
1029 dc390_MsgOut_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1030 {
1031     if( pSRB->SRBState & (SRB_UNEXPECT_RESEL+SRB_ABORT_SENT) )
1032         *psstatus = SCSI_NOP0;
1033     //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1034 }
1035
1036
1037 static void __inline__
1038 dc390_reprog (struct dc390_acb* pACB, struct dc390_dcb* pDCB)
1039 {
1040   DC390_write8 (Sync_Period, pDCB->SyncPeriod);
1041   DC390_write8 (Sync_Offset, pDCB->SyncOffset);
1042   DC390_write8 (CtrlReg3, pDCB->CtrlR3);
1043   DC390_write8 (CtrlReg4, pDCB->CtrlR4);
1044   dc390_SetXferRate (pACB, pDCB);
1045 }
1046
1047
1048 #ifdef DC390_DEBUG0
1049 static void
1050 dc390_printMsg (u8 *MsgBuf, u8 len)
1051 {
1052   int i;
1053   printk (" %02x", MsgBuf[0]);
1054   for (i = 1; i < len; i++)
1055     printk (" %02x", MsgBuf[i]);
1056   printk ("\n");
1057 }
1058 #endif
1059
1060 #define DC390_ENABLE_MSGOUT DC390_write8 (ScsiCmd, SET_ATN_CMD)
1061
1062 /* reject_msg */
1063 static void __inline__
1064 dc390_MsgIn_reject (struct dc390_acb* pACB, struct dc390_srb* pSRB)
1065 {
1066   pSRB->MsgOutBuf[0] = MESSAGE_REJECT;
1067   pSRB->MsgCnt = 1;
1068   DC390_ENABLE_MSGOUT;
1069   DEBUG0 (printk (KERN_INFO "DC390: Reject message\n"));
1070 }
1071
1072 /* abort command */
1073 static void
1074 dc390_EnableMsgOut_Abort ( struct dc390_acb* pACB, struct dc390_srb* pSRB )
1075 {
1076     pSRB->MsgOutBuf[0] = ABORT; 
1077     pSRB->MsgCnt = 1; DC390_ENABLE_MSGOUT;
1078     pSRB->pSRBDCB->DCBFlag &= ~ABORT_DEV_;
1079 }
1080
1081 static struct dc390_srb*
1082 dc390_MsgIn_QTag (struct dc390_acb* pACB, struct dc390_dcb* pDCB, s8 tag)
1083 {
1084   struct dc390_srb* pSRB = pDCB->pGoingSRB;
1085
1086   if (pSRB)
1087     {
1088         struct scsi_cmnd *scmd = scsi_find_tag(pSRB->pcmd->device, tag);
1089         pSRB = (struct dc390_srb *)scmd->host_scribble;
1090
1091         if (pDCB->DCBFlag & ABORT_DEV_)
1092         {
1093           pSRB->SRBState = SRB_ABORT_SENT;
1094           dc390_EnableMsgOut_Abort( pACB, pSRB );
1095         }
1096
1097         if (!(pSRB->SRBState & SRB_DISCONNECT))
1098                 goto mingx0;
1099
1100         pDCB->pActiveSRB = pSRB;
1101         pSRB->SRBState = SRB_DATA_XFER;
1102     }
1103   else
1104     {
1105     mingx0:
1106       pSRB = pACB->pTmpSRB;
1107       pSRB->SRBState = SRB_UNEXPECT_RESEL;
1108       pDCB->pActiveSRB = pSRB;
1109       pSRB->MsgOutBuf[0] = ABORT_TAG;
1110       pSRB->MsgCnt = 1; DC390_ENABLE_MSGOUT;
1111     }
1112   return pSRB;
1113 }
1114
1115
1116 /* set async transfer mode */
1117 static void 
1118 dc390_MsgIn_set_async (struct dc390_acb* pACB, struct dc390_srb* pSRB)
1119 {
1120   struct dc390_dcb* pDCB = pSRB->pSRBDCB;
1121   if (!(pSRB->SRBState & DO_SYNC_NEGO)) 
1122     printk (KERN_INFO "DC390: Target %i initiates Non-Sync?\n", pDCB->TargetID);
1123   pSRB->SRBState &= ~DO_SYNC_NEGO;
1124   pDCB->SyncMode &= ~(SYNC_ENABLE+SYNC_NEGO_DONE);
1125   pDCB->SyncPeriod = 0;
1126   pDCB->SyncOffset = 0;
1127   //pDCB->NegoPeriod = 50; /* 200ns <=> 5 MHz */
1128   pDCB->CtrlR3 = FAST_CLK;      /* fast clock / normal scsi */
1129   pDCB->CtrlR4 &= 0x3f;
1130   pDCB->CtrlR4 |= pACB->glitch_cfg;     /* glitch eater */
1131   dc390_reprog (pACB, pDCB);
1132 }
1133
1134 /* set sync transfer mode */
1135 static void
1136 dc390_MsgIn_set_sync (struct dc390_acb* pACB, struct dc390_srb* pSRB)
1137 {
1138   u8 bval;
1139   u16 wval, wval1;
1140   struct dc390_dcb* pDCB = pSRB->pSRBDCB;
1141   u8 oldsyncperiod = pDCB->SyncPeriod;
1142   u8 oldsyncoffset = pDCB->SyncOffset;
1143   
1144   if (!(pSRB->SRBState & DO_SYNC_NEGO))
1145     {
1146       printk (KERN_INFO "DC390: Target %i initiates Sync: %ins %i ... answer ...\n", 
1147               pDCB->TargetID, pSRB->MsgInBuf[3]<<2, pSRB->MsgInBuf[4]);
1148
1149       /* reject */
1150       //dc390_MsgIn_reject (pACB, pSRB);
1151       //return dc390_MsgIn_set_async (pACB, pSRB);
1152
1153       /* Reply with corrected SDTR Message */
1154       if (pSRB->MsgInBuf[4] > 15)
1155         { 
1156           printk (KERN_INFO "DC390: Lower Sync Offset to 15\n");
1157           pSRB->MsgInBuf[4] = 15;
1158         }
1159       if (pSRB->MsgInBuf[3] < pDCB->NegoPeriod)
1160         {
1161           printk (KERN_INFO "DC390: Set sync nego period to %ins\n", pDCB->NegoPeriod << 2);
1162           pSRB->MsgInBuf[3] = pDCB->NegoPeriod;
1163         }
1164       memcpy (pSRB->MsgOutBuf, pSRB->MsgInBuf, 5);
1165       pSRB->MsgCnt = 5;
1166       DC390_ENABLE_MSGOUT;
1167     }
1168
1169   pSRB->SRBState &= ~DO_SYNC_NEGO;
1170   pDCB->SyncMode |= SYNC_ENABLE+SYNC_NEGO_DONE;
1171   pDCB->SyncOffset &= 0x0f0;
1172   pDCB->SyncOffset |= pSRB->MsgInBuf[4];
1173   pDCB->NegoPeriod = pSRB->MsgInBuf[3];
1174
1175   wval = (u16) pSRB->MsgInBuf[3];
1176   wval = wval << 2; wval -= 3; wval1 = wval / 25;       /* compute speed */
1177   if( (wval1 * 25) != wval) wval1++;
1178   bval = FAST_CLK+FAST_SCSI;    /* fast clock / fast scsi */
1179
1180   pDCB->CtrlR4 &= 0x3f;         /* Glitch eater: 12ns less than normal */
1181   if (pACB->glitch_cfg != NS_TO_GLITCH(0))
1182     pDCB->CtrlR4 |= NS_TO_GLITCH(((GLITCH_TO_NS(pACB->glitch_cfg)) - 1));
1183   else
1184     pDCB->CtrlR4 |= NS_TO_GLITCH(0);
1185   if (wval1 < 4) pDCB->CtrlR4 |= NS_TO_GLITCH(0); /* Ultra */
1186
1187   if (wval1 >= 8)
1188     {
1189       wval1--;  /* Timing computation differs by 1 from FAST_SCSI */
1190       bval = FAST_CLK;          /* fast clock / normal scsi */
1191       pDCB->CtrlR4 |= pACB->glitch_cfg;         /* glitch eater */
1192     }
1193
1194   pDCB->CtrlR3 = bval;
1195   pDCB->SyncPeriod = (u8)wval1;
1196   
1197   if ((oldsyncperiod != wval1 || oldsyncoffset != pDCB->SyncOffset) && pDCB->TargetLUN == 0)
1198     {
1199       if (! (bval & FAST_SCSI)) wval1++;
1200       printk (KERN_INFO "DC390: Target %i: Sync transfer %i.%1i MHz, Offset %i\n", pDCB->TargetID, 
1201               40/wval1, ((40%wval1)*10+wval1/2)/wval1, pDCB->SyncOffset & 0x0f);
1202     }
1203   
1204   dc390_reprog (pACB, pDCB);
1205 }
1206
1207
1208 /* handle RESTORE_PTR */
1209 /* I presume, this command is already mapped, so, have to remap. */
1210 static void 
1211 dc390_restore_ptr (struct dc390_acb* pACB, struct dc390_srb* pSRB)
1212 {
1213     struct scsi_cmnd *pcmd = pSRB->pcmd;
1214     struct scatterlist *psgl;
1215     pSRB->TotalXferredLen = 0;
1216     pSRB->SGIndex = 0;
1217     if (pcmd->use_sg) {
1218         pSRB->pSegmentList = (struct scatterlist *)pcmd->request_buffer;
1219         psgl = pSRB->pSegmentList;
1220         //dc390_pci_sync(pSRB);
1221
1222         while (pSRB->TotalXferredLen + (unsigned long) sg_dma_len(psgl) < pSRB->Saved_Ptr)
1223         {
1224             pSRB->TotalXferredLen += (unsigned long) sg_dma_len(psgl);
1225             pSRB->SGIndex++;
1226             if( pSRB->SGIndex < pSRB->SGcount )
1227             {
1228                 pSRB->pSegmentList++;
1229                 psgl = pSRB->pSegmentList;
1230                 pSRB->SGBusAddr = cpu_to_le32(pci_dma_lo32(sg_dma_address(psgl)));
1231                 pSRB->SGToBeXferLen = cpu_to_le32(sg_dma_len(psgl));
1232             }
1233             else
1234                 pSRB->SGToBeXferLen = 0;
1235         }
1236         pSRB->SGToBeXferLen -= (pSRB->Saved_Ptr - pSRB->TotalXferredLen);
1237         pSRB->SGBusAddr += (pSRB->Saved_Ptr - pSRB->TotalXferredLen);
1238         printk (KERN_INFO "DC390: Pointer restored. Segment %i, Total %li, Bus %08lx\n",
1239                 pSRB->SGIndex, pSRB->Saved_Ptr, pSRB->SGBusAddr);
1240
1241     } else if(pcmd->request_buffer) {
1242         //dc390_pci_sync(pSRB);
1243
1244         sg_dma_len(&pSRB->Segmentx) = pcmd->request_bufflen - pSRB->Saved_Ptr;
1245         pSRB->SGcount = 1;
1246         pSRB->pSegmentList = (struct scatterlist *) &pSRB->Segmentx;
1247     } else {
1248          pSRB->SGcount = 0;
1249          printk (KERN_INFO "DC390: RESTORE_PTR message for Transfer without Scatter-Gather ??\n");
1250     }
1251
1252   pSRB->TotalXferredLen = pSRB->Saved_Ptr;
1253 }
1254
1255
1256 /* According to the docs, the AM53C974 reads the message and 
1257  * generates a Successful Operation IRQ before asserting ACK for
1258  * the last byte (how does it know whether it's the last ?) */
1259 /* The old code handled it in another way, indicating, that on
1260  * every message byte an IRQ is generated and every byte has to
1261  * be manually ACKed. Hmmm ?  (KG, 98/11/28) */
1262 /* The old implementation was correct. Sigh! */
1263
1264 /* Check if the message is complete */
1265 static u8 __inline__
1266 dc390_MsgIn_complete (u8 *msgbuf, u32 len)
1267
1268   if (*msgbuf == EXTENDED_MESSAGE)
1269   {
1270         if (len < 2) return 0;
1271         if (len < msgbuf[1] + 2) return 0;
1272   }
1273   else if (*msgbuf >= 0x20 && *msgbuf <= 0x2f) // two byte messages
1274         if (len < 2) return 0;
1275   return 1;
1276 }
1277
1278
1279
1280 /* read and eval received messages */
1281 static void
1282 dc390_MsgIn_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1283 {
1284     struct dc390_dcb*   pDCB = pACB->pActiveDCB;
1285
1286     /* Read the msg */
1287
1288     pSRB->MsgInBuf[pACB->MsgLen++] = DC390_read8 (ScsiFifo);
1289     //pSRB->SRBState = 0;
1290
1291     /* Msg complete ? */
1292     if (dc390_MsgIn_complete (pSRB->MsgInBuf, pACB->MsgLen))
1293       {
1294         DEBUG0 (printk (KERN_INFO "DC390: MsgIn:"); dc390_printMsg (pSRB->MsgInBuf, pACB->MsgLen));
1295         /* Now eval the msg */
1296         switch (pSRB->MsgInBuf[0]) 
1297           {
1298           case DISCONNECT: 
1299             pSRB->SRBState = SRB_DISCONNECT; break;
1300             
1301           case SIMPLE_QUEUE_TAG:
1302           case HEAD_OF_QUEUE_TAG:
1303           case ORDERED_QUEUE_TAG:
1304             pSRB = dc390_MsgIn_QTag (pACB, pDCB, pSRB->MsgInBuf[1]);
1305             break;
1306             
1307           case MESSAGE_REJECT: 
1308             DC390_write8 (ScsiCmd, RESET_ATN_CMD);
1309             pDCB->NegoPeriod = 50; /* 200ns <=> 5 MHz */
1310             if( pSRB->SRBState & DO_SYNC_NEGO)
1311               dc390_MsgIn_set_async (pACB, pSRB);
1312             break;
1313             
1314           case EXTENDED_MESSAGE:
1315             /* reject every extended msg but SDTR */
1316             if (pSRB->MsgInBuf[1] != 3 || pSRB->MsgInBuf[2] != EXTENDED_SDTR)
1317               dc390_MsgIn_reject (pACB, pSRB);
1318             else
1319               {
1320                 if (pSRB->MsgInBuf[3] == 0 || pSRB->MsgInBuf[4] == 0)
1321                   dc390_MsgIn_set_async (pACB, pSRB);
1322                 else
1323                   dc390_MsgIn_set_sync (pACB, pSRB);
1324               }
1325             
1326             // nothing has to be done
1327           case COMMAND_COMPLETE: break;
1328             
1329             // SAVE POINTER may be ignored as we have the struct dc390_srb* associated with the
1330             // scsi command. Thanks, Gerard, for pointing it out.
1331           case SAVE_POINTERS: 
1332             pSRB->Saved_Ptr = pSRB->TotalXferredLen;
1333             break;
1334             // The device might want to restart transfer with a RESTORE
1335           case RESTORE_POINTERS:
1336             DEBUG0(printk ("DC390: RESTORE POINTER message received ... try to handle\n"));
1337             dc390_restore_ptr (pACB, pSRB);
1338             break;
1339
1340             // reject unknown messages
1341           default: dc390_MsgIn_reject (pACB, pSRB);
1342           }
1343         
1344         /* Clear counter and MsgIn state */
1345         pSRB->SRBState &= ~SRB_MSGIN;
1346         pACB->MsgLen = 0;
1347       }
1348
1349     *psstatus = SCSI_NOP0;
1350     DC390_write8 (ScsiCmd, MSG_ACCEPTED_CMD);
1351     //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1352 }
1353
1354
1355 static void
1356 dc390_DataIO_Comm( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 ioDir)
1357 {
1358     struct scatterlist *psgl;
1359     unsigned long  lval;
1360     struct dc390_dcb*   pDCB = pACB->pActiveDCB;
1361
1362     if (pSRB == pACB->pTmpSRB)
1363     {
1364         if (pDCB)
1365                 printk(KERN_ERR "DC390: pSRB == pTmpSRB! (TagQ Error?) (%02i-%i)\n", pDCB->TargetID, pDCB->TargetLUN);
1366         else
1367                 printk(KERN_ERR "DC390: pSRB == pTmpSRB! (TagQ Error?) (DCB 0!)\n");
1368
1369         /* Try to recover - some broken disks react badly to tagged INQUIRY */
1370         if (pDCB && pACB->scan_devices && pDCB->GoingSRBCnt == 1) {
1371                 pSRB = pDCB->pGoingSRB;
1372                 pDCB->pActiveSRB = pSRB;
1373         } else {
1374                 pSRB->pSRBDCB = pDCB;
1375                 dc390_EnableMsgOut_Abort(pACB, pSRB);
1376                 if (pDCB)
1377                         pDCB->DCBFlag |= ABORT_DEV;
1378                 return;
1379         }
1380     }
1381
1382     if( pSRB->SGIndex < pSRB->SGcount )
1383     {
1384         DC390_write8 (DMA_Cmd, DMA_IDLE_CMD | ioDir /* | DMA_INT */);
1385         if( !pSRB->SGToBeXferLen )
1386         {
1387             psgl = pSRB->pSegmentList;
1388             pSRB->SGBusAddr = cpu_to_le32(pci_dma_lo32(sg_dma_address(psgl)));
1389             pSRB->SGToBeXferLen = cpu_to_le32(sg_dma_len(psgl));
1390             DEBUG1(printk (KERN_DEBUG " DC390: Next SG segment."));
1391         }
1392         lval = pSRB->SGToBeXferLen;
1393         DEBUG1(printk (KERN_DEBUG " DC390: Start transfer: %li bytes (address %08lx)\n", lval, pSRB->SGBusAddr));
1394         DC390_write8 (CtcReg_Low, (u8) lval);
1395         lval >>= 8;
1396         DC390_write8 (CtcReg_Mid, (u8) lval);
1397         lval >>= 8;
1398         DC390_write8 (CtcReg_High, (u8) lval);
1399
1400         DC390_write32 (DMA_XferCnt, pSRB->SGToBeXferLen);
1401         DC390_write32 (DMA_XferAddr, pSRB->SGBusAddr);
1402
1403         //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD | ioDir); /* | DMA_INT; */
1404         pSRB->SRBState = SRB_DATA_XFER;
1405
1406         DC390_write8 (ScsiCmd, DMA_COMMAND+INFO_XFER_CMD);
1407
1408         DC390_write8 (DMA_Cmd, DMA_START_CMD | ioDir | DMA_INT);
1409         //DEBUG1(DC390_write32 (DMA_ScsiBusCtrl, WRT_ERASE_DMA_STAT | EN_INT_ON_PCI_ABORT));
1410         //DEBUG1(printk (KERN_DEBUG "DC390: DMA_Status: %02x\n", DC390_read8 (DMA_Status)));
1411         //DEBUG1(DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT));
1412     }
1413     else    /* xfer pad */
1414     {
1415         if( pSRB->SGcount )
1416         {
1417             pSRB->AdaptStatus = H_OVER_UNDER_RUN;
1418             pSRB->SRBStatus |= OVER_RUN;
1419             DEBUG0(printk (KERN_WARNING " DC390: Overrun -"));
1420         }
1421         DEBUG0(printk (KERN_WARNING " Clear transfer pad \n"));
1422         DC390_write8 (CtcReg_Low, 0);
1423         DC390_write8 (CtcReg_Mid, 0);
1424         DC390_write8 (CtcReg_High, 0);
1425
1426         pSRB->SRBState |= SRB_XFERPAD;
1427         DC390_write8 (ScsiCmd, DMA_COMMAND+XFER_PAD_BYTE);
1428 /*
1429         DC390_write8 (DMA_Cmd, DMA_IDLE_CMD | ioDir); // | DMA_INT;
1430         DC390_write8 (DMA_Cmd, DMA_START_CMD | ioDir | DMA_INT);
1431 */
1432     }
1433 }
1434
1435
1436 static void
1437 dc390_DataOutPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1438 {
1439     dc390_DataIO_Comm (pACB, pSRB, WRITE_DIRECTION);
1440 }
1441
1442 static void
1443 dc390_DataInPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1444 {
1445     dc390_DataIO_Comm (pACB, pSRB, READ_DIRECTION);
1446 }
1447
1448 static void
1449 dc390_CommandPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1450 {
1451     struct dc390_dcb*   pDCB;
1452     u8  i, cnt;
1453     u8     *ptr;
1454
1455     DC390_write8 (ScsiCmd, RESET_ATN_CMD);
1456     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1457     if( !(pSRB->SRBFlag & AUTO_REQSENSE) )
1458     {
1459         cnt = (u8) pSRB->pcmd->cmd_len;
1460         ptr = (u8 *) pSRB->pcmd->cmnd;
1461         for(i=0; i < cnt; i++)
1462             DC390_write8 (ScsiFifo, *(ptr++));
1463     }
1464     else
1465     {
1466         DC390_write8 (ScsiFifo, REQUEST_SENSE);
1467         pDCB = pACB->pActiveDCB;
1468         DC390_write8 (ScsiFifo, pDCB->TargetLUN << 5);
1469         DC390_write8 (ScsiFifo, 0);
1470         DC390_write8 (ScsiFifo, 0);
1471         DC390_write8 (ScsiFifo, sizeof(pSRB->pcmd->sense_buffer));
1472         DC390_write8 (ScsiFifo, 0);
1473         DEBUG0(printk(KERN_DEBUG "DC390: AutoReqSense (CmndPhase)!\n"));
1474     }
1475     pSRB->SRBState = SRB_COMMAND;
1476     DC390_write8 (ScsiCmd, INFO_XFER_CMD);
1477 }
1478
1479 static void
1480 dc390_StatusPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1481 {
1482     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1483     pSRB->SRBState = SRB_STATUS;
1484     DC390_write8 (ScsiCmd, INITIATOR_CMD_CMPLTE);
1485     //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1486 }
1487
1488 static void
1489 dc390_MsgOutPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1490 {
1491     u8   bval, i, cnt;
1492     u8     *ptr;
1493     struct dc390_dcb*    pDCB;
1494
1495     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1496     pDCB = pACB->pActiveDCB;
1497     if( !(pSRB->SRBState & SRB_MSGOUT) )
1498     {
1499         cnt = pSRB->MsgCnt;
1500         if( cnt )
1501         {
1502             ptr = (u8 *) pSRB->MsgOutBuf;
1503             for(i=0; i < cnt; i++)
1504                 DC390_write8 (ScsiFifo, *(ptr++));
1505             pSRB->MsgCnt = 0;
1506             if( (pDCB->DCBFlag & ABORT_DEV_) &&
1507                 (pSRB->MsgOutBuf[0] == ABORT) )
1508                 pSRB->SRBState = SRB_ABORT_SENT;
1509         }
1510         else
1511         {
1512             bval = ABORT;       /* ??? MSG_NOP */
1513             if( (pSRB->pcmd->cmnd[0] == INQUIRY ) ||
1514                 (pSRB->pcmd->cmnd[0] == REQUEST_SENSE) ||
1515                 (pSRB->SRBFlag & AUTO_REQSENSE) )
1516             {
1517                 if( pDCB->SyncMode & SYNC_ENABLE )
1518                     goto  mop1;
1519             }
1520             DC390_write8 (ScsiFifo, bval);
1521         }
1522         DC390_write8 (ScsiCmd, INFO_XFER_CMD);
1523     }
1524     else
1525     {
1526 mop1:
1527         printk (KERN_ERR "DC390: OLD Sync Nego code triggered! (%i %i)\n", pDCB->TargetID, pDCB->TargetLUN);
1528         DC390_write8 (ScsiFifo, EXTENDED_MESSAGE);
1529         DC390_write8 (ScsiFifo, 3);     /*    ;length of extended msg */
1530         DC390_write8 (ScsiFifo, EXTENDED_SDTR); /*    ; sync nego */
1531         DC390_write8 (ScsiFifo, pDCB->NegoPeriod);
1532         if (pDCB->SyncOffset & 0x0f)
1533                     DC390_write8 (ScsiFifo, pDCB->SyncOffset);
1534         else
1535                     DC390_write8 (ScsiFifo, SYNC_NEGO_OFFSET);              
1536         pSRB->SRBState |= DO_SYNC_NEGO;
1537         DC390_write8 (ScsiCmd, INFO_XFER_CMD);
1538     }
1539 }
1540
1541 static void
1542 dc390_MsgInPhase( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1543 {
1544     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1545     if( !(pSRB->SRBState & SRB_MSGIN) )
1546     {
1547         pSRB->SRBState &= ~SRB_DISCONNECT;
1548         pSRB->SRBState |= SRB_MSGIN;
1549     }
1550     DC390_write8 (ScsiCmd, INFO_XFER_CMD);
1551     //DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1552 }
1553
1554 static void
1555 dc390_Nop_0( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1556 {
1557 }
1558
1559 static void
1560 dc390_Nop_1( struct dc390_acb* pACB, struct dc390_srb* pSRB, u8 *psstatus)
1561 {
1562 }
1563
1564
1565 static void
1566 dc390_SetXferRate( struct dc390_acb* pACB, struct dc390_dcb* pDCB )
1567 {
1568     u8  bval, i, cnt;
1569     struct dc390_dcb*   ptr;
1570
1571     if( !(pDCB->TargetLUN) )
1572     {
1573         if( !pACB->scan_devices )
1574         {
1575             ptr = pACB->pLinkDCB;
1576             cnt = pACB->DCBCnt;
1577             bval = pDCB->TargetID;
1578             for(i=0; i<cnt; i++)
1579             {
1580                 if( ptr->TargetID == bval )
1581                 {
1582                     ptr->SyncPeriod = pDCB->SyncPeriod;
1583                     ptr->SyncOffset = pDCB->SyncOffset;
1584                     ptr->CtrlR3 = pDCB->CtrlR3;
1585                     ptr->CtrlR4 = pDCB->CtrlR4;
1586                     ptr->SyncMode = pDCB->SyncMode;
1587                 }
1588                 ptr = ptr->pNextDCB;
1589             }
1590         }
1591     }
1592     return;
1593 }
1594
1595
1596 static void
1597 dc390_Disconnect( struct dc390_acb* pACB )
1598 {
1599     struct dc390_dcb *pDCB;
1600     struct dc390_srb *pSRB, *psrb;
1601     u8  i, cnt;
1602
1603     DEBUG0(printk(KERN_INFO "DISC,"));
1604
1605     if (!pACB->Connected) printk(KERN_ERR "DC390: Disconnect not-connected bus?\n");
1606     pACB->Connected = 0;
1607     pDCB = pACB->pActiveDCB;
1608     if (!pDCB)
1609      {
1610         DEBUG0(printk(KERN_ERR "ACB:%p->ActiveDCB:%p IOPort:%04x IRQ:%02x !\n",\
1611                pACB, pDCB, pACB->IOPortBase, pACB->IRQLevel));
1612         mdelay(400);
1613         DC390_read8 (INT_Status);       /* Reset Pending INT */
1614         DC390_write8 (ScsiCmd, EN_SEL_RESEL);
1615         return;
1616      }
1617     DC390_write8 (ScsiCmd, EN_SEL_RESEL);
1618     pSRB = pDCB->pActiveSRB;
1619     pACB->pActiveDCB = NULL;
1620     pSRB->ScsiPhase = SCSI_NOP0;
1621     if( pSRB->SRBState & SRB_UNEXPECT_RESEL )
1622         pSRB->SRBState = 0;
1623     else if( pSRB->SRBState & SRB_ABORT_SENT )
1624     {
1625         pDCB->TagMask = 0;
1626         pDCB->DCBFlag = 0;
1627         cnt = pDCB->GoingSRBCnt;
1628         pDCB->GoingSRBCnt = 0;
1629         pSRB = pDCB->pGoingSRB;
1630         for( i=0; i < cnt; i++)
1631         {
1632             psrb = pSRB->pNextSRB;
1633             dc390_Free_insert (pACB, pSRB);
1634             pSRB = psrb;
1635         }
1636         pDCB->pGoingSRB = NULL;
1637     }
1638     else
1639     {
1640         if( (pSRB->SRBState & (SRB_START_+SRB_MSGOUT)) ||
1641            !(pSRB->SRBState & (SRB_DISCONNECT+SRB_COMPLETED)) )
1642         {       /* Selection time out */
1643                 pSRB->TargetStatus = SCSI_STAT_SEL_TIMEOUT;
1644                 goto  disc1;
1645         }
1646         else if (!(pSRB->SRBState & SRB_DISCONNECT) && (pSRB->SRBState & SRB_COMPLETED))
1647         {
1648 disc1:
1649             dc390_freetag (pDCB, pSRB);
1650             pDCB->pActiveSRB = NULL;
1651             pSRB->SRBState = SRB_FREE;
1652             dc390_SRBdone( pACB, pDCB, pSRB);
1653         }
1654     }
1655     pACB->MsgLen = 0;
1656 }
1657
1658
1659 static void
1660 dc390_Reselect( struct dc390_acb* pACB )
1661 {
1662     struct dc390_dcb*   pDCB;
1663     struct dc390_srb*   pSRB;
1664     u8  id, lun;
1665
1666     DEBUG0(printk(KERN_INFO "RSEL,"));
1667     pACB->Connected = 1;
1668     pDCB = pACB->pActiveDCB;
1669     if( pDCB )
1670     {   /* Arbitration lost but Reselection won */
1671         DEBUG0(printk ("DC390: (ActiveDCB != 0: Arb. lost but resel. won)!\n"));
1672         pSRB = pDCB->pActiveSRB;
1673         if( !( pACB->scan_devices ) )
1674         {
1675             struct scsi_cmnd *pcmd = pSRB->pcmd;
1676             pcmd->resid = pcmd->request_bufflen;
1677             SET_RES_DID(pcmd->result, DID_SOFT_ERROR);
1678             dc390_Going_remove(pDCB, pSRB);
1679             dc390_Free_insert(pACB, pSRB);
1680             pcmd->scsi_done (pcmd);
1681             DEBUG0(printk(KERN_DEBUG"DC390: Return SRB %p to free\n", pSRB));
1682         }
1683     }
1684     /* Get ID */
1685     lun = DC390_read8 (ScsiFifo);
1686     DEBUG0(printk ("Dev %02x,", lun));
1687     if (!(lun & (1 << pACB->pScsiHost->this_id)))
1688       printk (KERN_ERR "DC390: Reselection must select host adapter: %02x!\n", lun);
1689     else
1690       lun ^= 1 << pACB->pScsiHost->this_id; /* Mask AdapterID */
1691     id = 0; while (lun >>= 1) id++;
1692     /* Get LUN */
1693     lun = DC390_read8 (ScsiFifo);
1694     if (!(lun & IDENTIFY_BASE)) printk (KERN_ERR "DC390: Resel: Expect identify message!\n");
1695     lun &= 7;
1696     DEBUG0(printk ("(%02i-%i),", id, lun));
1697     pDCB = dc390_findDCB (pACB, id, lun);
1698     if (!pDCB)
1699     {
1700         printk (KERN_ERR "DC390: Reselect from non existing device (%02i-%i)\n",
1701                     id, lun);
1702         return;
1703     }
1704     pACB->pActiveDCB = pDCB;
1705     /* TagQ: We expect a message soon, so never mind the exact SRB */
1706     if( pDCB->SyncMode & EN_TAG_QUEUEING )
1707     {
1708         pSRB = pACB->pTmpSRB;
1709         pDCB->pActiveSRB = pSRB;
1710     }
1711     else
1712     {
1713         pSRB = pDCB->pActiveSRB;
1714         if( !pSRB || !(pSRB->SRBState & SRB_DISCONNECT) )
1715         {
1716             pSRB= pACB->pTmpSRB;
1717             pSRB->SRBState = SRB_UNEXPECT_RESEL;
1718             printk (KERN_ERR "DC390: Reselect without outstanding cmnd (%02i-%i)\n",
1719                     id, lun);
1720             pDCB->pActiveSRB = pSRB;
1721             dc390_EnableMsgOut_Abort ( pACB, pSRB );
1722         }
1723         else
1724         {
1725             if( pDCB->DCBFlag & ABORT_DEV_ )
1726             {
1727                 pSRB->SRBState = SRB_ABORT_SENT;
1728                 printk (KERN_INFO "DC390: Reselect: Abort (%02i-%i)\n",
1729                         id, lun);
1730                 dc390_EnableMsgOut_Abort( pACB, pSRB );
1731             }
1732             else
1733                 pSRB->SRBState = SRB_DATA_XFER;
1734         }
1735     }
1736
1737     DEBUG1(printk (KERN_DEBUG "Resel SRB(%p): TagNum (%02x)\n", pSRB, pSRB->TagNumber));
1738     pSRB->ScsiPhase = SCSI_NOP0;
1739     DC390_write8 (Scsi_Dest_ID, pDCB->TargetID);
1740     DC390_write8 (Sync_Period, pDCB->SyncPeriod);
1741     DC390_write8 (Sync_Offset, pDCB->SyncOffset);
1742     DC390_write8 (CtrlReg1, pDCB->CtrlR1);
1743     DC390_write8 (CtrlReg3, pDCB->CtrlR3);
1744     DC390_write8 (CtrlReg4, pDCB->CtrlR4);      /* ; Glitch eater */
1745     DC390_write8 (ScsiCmd, MSG_ACCEPTED_CMD);   /* ;to release the /ACK signal */
1746 }
1747
1748 static int __inline__
1749 dc390_RequestSense(struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB)
1750 {
1751         struct scsi_cmnd *pcmd;
1752
1753         pcmd = pSRB->pcmd;
1754
1755         REMOVABLEDEBUG(printk(KERN_INFO "DC390: RequestSense(Cmd %02x, Id %02x, LUN %02x)\n",\
1756                               pcmd->cmnd[0], pDCB->TargetID, pDCB->TargetLUN));
1757
1758         pSRB->SRBFlag |= AUTO_REQSENSE;
1759         pSRB->SavedSGCount = pcmd->use_sg;
1760         pSRB->SavedTotXLen = pSRB->TotalXferredLen;
1761         pSRB->AdaptStatus = 0;
1762         pSRB->TargetStatus = 0; /* CHECK_CONDITION<<1; */
1763
1764         /* We are called from SRBdone, original PCI mapping has been removed
1765          * already, new one is set up from StartSCSI */
1766         pSRB->SGIndex = 0;
1767
1768         pSRB->TotalXferredLen = 0;
1769         pSRB->SGToBeXferLen = 0;
1770         return dc390_StartSCSI(pACB, pDCB, pSRB);
1771 }
1772
1773
1774 static void
1775 dc390_SRBdone( struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB )
1776 {
1777     u8 status;
1778     struct scsi_cmnd *pcmd;
1779
1780     pcmd = pSRB->pcmd;
1781     /* KG: Moved pci_unmap here */
1782     dc390_pci_unmap(pSRB);
1783
1784     status = pSRB->TargetStatus;
1785
1786     DEBUG0(printk (" SRBdone (%02x,%08x), SRB %p, pid %li\n", status, pcmd->result,\
1787                 pSRB, pcmd->pid));
1788     if(pSRB->SRBFlag & AUTO_REQSENSE)
1789     {   /* Last command was a Request Sense */
1790         pSRB->SRBFlag &= ~AUTO_REQSENSE;
1791         pSRB->AdaptStatus = 0;
1792         pSRB->TargetStatus = CHECK_CONDITION << 1;
1793
1794         //pcmd->result = MK_RES(DRIVER_SENSE,DID_OK,0,status);
1795         if (status == (CHECK_CONDITION << 1))
1796             pcmd->result = MK_RES_LNX(0, DID_BAD_TARGET, 0, /*CHECK_CONDITION*/0);
1797         else /* Retry */
1798         {
1799             if( pSRB->pcmd->cmnd[0] == TEST_UNIT_READY /* || pSRB->pcmd->cmnd[0] == START_STOP */)
1800             {
1801                 /* Don't retry on TEST_UNIT_READY */
1802                 pcmd->result = MK_RES_LNX(DRIVER_SENSE,DID_OK,0,CHECK_CONDITION);
1803                 REMOVABLEDEBUG(printk(KERN_INFO "Cmd=%02x, Result=%08x, XferL=%08x\n",pSRB->pcmd->cmnd[0],\
1804                        (u32) pcmd->result, (u32) pSRB->TotalXferredLen));
1805             } else {
1806                 SET_RES_DRV(pcmd->result, DRIVER_SENSE);
1807                 pcmd->use_sg = pSRB->SavedSGCount;
1808                 //pSRB->ScsiCmdLen       = (u8) (pSRB->Segment1[0] >> 8);
1809                 DEBUG0 (printk ("DC390: RETRY pid %li (%02x), target %02i-%02i\n", pcmd->pid, pcmd->cmnd[0], pcmd->device->id, pcmd->device->lun));
1810                 pSRB->TotalXferredLen = 0;
1811                 SET_RES_DID(pcmd->result, DID_SOFT_ERROR);
1812             }
1813         }
1814         goto cmd_done;
1815     }
1816     if( status )
1817     {
1818         if( status_byte(status) == CHECK_CONDITION )
1819         {
1820             if (dc390_RequestSense(pACB, pDCB, pSRB)) {
1821                 SET_RES_DID(pcmd->result, DID_ERROR);
1822                 goto cmd_done;
1823             }
1824             return;
1825         }
1826         else if( status_byte(status) == QUEUE_FULL )
1827         {
1828             scsi_track_queue_full(pcmd->device, pDCB->GoingSRBCnt - 1);
1829             pcmd->use_sg = pSRB->SavedSGCount;
1830             DEBUG0 (printk ("DC390: RETRY pid %li (%02x), target %02i-%02i\n", pcmd->pid, pcmd->cmnd[0], pcmd->device->id, pcmd->device->lun));
1831             pSRB->TotalXferredLen = 0;
1832             SET_RES_DID(pcmd->result, DID_SOFT_ERROR);
1833         }
1834         else if(status == SCSI_STAT_SEL_TIMEOUT)
1835         {
1836             pSRB->AdaptStatus = H_SEL_TIMEOUT;
1837             pSRB->TargetStatus = 0;
1838             pcmd->result = MK_RES(0,DID_NO_CONNECT,0,0);
1839             /* Devices are removed below ... */
1840         }
1841         else if (status_byte(status) == BUSY && 
1842                  (pcmd->cmnd[0] == TEST_UNIT_READY || pcmd->cmnd[0] == INQUIRY) &&
1843                  pACB->scan_devices)
1844         {
1845             pSRB->AdaptStatus = 0;
1846             pSRB->TargetStatus = status;
1847             pcmd->result = MK_RES(0,0,pSRB->EndMessage,/*status*/0);
1848         }
1849         else
1850         {   /* Another error */
1851             pSRB->TotalXferredLen = 0;
1852             SET_RES_DID(pcmd->result, DID_SOFT_ERROR);
1853             goto cmd_done;
1854         }
1855     }
1856     else
1857     {   /*  Target status == 0 */
1858         status = pSRB->AdaptStatus;
1859         if(status & H_OVER_UNDER_RUN)
1860         {
1861             pSRB->TargetStatus = 0;
1862             SET_RES_DID(pcmd->result,DID_OK);
1863             SET_RES_MSG(pcmd->result,pSRB->EndMessage);
1864         }
1865         else if( pSRB->SRBStatus & PARITY_ERROR)
1866         {
1867             //pcmd->result = MK_RES(0,DID_PARITY,pSRB->EndMessage,0);
1868             SET_RES_DID(pcmd->result,DID_PARITY);
1869             SET_RES_MSG(pcmd->result,pSRB->EndMessage);
1870         }
1871         else                   /* No error */
1872         {
1873             pSRB->AdaptStatus = 0;
1874             pSRB->TargetStatus = 0;
1875             SET_RES_DID(pcmd->result,DID_OK);
1876         }
1877     }
1878
1879 cmd_done:
1880     pcmd->resid = pcmd->request_bufflen - pSRB->TotalXferredLen;
1881
1882     dc390_Going_remove (pDCB, pSRB);
1883     /* Add to free list */
1884     dc390_Free_insert (pACB, pSRB);
1885
1886     DEBUG0(printk (KERN_DEBUG "DC390: SRBdone: done pid %li\n", pcmd->pid));
1887     pcmd->scsi_done (pcmd);
1888
1889     return;
1890 }
1891
1892
1893 /* Remove all SRBs from Going list and inform midlevel */
1894 static void
1895 dc390_DoingSRB_Done(struct dc390_acb* pACB, struct scsi_cmnd *cmd)
1896 {
1897     struct dc390_dcb *pDCB, *pdcb;
1898     struct dc390_srb *psrb, *psrb2;
1899     int i;
1900     struct scsi_cmnd *pcmd;
1901
1902     pDCB = pACB->pLinkDCB;
1903     pdcb = pDCB;
1904     if (! pdcb) return;
1905     do
1906     {
1907         psrb = pdcb->pGoingSRB;
1908         for (i = 0; i < pdcb->GoingSRBCnt; i++)
1909         {
1910             psrb2 = psrb->pNextSRB;
1911             pcmd = psrb->pcmd;
1912             dc390_Free_insert (pACB, psrb);
1913             psrb  = psrb2;
1914         }
1915         pdcb->GoingSRBCnt = 0;
1916         pdcb->pGoingSRB = NULL;
1917         pdcb->TagMask = 0;
1918         pdcb = pdcb->pNextDCB;
1919     } while( pdcb != pDCB );
1920 }
1921
1922
1923 static void
1924 dc390_ResetSCSIBus( struct dc390_acb* pACB )
1925 {
1926     //DC390_write8 (ScsiCmd, RST_DEVICE_CMD);
1927     //udelay (250);
1928     //DC390_write8 (ScsiCmd, NOP_CMD);
1929
1930     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1931     DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1932     DC390_write8 (ScsiCmd, RST_SCSI_BUS_CMD);
1933     pACB->Connected = 0;
1934
1935     return;
1936 }
1937
1938 static void
1939 dc390_ScsiRstDetect( struct dc390_acb* pACB )
1940 {
1941     printk ("DC390: Rst_Detect: laststat = %08x\n", dc390_laststatus);
1942     //DEBUG0(printk(KERN_INFO "RST_DETECT,"));
1943
1944     DC390_write8 (DMA_Cmd, DMA_IDLE_CMD);
1945     /* Unlock before ? */
1946     /* delay half a second */
1947     udelay (1000);
1948     DC390_write8 (ScsiCmd, CLEAR_FIFO_CMD);
1949     pACB->pScsiHost->last_reset = jiffies + 5*HZ/2
1950                     + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
1951     pACB->Connected = 0;
1952
1953     if( pACB->ACBFlag & RESET_DEV )
1954         pACB->ACBFlag |= RESET_DONE;
1955     else
1956     {   /* Reset was issued by sb else */
1957         pACB->ACBFlag |= RESET_DETECT;
1958
1959         dc390_ResetDevParam( pACB );
1960         dc390_DoingSRB_Done( pACB, NULL);
1961         //dc390_RecoverSRB( pACB );
1962         pACB->pActiveDCB = NULL;
1963         pACB->ACBFlag = 0;
1964     }
1965     return;
1966 }
1967
1968 static int DC390_queuecommand(struct scsi_cmnd *cmd,
1969                 void (*done)(struct scsi_cmnd *))
1970 {
1971         struct scsi_device *sdev = cmd->device;
1972         struct dc390_acb *acb = (struct dc390_acb *)sdev->host->hostdata;
1973         struct dc390_dcb *dcb = sdev->hostdata;
1974         struct dc390_srb *srb;
1975
1976         if (sdev->queue_depth <= dcb->GoingSRBCnt)
1977                 goto device_busy;
1978         if (acb->pActiveDCB)
1979                 goto host_busy;
1980         if (acb->ACBFlag & (RESET_DETECT|RESET_DONE|RESET_DEV))
1981                 goto host_busy;
1982
1983         srb = acb->pFreeSRB;
1984         if (unlikely(srb == NULL))
1985                 goto host_busy;
1986
1987         cmd->scsi_done = done;
1988         cmd->result = 0;
1989         acb->Cmds++;
1990
1991         acb->pFreeSRB = srb->pNextSRB;
1992         srb->pNextSRB = NULL;
1993
1994         srb->pSRBDCB = dcb;
1995         srb->pcmd = cmd;
1996         cmd->host_scribble = (char *)srb;
1997     
1998         srb->SGIndex = 0;
1999         srb->AdaptStatus = 0;
2000         srb->TargetStatus = 0;
2001         srb->MsgCnt = 0;
2002
2003         srb->SRBStatus = 0;
2004         srb->SRBFlag = 0;
2005         srb->SRBState = 0;
2006         srb->TotalXferredLen = 0;
2007         srb->SGBusAddr = 0;
2008         srb->SGToBeXferLen = 0;
2009         srb->ScsiPhase = 0;
2010         srb->EndMessage = 0;
2011         srb->TagNumber = SCSI_NO_TAG;
2012
2013         if (dc390_StartSCSI(acb, dcb, srb)) {
2014                 dc390_Free_insert(acb, srb);
2015                 goto host_busy;
2016         }
2017
2018         dc390_Going_append(dcb, srb);
2019
2020         return 0;
2021
2022  host_busy:
2023         return SCSI_MLQUEUE_HOST_BUSY;
2024
2025  device_busy:
2026         return SCSI_MLQUEUE_DEVICE_BUSY;
2027 }
2028
2029 static void dc390_dumpinfo (struct dc390_acb* pACB, struct dc390_dcb* pDCB, struct dc390_srb* pSRB)
2030 {
2031     struct pci_dev *pdev;
2032     u16 pstat;
2033
2034     if (!pDCB) pDCB = pACB->pActiveDCB;
2035     if (!pSRB && pDCB) pSRB = pDCB->pActiveSRB;
2036
2037     if (pSRB) 
2038     {
2039         printk ("DC390: SRB: Xferred %08lx, Remain %08lx, State %08x, Phase %02x\n",
2040                 pSRB->TotalXferredLen, pSRB->SGToBeXferLen, pSRB->SRBState,
2041                 pSRB->ScsiPhase);
2042         printk ("DC390: AdpaterStatus: %02x, SRB Status %02x\n", pSRB->AdaptStatus, pSRB->SRBStatus);
2043     }
2044     printk ("DC390: Status of last IRQ (DMA/SC/Int/IRQ): %08x\n", dc390_laststatus);
2045     printk ("DC390: Register dump: SCSI block:\n");
2046     printk ("DC390: XferCnt  Cmd Stat IntS IRQS FFIS Ctl1 Ctl2 Ctl3 Ctl4\n");
2047     printk ("DC390:  %06x   %02x   %02x   %02x",
2048             DC390_read8(CtcReg_Low) + (DC390_read8(CtcReg_Mid) << 8) + (DC390_read8(CtcReg_High) << 16),
2049             DC390_read8(ScsiCmd), DC390_read8(Scsi_Status), DC390_read8(Intern_State));
2050     printk ("   %02x   %02x   %02x   %02x   %02x   %02x\n",
2051             DC390_read8(INT_Status), DC390_read8(Current_Fifo), DC390_read8(CtrlReg1),
2052             DC390_read8(CtrlReg2), DC390_read8(CtrlReg3), DC390_read8(CtrlReg4));
2053     DC390_write32 (DMA_ScsiBusCtrl, WRT_ERASE_DMA_STAT | EN_INT_ON_PCI_ABORT);
2054     if (DC390_read8(Current_Fifo) & 0x1f)
2055       {
2056         printk ("DC390: FIFO:");
2057         while (DC390_read8(Current_Fifo) & 0x1f) printk (" %02x", DC390_read8(ScsiFifo));
2058         printk ("\n");
2059       }
2060     printk ("DC390: Register dump: DMA engine:\n");
2061     printk ("DC390: Cmd   STrCnt    SBusA    WrkBC    WrkAC Stat SBusCtrl\n");
2062     printk ("DC390:  %02x %08x %08x %08x %08x   %02x %08x\n",
2063             DC390_read8(DMA_Cmd), DC390_read32(DMA_XferCnt), DC390_read32(DMA_XferAddr),
2064             DC390_read32(DMA_Wk_ByteCntr), DC390_read32(DMA_Wk_AddrCntr),
2065             DC390_read8(DMA_Status), DC390_read32(DMA_ScsiBusCtrl));
2066     DC390_write32 (DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
2067
2068     pdev = pACB->pdev;
2069     pci_read_config_word(pdev, PCI_STATUS, &pstat);
2070     printk ("DC390: Register dump: PCI Status: %04x\n", pstat);
2071     printk ("DC390: In case of driver trouble read Documentation/scsi/tmscsim.txt\n");
2072 }
2073
2074
2075 static int DC390_abort(struct scsi_cmnd *cmd)
2076 {
2077         struct dc390_acb *pACB = (struct dc390_acb*) cmd->device->host->hostdata;
2078         struct dc390_dcb *pDCB = (struct dc390_dcb*) cmd->device->hostdata;
2079
2080         printk("DC390: Abort command (pid %li, Device %02i-%02i)\n",
2081                cmd->pid, cmd->device->id, cmd->device->lun);
2082
2083         /* abort() is too stupid for already sent commands at the moment. 
2084          * If it's called we are in trouble anyway, so let's dump some info 
2085          * into the syslog at least. (KG, 98/08/20,99/06/20) */
2086         dc390_dumpinfo(pACB, pDCB, NULL);
2087
2088         pDCB->DCBFlag |= ABORT_DEV_;
2089         printk(KERN_INFO "DC390: Aborted pid %li\n", cmd->pid);
2090
2091         return FAILED;
2092 }
2093
2094
2095 static void dc390_ResetDevParam( struct dc390_acb* pACB )
2096 {
2097     struct dc390_dcb *pDCB, *pdcb;
2098
2099     pDCB = pACB->pLinkDCB;
2100     if (! pDCB) return;
2101     pdcb = pDCB;
2102     do
2103     {
2104         pDCB->SyncMode &= ~SYNC_NEGO_DONE;
2105         pDCB->SyncPeriod = 0;
2106         pDCB->SyncOffset = 0;
2107         pDCB->TagMask = 0;
2108         pDCB->CtrlR3 = FAST_CLK;
2109         pDCB->CtrlR4 &= NEGATE_REQACKDATA | CTRL4_RESERVED | NEGATE_REQACK;
2110         pDCB->CtrlR4 |= pACB->glitch_cfg;
2111         pDCB = pDCB->pNextDCB;
2112     }
2113     while( pdcb != pDCB );
2114     pACB->ACBFlag &= ~(RESET_DEV | RESET_DONE | RESET_DETECT);
2115
2116 }
2117
2118 static int DC390_bus_reset (struct scsi_cmnd *cmd)
2119 {
2120         struct dc390_acb*    pACB = (struct dc390_acb*) cmd->device->host->hostdata;
2121         u8   bval;
2122
2123         spin_lock_irq(cmd->device->host->host_lock);
2124
2125         bval = DC390_read8(CtrlReg1) | DIS_INT_ON_SCSI_RST;
2126         DC390_write8(CtrlReg1, bval);   /* disable IRQ on bus reset */
2127
2128         pACB->ACBFlag |= RESET_DEV;
2129         dc390_ResetSCSIBus(pACB);
2130
2131         dc390_ResetDevParam(pACB);
2132         mdelay(1);
2133         pACB->pScsiHost->last_reset = jiffies + 3*HZ/2 
2134                 + HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
2135     
2136         DC390_write8(ScsiCmd, CLEAR_FIFO_CMD);
2137         DC390_read8(INT_Status);                /* Reset Pending INT */
2138
2139         dc390_DoingSRB_Done(pACB, cmd);
2140
2141         pACB->pActiveDCB = NULL;
2142         pACB->ACBFlag = 0;
2143
2144         bval = DC390_read8(CtrlReg1) & ~DIS_INT_ON_SCSI_RST;
2145         DC390_write8(CtrlReg1, bval);   /* re-enable interrupt */
2146
2147         spin_unlock_irq(cmd->device->host->host_lock);
2148
2149         return SUCCESS;
2150 }
2151
2152 /**
2153  * dc390_slave_alloc - Called by the scsi mid layer to tell us about a new
2154  * scsi device that we need to deal with.
2155  *
2156  * @scsi_device: The new scsi device that we need to handle.
2157  */
2158 static int dc390_slave_alloc(struct scsi_device *scsi_device)
2159 {
2160         struct dc390_acb *pACB = (struct dc390_acb*) scsi_device->host->hostdata;
2161         struct dc390_dcb *pDCB, *pDCB2 = NULL;
2162         uint id = scsi_device->id;
2163         uint lun = scsi_device->lun;
2164
2165         pDCB = kmalloc(sizeof(struct dc390_dcb), GFP_KERNEL);
2166         if (!pDCB)
2167                 return -ENOMEM;
2168         memset(pDCB, 0, sizeof(struct dc390_dcb));
2169
2170         if (!pACB->DCBCnt++) {
2171                 pACB->pLinkDCB = pDCB;
2172                 pACB->pDCBRunRobin = pDCB;
2173         } else {
2174                 pACB->pLastDCB->pNextDCB = pDCB;
2175         }
2176    
2177         pDCB->pNextDCB = pACB->pLinkDCB;
2178         pACB->pLastDCB = pDCB;
2179
2180         pDCB->pDCBACB = pACB;
2181         pDCB->TargetID = id;
2182         pDCB->TargetLUN = lun;
2183
2184         /*
2185          * Some values are for all LUNs: Copy them 
2186          * In a clean way: We would have an own structure for a SCSI-ID 
2187          */
2188         if (lun && (pDCB2 = dc390_findDCB(pACB, id, 0))) {
2189                 pDCB->DevMode = pDCB2->DevMode;
2190                 pDCB->SyncMode = pDCB2->SyncMode & SYNC_NEGO_DONE;
2191                 pDCB->SyncPeriod = pDCB2->SyncPeriod;
2192                 pDCB->SyncOffset = pDCB2->SyncOffset;
2193                 pDCB->NegoPeriod = pDCB2->NegoPeriod;
2194       
2195                 pDCB->CtrlR3 = pDCB2->CtrlR3;
2196                 pDCB->CtrlR4 = pDCB2->CtrlR4;
2197         } else {
2198                 u8 index = pACB->AdapterIndex;
2199                 PEEprom prom = (PEEprom) &dc390_eepromBuf[index][id << 2];
2200
2201                 pDCB->DevMode = prom->EE_MODE1;
2202                 pDCB->NegoPeriod =
2203                         (dc390_clock_period1[prom->EE_SPEED] * 25) >> 2;
2204                 pDCB->CtrlR3 = FAST_CLK;
2205                 pDCB->CtrlR4 = pACB->glitch_cfg | CTRL4_RESERVED;
2206                 if (dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION)
2207                         pDCB->CtrlR4 |= NEGATE_REQACKDATA | NEGATE_REQACK;
2208         }
2209
2210         if (pDCB->DevMode & SYNC_NEGO_)
2211                 pDCB->SyncMode |= SYNC_ENABLE;
2212         else {
2213                 pDCB->SyncMode = 0;
2214                 pDCB->SyncOffset &= ~0x0f;
2215         }
2216
2217         pDCB->CtrlR1 = pACB->pScsiHost->this_id;
2218         if (pDCB->DevMode & PARITY_CHK_)
2219                 pDCB->CtrlR1 |= PARITY_ERR_REPO;
2220
2221         pACB->scan_devices = 1;
2222         scsi_device->hostdata = pDCB;
2223         return 0;
2224 }
2225
2226 /**
2227  * dc390_slave_destroy - Called by the scsi mid layer to tell us about a
2228  * device that is going away.
2229  *
2230  * @scsi_device: The scsi device that we need to remove.
2231  */
2232 static void dc390_slave_destroy(struct scsi_device *scsi_device)
2233 {
2234         struct dc390_acb* pACB = (struct dc390_acb*) scsi_device->host->hostdata;
2235         struct dc390_dcb* pDCB = (struct dc390_dcb*) scsi_device->hostdata;
2236         struct dc390_dcb* pPrevDCB = pACB->pLinkDCB;
2237
2238         pACB->scan_devices = 0;
2239
2240         BUG_ON(pDCB->GoingSRBCnt > 1);
2241         
2242         if (pDCB == pACB->pLinkDCB) {
2243                 if (pACB->pLastDCB == pDCB) {
2244                         pDCB->pNextDCB = NULL;
2245                         pACB->pLastDCB = NULL;
2246                 }
2247                 pACB->pLinkDCB = pDCB->pNextDCB;
2248         } else {
2249                 while (pPrevDCB->pNextDCB != pDCB)
2250                         pPrevDCB = pPrevDCB->pNextDCB;
2251                 pPrevDCB->pNextDCB = pDCB->pNextDCB;
2252                 if (pDCB == pACB->pLastDCB)
2253                         pACB->pLastDCB = pPrevDCB;
2254         }
2255
2256         if (pDCB == pACB->pActiveDCB)
2257                 pACB->pActiveDCB = NULL;
2258         if (pDCB == pACB->pLinkDCB)
2259                 pACB->pLinkDCB = pDCB->pNextDCB;
2260         if (pDCB == pACB->pDCBRunRobin)
2261                 pACB->pDCBRunRobin = pDCB->pNextDCB;
2262         kfree(pDCB); 
2263         
2264         pACB->DCBCnt--;
2265 }
2266
2267 static int dc390_slave_configure(struct scsi_device *sdev)
2268 {
2269         struct dc390_acb *acb = (struct dc390_acb *)sdev->host->hostdata;
2270         struct dc390_dcb *dcb = (struct dc390_dcb *)sdev->hostdata;
2271
2272         acb->scan_devices = 0;
2273         if (sdev->tagged_supported && (dcb->DevMode & TAG_QUEUEING_)) {
2274                 dcb->SyncMode |= EN_TAG_QUEUEING;
2275                 scsi_activate_tcq(sdev, acb->TagMaxNum);
2276         }
2277
2278         return 0;
2279 }
2280
2281 static struct scsi_host_template driver_template = {
2282         .module                 = THIS_MODULE,
2283         .proc_name              = "tmscsim", 
2284         .name                   = DC390_BANNER " V" DC390_VERSION,
2285         .slave_alloc            = dc390_slave_alloc,
2286         .slave_configure        = dc390_slave_configure,
2287         .slave_destroy          = dc390_slave_destroy,
2288         .queuecommand           = DC390_queuecommand,
2289         .eh_abort_handler       = DC390_abort,
2290         .eh_bus_reset_handler   = DC390_bus_reset,
2291         .can_queue              = 1,
2292         .this_id                = 7,
2293         .sg_tablesize           = SG_ALL,
2294         .cmd_per_lun            = 1,
2295         .use_clustering         = DISABLE_CLUSTERING,
2296 };
2297
2298 /***********************************************************************
2299  * Functions for access to DC390 EEPROM
2300  * and some to emulate it
2301  *
2302  **********************************************************************/
2303
2304 static void __devinit dc390_eeprom_prepare_read(struct pci_dev *pdev, u8 cmd)
2305 {
2306         u8 carryFlag = 1, j = 0x80, bval;
2307         int i;
2308
2309         for (i = 0; i < 9; i++) {
2310                 if (carryFlag) {
2311                         pci_write_config_byte(pdev, 0x80, 0x40);
2312                         bval = 0xc0;
2313                 } else
2314                         bval = 0x80;
2315
2316                 udelay(160);
2317                 pci_write_config_byte(pdev, 0x80, bval);
2318                 udelay(160);
2319                 pci_write_config_byte(pdev, 0x80, 0);
2320                 udelay(160);
2321
2322                 carryFlag = (cmd & j) ? 1 : 0;
2323                 j >>= 1;
2324         }
2325 }
2326
2327 static u16 __devinit dc390_eeprom_get_data(struct pci_dev *pdev)
2328 {
2329         int i;
2330         u16 wval = 0;
2331         u8 bval;
2332
2333         for (i = 0; i < 16; i++) {
2334                 wval <<= 1;
2335
2336                 pci_write_config_byte(pdev, 0x80, 0x80);
2337                 udelay(160);
2338                 pci_write_config_byte(pdev, 0x80, 0x40);
2339                 udelay(160);
2340                 pci_read_config_byte(pdev, 0x00, &bval);
2341
2342                 if (bval == 0x22)
2343                         wval |= 1;
2344         }
2345
2346         return wval;
2347 }
2348
2349 static void __devinit dc390_read_eeprom(struct pci_dev *pdev, u16 *ptr)
2350 {
2351         u8 cmd = EEPROM_READ, i;
2352
2353         for (i = 0; i < 0x40; i++) {
2354                 pci_write_config_byte(pdev, 0xc0, 0);
2355                 udelay(160);
2356
2357                 dc390_eeprom_prepare_read(pdev, cmd++);
2358                 *ptr++ = dc390_eeprom_get_data(pdev);
2359
2360                 pci_write_config_byte(pdev, 0x80, 0);
2361                 pci_write_config_byte(pdev, 0x80, 0);
2362                 udelay(160);
2363         }
2364 }
2365
2366 /* Override EEprom values with explicitly set values */
2367 static void __devinit dc390_eeprom_override(u8 index)
2368 {
2369         u8 *ptr = (u8 *) dc390_eepromBuf[index], id;
2370
2371         /* Adapter Settings */
2372         if (tmscsim[0] != -2)
2373                 ptr[EE_ADAPT_SCSI_ID] = (u8)tmscsim[0]; /* Adapter ID */
2374         if (tmscsim[3] != -2)
2375                 ptr[EE_MODE2] = (u8)tmscsim[3];
2376         if (tmscsim[5] != -2)
2377                 ptr[EE_DELAY] = tmscsim[5];             /* Reset delay */
2378         if (tmscsim[4] != -2)
2379                 ptr[EE_TAG_CMD_NUM] = (u8)tmscsim[4];   /* Tagged Cmds */
2380
2381         /* Device Settings */
2382         for (id = 0; id < MAX_SCSI_ID; id++) {
2383                 if (tmscsim[2] != -2)
2384                         ptr[id << 2] = (u8)tmscsim[2];          /* EE_MODE1 */
2385                 if (tmscsim[1] != -2)
2386                         ptr[(id << 2) + 1] = (u8)tmscsim[1];    /* EE_Speed */
2387         }
2388 }
2389
2390 static int __devinitdata tmscsim_def[] = {
2391         7,
2392         0 /* 10MHz */,
2393         PARITY_CHK_ | SEND_START_ | EN_DISCONNECT_ | SYNC_NEGO_ | TAG_QUEUEING_,
2394         MORE2_DRV | GREATER_1G | RST_SCSI_BUS | ACTIVE_NEGATION | LUN_CHECK,
2395         3 /* 16 Tags per LUN */,
2396         1 /* s delay after Reset */,
2397 };
2398
2399 /* Copy defaults over set values where missing */
2400 static void __devinit dc390_fill_with_defaults (void)
2401 {
2402         int i;
2403
2404         for (i = 0; i < 6; i++) {
2405                 if (tmscsim[i] < 0 || tmscsim[i] > 255)
2406                         tmscsim[i] = tmscsim_def[i];
2407         }
2408
2409         /* Sanity checks */
2410         if (tmscsim[0] > 7)
2411                 tmscsim[0] = 7;
2412         if (tmscsim[1] > 7)
2413                 tmscsim[1] = 4;
2414         if (tmscsim[4] > 5)
2415                 tmscsim[4] = 4;
2416         if (tmscsim[5] > 180)
2417                 tmscsim[5] = 180;
2418 }
2419
2420 static void __devinit dc390_check_eeprom(struct pci_dev *pdev, u8 index)
2421 {
2422         u8 interpd[] = {1, 3, 5, 10, 16, 30, 60, 120};
2423         u8 EEbuf[128];
2424         u16 *ptr = (u16 *)EEbuf, wval = 0;
2425         int i;
2426
2427         dc390_read_eeprom(pdev, ptr);
2428         memcpy(dc390_eepromBuf[index], EEbuf, EE_ADAPT_SCSI_ID);
2429         memcpy(&dc390_eepromBuf[index][EE_ADAPT_SCSI_ID], 
2430                &EEbuf[REAL_EE_ADAPT_SCSI_ID], EE_LEN - EE_ADAPT_SCSI_ID);
2431
2432         dc390_eepromBuf[index][EE_DELAY] = interpd[dc390_eepromBuf[index][EE_DELAY]];
2433
2434         for (i = 0; i < 0x40; i++, ptr++)
2435                 wval += *ptr;
2436
2437         /* no Tekram EEprom found */
2438         if (wval != 0x1234) {
2439                 int speed;
2440
2441                 printk(KERN_INFO "DC390_init: No EEPROM found! Trying default settings ...\n");
2442
2443                 /*
2444                  * XXX(hch): bogus, because we might have tekram and
2445                  *           non-tekram hbas in a single machine.
2446                  */
2447                 dc390_fill_with_defaults();
2448
2449                 speed = dc390_clock_speed[tmscsim[1]];
2450                 printk(KERN_INFO "DC390: Used defaults: AdaptID=%i, SpeedIdx=%i (%i.%i MHz), "
2451                        "DevMode=0x%02x, AdaptMode=0x%02x, TaggedCmnds=%i (%i), DelayReset=%is\n", 
2452                        tmscsim[0], tmscsim[1], speed / 10, speed % 10,
2453                        (u8)tmscsim[2], (u8)tmscsim[3], tmscsim[4], 2 << (tmscsim[4]), tmscsim[5]);
2454         }
2455 }
2456
2457 static void __devinit dc390_init_hw(struct dc390_acb *pACB, u8 index)
2458 {
2459         struct Scsi_Host *shost = pACB->pScsiHost;
2460         u8 dstate;
2461
2462         /* Disable SCSI bus reset interrupt */
2463         DC390_write8(CtrlReg1, DIS_INT_ON_SCSI_RST | shost->this_id);
2464
2465         if (pACB->Gmode2 & RST_SCSI_BUS) {
2466                 dc390_ResetSCSIBus(pACB);
2467                 udelay(1000);
2468                 shost->last_reset = jiffies + HZ/2 +
2469                         HZ * dc390_eepromBuf[pACB->AdapterIndex][EE_DELAY];
2470         }
2471
2472         pACB->ACBFlag = 0;
2473
2474         /* Reset Pending INT */
2475         DC390_read8(INT_Status);
2476         
2477         /* 250ms selection timeout */
2478         DC390_write8(Scsi_TimeOut, SEL_TIMEOUT);
2479         
2480         /* Conversion factor = 0 , 40MHz clock */
2481         DC390_write8(Clk_Factor, CLK_FREQ_40MHZ);
2482         
2483         /* NOP cmd - clear command register */
2484         DC390_write8(ScsiCmd, NOP_CMD);
2485         
2486         /* Enable Feature and SCSI-2 */
2487         DC390_write8(CtrlReg2, EN_FEATURE+EN_SCSI2_CMD);
2488         
2489         /* Fast clock */
2490         DC390_write8(CtrlReg3, FAST_CLK);
2491
2492         /* Negation */
2493         DC390_write8(CtrlReg4, pACB->glitch_cfg | /* glitch eater */
2494                 (dc390_eepromBuf[index][EE_MODE2] & ACTIVE_NEGATION) ?
2495                  NEGATE_REQACKDATA : 0);
2496         
2497         /* Clear Transfer Count High: ID */
2498         DC390_write8(CtcReg_High, 0);
2499         DC390_write8(DMA_Cmd, DMA_IDLE_CMD);
2500         DC390_write8(ScsiCmd, CLEAR_FIFO_CMD);
2501         DC390_write32(DMA_ScsiBusCtrl, EN_INT_ON_PCI_ABORT);
2502
2503         dstate = DC390_read8(DMA_Status);
2504         DC390_write8(DMA_Status, dstate);
2505 }
2506
2507 static int __devinit dc390_probe_one(struct pci_dev *pdev,
2508                                     const struct pci_device_id *id)
2509 {
2510         struct dc390_acb *pACB;
2511         struct Scsi_Host *shost;
2512         unsigned long io_port;
2513         int error = -ENODEV, i;
2514
2515         if (pci_enable_device(pdev))
2516                 goto out;
2517
2518         pci_set_master(pdev);
2519
2520         error = -ENOMEM;
2521         shost = scsi_host_alloc(&driver_template, sizeof(struct dc390_acb));
2522         if (!shost)
2523                 goto out_disable_device;
2524
2525         pACB = (struct dc390_acb *)shost->hostdata;
2526         memset(pACB, 0, sizeof(struct dc390_acb));
2527
2528         dc390_check_eeprom(pdev, dc390_adapterCnt);
2529         dc390_eeprom_override(dc390_adapterCnt);
2530
2531         io_port = pci_resource_start(pdev, 0);
2532
2533         shost->this_id = dc390_eepromBuf[dc390_adapterCnt][EE_ADAPT_SCSI_ID];
2534         shost->io_port = io_port;
2535         shost->n_io_port = 0x80;
2536         shost->irq = pdev->irq;
2537         shost->base = io_port;
2538         shost->unique_id = io_port;
2539         shost->last_reset = jiffies;
2540         
2541         pACB->pScsiHost = shost;
2542         pACB->IOPortBase = (u16) io_port;
2543         pACB->IRQLevel = pdev->irq;
2544         
2545         shost->max_id = 8;
2546
2547         if (shost->max_id - 1 ==
2548             dc390_eepromBuf[dc390_adapterCnt][EE_ADAPT_SCSI_ID])
2549                 shost->max_id--;
2550
2551         if (dc390_eepromBuf[dc390_adapterCnt][EE_MODE2] & LUN_CHECK)
2552                 shost->max_lun = 8;
2553         else
2554                 shost->max_lun = 1;
2555
2556         pACB->pFreeSRB = pACB->SRB_array;
2557         pACB->SRBCount = MAX_SRB_CNT;
2558         pACB->AdapterIndex = dc390_adapterCnt;
2559         pACB->TagMaxNum =
2560                 2 << dc390_eepromBuf[dc390_adapterCnt][EE_TAG_CMD_NUM];
2561         pACB->Gmode2 = dc390_eepromBuf[dc390_adapterCnt][EE_MODE2];
2562
2563         for (i = 0; i < pACB->SRBCount-1; i++)
2564                 pACB->SRB_array[i].pNextSRB = &pACB->SRB_array[i+1];
2565         pACB->SRB_array[pACB->SRBCount-1].pNextSRB = NULL;
2566         pACB->pTmpSRB = &pACB->TmpSRB;
2567
2568         pACB->sel_timeout = SEL_TIMEOUT;
2569         pACB->glitch_cfg = EATER_25NS;
2570         pACB->pdev = pdev;
2571
2572         if (!request_region(io_port, shost->n_io_port, "tmscsim")) {
2573                 printk(KERN_ERR "DC390: register IO ports error!\n");
2574                 goto out_host_put;
2575         }
2576
2577         /* Reset Pending INT */
2578         DC390_read8_(INT_Status, io_port);
2579
2580         if (request_irq(pdev->irq, do_DC390_Interrupt, SA_SHIRQ,
2581                                 "tmscsim", pACB)) {
2582                 printk(KERN_ERR "DC390: register IRQ error!\n");
2583                 goto out_release_region;
2584         }
2585
2586         dc390_init_hw(pACB, dc390_adapterCnt);
2587         
2588         dc390_adapterCnt++;
2589
2590         pci_set_drvdata(pdev, shost);
2591
2592         error = scsi_add_host(shost, &pdev->dev);
2593         if (error)
2594                 goto out_free_irq;
2595         scsi_scan_host(shost);
2596         return 0;
2597
2598  out_free_irq:
2599         free_irq(pdev->irq, pACB);
2600  out_release_region:
2601         release_region(io_port, shost->n_io_port);
2602  out_host_put:
2603         scsi_host_put(shost);
2604  out_disable_device:
2605         pci_disable_device(pdev);
2606  out:
2607         return error;
2608 }
2609
2610 /**
2611  * dc390_remove_one - Called to remove a single instance of the adapter.
2612  *
2613  * @dev: The PCI device to remove.
2614  */
2615 static void __devexit dc390_remove_one(struct pci_dev *dev)
2616 {
2617         struct Scsi_Host *scsi_host = pci_get_drvdata(dev);
2618         unsigned long iflags;
2619         struct dc390_acb* pACB = (struct dc390_acb*) scsi_host->hostdata;
2620         u8 bval;
2621
2622         scsi_remove_host(scsi_host);
2623
2624         spin_lock_irqsave(scsi_host->host_lock, iflags);
2625         pACB->ACBFlag = RESET_DEV;
2626         bval = DC390_read8(CtrlReg1) | DIS_INT_ON_SCSI_RST;
2627         DC390_write8 (CtrlReg1, bval);  /* disable interrupt */
2628         if (pACB->Gmode2 & RST_SCSI_BUS)
2629                 dc390_ResetSCSIBus(pACB);
2630         spin_unlock_irqrestore(scsi_host->host_lock, iflags);
2631
2632         free_irq(scsi_host->irq, pACB);
2633         release_region(scsi_host->io_port, scsi_host->n_io_port);
2634
2635         pci_disable_device(dev);
2636         scsi_host_put(scsi_host);
2637         pci_set_drvdata(dev, NULL);
2638 }
2639
2640 static struct pci_device_id tmscsim_pci_tbl[] = {
2641         { PCI_VENDOR_ID_AMD, PCI_DEVICE_ID_AMD53C974,
2642                 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0 },
2643         { }
2644 };
2645 MODULE_DEVICE_TABLE(pci, tmscsim_pci_tbl);
2646
2647 static struct pci_driver dc390_driver = {
2648         .name           = "tmscsim",
2649         .id_table       = tmscsim_pci_tbl,
2650         .probe          = dc390_probe_one,
2651         .remove         = __devexit_p(dc390_remove_one),
2652 };
2653
2654 static int __init dc390_module_init(void)
2655 {
2656         if (tmscsim[0] == -1 || tmscsim[0] > 15) {
2657                 tmscsim[0] = 7;
2658                 tmscsim[1] = 4;
2659                 tmscsim[2] = PARITY_CHK_ | TAG_QUEUEING_;
2660                 tmscsim[3] = MORE2_DRV | GREATER_1G | RST_SCSI_BUS | ACTIVE_NEGATION;
2661                 tmscsim[4] = 2;
2662                 tmscsim[5] = 10;
2663                 printk (KERN_INFO "DC390: Using safe settings.\n");
2664         }
2665
2666         return pci_module_init(&dc390_driver);
2667 }
2668
2669 static void __exit dc390_module_exit(void)
2670 {
2671         pci_unregister_driver(&dc390_driver);
2672 }
2673
2674 module_init(dc390_module_init);
2675 module_exit(dc390_module_exit);
2676
2677 #ifndef MODULE
2678 static int __init dc390_setup (char *str)
2679 {       
2680         int ints[8],i, im;
2681
2682         get_options(str, ARRAY_SIZE(ints), ints);
2683         im = ints[0];
2684
2685         if (im > 6) {
2686                 printk (KERN_NOTICE "DC390: ignore extra params!\n");
2687                 im = 6;
2688         }
2689
2690         for (i = 0; i < im; i++)
2691                 tmscsim[i] = ints[i+1];
2692         /* dc390_checkparams (); */
2693         return 1;
2694 }
2695
2696 __setup("tmscsim=", dc390_setup);
2697 #endif