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