commented early_printk patch because of rejects.
[linux-flexiantxendom0-3.2.10.git] / drivers / scsi / dc395x.c
1 /*
2  * dc395x.c
3  *
4  * Device Driver for Tekram DC395(U/UW/F), DC315(U)
5  * PCI SCSI Bus Master Host Adapter
6  * (SCSI chip set used Tekram ASIC TRM-S1040)
7  *
8  * Authors:
9  *  C.L. Huang <ching@tekram.com.tw>
10  *  Erich Chen <erich@tekram.com.tw>
11  *  (C) Copyright 1995-1999 Tekram Technology Co., Ltd.
12  *
13  *  Kurt Garloff <garloff@suse.de>
14  *  (C) 1999-2000 Kurt Garloff
15  *
16  *  Oliver Neukum <oliver@neukum.name>
17  *  Ali Akcaagac <aliakc@web.de>
18  *  Jamie Lenehan <lenehan@twibble.org>
19  *  (C) 2003
20  *
21  * License: GNU GPL
22  *
23  *************************************************************************
24  *
25  * Redistribution and use in source and binary forms, with or without
26  * modification, are permitted provided that the following conditions
27  * are met:
28  * 1. Redistributions of source code must retain the above copyright
29  *    notice, this list of conditions and the following disclaimer.
30  * 2. Redistributions in binary form must reproduce the above copyright
31  *    notice, this list of conditions and the following disclaimer in the
32  *    documentation and/or other materials provided with the distribution.
33  * 3. The name of the author may not be used to endorse or promote products
34  *    derived from this software without specific prior written permission.
35  *
36  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
37  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
39  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
40  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
41  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
42  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
43  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
44  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
45  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
46  *
47  ************************************************************************
48  */
49 #include <linux/module.h>
50 #include <linux/moduleparam.h>
51 #include <linux/delay.h>
52 #include <linux/ctype.h>
53 #include <linux/blkdev.h>
54 #include <asm/io.h>
55 #include "scsi.h"
56 #include "hosts.h"
57 #include "dc395x.h"
58 #include <scsi/scsicam.h>       /* needed for scsicam_bios_param */
59 #include <linux/interrupt.h>
60 #include <linux/init.h>
61 #include <linux/spinlock.h>
62 #include <linux/pci.h>
63
64 /*---------------------------------------------------------------------------
65                                   Features
66  ---------------------------------------------------------------------------*/
67 /*
68  * Set to disable parts of the driver
69  */
70 /*#define DC395x_NO_DISCONNECT*/
71 /*#define DC395x_NO_TAGQ*/
72 /*#define DC395x_NO_SYNC*/
73 /*#define DC395x_NO_WIDE*/
74
75 /*---------------------------------------------------------------------------
76                                   Debugging
77  ---------------------------------------------------------------------------*/
78 /*
79  * Types of debugging that can be enabled and disabled
80  */
81 #define DBG_KG          0x0001
82 #define DBG_0           0x0002
83 #define DBG_1           0x0004
84 #define DBG_DCB         0x0008
85 #define DBG_PARSE       0x0010          /* debug command line parsing */
86 #define DBG_SGPARANOIA  0x0020
87 #define DBG_FIFO        0x0040
88 #define DBG_PIO         0x0080
89 #define DBG_RECURSION   0x0100          /* check for excessive recursion */
90 #define DBG_MALLOC      0x0200          /* report on memory allocations */
91 #define DBG_TRACE       0x0400
92 #define DBG_TRACEALL    0x0800
93
94
95 /*
96  * Set set of things to output debugging for.
97  * Undefine to remove all debugging
98  */
99 /*#define DEBUG_MASK (DBG_0|DBG_1|DBG_DCB|DBG_PARSE|DBG_SGPARANOIA|DBG_FIFO|DBG_PIO|DBG_TRACE|DBG_TRACEALL)*/
100 /*#define  DEBUG_MASK   DBG_0*/
101
102
103 /*
104  * Output a kernel mesage at the specified level and append the
105  * driver name and a ": " to the start of the message
106  */
107 #define dprintkl(level, format, arg...)  \
108     printk(level DC395X_NAME ": " format , ## arg)
109
110
111 #ifdef DEBUG_MASK
112 /*
113  * print a debug message - this is formated with KERN_DEBUG, then the
114  * driver name followed by a ": " and then the message is output. 
115  * This also checks that the specified debug level is enabled before
116  * outputing the message
117  */
118 #define dprintkdbg(type, format, arg...) \
119         do { \
120                 if ((type) & (DEBUG_MASK)) \
121                         dprintkl(KERN_DEBUG , format , ## arg); \
122         } while (0)
123
124 /*
125  * Check if the specified type of debugging is enabled
126  */
127 #define debug_enabled(type)     ((DEBUG_MASK) & (type))
128
129 #else
130 /*
131  * No debugging. Do nothing
132  */
133 #define dprintkdbg(type, format, arg...) \
134         do {} while (0)
135 #define debug_enabled(type)     (0)
136
137 #endif
138
139
140 /*
141  * The recursion debugging just counts entries into the driver and
142  * prints out a messge if it exceeds a certain limit. This variable
143  * hold the count.
144  */
145 #if debug_enabled(DBG_RECURSION)
146 static int dbg_in_driver = 0;
147 #endif
148
149
150 /*
151  * Memory allocation debugging
152  * Just reports when memory is allocated and/or released.
153  */
154 #if debug_enabled(DBG_MALLOC)
155 inline void *dc395x_kmalloc(size_t sz, int fl)
156 {
157         void *ptr = kmalloc(sz, fl);
158         dprintkl(KERN_DEBUG, "Alloc %i bytes @ %p w/ fl %08x\n", sz, ptr, fl);
159         return ptr;
160 }
161 inline void dc395x_kfree(const void *adr)
162 {
163         dprintkl(KERN_DEBUG, "Free mem @ %p\n", adr);
164         kfree(adr);
165 }
166 #else
167 #define dc395x_kmalloc(sz, fl)  kmalloc(sz, fl)
168 #define dc395x_kfree(adr) kfree(adr)
169 #endif
170
171
172 /*
173  * Debug/trace stuff
174  */
175 #if debug_enabled(DBG_TRACEALL)
176 # define TRACEOUTALL(x...) printk ( x)
177 #else
178 # define TRACEOUTALL(x...) do {} while (0)
179 #endif
180
181 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
182 # define DEBUGTRACEBUFSZ 512
183 static char tracebuf[64];
184 static char traceoverflow[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
185 # define TRACEPRINTF(x...) \
186         do { \
187                 int ln = sprintf(tracebuf, x); \
188                 if (srb->debugpos + ln >= DEBUGTRACEBUFSZ) { \
189                         srb->debugtrace[srb->debugpos] = 0; \
190                         srb->debugpos = DEBUGTRACEBUFSZ/5; \
191                         srb->debugtrace[srb->debugpos++] = '>'; \
192                 } \
193                 sprintf(srb->debugtrace + srb->debugpos, "%s", tracebuf); \
194                 srb->debugpos += ln - 1; \
195         } while (0)
196 # define TRACEOUT(x...) printk (x)
197 #else
198 # define TRACEPRINTF(x...) do {} while (0)
199 # define TRACEOUT(x...) do {} while (0)
200 #endif
201
202
203 /*---------------------------------------------------------------------------
204  ---------------------------------------------------------------------------*/
205
206 #ifndef PCI_VENDOR_ID_TEKRAM
207 #define PCI_VENDOR_ID_TEKRAM                    0x1DE1  /* Vendor ID    */
208 #endif
209 #ifndef PCI_DEVICE_ID_TEKRAM_TRMS1040
210 #define PCI_DEVICE_ID_TEKRAM_TRMS1040           0x0391  /* Device ID    */
211 #endif
212
213
214
215 #define DC395x_LOCK_IO(dev,flags)               spin_lock_irqsave(((struct Scsi_Host *)dev)->host_lock, flags)
216 #define DC395x_UNLOCK_IO(dev,flags)             spin_unlock_irqrestore(((struct Scsi_Host *)dev)->host_lock, flags)
217
218 #define DC395x_ACB_INITLOCK(acb)                spin_lock_init(&acb->smp_lock)
219 #define DC395x_ACB_LOCK(acb,acb_flags)          if (!acb->lock_level_count[cpuid]) { spin_lock_irqsave(&acb->smp_lock,acb_flags); acb->lock_level_count[cpuid]++; } else { acb->lock_level_count[cpuid]++; }
220 #define DC395x_ACB_UNLOCK(acb,acb_flags)        if (--acb->lock_level_count[cpuid] == 0) { spin_unlock_irqrestore(&acb->smp_lock,acb_flags); }
221
222 #define DC395x_SMP_IO_LOCK(dev,irq_flags)       spin_lock_irqsave(((struct Scsi_Host*)dev)->host_lock,irq_flags)
223 #define DC395x_SMP_IO_UNLOCK(dev,irq_flags)     spin_unlock_irqrestore(((struct Scsi_Host*)dev)->host_lock,irq_flags)
224
225
226 #define DC395x_read8(acb,address)               (u8)(inb(acb->IOPortBase + (address)))
227 #define DC395x_read8_(address, base)            (u8)(inb((USHORT)(base) + (address)))
228 #define DC395x_read16(acb,address)              (u16)(inw(acb->IOPortBase + (address)))
229 #define DC395x_read32(acb,address)              (u32)(inl(acb->IOPortBase + (address)))
230 #define DC395x_write8(acb,address,value)        outb((value), acb->IOPortBase + (address))
231 #define DC395x_write8_(address,value,base)      outb((value), (USHORT)(base) + (address))
232 #define DC395x_write16(acb,address,value)       outw((value), acb->IOPortBase + (address))
233 #define DC395x_write32(acb,address,value)       outl((value), acb->IOPortBase + (address))
234
235
236 #define BUS_ADDR(sg)            sg_dma_address(&(sg))
237 #define CPU_ADDR(sg)            (page_address((sg).page)+(sg).offset)
238 #define PAGE_ADDRESS(sg)        page_address((sg)->page)
239
240 /* cmd->result */
241 #define RES_TARGET              0x000000FF      /* Target State */
242 #define RES_TARGET_LNX  STATUS_MASK     /* Only official ... */
243 #define RES_ENDMSG              0x0000FF00      /* End Message */
244 #define RES_DID                 0x00FF0000      /* DID_ codes */
245 #define RES_DRV                 0xFF000000      /* DRIVER_ codes */
246
247 #define MK_RES(drv,did,msg,tgt) ((int)(drv)<<24 | (int)(did)<<16 | (int)(msg)<<8 | (int)(tgt))
248 #define MK_RES_LNX(drv,did,msg,tgt) ((int)(drv)<<24 | (int)(did)<<16 | (int)(msg)<<8 | (int)(tgt)<<1)
249
250 #define SET_RES_TARGET(who,tgt) { who &= ~RES_TARGET; who |= (int)(tgt); }
251 #define SET_RES_TARGET_LNX(who,tgt) { who &= ~RES_TARGET_LNX; who |= (int)(tgt) << 1; }
252 #define SET_RES_MSG(who,msg) { who &= ~RES_ENDMSG; who |= (int)(msg) << 8; }
253 #define SET_RES_DID(who,did) { who &= ~RES_DID; who |= (int)(did) << 16; }
254 #define SET_RES_DRV(who,drv) { who &= ~RES_DRV; who |= (int)(drv) << 24; }
255
256 /*
257 **************************************************************************
258 */
259 #define TAG_NONE 255
260
261 struct SGentry {
262         u32 address;            /* bus! address */
263         u32 length;
264 };
265
266
267 /*-----------------------------------------------------------------------
268   SCSI Request Block
269   -----------------------------------------------------------------------*/
270 struct ScsiReqBlk {
271         struct ScsiReqBlk *next;
272         struct DeviceCtlBlk *dcb;
273
274         /* HW scatter list (up to 64 entries) */
275         struct SGentry *segment_x;
276         Scsi_Cmnd *cmd;
277
278         unsigned char *virt_addr;       /* set by update_sg_list */
279
280         u32 total_xfer_length;
281         u32 xferred;            /* Backup for the already xferred len */
282
283         u32 sg_bus_addr;        /* bus address of DC395x scatterlist */
284
285         u16 state;
286         u8 sg_count;
287         u8 sg_index;
288
289         u8 msgin_buf[6];
290         u8 msgout_buf[6];
291
292         u8 adapter_status;
293         u8 target_status;
294         u8 msg_count;
295         u8 end_message;
296
297         u8 tag_number;
298         u8 status;
299         u8 retry_count;
300         u8 flag;
301
302         u8 scsi_phase;
303
304 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
305         u16 debugpos;
306         char *debugtrace;
307 #endif
308 };
309
310
311 /*-----------------------------------------------------------------------
312   Device Control Block
313   -----------------------------------------------------------------------*/
314 struct DeviceCtlBlk {
315         struct DeviceCtlBlk *next;
316         struct AdapterCtlBlk *acb;
317
318         struct ScsiReqBlk *going_srb;
319         struct ScsiReqBlk *going_last;
320
321         struct ScsiReqBlk *waiting_srb;
322         struct ScsiReqBlk *wait_list;
323
324         struct ScsiReqBlk *active_srb;
325         u32 tag_mask;
326
327         u16 max_command;
328
329         u16 going_srb_count;
330         u16 waiting_srb_count;
331         u8 target_id;           /* SCSI Target ID  (SCSI Only) */
332         u8 target_lun;          /* SCSI Log.  Unit (SCSI Only) */
333         u8 identify_msg;
334         u8 dev_mode;
335
336         u8 inquiry7;            /* To store Inquiry flags */
337         u8 sync_mode;           /* 0:async mode */
338         u8 min_nego_period;     /* for nego. */
339         u8 sync_period;         /* for reg.  */
340
341         u8 sync_offset;         /* for reg. and nego.(low nibble) */
342         u8 flag;
343         u8 dev_type;
344         u8 init_tcq_flag;
345 };
346
347 /*-----------------------------------------------------------------------
348   Adapter Control Block
349   -----------------------------------------------------------------------*/
350 struct AdapterCtlBlk {
351         struct Scsi_Host *scsi_host;
352         struct AdapterCtlBlk *next_acb;
353
354         u16 IOPortBase;
355
356         struct DeviceCtlBlk *link_dcb;
357         struct DeviceCtlBlk *last_dcb;
358         struct DeviceCtlBlk *dcb_run_robin;
359
360         struct DeviceCtlBlk *active_dcb;
361
362         struct ScsiReqBlk *free_srb;
363         struct ScsiReqBlk *tmp_srb;
364         struct timer_list waiting_timer;
365         struct timer_list selto_timer;
366
367         u16 srb_count;
368         u16 adapter_index;      /* nth Adapter this driver */
369
370         u8 dcb_count;
371         u8 sel_timeout;
372
373         u8 irq_level;
374         u8 tag_max_num;
375         u8 acb_flag;
376         u8 gmode2;
377
378         u8 config;
379         u8 lun_chk;
380         u8 scan_devices;
381         u8 hostid_bit;
382
383         u8 dcb_map[DC395x_MAX_SCSI_ID];
384         struct DeviceCtlBlk *children[DC395x_MAX_SCSI_ID][32];
385
386         struct pci_dev *dev;
387
388         u8 msg_len;
389
390         struct ScsiReqBlk srb_array[DC395x_MAX_SRB_CNT];
391         struct ScsiReqBlk srb;
392 };
393
394
395 /*
396  * The SEEPROM structure for TRM_S1040 
397  */
398 struct NVRamTarget {
399         u8 cfg0;                /* Target configuration byte 0  */
400         u8 period;              /* Target period                */
401         u8 cfg2;                /* Target configuration byte 2  */
402         u8 cfg3;                /* Target configuration byte 3  */
403 };
404
405
406 struct NvRamType {
407         u8 sub_vendor_id[2];    /* 0,1  Sub Vendor ID   */
408         u8 sub_sys_id[2];       /* 2,3  Sub System ID   */
409         u8 sub_class;           /* 4    Sub Class       */
410         u8 vendor_id[2];        /* 5,6  Vendor ID       */
411         u8 device_id[2];        /* 7,8  Device ID       */
412         u8 reserved;            /* 9    Reserved        */
413         struct NVRamTarget target[DC395x_MAX_SCSI_ID];
414                                                 /** 10,11,12,13
415                                                  ** 14,15,16,17
416                                                  ** ....
417                                                  ** ....
418                                                  ** 70,71,72,73
419                                                  */
420         u8 scsi_id;             /* 74 Host Adapter SCSI ID      */
421         u8 channel_cfg;         /* 75 Channel configuration     */
422         u8 delay_time;          /* 76 Power on delay time       */
423         u8 max_tag;             /* 77 Maximum tags              */
424         u8 reserved0;           /* 78  */
425         u8 boot_target;         /* 79  */
426         u8 boot_lun;            /* 80  */
427         u8 reserved1;           /* 81  */
428         u16 reserved2[22];      /* 82,..125 */
429         u16 cksum;              /* 126,127 */
430 };
431
432
433 /*---------------------------------------------------------------------------
434                             Forward declarations
435  ---------------------------------------------------------------------------*/
436 static void data_out_phase0(struct AdapterCtlBlk *acb,
437                             struct ScsiReqBlk *srb,
438                             u16 * pscsi_status);
439 static void data_in_phase0(struct AdapterCtlBlk *acb,
440                            struct ScsiReqBlk *srb,
441                            u16 * pscsi_status);
442 static void command_phase0(struct AdapterCtlBlk *acb,
443                            struct ScsiReqBlk *srb,
444                            u16 * pscsi_status);
445 static void status_phase0(struct AdapterCtlBlk *acb,
446                           struct ScsiReqBlk *srb,
447                           u16 * pscsi_status);
448 static void msgout_phase0(struct AdapterCtlBlk *acb,
449                           struct ScsiReqBlk *srb,
450                           u16 * pscsi_status);
451 static void msgin_phase0(struct AdapterCtlBlk *acb,
452                          struct ScsiReqBlk *srb,
453                          u16 * pscsi_status);
454 static void data_out_phase1(struct AdapterCtlBlk *acb,
455                             struct ScsiReqBlk *srb,
456                             u16 * pscsi_status);
457 static void data_in_phase1(struct AdapterCtlBlk *acb,
458                            struct ScsiReqBlk *srb,
459                            u16 * pscsi_status);
460 static void command_phase1(struct AdapterCtlBlk *acb,
461                            struct ScsiReqBlk *srb,
462                            u16 * pscsi_status);
463 static void status_phase1(struct AdapterCtlBlk *acb,
464                           struct ScsiReqBlk *srb,
465                           u16 * pscsi_status);
466 static void msgout_phase1(struct AdapterCtlBlk *acb,
467                           struct ScsiReqBlk *srb,
468                           u16 * pscsi_status);
469 static void msgin_phase1(struct AdapterCtlBlk *acb,
470                          struct ScsiReqBlk *srb,
471                          u16 * pscsi_status);
472 static void nop0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
473                  u16 * pscsi_status);
474 static void nop1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
475                  u16 * pscsi_status);
476 static void set_basic_config(struct AdapterCtlBlk *acb);
477 static void cleanup_after_transfer(struct AdapterCtlBlk *acb,
478                                    struct ScsiReqBlk *srb);
479 static void reset_scsi_bus(struct AdapterCtlBlk *acb);
480 static void data_io_transfer(struct AdapterCtlBlk *acb,
481                              struct ScsiReqBlk *srb, u16 io_dir);
482 static void disconnect(struct AdapterCtlBlk *acb);
483 static void reselect(struct AdapterCtlBlk *acb);
484 static u8 start_scsi(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
485                      struct ScsiReqBlk *srb);
486 static void build_srb(Scsi_Cmnd * cmd, struct DeviceCtlBlk *dcb,
487                       struct ScsiReqBlk *srb);
488 static void doing_srb_done(struct AdapterCtlBlk *acb, u8 did_code,
489                            Scsi_Cmnd * cmd, u8 force);
490 static void scsi_reset_detect(struct AdapterCtlBlk *acb);
491 static void pci_unmap_srb(struct AdapterCtlBlk *acb,
492                           struct ScsiReqBlk *srb);
493 static void pci_unmap_srb_sense(struct AdapterCtlBlk *acb,
494                                 struct ScsiReqBlk *srb);
495 static inline void enable_msgout_abort(struct AdapterCtlBlk *acb,
496                                        struct ScsiReqBlk *srb);
497 static void srb_done(struct AdapterCtlBlk *acb,
498                      struct DeviceCtlBlk *dcb,
499                      struct ScsiReqBlk *srb);
500 static void request_sense(struct AdapterCtlBlk *acb,
501                           struct DeviceCtlBlk *dcb,
502                           struct ScsiReqBlk *srb);
503 static inline void set_xfer_rate(struct AdapterCtlBlk *acb,
504                                  struct DeviceCtlBlk *dcb);
505 static void init_dcb(struct AdapterCtlBlk *acb,
506                      struct DeviceCtlBlk **pdcb, u8 target, u8 lun);
507 static void remove_dev(struct AdapterCtlBlk *acb,
508                        struct DeviceCtlBlk *dcb);
509 static void waiting_timeout(unsigned long ptr);
510
511
512 /*---------------------------------------------------------------------------
513                                  Static Data
514  ---------------------------------------------------------------------------*/
515 static struct AdapterCtlBlk *acb_list_head = NULL;
516 static struct AdapterCtlBlk *acb_list_tail = NULL;
517 static u16 adapter_count = 0;
518 static u16 current_sync_offset = 0;
519 static char monitor_next_irq = 0;
520
521 /* 
522  * dc395x_statev = (void *)dc395x_scsi_phase0[phase]
523  */
524 static void *dc395x_scsi_phase0[] = {
525         data_out_phase0,/* phase:0 */
526         data_in_phase0, /* phase:1 */
527         command_phase0, /* phase:2 */
528         status_phase0,  /* phase:3 */
529         nop0,           /* phase:4 PH_BUS_FREE .. initial phase */
530         nop0,           /* phase:5 PH_BUS_FREE .. initial phase */
531         msgout_phase0,  /* phase:6 */
532         msgin_phase0,   /* phase:7 */
533 };
534
535 /*
536  * dc395x_statev = (void *)dc395x_scsi_phase1[phase]
537  */
538 static void *dc395x_scsi_phase1[] = {
539         data_out_phase1,/* phase:0 */
540         data_in_phase1, /* phase:1 */
541         command_phase1, /* phase:2 */
542         status_phase1,  /* phase:3 */
543         nop1,           /* phase:4 PH_BUS_FREE .. initial phase */
544         nop1,           /* phase:5 PH_BUS_FREE .. initial phase */
545         msgout_phase1,  /* phase:6 */
546         msgin_phase1,   /* phase:7 */
547 };
548
549 struct NvRamType eeprom_buf[DC395x_MAX_ADAPTER_NUM];
550 /*
551  *Fast20:       000      50ns, 20.0 MHz
552  *              001      75ns, 13.3 MHz
553  *              010     100ns, 10.0 MHz
554  *              011     125ns,  8.0 MHz
555  *              100     150ns,  6.6 MHz
556  *              101     175ns,  5.7 MHz
557  *              110     200ns,  5.0 MHz
558  *              111     250ns,  4.0 MHz
559  *
560  *Fast40(LVDS): 000      25ns, 40.0 MHz
561  *              001      50ns, 20.0 MHz
562  *              010      75ns, 13.3 MHz
563  *              011     100ns, 10.0 MHz
564  *              100     125ns,  8.0 MHz
565  *              101     150ns,  6.6 MHz
566  *              110     175ns,  5.7 MHz
567  *              111     200ns,  5.0 MHz
568  */
569 /*static u8     clock_period[] = {12,19,25,31,37,44,50,62};*/
570
571 /* real period:48ns,76ns,100ns,124ns,148ns,176ns,200ns,248ns */
572 static u8 clock_period[] = { 12, 18, 25, 31, 37, 43, 50, 62 };
573 static u16 clock_speed[] = { 200, 133, 100, 80, 67, 58, 50, 40 };
574 /* real period:48ns,72ns,100ns,124ns,148ns,172ns,200ns,248ns */
575
576
577
578 /*---------------------------------------------------------------------------
579                                 Configuration
580   ---------------------------------------------------------------------------*/
581 /*
582  * Module/boot parameters currently effect *all* instances of the
583  * card in the system.
584  */
585
586 /*
587  * Command line parameters are stored in a structure below.
588  * These are the index's into the structure for the various
589  * command line options.
590  */
591 #define CFG_ADAPTER_ID          0
592 #define CFG_MAX_SPEED           1
593 #define CFG_DEV_MODE            2
594 #define CFG_ADAPTER_MODE        3
595 #define CFG_TAGS                4
596 #define CFG_RESET_DELAY         5
597
598 #define CFG_NUM                 6       /* number of configuration items */
599
600
601 /*
602  * Value used to indicate that a command line override
603  * hasn't been used to modify the value.
604  */
605 #define CFG_PARAM_UNSET -1
606
607
608 /*
609  * Hold command line parameters.
610  */
611 struct ParameterData {
612         int value;              /* value of this setting */
613         int min;                /* minimum value */
614         int max;                /* maximum value */
615         int def;                /* default value */
616         int safe;               /* safe value */
617 };
618 static struct ParameterData __initdata cfg_data[] = {
619         { /* adapter id */
620                 CFG_PARAM_UNSET,
621                 0,
622                 15,
623                 7,
624                 7
625         },
626         { /* max speed */
627                 CFG_PARAM_UNSET,
628                   0,
629                   7,
630                   1,    /* 13.3Mhz */
631                   4,    /*  6.7Hmz */
632         },
633         { /* dev mode */
634                 CFG_PARAM_UNSET,
635                 0,
636                 0x3f,
637                 NTC_DO_PARITY_CHK | NTC_DO_DISCONNECT | NTC_DO_SYNC_NEGO |
638                         NTC_DO_WIDE_NEGO | NTC_DO_TAG_QUEUEING |
639                         NTC_DO_SEND_START,
640                 NTC_DO_PARITY_CHK | NTC_DO_SEND_START
641         },
642         { /* adapter mode */
643                 CFG_PARAM_UNSET,
644                 0,
645                 0x2f,
646 #ifdef CONFIG_SCSI_MULTI_LUN
647                         NAC_SCANLUN |
648 #endif
649                 NAC_GT2DRIVES | NAC_GREATER_1G | NAC_POWERON_SCSI_RESET
650                         /*| NAC_ACTIVE_NEG*/,
651                 NAC_GT2DRIVES | NAC_GREATER_1G | NAC_POWERON_SCSI_RESET | 0x08
652         },
653         { /* tags */
654                 CFG_PARAM_UNSET,
655                 0,
656                 5,
657                 3,      /* 16 tags (??) */
658                 2,
659         },
660         { /* reset delay */
661                 CFG_PARAM_UNSET,
662                 0,
663                 180,
664                 1,      /* 1 second */
665                 10,     /* 10 seconds */
666         }
667 };
668
669
670 /*
671  * Safe settings. If set to zero the the BIOS/default values with command line
672  * overrides will be used. If set to 1 then safe and slow settings will be used.
673  */
674 static int use_safe_settings = 0;
675 module_param_named(safe, use_safe_settings, bool, 0);
676 MODULE_PARM_DESC(safe, "Use safe and slow settings only. Default: false");
677
678
679 module_param_named(adapter_id, cfg_data[CFG_ADAPTER_ID].value, int, 0);
680 MODULE_PARM_DESC(adapter_id, "Adapter SCSI ID. Default 7 (0-15)");
681
682 module_param_named(max_speed, cfg_data[CFG_MAX_SPEED].value, int, 0);
683 MODULE_PARM_DESC(max_speed, "Maximum bus speed. Default 1 (0-7) Speeds: 0=20, 1=13.3, 2=10, 3=8, 4=6.7, 5=5.8, 6=5, 7=4 Mhz");
684
685 module_param_named(dev_mode, cfg_data[CFG_DEV_MODE].value, int, 0);
686 MODULE_PARM_DESC(dev_mode, "Device mode.");
687
688 module_param_named(adapter_mode, cfg_data[CFG_ADAPTER_MODE].value, int, 0);
689 MODULE_PARM_DESC(adapter_mode, "Adapter mode.");
690
691 module_param_named(tags, cfg_data[CFG_TAGS].value, int, 0);
692 MODULE_PARM_DESC(tags, "Number of tags (1<<x). Default 3 (0-5)");
693
694 module_param_named(reset_delay, cfg_data[CFG_RESET_DELAY].value, int, 0);
695 MODULE_PARM_DESC(reset_delay, "Reset delay in seconds. Default 1 (0-180)");
696
697
698 /**
699  * set_safe_settings - if the use_safe_settings option is set then
700  * set all values to the safe and slow values.
701  **/
702 static
703 void __init set_safe_settings(void)
704 {
705         if (use_safe_settings)
706         {
707                 int i;
708
709                 dprintkl(KERN_INFO, "Using safe settings.\n");
710                 for (i = 0; i < CFG_NUM; i++)
711                 {
712                         cfg_data[i].value = cfg_data[i].safe;
713                 }
714         }
715 }
716
717
718 /**
719  * fix_settings - reset any boot parameters which are out of range
720  * back to the default values.
721  **/
722 static
723 void __init fix_settings(void)
724 {
725         int i;
726
727         dprintkdbg(DBG_PARSE, "setup %08x %08x %08x %08x %08x %08x\n",
728                     cfg_data[CFG_ADAPTER_ID].value,
729                     cfg_data[CFG_MAX_SPEED].value,
730                     cfg_data[CFG_DEV_MODE].value,
731                     cfg_data[CFG_ADAPTER_MODE].value,
732                     cfg_data[CFG_TAGS].value,
733                     cfg_data[CFG_RESET_DELAY].value);
734         for (i = 0; i < CFG_NUM; i++)
735         {
736                 if (cfg_data[i].value < cfg_data[i].min ||
737                         cfg_data[i].value > cfg_data[i].max)
738                 {
739                         cfg_data[i].value = cfg_data[i].def;
740                 }
741         }
742 }
743
744
745
746 /*
747  * Mapping from the eeprom delay index value (index into this array)
748  * to the the number of actual seconds that the delay should be for.
749  */
750 static
751 char __initdata eeprom_index_to_delay_map[] = { 1, 3, 5, 10, 16, 30, 60, 120 };
752
753
754 /**
755  * eeprom_index_to_delay - Take the eeprom delay setting and convert it
756  * into a number of seconds.
757  *
758  * @eeprom: The eeprom structure in which we find the delay index to map.
759  **/
760 static
761 void __init eeprom_index_to_delay(struct NvRamType *eeprom)
762 {
763         eeprom->delay_time = eeprom_index_to_delay_map[eeprom->delay_time];
764 }
765
766
767 /**
768  * delay_to_eeprom_index - Take a delay in seconds and return the closest
769  * eeprom index which will delay for at least that amount of seconds.
770  *
771  * @delay: The delay, in seconds, to find the eeprom index for.
772  **/
773 static int __init delay_to_eeprom_index(int delay)
774 {
775         u8 idx = 0;
776         while (idx < 7 && eeprom_index_to_delay_map[idx] < delay) {
777                 idx++;
778         }
779         return idx;
780 }
781
782
783 /**
784  * eeprom_override - Override the eeprom settings, in the provided
785  * eeprom structure, with values that have been set on the command
786  * line.
787  *
788  * @eeprom: The eeprom data to override with command line options.
789  **/
790 static
791 void __init eeprom_override(struct NvRamType *eeprom)
792 {
793         u8 id;
794
795         /* Adapter Settings */
796         if (cfg_data[CFG_ADAPTER_ID].value != CFG_PARAM_UNSET) {
797                 eeprom->scsi_id =
798                     (u8)cfg_data[CFG_ADAPTER_ID].value;
799         }
800         if (cfg_data[CFG_ADAPTER_MODE].value != CFG_PARAM_UNSET) {
801                 eeprom->channel_cfg =
802                     (u8)cfg_data[CFG_ADAPTER_MODE].value;
803         }
804         if (cfg_data[CFG_RESET_DELAY].value != CFG_PARAM_UNSET) {
805                 eeprom->delay_time =
806                     delay_to_eeprom_index(cfg_data[CFG_RESET_DELAY].value);
807         }
808         if (cfg_data[CFG_TAGS].value != CFG_PARAM_UNSET) {
809                 eeprom->max_tag = (u8)cfg_data[CFG_TAGS].value;
810         }
811
812         /* Device Settings */
813         for (id = 0; id < DC395x_MAX_SCSI_ID; id++) {
814                 if (cfg_data[CFG_DEV_MODE].value != CFG_PARAM_UNSET) {
815                         eeprom->target[id].cfg0 =
816                             (u8)cfg_data[CFG_DEV_MODE].value;
817                 }
818                 if (cfg_data[CFG_MAX_SPEED].value != CFG_PARAM_UNSET) {
819                         eeprom->target[id].period =
820                             (u8)cfg_data[CFG_MAX_SPEED].value;
821                 }
822         }
823 }
824
825
826 /*---------------------------------------------------------------------------
827  ---------------------------------------------------------------------------*/
828
829
830 /*
831  * Queueing philosphy:
832  * There are a couple of lists:
833  * - Waiting: Contains a list of SRBs not yet sent (per DCB)
834  * - Free: List of free SRB slots
835  * 
836  * If there are no waiting commands for the DCB, the new one is sent to the bus
837  * otherwise the oldest one is taken from the Waiting list and the new one is 
838  * queued to the Waiting List
839  * 
840  * Lists are managed using two pointers and eventually a counter
841  */
842
843 /* Nomen est omen ... */
844 static inline
845 void free_tag(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
846 {
847         if (srb->tag_number < 255) {
848                 dcb->tag_mask &= ~(1 << srb->tag_number);       /* free tag mask */
849                 srb->tag_number = 255;
850         }
851 }
852
853
854 /* Find cmd in SRB list */
855 inline static
856 struct ScsiReqBlk *find_cmd(Scsi_Cmnd * cmd,
857                             struct ScsiReqBlk *start)
858 {
859         struct ScsiReqBlk *psrb = start;
860         if (!start)
861                 return 0;
862         do {
863                 if (psrb->cmd == cmd)
864                         return psrb;
865                 psrb = psrb->next;
866         } while (psrb && psrb != start);
867         return 0;
868 }
869
870
871 /* Return next free SRB */
872 static inline
873 struct ScsiReqBlk *get_srb_free(struct AdapterCtlBlk *acb)
874 {
875         struct ScsiReqBlk *srb;
876
877         /*DC395x_Free_integrity (acb); */
878         srb = acb->free_srb;
879         if (!srb)
880                 dprintkl(KERN_ERR, "Out of Free SRBs :-(\n");
881         if (srb) {
882                 acb->free_srb = srb->next;
883                 srb->next = NULL;
884         }
885
886         return srb;
887 }
888
889
890 /* Insert SRB oin top of free list */
891 static inline
892 void insert_srb_free(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
893 {
894         dprintkdbg(DBG_0, "Free SRB %p\n", srb);
895         srb->next = acb->free_srb;
896         acb->free_srb = srb;
897 }
898
899
900 /* Inserts a SRB to the top of the Waiting list */
901 static inline
902 void insert_srb_waiting(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
903 {
904         dprintkdbg(DBG_0, "Insert srb %p cmd %li to Waiting\n", srb, srb->cmd->pid);
905         srb->next = dcb->waiting_srb;
906         if (!dcb->waiting_srb)
907                 dcb->wait_list = srb;
908         dcb->waiting_srb = srb;
909         dcb->waiting_srb_count++;
910 }
911
912
913 /* Queue SRB to waiting list */
914 static inline
915 void append_srb_waiting(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
916 {
917         dprintkdbg(DBG_0, "Append srb %p cmd %li to Waiting\n", srb, srb->cmd->pid);
918         if (dcb->waiting_srb)
919                 dcb->wait_list->next = srb;
920         else
921                 dcb->waiting_srb = srb;
922
923         dcb->wait_list = srb;
924         /* No next one in waiting list */
925         srb->next = NULL;
926         dcb->waiting_srb_count++;
927 }
928
929
930 static inline
931 void append_srb_going(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
932 {
933         dprintkdbg(DBG_0, "Append SRB %p to Going\n", srb);
934         /* Append to the list of Going commands */
935         if (dcb->going_srb)
936                 dcb->going_last->next = srb;
937         else
938                 dcb->going_srb = srb;
939
940         dcb->going_last = srb;
941         /* No next one in sent list */
942         srb->next = NULL;
943         dcb->going_srb_count++;
944 }
945
946
947 /* Find predecessor SRB */
948 inline static
949 struct ScsiReqBlk *find_srb_prev(struct ScsiReqBlk *srb,
950                                  struct ScsiReqBlk *start)
951 {
952         struct ScsiReqBlk *p = start;
953         if (!start)
954                 return 0;
955         do {
956                 if (p->next == srb)
957                         return p;
958                 p = p->next;
959         } while (p && p != start);
960         return 0;
961 }
962
963
964 /* Remove SRB from SRB queue */
965 inline static
966 struct ScsiReqBlk *remove_srb(struct ScsiReqBlk *srb,
967                               struct ScsiReqBlk *pre)
968 {
969         if (pre->next != srb)
970                 pre = find_srb_prev(srb, pre);
971         if (!pre) {
972                 dprintkl(KERN_ERR, "Internal ERROR: SRB to rmv not found in Q!\n");
973                 return 0;
974         }
975         pre->next = srb->next;
976         /*srb->next = NULL; */
977         return pre;
978 }
979
980
981 /* Remove SRB from Going queue */
982 static
983 void remove_srb_going(struct DeviceCtlBlk *dcb,
984                       struct ScsiReqBlk *srb,
985                       struct ScsiReqBlk *hint)
986 {
987         struct ScsiReqBlk *pre = NULL;
988         dprintkdbg(DBG_0, "Remove SRB %p from Going\n", srb);
989         if (!srb)
990                 dprintkl(KERN_ERR, "Going_remove %p!\n", srb);
991         if (srb == dcb->going_srb)
992                 dcb->going_srb = srb->next;
993         else if (hint && hint->next == srb)
994                 pre = remove_srb(srb, hint);
995         else
996                 pre = remove_srb(srb, dcb->going_srb);
997         if (srb == dcb->going_last)
998                 dcb->going_last = pre;
999         dcb->going_srb_count--;
1000 }
1001
1002
1003 /* Remove SRB from Waiting queue */
1004 static
1005 void remove_srb_waiting(struct DeviceCtlBlk *dcb,
1006                         struct ScsiReqBlk *srb,
1007                         struct ScsiReqBlk *hint)
1008 {
1009         struct ScsiReqBlk *pre = NULL;
1010         dprintkdbg(DBG_0, "Remove SRB %p from Waiting\n", srb);
1011         if (!srb)
1012                 dprintkl(KERN_ERR, "Waiting_remove %p!\n", srb);
1013         if (srb == dcb->waiting_srb)
1014                 dcb->waiting_srb = srb->next;
1015         else if (hint && hint->next == srb)
1016                 pre = remove_srb(srb, hint);
1017         else
1018                 pre = remove_srb(srb, dcb->waiting_srb);
1019         if (srb == dcb->wait_list)
1020                 dcb->wait_list = pre;
1021         dcb->waiting_srb_count--;
1022 }
1023
1024
1025 /* Moves SRB from Going list to the top of Waiting list */
1026 static
1027 void move_srb_going_to_waiting(struct DeviceCtlBlk *dcb,
1028                                struct ScsiReqBlk *srb)
1029 {
1030         dprintkdbg(DBG_0, "Going_to_Waiting (SRB %p) pid = %li\n", srb, srb->cmd->pid);
1031         /* Remove SRB from Going */
1032         remove_srb_going(dcb, srb, 0);
1033         TRACEPRINTF("GtW *");
1034         /* Insert on top of Waiting */
1035         insert_srb_waiting(dcb, srb);
1036         /* Tag Mask must be freed elsewhere ! (KG, 99/06/18) */
1037 }
1038
1039
1040 /* Moves first SRB from Waiting list to Going list */
1041 static inline
1042 void move_srb_waiting_to_going(struct DeviceCtlBlk *dcb,
1043                                struct ScsiReqBlk *srb)
1044 {
1045         /* Remove from waiting list */
1046         dprintkdbg(DBG_0, "Remove SRB %p from head of Waiting\n", srb);
1047         remove_srb_waiting(dcb, srb, 0);
1048         TRACEPRINTF("WtG *");
1049         append_srb_going(dcb, srb);
1050 }
1051
1052
1053 /* Sets the timer to wake us up */
1054 static
1055 void waiting_set_timer(struct AdapterCtlBlk *acb, unsigned long to)
1056 {
1057         if (timer_pending(&acb->waiting_timer))
1058                 return;
1059         init_timer(&acb->waiting_timer);
1060         acb->waiting_timer.function = waiting_timeout;
1061         acb->waiting_timer.data = (unsigned long) acb;
1062         if (time_before(jiffies + to, acb->scsi_host->last_reset - HZ / 2))
1063                 acb->waiting_timer.expires =
1064                     acb->scsi_host->last_reset - HZ / 2 + 1;
1065         else
1066                 acb->waiting_timer.expires = jiffies + to + 1;
1067         add_timer(&acb->waiting_timer);
1068 }
1069
1070
1071 /* Send the next command from the waiting list to the bus */
1072 static
1073 void waiting_process_next(struct AdapterCtlBlk *acb)
1074 {
1075         struct DeviceCtlBlk *ptr;
1076         struct DeviceCtlBlk *ptr1;
1077         struct ScsiReqBlk *srb;
1078
1079         if ((acb->active_dcb)
1080             || (acb->acb_flag & (RESET_DETECT + RESET_DONE + RESET_DEV)))
1081                 return;
1082         if (timer_pending(&acb->waiting_timer))
1083                 del_timer(&acb->waiting_timer);
1084         ptr = acb->dcb_run_robin;
1085         if (!ptr) {             /* This can happen! */
1086                 ptr = acb->link_dcb;
1087                 acb->dcb_run_robin = ptr;
1088         }
1089         ptr1 = ptr;
1090         if (!ptr1)
1091                 return;
1092         do {
1093                 /* Make sure, the next another device gets scheduled ... */
1094                 acb->dcb_run_robin = ptr1->next;
1095                 if (!(srb = ptr1->waiting_srb)
1096                     || (ptr1->max_command <= ptr1->going_srb_count))
1097                         ptr1 = ptr1->next;
1098                 else {
1099                         /* Try to send to the bus */
1100                         if (!start_scsi(acb, ptr1, srb))
1101                                 move_srb_waiting_to_going(ptr1, srb);
1102                         else
1103                                 waiting_set_timer(acb, HZ / 50);
1104                         break;
1105                 }
1106         } while (ptr1 != ptr);
1107         return;
1108 }
1109
1110
1111 /* Wake up waiting queue */
1112 static void waiting_timeout(unsigned long ptr)
1113 {
1114         unsigned long flags;
1115         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *) ptr;
1116         dprintkdbg(DBG_KG, "Debug: Waiting queue woken up by timer.\n");
1117         DC395x_LOCK_IO(acb->scsi_host, flags);
1118         waiting_process_next(acb);
1119         DC395x_UNLOCK_IO(acb->scsi_host, flags);
1120 }
1121
1122
1123 /* Get the DCB for a given ID/LUN combination */
1124 static inline
1125 struct DeviceCtlBlk *find_dcb(struct AdapterCtlBlk *acb, u8 id, u8 lun)
1126 {
1127         return acb->children[id][lun];
1128 }
1129
1130
1131 /***********************************************************************
1132  * Function: static void send_srb (struct AdapterCtlBlk* acb, struct ScsiReqBlk* srb)
1133  *
1134  * Purpose: Send SCSI Request Block (srb) to adapter (acb)
1135  *
1136  *            dc395x_queue_command
1137  *            waiting_process_next
1138  *
1139  ***********************************************************************/
1140 static
1141 void send_srb(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
1142 {
1143         struct DeviceCtlBlk *dcb;
1144
1145         dcb = srb->dcb;
1146         if ((dcb->max_command <= dcb->going_srb_count) ||
1147             (acb->active_dcb) ||
1148             (acb->acb_flag & (RESET_DETECT + RESET_DONE + RESET_DEV))) {
1149                 append_srb_waiting(dcb, srb);
1150                 waiting_process_next(acb);
1151                 return;
1152         }
1153 #if 0
1154         if (dcb->waiting_srb) {
1155                 append_srb_waiting(dcb, srb);
1156                 /*      srb = waiting_srb_get(dcb); *//* non-existent */
1157                 srb = dcb->waiting_srb;
1158                 /* Remove from waiting list */
1159                 dcb->waiting_srb = srb->next;
1160                 srb->next = NULL;
1161                 if (!dcb->waiting_srb)
1162                         dcb->wait_list = NULL;
1163         }
1164 #endif
1165
1166         if (!start_scsi(acb, dcb, srb))
1167                 append_srb_going(dcb, srb);
1168         else {
1169                 insert_srb_waiting(dcb, srb);
1170                 waiting_set_timer(acb, HZ / 50);
1171         }
1172 }
1173
1174
1175 /*
1176  *********************************************************************
1177  *
1178  * Function: static void build_srb (Scsi_Cmd *cmd, struct DeviceCtlBlk* dcb, struct ScsiReqBlk* srb)
1179  *
1180  *  Purpose: Prepare SRB for being sent to Device DCB w/ command *cmd
1181  *
1182  *********************************************************************
1183  */
1184 static
1185 void build_srb(Scsi_Cmnd * cmd, struct DeviceCtlBlk *dcb,
1186                struct ScsiReqBlk *srb)
1187 {
1188         int i, max;
1189         struct SGentry *sgp;
1190         struct scatterlist *sl;
1191         u32 request_size;
1192         int dir;
1193
1194         dprintkdbg(DBG_0, "build_srb..............\n");
1195         /*memset (srb, 0, sizeof (struct ScsiReqBlk)); */
1196         srb->dcb = dcb;
1197         srb->cmd = cmd;
1198         /* Find out about direction */
1199         dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
1200
1201         if (cmd->use_sg && dir != PCI_DMA_NONE) {
1202                 unsigned int len = 0;
1203                 /* TODO: In case usg_sg and the no of segments differ, things
1204                  * will probably go wrong. */
1205                 max = srb->sg_count =
1206                     pci_map_sg(dcb->acb->dev,
1207                                (struct scatterlist *) cmd->request_buffer,
1208                                cmd->use_sg, dir);
1209                 sgp = srb->segment_x;
1210                 request_size = cmd->request_bufflen;
1211                 dprintkdbg(DBG_SGPARANOIA, 
1212                        "BuildSRB: Bufflen = %d, buffer = %p, use_sg = %d\n",
1213                        cmd->request_bufflen, cmd->request_buffer,
1214                        cmd->use_sg);
1215                 dprintkdbg(DBG_SGPARANOIA, 
1216                        "Mapped %i Segments to %i\n", cmd->use_sg,
1217                        srb->sg_count);
1218                 sl = (struct scatterlist *) cmd->request_buffer;
1219
1220                 srb->virt_addr = page_address(sl->page);
1221                 for (i = 0; i < max; i++) {
1222                         u32 busaddr = (u32) sg_dma_address(&sl[i]);
1223                         u32 seglen = (u32) sl[i].length;
1224                         sgp[i].address = busaddr;
1225                         sgp[i].length = seglen;
1226                         len += seglen;
1227                         dprintkdbg(DBG_SGPARANOIA,
1228                                "Setting up sgp %d, address = 0x%08x, length = %d, tot len = %d\n",
1229                                i, busaddr, seglen, len);
1230                 }
1231                 sgp += max - 1;
1232                 /* Fixup for last buffer too big as it is allocated on even page boundaries */
1233                 if (len > request_size) {
1234 #if debug_enabled(DBG_KG) || debug_enabled(DBG_SGPARANOIA)
1235                         dprintkdbg(DBG_KG|DBG_SGPARANOIA,
1236                                "Fixup SG total length: %d->%d, last seg %d->%d\n",
1237                                len, request_size, sgp->length,
1238                                sgp->length - (len - request_size));
1239 #endif
1240                         sgp->length -= (len - request_size);
1241                         len = request_size;
1242                 }
1243                 /* WIDE padding */
1244                 if (dcb->sync_period & WIDE_SYNC && len % 2) {
1245                         len++;
1246                         sgp->length++;
1247                 }
1248                 srb->total_xfer_length = len;   /*? */
1249                 /* Hopefully this does not cross a page boundary ... */
1250                 srb->sg_bus_addr =
1251                     pci_map_single(dcb->acb->dev, srb->segment_x,
1252                                    sizeof(struct SGentry) *
1253                                    DC395x_MAX_SG_LISTENTRY,
1254                                    PCI_DMA_TODEVICE);
1255                 dprintkdbg(DBG_SGPARANOIA,
1256                        "Map SG descriptor list %p (%05x) to %08x\n",
1257                        srb->segment_x,
1258                        sizeof(struct SGentry) * DC395x_MAX_SG_LISTENTRY,
1259                        srb->sg_bus_addr);
1260         } else {
1261                 if (cmd->request_buffer && dir != PCI_DMA_NONE) {
1262                         u32 len = cmd->request_bufflen; /* Actual request size */
1263                         srb->sg_count = 1;
1264                         srb->segment_x[0].address =
1265                             pci_map_single(dcb->acb->dev,
1266                                            cmd->request_buffer, len, dir);
1267                         /* WIDE padding */
1268                         if (dcb->sync_period & WIDE_SYNC && len % 2)
1269                                 len++;
1270                         srb->segment_x[0].length = len;
1271                         srb->total_xfer_length = len;
1272                         srb->virt_addr = cmd->request_buffer;
1273                         srb->sg_bus_addr = 0;
1274                         dprintkdbg(DBG_SGPARANOIA,
1275                                "BuildSRB: len = %d, buffer = %p, use_sg = %d, map %08x\n",
1276                                len, cmd->request_buffer, cmd->use_sg,
1277                                srb->segment_x[0].address);
1278                 } else {
1279                         srb->sg_count = 0;
1280                         srb->total_xfer_length = 0;
1281                         srb->sg_bus_addr = 0;
1282                         srb->virt_addr = 0;
1283                         dprintkdbg(DBG_SGPARANOIA,
1284                                "BuildSRB: buflen = %d, buffer = %p, use_sg = %d, NOMAP %08x\n",
1285                                cmd->bufflen, cmd->request_buffer,
1286                                cmd->use_sg, srb->segment_x[0].address);
1287                 }
1288         }
1289
1290         srb->sg_index = 0;
1291         srb->adapter_status = 0;
1292         srb->target_status = 0;
1293         srb->msg_count = 0;
1294         srb->status = 0;
1295         srb->flag = 0;
1296         srb->state = 0;
1297         srb->retry_count = 0;
1298
1299 #if debug_enabled(DBG_TRACE|DBG_TRACEALL) && debug_enabled(DBG_SGPARANOIA)
1300         if ((unsigned long)srb->debugtrace & (DEBUGTRACEBUFSZ - 1)) {
1301                 dprintkdbg(DBG_SGPARANOIA,
1302                         "SRB %i (%p): debugtrace %p corrupt!\n",
1303                        (srb - dcb->acb->srb_array) /
1304                        sizeof(struct ScsiReqBlk), srb, srb->debugtrace);
1305         }
1306 #endif
1307 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
1308         srb->debugpos = 0;
1309         srb->debugtrace = 0;
1310 #endif
1311         TRACEPRINTF("pid %li(%li):%02x %02x..(%i-%i) *", cmd->pid,
1312                     jiffies, cmd->cmnd[0], cmd->cmnd[1],
1313                     cmd->device->id, cmd->device->lun);
1314         srb->tag_number = TAG_NONE;
1315
1316         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
1317         srb->end_message = 0;
1318         return;
1319 }
1320
1321
1322
1323 /**
1324  * dc395x_queue_command - queue scsi command passed from the mid
1325  * layer, invoke 'done' on completion
1326  *
1327  * @cmd: pointer to scsi command object
1328  * @done: function pointer to be invoked on completion
1329  *
1330  * Returns 1 if the adapter (host) is busy, else returns 0. One
1331  * reason for an adapter to be busy is that the number
1332  * of outstanding queued commands is already equal to
1333  * struct Scsi_Host::can_queue .
1334  *
1335  * Required: if struct Scsi_Host::can_queue is ever non-zero
1336  *           then this function is required.
1337  *
1338  * Locks: struct Scsi_Host::host_lock held on entry (with "irqsave")
1339  *        and is expected to be held on return.
1340  *
1341  **/
1342 static int
1343 dc395x_queue_command(Scsi_Cmnd *cmd, void (*done)(Scsi_Cmnd *))
1344 {
1345         struct DeviceCtlBlk *dcb;
1346         struct ScsiReqBlk *srb;
1347         struct AdapterCtlBlk *acb =
1348             (struct AdapterCtlBlk *)cmd->device->host->hostdata;
1349
1350         dprintkdbg(DBG_0, "Queue Cmd=%02x,Tgt=%d,LUN=%d (pid=%li)\n",
1351                    cmd->cmnd[0],
1352                    cmd->device->id,
1353                    cmd->device->lun,
1354                    cmd->pid);
1355
1356 #if debug_enabled(DBG_RECURSION)
1357         if (dbg_in_driver++ > NORM_REC_LVL) {
1358                 dprintkl(KERN_DEBUG,
1359                         "%i queue_command () recursion? (pid=%li)\n",
1360                         dbg_in_driver, cmd->pid);
1361         }
1362 #endif
1363
1364         /* Assume BAD_TARGET; will be cleared later */
1365         cmd->result = DID_BAD_TARGET << 16;
1366
1367         /* ignore invalid targets */
1368         if (cmd->device->id >= acb->scsi_host->max_id ||
1369             cmd->device->lun >= acb->scsi_host->max_lun ||
1370             cmd->device->lun >31) {
1371                 goto complete;
1372         }
1373
1374         /* does the specified lun on the specified device exist */
1375         if (!(acb->dcb_map[cmd->device->id] & (1 << cmd->device->lun))) {
1376                 dprintkl(KERN_INFO, "Ignore target %02x lun %02x\n", cmd->device->id,
1377                        cmd->device->lun);
1378                 goto complete;
1379         }
1380
1381         /* do we have a DCB for the device */
1382         dcb = find_dcb(acb, cmd->device->id, cmd->device->lun);
1383         if (!dcb) {
1384                 /* should never happen */
1385                 dprintkl(KERN_ERR, "no DCB failed, target %02x lun %02x\n",
1386                                    cmd->device->id, cmd->device->lun);
1387                 dprintkl(KERN_ERR, "No DCB in queuecommand (2)!\n");
1388                 goto complete;
1389         }
1390
1391         /* set callback and clear result in the command */
1392         cmd->scsi_done = done;
1393         cmd->result = 0;
1394
1395         /* get a free SRB */
1396         srb = get_srb_free(acb);
1397         if (!srb)
1398         {
1399                 /*
1400                  * Return 1 since we are unable to queue this command at this
1401                  * point in time.
1402                  */
1403                 dprintkdbg(DBG_0, "No free SRB's in queuecommand\n");
1404                 return 1;
1405         }
1406
1407         /* build srb for the command */
1408         build_srb(cmd, dcb, srb);
1409
1410         if (dcb->waiting_srb) {
1411                 /* append to waiting queue */
1412                 append_srb_waiting(dcb, srb);
1413                 waiting_process_next(acb);
1414         } else {
1415                 /* process immediately */
1416                 send_srb(acb, srb);
1417         }
1418         dprintkdbg(DBG_1, "... command (pid %li) queued successfully.\n", cmd->pid);
1419
1420 #if debug_enabled(DBG_RECURSION)
1421         dbg_in_driver--
1422 #endif
1423         return 0;
1424
1425 complete:
1426         /*
1427          * Complete the command immediatey, and then return 0 to
1428          * indicate that we have handled the command. This is usually
1429          * done when the commad is for things like non existent
1430          * devices.
1431          */
1432 #if debug_enabled(DBG_RECURSION)
1433                 dbg_in_driver--
1434 #endif
1435         done(cmd);
1436         return 0;
1437 }
1438
1439
1440 /***********************************************************************
1441  * Function static int dc395x_slave_alloc()
1442  *
1443  * Purpose: Allocate DCB
1444  ***********************************************************************/
1445 static int dc395x_slave_alloc(struct scsi_device *sdp)
1446 {
1447         struct AdapterCtlBlk *acb;
1448         struct DeviceCtlBlk *dummy;
1449
1450         acb = (struct AdapterCtlBlk *) sdp->host->hostdata;
1451
1452         init_dcb(acb, &dummy, sdp->id, sdp->lun);
1453
1454         return dummy ? 0 : -ENOMEM;
1455 }
1456
1457
1458 static void dc395x_slave_destroy(struct scsi_device *sdp)
1459 {
1460         struct AdapterCtlBlk *acb;
1461         struct DeviceCtlBlk *dcb;
1462
1463         acb = (struct AdapterCtlBlk *) sdp->host->hostdata;
1464         dcb = find_dcb(acb, sdp->id, sdp->lun);
1465
1466         remove_dev(acb, dcb);
1467 }
1468
1469
1470 /*
1471  *********************************************************************
1472  *
1473  * Function   : dc395x_bios_param
1474  * Description: Return the disk geometry for the given SCSI device.
1475  *********************************************************************
1476  */
1477 static
1478 int dc395x_bios_param(struct scsi_device *sdev,
1479                       struct block_device *bdev,
1480                       sector_t capacity,
1481                       int *info)
1482 {
1483 #ifdef CONFIG_SCSI_DC395x_TRMS1040_TRADMAP
1484         int heads, sectors, cylinders;
1485         struct AdapterCtlBlk *acb;
1486         int size = capacity;
1487
1488         dprintkdbg(DBG_0, "dc395x_bios_param..............\n");
1489         acb = (struct AdapterCtlBlk *) sdev->host->hostdata;
1490         heads = 64;
1491         sectors = 32;
1492         cylinders = size / (heads * sectors);
1493
1494         if ((acb->gmode2 & NAC_GREATER_1G) && (cylinders > 1024)) {
1495                 heads = 255;
1496                 sectors = 63;
1497                 cylinders = size / (heads * sectors);
1498         }
1499         geom[0] = heads;
1500         geom[1] = sectors;
1501         geom[2] = cylinders;
1502         return 0;
1503 #else
1504         return scsicam_bios_param(bdev, capacity, info);
1505 #endif
1506 }
1507
1508
1509 /*
1510  * DC395x register dump
1511  */
1512 static
1513 void dump_register_info(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
1514                         struct ScsiReqBlk *srb)
1515 {
1516         u16 pstat;
1517         struct pci_dev *dev = acb->dev;
1518         pci_read_config_word(dev, PCI_STATUS, &pstat);
1519         if (!dcb)
1520                 dcb = acb->active_dcb;
1521         if (!srb && dcb)
1522                 srb = dcb->active_srb;
1523         if (srb) {
1524                 if (!(srb->cmd))
1525                         dprintkl(KERN_INFO, "dump: SRB %p: cmd %p OOOPS!\n", srb,
1526                                srb->cmd);
1527                 else
1528                         dprintkl(KERN_INFO, "dump: SRB %p: cmd %p pid %li: %02x (%02i-%i)\n",
1529                                srb, srb->cmd, srb->cmd->pid,
1530                                srb->cmd->cmnd[0], srb->cmd->device->id,
1531                                srb->cmd->device->lun);
1532                 printk("              SGList %p Cnt %i Idx %i Len %i\n",
1533                        srb->segment_x, srb->sg_count, srb->sg_index,
1534                        srb->total_xfer_length);
1535                 printk
1536                     ("              State %04x Status %02x Phase %02x (%sconn.)\n",
1537                      srb->state, srb->status, srb->scsi_phase,
1538                      (acb->active_dcb) ? "" : "not");
1539                 TRACEOUT("        %s\n", srb->debugtrace);
1540         }
1541         dprintkl(KERN_INFO, "dump: SCSI block\n");
1542         printk
1543             ("              Status %04x FIFOCnt %02x Signals %02x IRQStat %02x\n",
1544              DC395x_read16(acb, TRM_S1040_SCSI_STATUS),
1545              DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
1546              DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL),
1547              DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS));
1548         printk
1549             ("              Sync %02x Target %02x RSelID %02x SCSICtr %08x\n",
1550              DC395x_read8(acb, TRM_S1040_SCSI_SYNC),
1551              DC395x_read8(acb, TRM_S1040_SCSI_TARGETID),
1552              DC395x_read8(acb, TRM_S1040_SCSI_IDMSG),
1553              DC395x_read32(acb, TRM_S1040_SCSI_COUNTER));
1554         printk
1555             ("              IRQEn %02x Config %04x Cfg2 %02x Cmd %02x SelTO %02x\n",
1556              DC395x_read8(acb, TRM_S1040_SCSI_INTEN),
1557              DC395x_read16(acb, TRM_S1040_SCSI_CONFIG0),
1558              DC395x_read8(acb, TRM_S1040_SCSI_CONFIG2),
1559              DC395x_read8(acb, TRM_S1040_SCSI_COMMAND),
1560              DC395x_read8(acb, TRM_S1040_SCSI_TIMEOUT));
1561         dprintkl(KERN_INFO, "dump: DMA block\n");
1562         printk
1563             ("              Cmd %04x FIFOCnt %02x FStat %02x IRQStat %02x IRQEn %02x Cfg %04x\n",
1564              DC395x_read16(acb, TRM_S1040_DMA_COMMAND),
1565              DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
1566              DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
1567              DC395x_read8(acb, TRM_S1040_DMA_STATUS),
1568              DC395x_read8(acb, TRM_S1040_DMA_INTEN),
1569              DC395x_read16(acb, TRM_S1040_DMA_CONFIG));
1570         printk("              TCtr %08x CTCtr %08x Addr %08x%08x\n",
1571                DC395x_read32(acb, TRM_S1040_DMA_XCNT),
1572                DC395x_read32(acb, TRM_S1040_DMA_CXCNT),
1573                DC395x_read32(acb, TRM_S1040_DMA_XHIGHADDR),
1574                DC395x_read32(acb, TRM_S1040_DMA_XLOWADDR));
1575         dprintkl(KERN_INFO, "dump: Misc: GCtrl %02x GStat %02x GTmr %02x\n",
1576                DC395x_read8(acb, TRM_S1040_GEN_CONTROL),
1577                DC395x_read8(acb, TRM_S1040_GEN_STATUS),
1578                DC395x_read8(acb, TRM_S1040_GEN_TIMER));
1579         dprintkl(KERN_INFO, "dump: PCI Status %04x\n", pstat);
1580
1581
1582 }
1583
1584
1585 static inline void clear_fifo(struct AdapterCtlBlk *acb, char *txt)
1586 {
1587 #if debug_enabled(DBG_FIFO)
1588         u8 lines = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
1589         u8 fifocnt = DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT);
1590         if (!(fifocnt & 0x40))
1591                 dprintkdbg(DBG_FIFO,
1592                        "Clr FIFO (%i bytes) on phase %02x in %s\n",
1593                         fifocnt & 0x3f, lines, txt);
1594 #endif
1595 #if debug_enabled(DBG_TRACE)   
1596         if (acb->active_dcb && acb->active_dcb->active_srb) {
1597                 struct ScsiReqBlk *srb = acb->active_dcb->active_srb;
1598                 TRACEPRINTF("#*");
1599         }
1600 #endif
1601         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_CLRFIFO);
1602 }
1603
1604
1605 /*
1606  ********************************************************************
1607  *
1608  *              DC395x_reset      scsi_reset_detect
1609  *
1610  ********************************************************************
1611  */
1612 static void reset_dev_param(struct AdapterCtlBlk *acb)
1613 {
1614         struct DeviceCtlBlk *dcb;
1615         struct DeviceCtlBlk *dcb_temp;
1616         struct NvRamType *eeprom;
1617         u8 period_index;
1618         u16 index;
1619
1620         dprintkdbg(DBG_0, "reset_dev_param..............\n");
1621         dcb = acb->link_dcb;
1622         if (dcb == NULL)
1623                 return;
1624
1625         dcb_temp = dcb;
1626         do {
1627                 dcb->sync_mode &= ~(SYNC_NEGO_DONE + WIDE_NEGO_DONE);
1628                 dcb->sync_period = 0;
1629                 dcb->sync_offset = 0;
1630                 index = acb->adapter_index;
1631                 eeprom = &eeprom_buf[index];
1632
1633                 dcb->dev_mode = eeprom->target[dcb->target_id].cfg0;
1634                 /*dcb->AdpMode = eeprom->channel_cfg; */
1635                 period_index = eeprom->target[dcb->target_id].period & 0x07;
1636                 dcb->min_nego_period = clock_period[period_index];
1637                 if (!(dcb->dev_mode & NTC_DO_WIDE_NEGO)
1638                     || !(acb->config & HCC_WIDE_CARD))
1639                         dcb->sync_mode &= ~WIDE_NEGO_ENABLE;
1640
1641                 dcb = dcb->next;
1642         }
1643         while (dcb_temp != dcb && dcb != NULL);
1644 }
1645
1646
1647 /*
1648  *********************************************************************
1649  * Function : int dc395x_eh_bus_reset(Scsi_Cmnd *cmd)
1650  * Purpose  : perform a hard reset on the SCSI bus
1651  * Inputs   : cmd - some command for this host (for fetching hooks)
1652  * Returns  : SUCCESS (0x2002) on success, else FAILED (0x2003).
1653  *********************************************************************
1654  */
1655 static int dc395x_eh_bus_reset(Scsi_Cmnd * cmd)
1656 {
1657         struct AdapterCtlBlk *acb;
1658         /*u32         acb_flags=0; */
1659
1660         dprintkl(KERN_INFO, "reset requested!\n");
1661         acb = (struct AdapterCtlBlk *) cmd->device->host->hostdata;
1662         /* mid level guarantees no recursion */
1663         /*DC395x_ACB_LOCK(acb,acb_flags); */
1664
1665         if (timer_pending(&acb->waiting_timer))
1666                 del_timer(&acb->waiting_timer);
1667
1668         /*
1669          * disable interrupt    
1670          */
1671         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0x00);
1672         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x00);
1673         DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
1674         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
1675
1676         reset_scsi_bus(acb);
1677         udelay(500);
1678
1679         /* We may be in serious trouble. Wait some seconds */
1680         acb->scsi_host->last_reset =
1681             jiffies + 3 * HZ / 2 +
1682             HZ * eeprom_buf[acb->adapter_index].delay_time;
1683
1684         /*
1685          * re-enable interrupt      
1686          */
1687         /* Clear SCSI FIFO          */
1688         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
1689         clear_fifo(acb, "reset");
1690         /* Delete pending IRQ */
1691         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
1692         set_basic_config(acb);
1693
1694         reset_dev_param(acb);
1695         doing_srb_done(acb, DID_RESET, cmd, 0);
1696
1697         acb->active_dcb = NULL;
1698
1699         acb->acb_flag = 0;      /* RESET_DETECT, RESET_DONE ,RESET_DEV */
1700         waiting_process_next(acb);
1701
1702         /*DC395x_ACB_LOCK(acb,acb_flags); */
1703         return SUCCESS;
1704 }
1705
1706
1707 /*
1708  *********************************************************************
1709  * Function : int dc395x_eh_abort(Scsi_Cmnd *cmd)
1710  * Purpose  : abort an errant SCSI command
1711  * Inputs   : cmd - command to be aborted
1712  * Returns  : SUCCESS (0x2002) on success, else FAILED (0x2003).
1713  *********************************************************************
1714  */
1715 static int dc395x_eh_abort(Scsi_Cmnd * cmd)
1716 {
1717         /*
1718          * Look into our command queues: If it has not been sent already,
1719          * we remove it and return success. Otherwise fail.
1720          */
1721         struct AdapterCtlBlk *acb =
1722             (struct AdapterCtlBlk *) cmd->device->host->hostdata;
1723         struct DeviceCtlBlk *dcb;
1724         struct ScsiReqBlk *srb;
1725
1726         dprintkl(KERN_INFO, "eh abort: cmd %p (pid %li, %02i-%i) ",
1727                              cmd,
1728                              cmd->pid,
1729                              cmd->device->id,
1730                              cmd->device->lun);
1731
1732         dcb = find_dcb(acb, cmd->device->id, cmd->device->lun);
1733         if (!dcb) {
1734                 dprintkl(KERN_DEBUG, "abort - no DCB found");
1735                 return FAILED;
1736         }
1737
1738         srb = find_cmd(cmd, dcb->waiting_srb);
1739         if (srb) {
1740                 remove_srb_waiting(dcb, srb, 0);
1741                 pci_unmap_srb_sense(acb, srb);
1742                 pci_unmap_srb(acb, srb);
1743                 free_tag(dcb, srb);
1744                 insert_srb_free(acb, srb);
1745                 dprintkl(KERN_DEBUG, "abort - command found in waiting commands queue");
1746                 cmd->result = DID_ABORT << 16;
1747                 return SUCCESS;
1748         }
1749         srb = find_cmd(cmd, dcb->going_srb);
1750         if (srb) {
1751                 dprintkl(KERN_DEBUG, "abort - command currently in progress");
1752                 /* XXX: Should abort the command here */
1753         } else {
1754                 dprintkl(KERN_DEBUG, "abort - command not found");
1755         }
1756         return FAILED;
1757 }
1758
1759
1760 /* SDTR */
1761 static
1762 void build_sdtr(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
1763                 struct ScsiReqBlk *srb)
1764 {
1765         u8 *ptr = srb->msgout_buf + srb->msg_count;
1766         if (srb->msg_count > 1) {
1767                 dprintkl(KERN_INFO,
1768                        "Build_SDTR: msgout_buf BUSY (%i: %02x %02x)\n",
1769                        srb->msg_count, srb->msgout_buf[0],
1770                        srb->msgout_buf[1]);
1771                 return;
1772         }
1773         if (!(dcb->dev_mode & NTC_DO_SYNC_NEGO)) {
1774                 dcb->sync_offset = 0;
1775                 dcb->min_nego_period = 200 >> 2;
1776         } else if (dcb->sync_offset == 0)
1777                 dcb->sync_offset = SYNC_NEGO_OFFSET;
1778
1779         *ptr++ = MSG_EXTENDED;  /* (01h) */
1780         *ptr++ = 3;             /* length */
1781         *ptr++ = EXTENDED_SDTR; /* (01h) */
1782         *ptr++ = dcb->min_nego_period;  /* Transfer period (in 4ns) */
1783         *ptr++ = dcb->sync_offset;      /* Transfer period (max. REQ/ACK dist) */
1784         srb->msg_count += 5;
1785         srb->state |= SRB_DO_SYNC_NEGO;
1786         TRACEPRINTF("S *");
1787 }
1788
1789
1790 /* SDTR */
1791 static
1792 void build_wdtr(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
1793                 struct ScsiReqBlk *srb)
1794 {
1795         u8 wide =
1796             ((dcb->dev_mode & NTC_DO_WIDE_NEGO) & (acb->
1797                                                    config & HCC_WIDE_CARD))
1798             ? 1 : 0;
1799         u8 *ptr = srb->msgout_buf + srb->msg_count;
1800         if (srb->msg_count > 1) {
1801                 dprintkl(KERN_INFO,
1802                        "Build_WDTR: msgout_buf BUSY (%i: %02x %02x)\n",
1803                        srb->msg_count, srb->msgout_buf[0],
1804                        srb->msgout_buf[1]);
1805                 return;
1806         }
1807         *ptr++ = MSG_EXTENDED;  /* (01h) */
1808         *ptr++ = 2;             /* length */
1809         *ptr++ = EXTENDED_WDTR; /* (03h) */
1810         *ptr++ = wide;
1811         srb->msg_count += 4;
1812         srb->state |= SRB_DO_WIDE_NEGO;
1813         TRACEPRINTF("W *");
1814 }
1815
1816
1817 #if 0
1818 /* Timer to work around chip flaw: When selecting and the bus is 
1819  * busy, we sometimes miss a Selection timeout IRQ */
1820 void selection_timeout_missed(unsigned long ptr);
1821 /* Sets the timer to wake us up */
1822 static void selto_timer(struct AdapterCtlBlk *acb)
1823 {
1824         if (timer_pending(&acb->selto_timer))
1825                 return;
1826         init_timer(&acb->selto_timer);
1827         acb->selto_timer.function = selection_timeout_missed;
1828         acb->selto_timer.data = (unsigned long) acb;
1829         if (time_before
1830             (jiffies + HZ, acb->scsi_host->last_reset + HZ / 2))
1831                 acb->selto_timer.expires =
1832                     acb->scsi_host->last_reset + HZ / 2 + 1;
1833         else
1834                 acb->selto_timer.expires = jiffies + HZ + 1;
1835         add_timer(&acb->selto_timer);
1836 }
1837
1838
1839 void selection_timeout_missed(unsigned long ptr)
1840 {
1841         unsigned long flags;
1842         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *) ptr;
1843         struct ScsiReqBlk *srb;
1844         dprintkl(KERN_DEBUG, "Chip forgot to produce SelTO IRQ!\n");
1845         if (!acb->active_dcb || !acb->active_dcb->active_srb) {
1846                 dprintkl(KERN_DEBUG, "... but no cmd pending? Oops!\n");
1847                 return;
1848         }
1849         DC395x_LOCK_IO(acb->scsi_host, flags);
1850         srb = acb->active_dcb->active_srb;
1851         TRACEPRINTF("N/TO *");
1852         disconnect(acb);
1853         DC395x_UNLOCK_IO(acb->scsi_host, flags);
1854 }
1855 #endif
1856
1857
1858 /*
1859  * scsiio
1860  *              DC395x_DoWaitingSRB    srb_done 
1861  *              send_srb         request_sense
1862  */
1863 static
1864 u8 start_scsi(struct AdapterCtlBlk * acb, struct DeviceCtlBlk * dcb,
1865               struct ScsiReqBlk * srb)
1866 {
1867         u16 s_stat2, return_code;
1868         u8 s_stat, scsicommand, i, identify_message;
1869         u8 *ptr;
1870
1871         dprintkdbg(DBG_0, "start_scsi..............\n");
1872         srb->tag_number = TAG_NONE;     /* acb->tag_max_num: had error read in eeprom */
1873
1874         s_stat = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
1875         s_stat2 = 0;
1876         s_stat2 = DC395x_read16(acb, TRM_S1040_SCSI_STATUS);
1877         TRACEPRINTF("Start %02x *", s_stat);
1878 #if 1
1879         if (s_stat & 0x20 /* s_stat2 & 0x02000 */ ) {
1880                 dprintkdbg(DBG_KG,
1881                        "StartSCSI: pid %li(%02i-%i): BUSY %02x %04x\n",
1882                        srb->cmd->pid, dcb->target_id, dcb->target_lun,
1883                        s_stat, s_stat2);
1884                 /*
1885                  * Try anyway?
1886                  *
1887                  * We could, BUT: Sometimes the TRM_S1040 misses to produce a Selection
1888                  * Timeout, a Disconnect or a Reselction IRQ, so we would be screwed!
1889                  * (This is likely to be a bug in the hardware. Obviously, most people
1890                  *  only have one initiator per SCSI bus.)
1891                  * Instead let this fail and have the timer make sure the command is 
1892                  * tried again after a short time
1893                  */
1894                 TRACEPRINTF("^*");
1895                 /*selto_timer (acb); */
1896                 /*monitor_next_irq = 1; */
1897                 return 1;
1898         }
1899 #endif
1900         if (acb->active_dcb) {
1901                 dprintkl(KERN_DEBUG, "We try to start a SCSI command (%li)!\n",
1902                        srb->cmd->pid);
1903                 dprintkl(KERN_DEBUG, "While another one (%li) is active!!\n",
1904                        (acb->active_dcb->active_srb ? acb->active_dcb->
1905                         active_srb->cmd->pid : 0));
1906                 TRACEOUT(" %s\n", srb->debugtrace);
1907                 if (acb->active_dcb->active_srb)
1908                         TRACEOUT(" %s\n",
1909                                  acb->active_dcb->active_srb->debugtrace);
1910                 return 1;
1911         }
1912         if (DC395x_read16(acb, TRM_S1040_SCSI_STATUS) & SCSIINTERRUPT) {
1913                 dprintkdbg(DBG_KG,
1914                        "StartSCSI failed (busy) for pid %li(%02i-%i)\n",
1915                        srb->cmd->pid, dcb->target_id, dcb->target_lun);
1916                 TRACEPRINTF("°*");
1917                 return 1;
1918         }
1919         /* Allow starting of SCSI commands half a second before we allow the mid-level
1920          * to queue them again after a reset */
1921         if (time_before(jiffies, acb->scsi_host->last_reset - HZ / 2)) {
1922                 dprintkdbg(DBG_KG, 
1923                        "We were just reset and don't accept commands yet!\n");
1924                 return 1;
1925         }
1926
1927         /* Flush FIFO */
1928         clear_fifo(acb, "Start");
1929         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);
1930         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);
1931         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);
1932         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);
1933         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
1934
1935         identify_message = dcb->identify_msg;
1936         /*DC395x_TRM_write8(TRM_S1040_SCSI_IDMSG, identify_message); */
1937         /* Don't allow disconnection for AUTO_REQSENSE: Cont.All.Cond.! */
1938         if (srb->flag & AUTO_REQSENSE)
1939                 identify_message &= 0xBF;
1940
1941         if (((srb->cmd->cmnd[0] == INQUIRY)
1942              || (srb->cmd->cmnd[0] == REQUEST_SENSE)
1943              || (srb->flag & AUTO_REQSENSE))
1944             && (((dcb->sync_mode & WIDE_NEGO_ENABLE)
1945                  && !(dcb->sync_mode & WIDE_NEGO_DONE))
1946                 || ((dcb->sync_mode & SYNC_NEGO_ENABLE)
1947                     && !(dcb->sync_mode & SYNC_NEGO_DONE)))
1948             && (dcb->target_lun == 0)) {
1949                 srb->msgout_buf[0] = identify_message;
1950                 srb->msg_count = 1;
1951                 scsicommand = SCMD_SEL_ATNSTOP;
1952                 srb->state = SRB_MSGOUT;
1953 #ifndef SYNC_FIRST
1954                 if (dcb->sync_mode & WIDE_NEGO_ENABLE
1955                     && dcb->inquiry7 & SCSI_INQ_WBUS16) {
1956                         build_wdtr(acb, dcb, srb);
1957                         goto no_cmd;
1958                 }
1959 #endif
1960                 if (dcb->sync_mode & SYNC_NEGO_ENABLE
1961                     && dcb->inquiry7 & SCSI_INQ_SYNC) {
1962                         build_sdtr(acb, dcb, srb);
1963                         goto no_cmd;
1964                 }
1965                 if (dcb->sync_mode & WIDE_NEGO_ENABLE
1966                     && dcb->inquiry7 & SCSI_INQ_WBUS16) {
1967                         build_wdtr(acb, dcb, srb);
1968                         goto no_cmd;
1969                 }
1970                 srb->msg_count = 0;
1971         }
1972         /* 
1973          ** Send identify message   
1974          */
1975         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, identify_message);
1976
1977         scsicommand = SCMD_SEL_ATN;
1978         srb->state = SRB_START_;
1979 #ifndef DC395x_NO_TAGQ
1980         if ((dcb->sync_mode & EN_TAG_QUEUEING)
1981             && (identify_message & 0xC0)) {
1982                 /* Send Tag message */
1983                 u32 tag_mask = 1;
1984                 u8 tag_number = 0;
1985                 while (tag_mask & dcb->tag_mask
1986                        && tag_number <= dcb->max_command) {
1987                         tag_mask = tag_mask << 1;
1988                         tag_number++;
1989                 }
1990                 if (tag_number >= dcb->max_command) {
1991                         dprintkl(KERN_WARNING,
1992                                "Start_SCSI: Out of tags for pid %li (%i-%i)\n",
1993                                srb->cmd->pid, srb->cmd->device->id,
1994                                srb->cmd->device->lun);
1995                         srb->state = SRB_READY;
1996                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
1997                                        DO_HWRESELECT);
1998                         return 1;
1999                 }
2000                 /* 
2001                  ** Send Tag id
2002                  */
2003                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, MSG_SIMPLE_QTAG);
2004                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, tag_number);
2005                 dcb->tag_mask |= tag_mask;
2006                 srb->tag_number = tag_number;
2007                 TRACEPRINTF("Tag %i *", tag_number);
2008
2009                 scsicommand = SCMD_SEL_ATN3;
2010                 srb->state = SRB_START_;
2011         }
2012 #endif
2013 /*polling:*/
2014         /*
2015          *          Send CDB ..command block .........                     
2016          */
2017         dprintkdbg(DBG_KG, 
2018                "StartSCSI (pid %li) %02x (%i-%i): Tag %i\n",
2019                srb->cmd->pid, srb->cmd->cmnd[0],
2020                srb->cmd->device->id, srb->cmd->device->lun,
2021                srb->tag_number);
2022         if (srb->flag & AUTO_REQSENSE) {
2023                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, REQUEST_SENSE);
2024                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, (dcb->target_lun << 5));
2025                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2026                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2027                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
2028                               sizeof(srb->cmd->sense_buffer));
2029                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2030         } else {
2031                 ptr = (u8 *) srb->cmd->cmnd;
2032                 for (i = 0; i < srb->cmd->cmd_len; i++)
2033                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr++);
2034         }
2035       no_cmd:
2036         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
2037                        DO_HWRESELECT | DO_DATALATCH);
2038         if (DC395x_read16(acb, TRM_S1040_SCSI_STATUS) & SCSIINTERRUPT) {
2039                 /* 
2040                  * If start_scsi return 1:
2041                  * we caught an interrupt (must be reset or reselection ... )
2042                  * : Let's process it first!
2043                  */
2044                 dprintkdbg(DBG_0, "Debug: StartSCSI failed (busy) for pid %li(%02i-%i)!\n",
2045                         srb->cmd->pid, dcb->target_id, dcb->target_lun);
2046                 /*clear_fifo (acb, "Start2"); */
2047                 /*DC395x_write16 (TRM_S1040_SCSI_CONTROL, DO_HWRESELECT | DO_DATALATCH); */
2048                 srb->state = SRB_READY;
2049                 free_tag(dcb, srb);
2050                 srb->msg_count = 0;
2051                 return_code = 1;
2052                 /* This IRQ should NOT get lost, as we did not acknowledge it */
2053         } else {
2054                 /* 
2055                  * If start_scsi returns 0:
2056                  * we know that the SCSI processor is free
2057                  */
2058                 srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
2059                 dcb->active_srb = srb;
2060                 acb->active_dcb = dcb;
2061                 return_code = 0;
2062                 /* it's important for atn stop */
2063                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
2064                                DO_DATALATCH | DO_HWRESELECT);
2065                 /*
2066                  ** SCSI command
2067                  */
2068                 TRACEPRINTF("%02x *", scsicommand);
2069                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, scsicommand);
2070         }
2071         return return_code;
2072 }
2073
2074
2075 /*
2076  ********************************************************************
2077  * scsiio
2078  *              init_adapter
2079  ********************************************************************
2080  */
2081
2082 /**
2083  * dc395x_handle_interrupt - Handle an interrupt that has been confirmed to
2084  *                           have been triggered for this card.
2085  *
2086  * @acb:         a pointer to the adpter control block
2087  * @scsi_status: the status return when we checked the card
2088  **/
2089 static void dc395x_handle_interrupt(struct AdapterCtlBlk *acb, u16 scsi_status)
2090 {
2091         struct DeviceCtlBlk *dcb;
2092         struct ScsiReqBlk *srb;
2093         u16 phase;
2094         u8 scsi_intstatus;
2095         unsigned long flags;
2096         void (*dc395x_statev) (struct AdapterCtlBlk *, struct ScsiReqBlk *,
2097                                u16 *);
2098
2099         DC395x_LOCK_IO(acb->scsi_host, flags);
2100
2101         /* This acknowledges the IRQ */
2102         scsi_intstatus = DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
2103         if ((scsi_status & 0x2007) == 0x2002)
2104                 dprintkl(KERN_DEBUG, "COP after COP completed? %04x\n",
2105                        scsi_status);
2106 #if 1                           /*def DBG_0 */
2107         if (monitor_next_irq) {
2108                 dprintkl(KERN_INFO,
2109                        "status=%04x intstatus=%02x\n", scsi_status,
2110                        scsi_intstatus);
2111                 monitor_next_irq--;
2112         }
2113 #endif
2114         /*DC395x_ACB_LOCK(acb,acb_flags); */
2115         if (debug_enabled(DBG_KG)) {
2116                 if (scsi_intstatus & INT_SELTIMEOUT)
2117                 dprintkdbg(DBG_KG, "Sel Timeout IRQ\n");
2118         }
2119         /*dprintkl(KERN_DEBUG, "DC395x_IRQ: intstatus = %02x ", scsi_intstatus); */
2120
2121         if (timer_pending(&acb->selto_timer))
2122                 del_timer(&acb->selto_timer);
2123
2124         if (scsi_intstatus & (INT_SELTIMEOUT | INT_DISCONNECT)) {
2125                 disconnect(acb);        /* bus free interrupt  */
2126                 goto out_unlock;
2127         }
2128         if (scsi_intstatus & INT_RESELECTED) {
2129                 reselect(acb);
2130                 goto out_unlock;
2131         }
2132         if (scsi_intstatus & INT_SELECT) {
2133                 dprintkl(KERN_INFO, "Host does not support target mode!\n");
2134                 goto out_unlock;
2135         }
2136         if (scsi_intstatus & INT_SCSIRESET) {
2137                 scsi_reset_detect(acb);
2138                 goto out_unlock;
2139         }
2140         if (scsi_intstatus & (INT_BUSSERVICE | INT_CMDDONE)) {
2141                 dcb = acb->active_dcb;
2142                 if (!dcb) {
2143                         dprintkl(KERN_DEBUG,
2144                                "Oops: BusService (%04x %02x) w/o ActiveDCB!\n",
2145                                scsi_status, scsi_intstatus);
2146                         goto out_unlock;
2147                 }
2148                 srb = dcb->active_srb;
2149                 if (dcb->flag & ABORT_DEV_) {
2150                         dprintkdbg(DBG_0, "MsgOut Abort Device.....\n");
2151                         enable_msgout_abort(acb, srb);
2152                 }
2153                 /*
2154                  ************************************************************
2155                  * software sequential machine
2156                  ************************************************************
2157                  */
2158                 phase = (u16) srb->scsi_phase;
2159                 /* 
2160                  * 62037 or 62137
2161                  * call  dc395x_scsi_phase0[]... "phase entry"
2162                  * handle every phase before start transfer
2163                  */
2164                 /* data_out_phase0,     phase:0 */
2165                 /* data_in_phase0,      phase:1 */
2166                 /* command_phase0,      phase:2 */
2167                 /* status_phase0,       phase:3 */
2168                 /* nop0,                phase:4 PH_BUS_FREE .. initial phase */
2169                 /* nop0,                phase:5 PH_BUS_FREE .. initial phase */
2170                 /* msgout_phase0,       phase:6 */
2171                 /* msgin_phase0,        phase:7 */
2172                 dc395x_statev = (void *) dc395x_scsi_phase0[phase];
2173                 dc395x_statev(acb, srb, &scsi_status);
2174                 /* 
2175                  *$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 
2176                  *
2177                  *        if there were any exception occured
2178                  *        scsi_status will be modify to bus free phase
2179                  * new scsi_status transfer out from ... previous dc395x_statev
2180                  *
2181                  *$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$ 
2182                  */
2183                 srb->scsi_phase = scsi_status & PHASEMASK;
2184                 phase = (u16) scsi_status & PHASEMASK;
2185                 /* 
2186                  * call  dc395x_scsi_phase1[]... "phase entry"
2187                  * handle every phase do transfer
2188                  */
2189                 /* data_out_phase1,     phase:0 */
2190                 /* data_in_phase1,      phase:1 */
2191                 /* command_phase1,      phase:2 */
2192                 /* status_phase1,       phase:3 */
2193                 /* nop1,                phase:4 PH_BUS_FREE .. initial phase */
2194                 /* nop1,                phase:5 PH_BUS_FREE .. initial phase */
2195                 /* msgout_phase1,       phase:6 */
2196                 /* msgin_phase1,        phase:7 */
2197                 dc395x_statev = (void *) dc395x_scsi_phase1[phase];
2198                 dc395x_statev(acb, srb, &scsi_status);
2199         }
2200       out_unlock:
2201         DC395x_UNLOCK_IO(acb->scsi_host, flags);
2202         return;
2203 }
2204
2205
2206 static
2207 irqreturn_t dc395x_interrupt(int irq, void *dev_id, struct pt_regs *regs)
2208 {
2209         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)dev_id;
2210         u16 scsi_status;
2211         u8 dma_status;
2212         irqreturn_t handled = IRQ_NONE;
2213
2214         dprintkdbg(DBG_0, "dc395x_interrupt..............\n");
2215 #if debug_enabled(DBG_RECURSION)
2216         if (dbg_in_driver++ > NORM_REC_LVL) {
2217                 dprintkl(KERN_DEBUG, "%i interrupt recursion?\n", dbg_in_driver);
2218         }
2219 #endif
2220
2221         /*
2222          * Check for pending interupt
2223          */
2224         scsi_status = DC395x_read16(acb, TRM_S1040_SCSI_STATUS);
2225         dma_status = DC395x_read8(acb, TRM_S1040_DMA_STATUS);
2226         if (scsi_status & SCSIINTERRUPT) {
2227                 /* interupt pending - let's process it! */
2228                 dc395x_handle_interrupt(acb, scsi_status);
2229                 handled = IRQ_HANDLED;
2230         }
2231         else if (dma_status & 0x20) {
2232                 /* Error from the DMA engine */
2233                 dprintkl(KERN_INFO, "Interrupt from DMA engine: %02x!\n", dma_status);
2234 #if 0
2235                 dprintkl(KERN_INFO, "This means DMA error! Try to handle ...\n");
2236                 if (acb->active_dcb) {
2237                         acb->active_dcb-> flag |= ABORT_DEV_;
2238                         if (acb->active_dcb->active_srb)
2239                                 enable_msgout_abort(acb, acb->active_dcb->active_srb);
2240                 }
2241                 DC395x_write8(acb, TRM_S1040_DMA_CONTROL, ABORTXFER | CLRXFIFO);
2242 #else
2243                 dprintkl(KERN_INFO, "Ignoring DMA error (probably a bad thing) ...\n");
2244                 acb = NULL;
2245 #endif
2246                 handled = IRQ_HANDLED;
2247         }
2248
2249 #if debug_enabled(DBG_RECURSION)
2250         dbg_in_driver--
2251 #endif
2252         return handled;
2253 }
2254
2255
2256 /*
2257  ********************************************************************
2258  * scsiio
2259  *      msgout_phase0: one of dc395x_scsi_phase0[] vectors
2260  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2261  *                                 if phase =6
2262  ********************************************************************
2263  */
2264 static
2265 void msgout_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2266                     u16 * pscsi_status)
2267 {
2268         dprintkdbg(DBG_0, "msgout_phase0.....\n");
2269         if (srb->state & (SRB_UNEXPECT_RESEL + SRB_ABORT_SENT)) {
2270                 *pscsi_status = PH_BUS_FREE;    /*.. initial phase */
2271         }
2272         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2273         srb->state &= ~SRB_MSGOUT;
2274         TRACEPRINTF("MOP0 *");
2275 }
2276
2277
2278 /*
2279  ********************************************************************
2280  * scsiio
2281  *      msgout_phase1: one of dc395x_scsi_phase0[] vectors
2282  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2283  *                                      if phase =6         
2284  ********************************************************************
2285  */
2286 static
2287 void msgout_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2288                     u16 * pscsi_status)
2289 {
2290         u16 i;
2291         u8 *ptr;
2292         struct DeviceCtlBlk *dcb;
2293
2294         dprintkdbg(DBG_0, "msgout_phase1..............\n");
2295         TRACEPRINTF("MOP1*");
2296         dcb = acb->active_dcb;
2297         clear_fifo(acb, "MOP1");
2298         if (!(srb->state & SRB_MSGOUT)) {
2299                 srb->state |= SRB_MSGOUT;
2300                 dprintkl(KERN_DEBUG, "Debug: pid %li: MsgOut Phase unexpected.\n", srb->cmd->pid);      /* So what ? */
2301         }
2302         if (!srb->msg_count) {
2303                 dprintkdbg(DBG_0, "Debug: pid %li: NOP Msg (no output message there).\n",
2304                         srb->cmd->pid);
2305                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, MSG_NOP);
2306                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2307                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
2308                 TRACEPRINTF("\\*");
2309                 TRACEOUT(" %s\n", srb->debugtrace);
2310                 return;
2311         }
2312         ptr = (u8 *) srb->msgout_buf;
2313         TRACEPRINTF("(*");
2314         /*dprintkl(KERN_DEBUG, "Send msg: "); print_msg (ptr, srb->msg_count); */
2315         /*dprintkl(KERN_DEBUG, "MsgOut: "); */
2316         for (i = 0; i < srb->msg_count; i++) {
2317                 TRACEPRINTF("%02x *", *ptr);
2318                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr++);
2319         }
2320         TRACEPRINTF(")*");
2321         srb->msg_count = 0;
2322         /*printk("\n"); */
2323         if (/*(dcb->flag & ABORT_DEV_) && */
2324             (srb->msgout_buf[0] == MSG_ABORT))
2325                 srb->state = SRB_ABORT_SENT;
2326
2327         /*1.25 */
2328         /*DC395x_write16 (TRM_S1040_SCSI_CONTROL, DO_DATALATCH); *//* it's important for atn stop */
2329         /*
2330          ** SCSI command 
2331          */
2332         /*TRACEPRINTF (".*"); */
2333         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
2334 }
2335
2336
2337 /*
2338  ********************************************************************
2339  * scsiio
2340  *      command_phase0: one of dc395x_scsi_phase0[] vectors
2341  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2342  *                              if phase =2 
2343  ********************************************************************
2344  */
2345 static
2346 void command_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2347                     u16 * pscsi_status)
2348 {
2349         TRACEPRINTF("COP0 *");
2350         /*1.25 */
2351         /*clear_fifo (acb, COP0); */
2352         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
2353 }
2354
2355
2356 /*
2357  ********************************************************************
2358  * scsiio
2359  *      command_phase1: one of dc395x_scsi_phase1[] vectors
2360  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
2361  *                              if phase =2      
2362  ********************************************************************
2363  */
2364 static
2365 void command_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2366                     u16 * pscsi_status)
2367 {
2368         struct DeviceCtlBlk *dcb;
2369         u8 *ptr;
2370         u16 i;
2371
2372         dprintkdbg(DBG_0, "command_phase1..............\n");
2373         TRACEPRINTF("COP1*");
2374         clear_fifo(acb, "COP1");
2375         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_CLRATN);
2376         if (!(srb->flag & AUTO_REQSENSE)) {
2377                 ptr = (u8 *) srb->cmd->cmnd;
2378                 for (i = 0; i < srb->cmd->cmd_len; i++) {
2379                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr);
2380                         ptr++;
2381                 }
2382         } else {
2383                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, REQUEST_SENSE);
2384                 dcb = acb->active_dcb;
2385                 /* target id */
2386                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, (dcb->target_lun << 5));
2387                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2388                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2389                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
2390                               sizeof(srb->cmd->sense_buffer));
2391                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2392         }
2393         srb->state |= SRB_COMMAND;
2394         /* it's important for atn stop */
2395         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
2396         /* SCSI command */
2397         TRACEPRINTF(".*");
2398         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
2399 }
2400
2401
2402 /* Do sanity checks for S/G list */
2403 static inline void check_sg_list(struct ScsiReqBlk *srb)
2404 {
2405         if (debug_enabled(DBG_SGPARANOIA)) {
2406                 unsigned len = 0;
2407                 unsigned idx = srb->sg_index;
2408                 struct SGentry *psge = srb->segment_x + idx;
2409                 for (; idx < srb->sg_count; psge++, idx++)
2410                         len += psge->length;
2411                 if (len != srb->total_xfer_length)
2412                         dprintkdbg(DBG_SGPARANOIA,
2413                                "Inconsistent SRB S/G lengths (Tot=%i, Count=%i) !!\n",
2414                                srb->total_xfer_length, len);
2415         }                              
2416 }
2417
2418
2419 /*
2420  * Compute the next Scatter Gather list index and adjust its length
2421  * and address if necessary; also compute virt_addr
2422  */
2423 static void update_sg_list(struct ScsiReqBlk *srb, u32 left)
2424 {
2425         struct SGentry *psge;
2426         u32 xferred = 0;
2427         u8 idx;
2428         Scsi_Cmnd *cmd = srb->cmd;
2429         struct scatterlist *sg;
2430         int segment = cmd->use_sg;
2431
2432         dprintkdbg(DBG_KG, "Update SG: Total %i, Left %i\n",
2433                srb->total_xfer_length, left);
2434         check_sg_list(srb);
2435         psge = srb->segment_x + srb->sg_index;
2436         /* data that has already been transferred */
2437         xferred = srb->total_xfer_length - left;
2438         if (srb->total_xfer_length != left) {
2439                 /*check_sg_list_TX (srb, xferred); */
2440                 /* Remaining */
2441                 srb->total_xfer_length = left;
2442                 /* parsing from last time disconnect SGIndex */
2443                 for (idx = srb->sg_index; idx < srb->sg_count; idx++) {
2444                         /* Complete SG entries done */
2445                         if (xferred >= psge->length)
2446                                 xferred -= psge->length;
2447                         /* Partial SG entries done */
2448                         else {
2449                                 psge->length -= xferred;        /* residue data length  */
2450                                 psge->address += xferred;       /* residue data pointer */
2451                                 srb->sg_index = idx;
2452                                 pci_dma_sync_single(srb->dcb->
2453                                                     acb->dev,
2454                                                     srb->sg_bus_addr,
2455                                                     sizeof(struct SGentry)
2456                                                     *
2457                                                     DC395x_MAX_SG_LISTENTRY,
2458                                                     PCI_DMA_TODEVICE);
2459                                 break;
2460                         }
2461                         psge++;
2462                 }
2463                 check_sg_list(srb);
2464         }
2465         /* We need the corresponding virtual address sg_to_virt */
2466         /*dprintkl(KERN_DEBUG, "sg_to_virt: bus %08x -> virt ", psge->address); */
2467         if (!segment) {
2468                 srb->virt_addr += xferred;
2469                 /*printk("%p\n", srb->virt_addr); */
2470                 return;
2471         }
2472         /* We have to walk the scatterlist to find it */
2473         sg = (struct scatterlist *) cmd->request_buffer;
2474         while (segment--) {
2475                 /*printk("(%08x)%p ", BUS_ADDR(*sg), PAGE_ADDRESS(sg)); */
2476                 unsigned long mask =
2477                     ~((unsigned long) sg->length - 1) & PAGE_MASK;
2478                 if ((BUS_ADDR(*sg) & mask) == (psge->address & mask)) {
2479                         srb->virt_addr = (PAGE_ADDRESS(sg)
2480                                            + psge->address -
2481                                            (psge->address & PAGE_MASK));
2482                         /*printk("%p\n", srb->virt_addr); */
2483                         return;
2484                 }
2485                 ++sg;
2486         }
2487         dprintkl(KERN_ERR, "sg_to_virt failed!\n");
2488         srb->virt_addr = 0;
2489 }
2490
2491
2492 /* 
2493  * cleanup_after_transfer
2494  * 
2495  * Makes sure, DMA and SCSI engine are empty, after the transfer has finished
2496  * KG: Currently called from  StatusPhase1 ()
2497  * Should probably also be called from other places
2498  * Best might be to call it in DataXXPhase0, if new phase will differ 
2499  */
2500 static
2501 void cleanup_after_transfer(struct AdapterCtlBlk *acb,
2502                             struct ScsiReqBlk *srb)
2503 {
2504         TRACEPRINTF(" Cln*");
2505         /*DC395x_write8 (TRM_S1040_DMA_STATUS, FORCEDMACOMP); */
2506         if (DC395x_read16(acb, TRM_S1040_DMA_COMMAND) & 0x0001) {       /* read */
2507                 if (!(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x40))
2508                         clear_fifo(acb, "ClnIn");
2509
2510                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80))
2511                         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
2512         } else {                /* write */
2513                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80))
2514                         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
2515
2516                 if (!(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x40))
2517                         clear_fifo(acb, "ClnOut");
2518
2519         }
2520         /*1.25 */
2521         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
2522 }
2523
2524
2525 /*
2526  * Those no of bytes will be transfered w/ PIO through the SCSI FIFO
2527  * Seems to be needed for unknown reasons; could be a hardware bug :-(
2528  */
2529 #define DC395x_LASTPIO 4
2530 /*
2531  ********************************************************************
2532  * scsiio
2533  *      data_out_phase0: one of dc395x_scsi_phase0[] vectors
2534  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2535  *                              if phase =0 
2536  ********************************************************************
2537  */
2538 static
2539 void data_out_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2540                      u16 * pscsi_status)
2541 {
2542         u16 scsi_status;
2543         u32 d_left_counter = 0;
2544         struct DeviceCtlBlk *dcb = srb->dcb;
2545
2546         dprintkdbg(DBG_0, "data_out_phase0.....\n");
2547         TRACEPRINTF("DOP0*");
2548         dcb = srb->dcb;
2549         scsi_status = *pscsi_status;
2550
2551         /*
2552          * KG: We need to drain the buffers before we draw any conclusions!
2553          * This means telling the DMA to push the rest into SCSI, telling
2554          * SCSI to push the rest to the bus.
2555          * However, the device might have been the one to stop us (phase
2556          * change), and the data in transit just needs to be accounted so
2557          * it can be retransmitted.)
2558          */
2559         /* 
2560          * KG: Stop DMA engine pushing more data into the SCSI FIFO
2561          * If we need more data, the DMA SG list will be freshly set up, anyway
2562          */
2563         dprintkdbg(DBG_PIO, "DOP0: DMA_FCNT: %02x, DMA_FSTAT: %02x, SCSI_FCNT: %02x, CTR %06x, stat %04x, Tot: %06x\n",
2564                DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2565                DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2566                DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2567                DC395x_read32(acb, TRM_S1040_SCSI_COUNTER), scsi_status,
2568                srb->total_xfer_length);
2569         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, STOPDMAXFER | CLRXFIFO);
2570
2571         if (!(srb->state & SRB_XFERPAD)) {
2572                 if (scsi_status & PARITYERROR)
2573                         srb->status |= PARITY_ERROR;
2574
2575                 /*
2576                  * KG: Right, we can't just rely on the SCSI_COUNTER, because this
2577                  * is the no of bytes it got from the DMA engine not the no it 
2578                  * transferred successfully to the device. (And the difference could
2579                  * be as much as the FIFO size, I guess ...)
2580                  */
2581                 if (!(scsi_status & SCSIXFERDONE)) {
2582                         /*
2583                          * when data transfer from DMA FIFO to SCSI FIFO
2584                          * if there was some data left in SCSI FIFO
2585                          */
2586                         d_left_counter =
2587                             (u32) (DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) &
2588                                    0x1F);
2589                         if (dcb->sync_period & WIDE_SYNC)
2590                                 d_left_counter <<= 1;
2591
2592                         dprintkdbg(DBG_KG,
2593                                "Debug: SCSI FIFO contains %i %s in DOP0\n",
2594                                DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2595                                (dcb->
2596                                 sync_period & WIDE_SYNC) ? "words" :
2597                                "bytes");
2598                         dprintkdbg(DBG_KG,
2599                                "SCSI FIFOCNT %02x, SCSI CTR %08x\n",
2600                                DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2601                                DC395x_read32(acb, TRM_S1040_SCSI_COUNTER));
2602                         dprintkdbg(DBG_KG,
2603                                "DMA FIFOCNT %04x, FIFOSTAT %02x, DMA CTR %08x\n",
2604                                DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2605                                DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2606                                DC395x_read32(acb, TRM_S1040_DMA_CXCNT));
2607
2608                         /*
2609                          * if WIDE scsi SCSI FIFOCNT unit is word !!!
2610                          * so need to *= 2
2611                          */
2612                 }
2613                 /*
2614                  * calculate all the residue data that not yet tranfered
2615                  * SCSI transfer counter + left in SCSI FIFO data
2616                  *
2617                  * .....TRM_S1040_SCSI_COUNTER (24bits)
2618                  * The counter always decrement by one for every SCSI byte transfer.
2619                  * .....TRM_S1040_SCSI_FIFOCNT ( 5bits)
2620                  * The counter is SCSI FIFO offset counter (in units of bytes or! words)
2621                  */
2622                 if (srb->total_xfer_length > DC395x_LASTPIO)
2623                         d_left_counter +=
2624                             DC395x_read32(acb, TRM_S1040_SCSI_COUNTER);
2625                 TRACEPRINTF("%06x *", d_left_counter);
2626
2627                 /* Is this a good idea? */
2628                 /*clear_fifo (acb, "DOP1"); */
2629                 /* KG: What is this supposed to be useful for? WIDE padding stuff? */
2630                 if (d_left_counter == 1 && dcb->sync_period & WIDE_SYNC
2631                     && srb->cmd->request_bufflen % 2) {
2632                         d_left_counter = 0;
2633                         dprintkl(KERN_INFO, "DOP0: Discard 1 byte. (%02x)\n",
2634                                scsi_status);
2635                 }
2636                 /*
2637                  * KG: Oops again. Same thinko as above: The SCSI might have been
2638                  * faster than the DMA engine, so that it ran out of data.
2639                  * In that case, we have to do just nothing! 
2640                  * But: Why the interrupt: No phase change. No XFERCNT_2_ZERO. Or?
2641                  */
2642                 /*
2643                  * KG: This is nonsense: We have been WRITING data to the bus
2644                  * If the SCSI engine has no bytes left, how should the DMA engine?
2645                  */
2646                 if ((d_left_counter ==
2647                      0) /*|| (scsi_status & SCSIXFERCNT_2_ZERO) ) */ ) {
2648                         /*
2649                          * int ctr = 6000000; u8 TempDMAstatus;
2650                          * do
2651                          * {
2652                          *  TempDMAstatus = DC395x_read8(acb, TRM_S1040_DMA_STATUS);
2653                          * } while( !(TempDMAstatus & DMAXFERCOMP) && --ctr);
2654                          * if (ctr < 6000000-1) dprintkl(KERN_DEBUG, "DMA should be complete ... in DOP1\n");
2655                          * if (!ctr) dprintkl(KERN_ERR, "Deadlock in DataOutPhase0 !!\n");
2656                          */
2657                         srb->total_xfer_length = 0;
2658                 } else {        /* Update SG list         */
2659                         /*
2660                          * if transfer not yet complete
2661                          * there were some data residue in SCSI FIFO or
2662                          * SCSI transfer counter not empty
2663                          */
2664                         long oldxferred =
2665                             srb->total_xfer_length - d_left_counter;
2666                         const int diff =
2667                             (dcb->sync_period & WIDE_SYNC) ? 2 : 1;
2668                         update_sg_list(srb, d_left_counter);
2669                         /* KG: Most ugly hack! Apparently, this works around a chip bug */
2670                         if ((srb->segment_x[srb->sg_index].length ==
2671                              diff && srb->cmd->use_sg)
2672                             || ((oldxferred & ~PAGE_MASK) ==
2673                                 (PAGE_SIZE - diff))
2674                             ) {
2675                                 dprintkl(KERN_INFO,
2676                                        "Work around chip bug (%i)?\n", diff);
2677                                 d_left_counter =
2678                                     srb->total_xfer_length - diff;
2679                                 update_sg_list(srb, d_left_counter);
2680                                 /*srb->total_xfer_length -= diff; */
2681                                 /*srb->virt_addr += diff; */
2682                                 /*if (srb->cmd->use_sg) */
2683                                 /*      srb->sg_index++; */
2684                         }
2685                 }
2686         }
2687 #if 0
2688         if (!(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x40))
2689                 dprintkl(KERN_DEBUG,
2690                         "DOP0(%li): %i bytes in SCSI FIFO! (Clear!)\n",
2691                         srb->cmd->pid,
2692                         DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x1f);
2693 #endif
2694         /*clear_fifo (acb, "DOP0"); */
2695         /*DC395x_write8 (TRM_S1040_DMA_CONTROL, CLRXFIFO | ABORTXFER); */
2696 #if 1
2697         if ((*pscsi_status & PHASEMASK) != PH_DATA_OUT) {
2698                 /*dprintkl(KERN_DEBUG, "Debug: Clean up after Data Out ...\n"); */
2699                 cleanup_after_transfer(acb, srb);
2700         }
2701 #endif
2702         TRACEPRINTF(".*");
2703 }
2704
2705
2706 /*
2707  ********************************************************************
2708  * scsiio
2709  *      data_out_phase1: one of dc395x_scsi_phase0[] vectors
2710  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2711  *                              if phase =0    
2712  *              62037
2713  ********************************************************************
2714  */
2715 static
2716 void data_out_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2717                      u16 * pscsi_status)
2718 {
2719
2720         dprintkdbg(DBG_0, "data_out_phase1.....\n");
2721         /*1.25 */
2722         TRACEPRINTF("DOP1*");
2723         clear_fifo(acb, "DOP1");
2724         /*
2725          ** do prepare befor transfer when data out phase
2726          */
2727         data_io_transfer(acb, srb, XFERDATAOUT);
2728         TRACEPRINTF(".*");
2729 }
2730
2731
2732 /*
2733  ********************************************************************
2734  * scsiio
2735  *      data_in_phase0: one of dc395x_scsi_phase1[] vectors
2736  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
2737  *                              if phase =1  
2738  ********************************************************************
2739  */
2740 static
2741 void data_in_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2742                     u16 * pscsi_status)
2743 {
2744         u16 scsi_status;
2745         u32 d_left_counter = 0;
2746         /*struct DeviceCtlBlk*   dcb = srb->dcb; */
2747         /*u8 bval; */
2748
2749         dprintkdbg(DBG_0, "data_in_phase0..............\n");
2750         TRACEPRINTF("DIP0*");
2751         scsi_status = *pscsi_status;
2752
2753         /*
2754          * KG: DataIn is much more tricky than DataOut. When the device is finished
2755          * and switches to another phase, the SCSI engine should be finished too.
2756          * But: There might still be bytes left in its FIFO to be fetched by the DMA
2757          * engine and transferred to memory.
2758          * We should wait for the FIFOs to be emptied by that (is there any way to 
2759          * enforce this?) and then stop the DMA engine, because it might think, that
2760          * there are more bytes to follow. Yes, the device might disconnect prior to
2761          * having all bytes transferred! 
2762          * Also we should make sure that all data from the DMA engine buffer's really
2763          * made its way to the system memory! Some documentation on this would not
2764          * seem to be a bad idea, actually.
2765          */
2766         if (!(srb->state & SRB_XFERPAD)) {
2767                 if (scsi_status & PARITYERROR) {
2768                         dprintkl(KERN_INFO,
2769                                "Parity Error (pid %li, target %02i-%i)\n",
2770                                srb->cmd->pid, srb->cmd->device->id,
2771                                srb->cmd->device->lun);
2772                         srb->status |= PARITY_ERROR;
2773                 }
2774                 /*
2775                  * KG: We should wait for the DMA FIFO to be empty ...
2776                  * but: it would be better to wait first for the SCSI FIFO and then the
2777                  * the DMA FIFO to become empty? How do we know, that the device not already
2778                  * sent data to the FIFO in a MsgIn phase, eg.?
2779                  */
2780                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80)) {
2781 #if 0
2782                         int ctr = 6000000;
2783                         dprintkl(KERN_DEBUG,
2784                                "DIP0: Wait for DMA FIFO to flush ...\n");
2785                         /*DC395x_write8  (TRM_S1040_DMA_CONTROL, STOPDMAXFER); */
2786                         /*DC395x_write32 (TRM_S1040_SCSI_COUNTER, 7); */
2787                         /*DC395x_write8  (TRM_S1040_SCSI_COMMAND, SCMD_DMA_IN); */
2788                         while (!
2789                                (DC395x_read16(acb, TRM_S1040_DMA_FIFOSTAT) &
2790                                 0x80) && --ctr);
2791                         if (ctr < 6000000 - 1)
2792                                 dprintkl(KERN_DEBUG
2793                                        "DIP0: Had to wait for DMA ...\n");
2794                         if (!ctr)
2795                                 dprintkl(KERN_ERR,
2796                                        "Deadlock in DIP0 waiting for DMA FIFO empty!!\n");
2797                         /*DC395x_write32 (TRM_S1040_SCSI_COUNTER, 0); */
2798 #endif
2799                         dprintkdbg(DBG_KG, "DIP0: DMA_FIFO: %02x %02x\n",
2800                                DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2801                                DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT));
2802                 }
2803                 /* Now: Check remainig data: The SCSI counters should tell us ... */
2804                 d_left_counter = DC395x_read32(acb, TRM_S1040_SCSI_COUNTER)
2805                     + ((DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x1f)
2806                        << ((srb->dcb->sync_period & WIDE_SYNC) ? 1 :
2807                            0));
2808
2809                 dprintkdbg(DBG_KG, "SCSI FIFO contains %i %s in DIP0\n",
2810                           DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x1f,
2811                           (srb->dcb->
2812                           sync_period & WIDE_SYNC) ? "words" : "bytes");
2813                 dprintkdbg(DBG_KG, "SCSI FIFOCNT %02x, SCSI CTR %08x\n",
2814                           DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2815                           DC395x_read32(acb, TRM_S1040_SCSI_COUNTER));
2816                 dprintkdbg(DBG_KG, "DMA FIFOCNT %02x,%02x DMA CTR %08x\n",
2817                           DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2818                           DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2819                           DC395x_read32(acb, TRM_S1040_DMA_CXCNT));
2820                 dprintkdbg(DBG_KG, "Remaining: TotXfer: %i, SCSI FIFO+Ctr: %i\n",
2821                           srb->total_xfer_length, d_left_counter);
2822 #if DC395x_LASTPIO
2823                 /* KG: Less than or equal to 4 bytes can not be transfered via DMA, it seems. */
2824                 if (d_left_counter
2825                     && srb->total_xfer_length <= DC395x_LASTPIO) {
2826                         /*u32 addr = (srb->segment_x[srb->sg_index].address); */
2827                         /*update_sg_list (srb, d_left_counter); */
2828                         dprintkdbg(DBG_PIO, "DIP0: PIO (%i %s) to %p for remaining %i bytes:",
2829                                   DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) &
2830                                   0x1f,
2831                                   (srb->dcb->
2832                                    sync_period & WIDE_SYNC) ? "words" :
2833                                   "bytes", srb->virt_addr,
2834                                   srb->total_xfer_length);
2835
2836                         if (srb->dcb->sync_period & WIDE_SYNC)
2837                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2,
2838                                               CFG2_WIDEFIFO);
2839
2840                         while (DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) !=
2841                                0x40) {
2842                                 u8 byte =
2843                                     DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2844                                 *(srb->virt_addr)++ = byte;
2845                                 if (debug_enabled(DBG_PIO))
2846                                         printk(" %02x", byte);
2847                                 srb->total_xfer_length--;
2848                                 d_left_counter--;
2849                                 srb->segment_x[srb->sg_index].length--;
2850                                 if (srb->total_xfer_length
2851                                     && !srb->segment_x[srb->sg_index].
2852                                     length) {
2853                                         if (debug_enabled(DBG_PIO))
2854                                                 printk(" (next segment)");
2855                                         srb->sg_index++;
2856                                         update_sg_list(srb,
2857                                                              d_left_counter);
2858                                 }
2859                         }
2860                         if (srb->dcb->sync_period & WIDE_SYNC) {
2861 #if 1                           /* Read the last byte ... */
2862                                 if (srb->total_xfer_length > 0) {
2863                                         u8 byte =
2864                                             DC395x_read8
2865                                             (acb, TRM_S1040_SCSI_FIFO);
2866                                         *(srb->virt_addr)++ = byte;
2867                                         srb->total_xfer_length--;
2868                                         if (debug_enabled(DBG_PIO))
2869                                                 printk(" %02x", byte);
2870                                 }
2871 #endif
2872                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2, 0);
2873                         }
2874                         /*printk(" %08x", *(u32*)(bus_to_virt (addr))); */
2875                         /*srb->total_xfer_length = 0; */
2876                         if (debug_enabled(DBG_PIO))
2877                                 printk("\n");
2878                 }
2879 #endif                          /* DC395x_LASTPIO */
2880
2881 #if 0
2882                 /*
2883                  * KG: This was in DATAOUT. Does it also belong here?
2884                  * Nobody seems to know what counter and fifo_cnt count exactly ...
2885                  */
2886                 if (!(scsi_status & SCSIXFERDONE)) {
2887                         /*
2888                          * when data transfer from DMA FIFO to SCSI FIFO
2889                          * if there was some data left in SCSI FIFO
2890                          */
2891                         d_left_counter =
2892                             (u32) (DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) &
2893                                    0x1F);
2894                         if (srb->dcb->sync_period & WIDE_SYNC)
2895                                 d_left_counter <<= 1;
2896                         /*
2897                          * if WIDE scsi SCSI FIFOCNT unit is word !!!
2898                          * so need to *= 2
2899                          * KG: Seems to be correct ...
2900                          */
2901                 }
2902 #endif
2903                 /*d_left_counter += DC395x_read32(acb, TRM_S1040_SCSI_COUNTER); */
2904 #if 0
2905                 dprintkl(KERN_DEBUG,
2906                        "DIP0: ctr=%08x, DMA_FIFO=%02x,%02x SCSI_FIFO=%02x\n",
2907                        d_left_counter, DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2908                        DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2909                        DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT));
2910                 dprintkl(KERN_DEBUG, "DIP0: DMAStat %02x\n",
2911                        DC395x_read8(acb, TRM_S1040_DMA_STATUS));
2912 #endif
2913
2914                 /* KG: This should not be needed any more! */
2915                 if ((d_left_counter == 0)
2916                     || (scsi_status & SCSIXFERCNT_2_ZERO)) {
2917 #if 0
2918                         int ctr = 6000000;
2919                         u8 TempDMAstatus;
2920                         do {
2921                                 TempDMAstatus =
2922                                     DC395x_read8(acb, TRM_S1040_DMA_STATUS);
2923                         } while (!(TempDMAstatus & DMAXFERCOMP) && --ctr);
2924                         if (!ctr)
2925                                 dprintkl(KERN_ERR,
2926                                        "Deadlock in DataInPhase0 waiting for DMA!!\n");
2927                         srb->total_xfer_length = 0;
2928 #endif
2929 #if 0                           /*def DBG_KG             */
2930                         dprintkl(KERN_DEBUG,
2931                                "DIP0: DMA not yet ready: %02x: %i -> %i bytes\n",
2932                                DC395x_read8(acb, TRM_S1040_DMA_STATUS),
2933                                srb->total_xfer_length, d_left_counter);
2934 #endif
2935                         srb->total_xfer_length = d_left_counter;
2936                 } else {        /* phase changed */
2937                         /*
2938                          * parsing the case:
2939                          * when a transfer not yet complete 
2940                          * but be disconnected by target
2941                          * if transfer not yet complete
2942                          * there were some data residue in SCSI FIFO or
2943                          * SCSI transfer counter not empty
2944                          */
2945                         update_sg_list(srb, d_left_counter);
2946                 }
2947         }
2948         /* KG: The target may decide to disconnect: Empty FIFO before! */
2949         if ((*pscsi_status & PHASEMASK) != PH_DATA_IN) {
2950                 /*dprintkl(KERN_DEBUG, "Debug: Clean up after Data In  ...\n"); */
2951                 cleanup_after_transfer(acb, srb);
2952         }
2953 #if 0
2954         /* KG: Make sure, no previous transfers are pending! */
2955         bval = DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT);
2956         if (!(bval & 0x40)) {
2957                 bval &= 0x1f;
2958                 dprintkl(KERN_DEBUG,
2959                        "DIP0(%li): %i bytes in SCSI FIFO (stat %04x) (left %08x)!!\n",
2960                        srb->cmd->pid, bval & 0x1f, scsi_status,
2961                        d_left_counter);
2962                 if ((d_left_counter == 0)
2963                     || (scsi_status & SCSIXFERCNT_2_ZERO)) {
2964                         dprintkl(KERN_DEBUG, "Clear FIFO!\n");
2965                         clear_fifo(acb, "DIP0");
2966                 }
2967         }
2968 #endif
2969         /*DC395x_write8 (TRM_S1040_DMA_CONTROL, CLRXFIFO | ABORTXFER); */
2970
2971         /*clear_fifo (acb, "DIP0"); */
2972         /*DC395x_write16 (TRM_S1040_SCSI_CONTROL, DO_DATALATCH); */
2973         TRACEPRINTF(".*");
2974 }
2975
2976
2977 /*
2978  ********************************************************************
2979  * scsiio
2980  *      data_in_phase1: one of dc395x_scsi_phase0[] vectors
2981  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
2982  *                              if phase =1 
2983  ********************************************************************
2984  */
2985 static
2986 void data_in_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2987                     u16 * pscsi_status)
2988 {
2989         dprintkdbg(DBG_0, "data_in_phase1.....\n");
2990         /* FIFO should be cleared, if previous phase was not DataPhase */
2991         /*clear_fifo (acb, "DIP1"); */
2992         /* Allow data in! */
2993         /*DC395x_write16 (TRM_S1040_SCSI_CONTROL, DO_DATALATCH); */
2994         TRACEPRINTF("DIP1:*");
2995         /*
2996          ** do prepare before transfer when data in phase
2997          */
2998         data_io_transfer(acb, srb, XFERDATAIN);
2999         TRACEPRINTF(".*");
3000 }
3001
3002
3003 /*
3004  ********************************************************************
3005  * scsiio
3006  *              data_out_phase1
3007  *              data_in_phase1
3008  ********************************************************************
3009  */
3010 static
3011 void data_io_transfer(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3012                       u16 io_dir)
3013 {
3014         u8 bval;
3015         struct DeviceCtlBlk *dcb;
3016
3017         dprintkdbg(DBG_0, "DataIO_transfer %c (pid %li): len = %i, SG: %i/%i\n",
3018                ((io_dir & DMACMD_DIR) ? 'r' : 'w'), srb->cmd->pid,
3019                srb->total_xfer_length, srb->sg_index,
3020                srb->sg_count);
3021         TRACEPRINTF("%05x(%i/%i)*", srb->total_xfer_length,
3022                     srb->sg_index, srb->sg_count);
3023         dcb = srb->dcb;
3024         if (srb == acb->tmp_srb) {
3025                 dprintkl(KERN_ERR, "Using tmp_srb in DataPhase!\n");
3026         }
3027         if (srb->sg_index < srb->sg_count) {
3028                 if (srb->total_xfer_length > DC395x_LASTPIO) {
3029                         u8 dma_status = DC395x_read8(acb, TRM_S1040_DMA_STATUS);
3030                         /*
3031                          * KG: What should we do: Use SCSI Cmd 0x90/0x92?
3032                          * Maybe, even ABORTXFER would be appropriate
3033                          */
3034                         if (dma_status & XFERPENDING) {
3035                                 dprintkl(KERN_DEBUG, "Xfer pending! Expect trouble!!\n");
3036                                 dump_register_info(acb, dcb, srb);
3037                                 DC395x_write8(acb, TRM_S1040_DMA_CONTROL,
3038                                               CLRXFIFO);
3039                         }
3040                         /*clear_fifo (acb, "IO"); */
3041                         /* 
3042                          * load what physical address of Scatter/Gather list table want to be
3043                          * transfer 
3044                          */
3045                         srb->state |= SRB_DATA_XFER;
3046                         DC395x_write32(acb, TRM_S1040_DMA_XHIGHADDR, 0);
3047                         if (srb->cmd->use_sg) { /* with S/G */
3048                                 io_dir |= DMACMD_SG;
3049                                 DC395x_write32(acb, TRM_S1040_DMA_XLOWADDR,
3050                                                srb->sg_bus_addr +
3051                                                sizeof(struct SGentry) *
3052                                                srb->sg_index);
3053                                 /* load how many bytes in the Scatter/Gather list table */
3054                                 DC395x_write32(acb, TRM_S1040_DMA_XCNT,
3055                                                ((u32)
3056                                                 (srb->sg_count -
3057                                                  srb->sg_index) << 3));
3058                         } else {        /* without S/G */
3059                                 io_dir &= ~DMACMD_SG;
3060                                 DC395x_write32(acb, TRM_S1040_DMA_XLOWADDR,
3061                                                srb->segment_x[0].address);
3062                                 DC395x_write32(acb, TRM_S1040_DMA_XCNT,
3063                                                srb->segment_x[0].length);
3064                         }
3065                         /* load total transfer length (24bits) max value 16Mbyte */
3066                         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER,
3067                                        srb->total_xfer_length);
3068                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3069                         if (io_dir & DMACMD_DIR) {      /* read */
3070                                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
3071                                               SCMD_DMA_IN);
3072                                 DC395x_write16(acb, TRM_S1040_DMA_COMMAND,
3073                                                io_dir);
3074                         } else {
3075                                 DC395x_write16(acb, TRM_S1040_DMA_COMMAND,
3076                                                io_dir);
3077                                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
3078                                               SCMD_DMA_OUT);
3079                         }
3080
3081                 }
3082 #if DC395x_LASTPIO
3083                 else if (srb->total_xfer_length > 0) {  /* The last four bytes: Do PIO */
3084                         /*clear_fifo (acb, "IO"); */
3085                         /* 
3086                          * load what physical address of Scatter/Gather list table want to be
3087                          * transfer 
3088                          */
3089                         srb->state |= SRB_DATA_XFER;
3090                         /* load total transfer length (24bits) max value 16Mbyte */
3091                         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER,
3092                                        srb->total_xfer_length);
3093                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3094                         if (io_dir & DMACMD_DIR) {      /* read */
3095                                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
3096                                               SCMD_FIFO_IN);
3097                         } else {        /* write */
3098                                 int ln = srb->total_xfer_length;
3099                                 if (srb->dcb->sync_period & WIDE_SYNC)
3100                                         DC395x_write8
3101                                             (acb, TRM_S1040_SCSI_CONFIG2,
3102                                              CFG2_WIDEFIFO);
3103                                 dprintkdbg(DBG_PIO, "DOP1: PIO %i bytes from %p:",
3104                                           srb->total_xfer_length,
3105                                           srb->virt_addr);
3106                                 while (srb->total_xfer_length) {
3107                                         if (debug_enabled(DBG_PIO))
3108                                                 printk(" %02x", (unsigned char) *(srb->virt_addr));
3109                                         DC395x_write8
3110                                             (acb, TRM_S1040_SCSI_FIFO,
3111                                              *(srb->virt_addr)++);
3112                                         srb->total_xfer_length--;
3113                                         srb->segment_x[srb->sg_index].
3114                                             length--;
3115                                         if (srb->total_xfer_length
3116                                             && !srb->segment_x[srb->
3117                                                                sg_index].
3118                                             length) {
3119                                                 if (debug_enabled(DBG_PIO))
3120                                                         printk(" (next segment)");
3121                                                 srb->sg_index++;
3122                                                 update_sg_list(srb,
3123                                                                srb->total_xfer_length);
3124                                         }
3125                                 }
3126                                 if (srb->dcb->sync_period & WIDE_SYNC) {
3127                                         if (ln % 2) {
3128                                                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
3129                                                 if (debug_enabled(DBG_PIO))
3130                                                         printk(" |00");
3131                                         }
3132                                         DC395x_write8
3133                                             (acb, TRM_S1040_SCSI_CONFIG2, 0);
3134                                 }
3135                                 /*DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, ln); */
3136                                 if (debug_enabled(DBG_PIO))
3137                                         printk("\n");
3138                                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
3139                                                   SCMD_FIFO_OUT);
3140                         }
3141                 }
3142 #endif                          /* DC395x_LASTPIO */
3143                 else {          /* xfer pad */
3144
3145                         u8 data = 0, data2 = 0;
3146                         if (srb->sg_count) {
3147                                 srb->adapter_status = H_OVER_UNDER_RUN;
3148                                 srb->status |= OVER_RUN;
3149                         }
3150                         /*
3151                          * KG: despite the fact that we are using 16 bits I/O ops
3152                          * the SCSI FIFO is only 8 bits according to the docs
3153                          * (we can set bit 1 in 0x8f to serialize FIFO access ...)
3154                          */
3155                         if (dcb->sync_period & WIDE_SYNC) {
3156                                 DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 2);
3157                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2,
3158                                               CFG2_WIDEFIFO);
3159                                 if (io_dir & DMACMD_DIR) {      /* read */
3160                                         data =
3161                                             DC395x_read8
3162                                             (acb, TRM_S1040_SCSI_FIFO);
3163                                         data2 =
3164                                             DC395x_read8
3165                                             (acb, TRM_S1040_SCSI_FIFO);
3166                                         /*dprintkl(KERN_DEBUG, "DataIO: Xfer pad: %02x %02x\n", data, data2); */
3167                                 } else {
3168                                         /* Danger, Robinson: If you find KGs scattered over the wide
3169                                          * disk, the driver or chip is to blame :-( */
3170                                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
3171                                                       'K');
3172                                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
3173                                                       'G');
3174                                 }
3175                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2, 0);
3176                         } else {
3177                                 DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 1);
3178                                 /* Danger, Robinson: If you find a collection of Ks on your disk
3179                                  * something broke :-( */
3180                                 if (io_dir & DMACMD_DIR) {      /* read */
3181                                         data =
3182                                             DC395x_read8
3183                                             (acb, TRM_S1040_SCSI_FIFO);
3184                                         /*dprintkl(KERN_DEBUG, "DataIO: Xfer pad: %02x\n", data); */
3185                                 } else {
3186                                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
3187                                                       'K');
3188                                 }
3189                         }
3190                         srb->state |= SRB_XFERPAD;
3191                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3192                         /*
3193                          * SCSI command 
3194                          */
3195                         bval =
3196                             (io_dir & DMACMD_DIR) ? SCMD_FIFO_IN :
3197                             SCMD_FIFO_OUT;
3198                         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, bval);
3199                 }
3200         }
3201         /*monitor_next_irq = 2; */
3202         /*printk(" done\n"); */
3203 }
3204
3205
3206 /*
3207  ********************************************************************
3208  * scsiio
3209  *      status_phase0: one of dc395x_scsi_phase0[] vectors
3210  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
3211  *                              if phase =3  
3212  ********************************************************************
3213  */
3214 static
3215 void status_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3216                    u16 * pscsi_status)
3217 {
3218         dprintkdbg(DBG_0, "StatusPhase0 (pid %li)\n", srb->cmd->pid);
3219         TRACEPRINTF("STP0 *");
3220         srb->target_status = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
3221         srb->end_message = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);      /* get message */
3222         srb->state = SRB_COMPLETED;
3223         *pscsi_status = PH_BUS_FREE;    /*.. initial phase */
3224         /*1.25 */
3225         /*clear_fifo (acb, "STP0"); */
3226         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3227         /*
3228          ** SCSI command 
3229          */
3230         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
3231 }
3232
3233
3234 /*
3235  ********************************************************************
3236  * scsiio
3237  *      status_phase1: one of dc395x_scsi_phase1[] vectors
3238  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
3239  *                              if phase =3 
3240  ********************************************************************
3241  */
3242 static
3243 void status_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3244                    u16 * pscsi_status)
3245 {
3246         dprintkdbg(DBG_0, "StatusPhase1 (pid=%li)\n", srb->cmd->pid);
3247         TRACEPRINTF("STP1 *");
3248         /* Cleanup is now done at the end of DataXXPhase0 */
3249         /*cleanup_after_transfer (acb, srb); */
3250
3251         srb->state = SRB_STATUS;
3252         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3253         /*
3254          * SCSI command 
3255          */
3256         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_COMP);
3257 }
3258
3259 /* Message handling */
3260
3261 #if 0
3262 /* Print received message */
3263 static void print_msg(u8 * msg_buf, u32 len)
3264 {
3265         int i;
3266         printk(" %02x", msg_buf[0]);
3267         for (i = 1; i < len; i++)
3268                 printk(" %02x", msg_buf[i]);
3269         printk("\n");
3270 }
3271 #endif
3272
3273 /* Check if the message is complete */
3274 static inline u8 msgin_completed(u8 * msgbuf, u32 len)
3275 {
3276         if (*msgbuf == EXTENDED_MESSAGE) {
3277                 if (len < 2)
3278                         return 0;
3279                 if (len < msgbuf[1] + 2)
3280                         return 0;
3281         } else if (*msgbuf >= 0x20 && *msgbuf <= 0x2f)  /* two byte messages */
3282                 if (len < 2)
3283                         return 0;
3284         return 1;
3285 }
3286
3287 #define DC395x_ENABLE_MSGOUT \
3288  DC395x_write16 (acb, TRM_S1040_SCSI_CONTROL, DO_SETATN); \
3289  srb->state |= SRB_MSGOUT
3290
3291
3292 /* reject_msg */
3293 static inline
3294 void msgin_reject(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
3295 {
3296         srb->msgout_buf[0] = MESSAGE_REJECT;
3297         srb->msg_count = 1;
3298         DC395x_ENABLE_MSGOUT;
3299         srb->state &= ~SRB_MSGIN;
3300         srb->state |= SRB_MSGOUT;
3301         dprintkl(KERN_INFO,
3302                "Reject message %02x from %02i-%i\n", srb->msgin_buf[0],
3303                srb->dcb->target_id, srb->dcb->target_lun);
3304         TRACEPRINTF("\\*");
3305 }
3306
3307
3308 /* abort command */
3309 static inline
3310 void enable_msgout_abort(struct AdapterCtlBlk *acb,
3311                          struct ScsiReqBlk *srb)
3312 {
3313         srb->msgout_buf[0] = ABORT;
3314         srb->msg_count = 1;
3315         DC395x_ENABLE_MSGOUT;
3316         srb->state &= ~SRB_MSGIN;
3317         srb->state |= SRB_MSGOUT;
3318         /*
3319            if (srb->dcb)
3320            srb->dcb->flag &= ~ABORT_DEV_;
3321          */
3322         TRACEPRINTF("#*");
3323 }
3324
3325
3326 static
3327 struct ScsiReqBlk *msgin_qtag(struct AdapterCtlBlk *acb,
3328                               struct DeviceCtlBlk *dcb,
3329                               u8 tag)
3330 {
3331         struct ScsiReqBlk *last_srb = dcb->going_last;
3332         struct ScsiReqBlk *srb = dcb->going_srb;
3333         dprintkdbg(DBG_0, "QTag Msg (SRB %p): %i\n", srb, tag);
3334         if (!(dcb->tag_mask & (1 << tag)))
3335                 dprintkl(KERN_DEBUG,
3336                        "MsgIn_QTag: tag_mask (%08x) does not reserve tag %i!\n",
3337                        dcb->tag_mask, tag);
3338
3339         if (!srb)
3340                 goto mingx0;
3341         while (srb) {
3342                 if (srb->tag_number == tag)
3343                         break;
3344                 if (srb == last_srb)
3345                         goto mingx0;
3346                 srb = srb->next;
3347         }
3348         dprintkdbg(DBG_0, "pid %li (%i-%i)\n", srb->cmd->pid,
3349                srb->dcb->target_id, srb->dcb->target_lun);
3350         if (dcb->flag & ABORT_DEV_) {
3351                 /*srb->state = SRB_ABORT_SENT; */
3352                 enable_msgout_abort(acb, srb);
3353         }
3354
3355         if (!(srb->state & SRB_DISCONNECT))
3356                 goto mingx0;
3357
3358         /* Tag found */
3359         TRACEPRINTF("[%s]*", dcb->active_srb->debugtrace);
3360         TRACEPRINTF("RTag*");
3361         /* Just for debugging ... */
3362         last_srb = srb;
3363         srb = dcb->active_srb;
3364         TRACEPRINTF("Found.*");
3365         srb = last_srb;
3366
3367         memcpy(srb->msgin_buf, dcb->active_srb->msgin_buf, acb->msg_len);
3368         srb->state |= dcb->active_srb->state;
3369         srb->state |= SRB_DATA_XFER;
3370         dcb->active_srb = srb;
3371         /* How can we make the DORS happy? */
3372         return srb;
3373
3374       mingx0:
3375         srb = acb->tmp_srb;
3376         srb->state = SRB_UNEXPECT_RESEL;
3377         dcb->active_srb = srb;
3378         srb->msgout_buf[0] = MSG_ABORT_TAG;
3379         srb->msg_count = 1;
3380         DC395x_ENABLE_MSGOUT;
3381         TRACEPRINTF("?*");
3382         dprintkl(KERN_DEBUG, "Unknown tag received: %i: abort !!\n", tag);
3383         return srb;
3384 }
3385
3386
3387 /* Reprogram registers */
3388 static inline void
3389 reprogram_regs(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb)
3390 {
3391         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);
3392         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);
3393         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);
3394         set_xfer_rate(acb, dcb);
3395 }
3396
3397
3398 /* set async transfer mode */
3399 static
3400 void msgin_set_async(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
3401 {
3402         struct DeviceCtlBlk *dcb = srb->dcb;
3403         dprintkl(KERN_DEBUG, "Target %02i: No sync transfers\n", dcb->target_id);
3404         TRACEPRINTF("!S *");
3405         dcb->sync_mode &= ~(SYNC_NEGO_ENABLE);
3406         dcb->sync_mode |= SYNC_NEGO_DONE;
3407         /*dcb->sync_period &= 0; */
3408         dcb->sync_offset = 0;
3409         dcb->min_nego_period = 200 >> 2;        /* 200ns <=> 5 MHz */
3410         srb->state &= ~SRB_DO_SYNC_NEGO;
3411         reprogram_regs(acb, dcb);
3412         if ((dcb->sync_mode & WIDE_NEGO_ENABLE)
3413             && !(dcb->sync_mode & WIDE_NEGO_DONE)) {
3414                 build_wdtr(acb, dcb, srb);
3415                 DC395x_ENABLE_MSGOUT;
3416                 dprintkdbg(DBG_0, "SDTR(rej): Try WDTR anyway ...\n");
3417         }
3418 }
3419
3420
3421 /* set sync transfer mode */
3422 static
3423 void msgin_set_sync(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
3424 {
3425         u8 bval;
3426         int fact;
3427         struct DeviceCtlBlk *dcb = srb->dcb;
3428         /*u8 oldsyncperiod = dcb->sync_period; */
3429         /*u8 oldsyncoffset = dcb->sync_offset; */
3430
3431         dprintkdbg(DBG_1, "Target %02i: Sync: %ins (%02i.%01i MHz) Offset %i\n",
3432                dcb->target_id, srb->msgin_buf[3] << 2,
3433                (250 / srb->msgin_buf[3]),
3434                ((250 % srb->msgin_buf[3]) * 10) / srb->msgin_buf[3],
3435                srb->msgin_buf[4]);
3436
3437         if (srb->msgin_buf[4] > 15)
3438                 srb->msgin_buf[4] = 15;
3439         if (!(dcb->dev_mode & NTC_DO_SYNC_NEGO))
3440                 dcb->sync_offset = 0;
3441         else if (dcb->sync_offset == 0)
3442                 dcb->sync_offset = srb->msgin_buf[4];
3443         if (srb->msgin_buf[4] > dcb->sync_offset)
3444                 srb->msgin_buf[4] = dcb->sync_offset;
3445         else
3446                 dcb->sync_offset = srb->msgin_buf[4];
3447         bval = 0;
3448         while (bval < 7 && (srb->msgin_buf[3] > clock_period[bval]
3449                             || dcb->min_nego_period >
3450                             clock_period[bval]))
3451                 bval++;
3452         if (srb->msgin_buf[3] < clock_period[bval])
3453                 dprintkl(KERN_INFO,
3454                        "Increase sync nego period to %ins\n",
3455                        clock_period[bval] << 2);
3456         srb->msgin_buf[3] = clock_period[bval];
3457         dcb->sync_period &= 0xf0;
3458         dcb->sync_period |= ALT_SYNC | bval;
3459         dcb->min_nego_period = srb->msgin_buf[3];
3460
3461         if (dcb->sync_period & WIDE_SYNC)
3462                 fact = 500;
3463         else
3464                 fact = 250;
3465
3466         dprintkl(KERN_INFO,
3467                "Target %02i: %s Sync: %ins Offset %i (%02i.%01i MB/s)\n",
3468                dcb->target_id, (fact == 500) ? "Wide16" : "",
3469                dcb->min_nego_period << 2, dcb->sync_offset,
3470                (fact / dcb->min_nego_period),
3471                ((fact % dcb->min_nego_period) * 10 +
3472                 dcb->min_nego_period / 2) / dcb->min_nego_period);
3473
3474         TRACEPRINTF("S%i *", dcb->min_nego_period << 2);
3475         if (!(srb->state & SRB_DO_SYNC_NEGO)) {
3476                 /* Reply with corrected SDTR Message */
3477                 dprintkl(KERN_DEBUG, " .. answer w/  %ins %i\n",
3478                        srb->msgin_buf[3] << 2, srb->msgin_buf[4]);
3479
3480                 memcpy(srb->msgout_buf, srb->msgin_buf, 5);
3481                 srb->msg_count = 5;
3482                 DC395x_ENABLE_MSGOUT;
3483                 dcb->sync_mode |= SYNC_NEGO_DONE;
3484         } else {
3485                 if ((dcb->sync_mode & WIDE_NEGO_ENABLE)
3486                     && !(dcb->sync_mode & WIDE_NEGO_DONE)) {
3487                         build_wdtr(acb, dcb, srb);
3488                         DC395x_ENABLE_MSGOUT;
3489                         dprintkdbg(DBG_0, "SDTR: Also try WDTR ...\n");
3490                 }
3491         }
3492         srb->state &= ~SRB_DO_SYNC_NEGO;
3493         dcb->sync_mode |= SYNC_NEGO_DONE | SYNC_NEGO_ENABLE;
3494
3495         reprogram_regs(acb, dcb);
3496 }
3497
3498
3499 static inline
3500 void msgin_set_nowide(struct AdapterCtlBlk *acb,
3501                       struct ScsiReqBlk *srb)
3502 {
3503         struct DeviceCtlBlk *dcb = srb->dcb;
3504         dprintkdbg(DBG_KG, "WDTR got rejected from target %02i\n",
3505                dcb->target_id);
3506         TRACEPRINTF("!W *");
3507         dcb->sync_period &= ~WIDE_SYNC;
3508         dcb->sync_mode &= ~(WIDE_NEGO_ENABLE);
3509         dcb->sync_mode |= WIDE_NEGO_DONE;
3510         srb->state &= ~SRB_DO_WIDE_NEGO;
3511         reprogram_regs(acb, dcb);
3512         if ((dcb->sync_mode & SYNC_NEGO_ENABLE)
3513             && !(dcb->sync_mode & SYNC_NEGO_DONE)) {
3514                 build_sdtr(acb, dcb, srb);
3515                 DC395x_ENABLE_MSGOUT;
3516                 dprintkdbg(DBG_0, "WDTR(rej): Try SDTR anyway ...\n");
3517         }
3518 }
3519
3520 static
3521 void msgin_set_wide(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
3522 {
3523         struct DeviceCtlBlk *dcb = srb->dcb;
3524         u8 wide = (dcb->dev_mode & NTC_DO_WIDE_NEGO
3525                    && acb->config & HCC_WIDE_CARD) ? 1 : 0;
3526         if (srb->msgin_buf[3] > wide)
3527                 srb->msgin_buf[3] = wide;
3528         /* Completed */
3529         if (!(srb->state & SRB_DO_WIDE_NEGO)) {
3530                 dprintkl(KERN_DEBUG,
3531                        "Target %02i initiates Wide Nego ...\n",
3532                        dcb->target_id);
3533                 memcpy(srb->msgout_buf, srb->msgin_buf, 4);
3534                 srb->msg_count = 4;
3535                 srb->state |= SRB_DO_WIDE_NEGO;
3536                 DC395x_ENABLE_MSGOUT;
3537         }
3538
3539         dcb->sync_mode |= (WIDE_NEGO_ENABLE | WIDE_NEGO_DONE);
3540         if (srb->msgin_buf[3] > 0)
3541                 dcb->sync_period |= WIDE_SYNC;
3542         else
3543                 dcb->sync_period &= ~WIDE_SYNC;
3544         srb->state &= ~SRB_DO_WIDE_NEGO;
3545         TRACEPRINTF("W%i *", (dcb->sync_period & WIDE_SYNC ? 1 : 0));
3546         /*dcb->sync_mode &= ~(WIDE_NEGO_ENABLE+WIDE_NEGO_DONE); */
3547         dprintkdbg(DBG_KG,
3548                "Wide transfers (%i bit) negotiated with target %02i\n",
3549                (8 << srb->msgin_buf[3]), dcb->target_id);
3550         reprogram_regs(acb, dcb);
3551         if ((dcb->sync_mode & SYNC_NEGO_ENABLE)
3552             && !(dcb->sync_mode & SYNC_NEGO_DONE)) {
3553                 build_sdtr(acb, dcb, srb);
3554                 DC395x_ENABLE_MSGOUT;
3555                 dprintkdbg(DBG_0, "WDTR: Also try SDTR ...\n");
3556         }
3557 }
3558
3559
3560 /*
3561  ********************************************************************
3562  * scsiio
3563  *      msgin_phase0: one of dc395x_scsi_phase0[] vectors
3564  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
3565  *                              if phase =7   
3566  *
3567  * extended message codes:
3568  *
3569  *      code    description
3570  *
3571  *      02h     Reserved
3572  *      00h     MODIFY DATA  POINTER
3573  *      01h     SYNCHRONOUS DATA TRANSFER REQUEST
3574  *      03h     WIDE DATA TRANSFER REQUEST
3575  *   04h - 7Fh  Reserved
3576  *   80h - FFh  Vendor specific
3577  *  
3578  ********************************************************************
3579  */
3580 static
3581 void msgin_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3582                   u16 * pscsi_status)
3583 {
3584         struct DeviceCtlBlk *dcb;
3585
3586         dprintkdbg(DBG_0, "msgin_phase0..............\n");
3587         TRACEPRINTF("MIP0*");
3588         dcb = acb->active_dcb;
3589
3590         srb->msgin_buf[acb->msg_len++] = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
3591         if (msgin_completed(srb->msgin_buf, acb->msg_len)) {
3592                 TRACEPRINTF("(%02x)*", srb->msgin_buf[0]);
3593                 /*dprintkl(KERN_INFO, "MsgIn:"); */
3594                 /*print_msg (srb->msgin_buf, acb->msg_len); */
3595
3596                 /* Now eval the msg */
3597                 switch (srb->msgin_buf[0]) {
3598                 case DISCONNECT:
3599                         srb->state = SRB_DISCONNECT;
3600                         break;
3601
3602                 case SIMPLE_QUEUE_TAG:
3603                 case HEAD_OF_QUEUE_TAG:
3604                 case ORDERED_QUEUE_TAG:
3605                         TRACEPRINTF("(%02x)*", srb->msgin_buf[1]);
3606                         srb =
3607                             msgin_qtag(acb, dcb,
3608                                               srb->msgin_buf[1]);
3609                         break;
3610
3611                 case MESSAGE_REJECT:
3612                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
3613                                        DO_CLRATN | DO_DATALATCH);
3614                         /* A sync nego message was rejected ! */
3615                         if (srb->state & SRB_DO_SYNC_NEGO) {
3616                                 msgin_set_async(acb, srb);
3617                                 break;
3618                         }
3619                         /* A wide nego message was rejected ! */
3620                         if (srb->state & SRB_DO_WIDE_NEGO) {
3621                                 msgin_set_nowide(acb, srb);
3622                                 break;
3623                         }
3624                         enable_msgout_abort(acb, srb);
3625                         /*srb->state |= SRB_ABORT_SENT */
3626                         break;
3627
3628                 case EXTENDED_MESSAGE:
3629                         TRACEPRINTF("(%02x)*", srb->msgin_buf[2]);
3630                         /* SDTR */
3631                         if (srb->msgin_buf[1] == 3
3632                             && srb->msgin_buf[2] == EXTENDED_SDTR) {
3633                                 msgin_set_sync(acb, srb);
3634                                 break;
3635                         }
3636                         /* WDTR */
3637                         if (srb->msgin_buf[1] == 2 && srb->msgin_buf[2] == EXTENDED_WDTR && srb->msgin_buf[3] <= 2) {   /* sanity check ... */
3638                                 msgin_set_wide(acb, srb);
3639                                 break;
3640                         }
3641                         msgin_reject(acb, srb);
3642                         break;
3643
3644                         /* Discard  wide residual */
3645                 case MSG_IGNOREWIDE:
3646                         dprintkdbg(DBG_0, "Ignore Wide Residual!\n");
3647                         /*DC395x_write32 (TRM_S1040_SCSI_COUNTER, 1); */
3648                         /*DC395x_read8 (TRM_S1040_SCSI_FIFO); */
3649                         break;
3650
3651                         /* nothing has to be done */
3652                 case COMMAND_COMPLETE:
3653                         break;
3654
3655                         /*
3656                          * SAVE POINTER may be ignored as we have the struct ScsiReqBlk* associated with the
3657                          * scsi command. Thanks, Gérard, for pointing it out.
3658                          */
3659                 case SAVE_POINTERS:
3660                         dprintkdbg(DBG_0, "SAVE POINTER message received (pid %li: rem.%i) ... ignore :-(\n",
3661                                srb->cmd->pid, srb->total_xfer_length);
3662                         /*srb->Saved_Ptr = srb->TotalxferredLen; */
3663                         break;
3664                         /* The device might want to restart transfer with a RESTORE */
3665                 case RESTORE_POINTERS:
3666                         dprintkl(KERN_DEBUG,
3667                                "RESTORE POINTER message received ... ignore :-(\n");
3668                         /*dc395x_restore_ptr (acb, srb); */
3669                         break;
3670                 case ABORT:
3671                         dprintkl(KERN_DEBUG,
3672                                "ABORT msg received (pid %li %02i-%i)\n",
3673                                srb->cmd->pid, dcb->target_id,
3674                                dcb->target_lun);
3675                         dcb->flag |= ABORT_DEV_;
3676                         enable_msgout_abort(acb, srb);
3677                         break;
3678                         /* reject unknown messages */
3679                 default:
3680                         if (srb->msgin_buf[0] & IDENTIFY_BASE) {
3681                                 dprintkl(KERN_DEBUG, "Identify Message received?\n");
3682                                 /*TRACEOUT (" %s\n", srb->debugtrace); */
3683                                 srb->msg_count = 1;
3684                                 srb->msgout_buf[0] = dcb->identify_msg;
3685                                 DC395x_ENABLE_MSGOUT;
3686                                 srb->state |= SRB_MSGOUT;
3687                                 /*break; */
3688                         }
3689                         msgin_reject(acb, srb);
3690                         TRACEOUT(" %s\n", srb->debugtrace);
3691                 }
3692                 TRACEPRINTF(".*");
3693
3694                 /* Clear counter and MsgIn state */
3695                 srb->state &= ~SRB_MSGIN;
3696                 acb->msg_len = 0;
3697         }
3698
3699         /*1.25 */
3700         if ((*pscsi_status & PHASEMASK) != PH_MSG_IN)
3701 #if 0
3702                 clear_fifo(acb, "MIP0_");
3703 #else
3704                 TRACEPRINTF("N/Cln *");
3705 #endif
3706         *pscsi_status = PH_BUS_FREE;
3707         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important ... you know! */
3708         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
3709 }
3710
3711
3712 /*
3713  ********************************************************************
3714  * scsiio
3715  *      msgin_phase1: one of dc395x_scsi_phase1[] vectors
3716  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
3717  *                              if phase =7        
3718  ********************************************************************
3719  */
3720 static
3721 void msgin_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3722                   u16 * pscsi_status)
3723 {
3724         dprintkdbg(DBG_0, "msgin_phase1..............\n");
3725         TRACEPRINTF("MIP1 *");
3726         clear_fifo(acb, "MIP1");
3727         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 1);
3728         if (!(srb->state & SRB_MSGIN)) {
3729                 srb->state &= ~SRB_DISCONNECT;
3730                 srb->state |= SRB_MSGIN;
3731         }
3732         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3733         /*
3734          * SCSI command 
3735          */
3736         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_IN);
3737 }
3738
3739
3740 /*
3741  ********************************************************************
3742  * scsiio
3743  *      nop0: one of dc395x_scsi_phase1[] ,dc395x_scsi_phase0[] vectors
3744  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
3745  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
3746  *                              if phase =4 ..PH_BUS_FREE
3747  ********************************************************************
3748  */
3749 static
3750 void nop0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3751           u16 * pscsi_status)
3752 {
3753         /*TRACEPRINTF("NOP0 *"); */
3754 }
3755
3756
3757 /*
3758  ********************************************************************
3759  * scsiio
3760  *      nop1: one of dc395x_scsi_phase0[] ,dc395x_scsi_phase1[] vectors
3761  *       dc395x_statev = (void *)dc395x_scsi_phase0[phase]
3762  *       dc395x_statev = (void *)dc395x_scsi_phase1[phase]
3763  *                              if phase =5
3764  ********************************************************************
3765  */
3766 static
3767 void nop1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
3768           u16 * pscsi_status)
3769 {
3770         /*TRACEPRINTF("NOP1 *"); */
3771 }
3772
3773
3774 /*
3775  ********************************************************************
3776  * scsiio
3777  *              msgin_phase0
3778  ********************************************************************
3779  */
3780 static
3781 void set_xfer_rate(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb)
3782 {
3783         u8 bval;
3784         u16 cnt, i;
3785         struct DeviceCtlBlk *dcb_temp;
3786
3787         /*
3788          ** set all lun device's  period , offset
3789          */
3790         if (!(dcb->identify_msg & 0x07)) {
3791                 if (acb->scan_devices)
3792                         current_sync_offset = dcb->sync_offset;
3793                 else {
3794                         dcb_temp = acb->link_dcb;
3795                         cnt = acb->dcb_count;
3796                         bval = dcb->target_id;
3797                         for (i = 0; i < cnt; i++) {
3798                                 if (dcb_temp->target_id == bval) {
3799                                         dcb_temp->sync_period =
3800                                             dcb->sync_period;
3801                                         dcb_temp->sync_offset =
3802                                             dcb->sync_offset;
3803                                         dcb_temp->sync_mode =
3804                                             dcb->sync_mode;
3805                                         dcb_temp->min_nego_period =
3806                                             dcb->min_nego_period;
3807                                 }
3808                                 dcb_temp = dcb_temp->next;
3809                         }
3810                 }
3811         }
3812         return;
3813 }
3814
3815
3816 /*
3817  ********************************************************************
3818  * scsiio
3819  *              dc395x_interrupt
3820  ********************************************************************
3821  */
3822 static void disconnect(struct AdapterCtlBlk *acb)
3823 {
3824         struct DeviceCtlBlk *dcb;
3825         struct ScsiReqBlk *srb;
3826
3827         dprintkdbg(DBG_0, "Disconnect (pid=%li)\n", acb->active_dcb->active_srb->cmd->pid);
3828         dcb = acb->active_dcb;
3829         if (!dcb) {
3830                 dprintkl(KERN_ERR, "Disc: Exception Disconnect dcb=NULL !!\n ");
3831                 udelay(500);
3832                 /* Suspend queue for a while */
3833                 acb->scsi_host->last_reset =
3834                     jiffies + HZ / 2 +
3835                     HZ *
3836                     eeprom_buf[acb->adapter_index].
3837                     delay_time;
3838                 clear_fifo(acb, "DiscEx");
3839                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT);
3840                 return;
3841         }
3842         srb = dcb->active_srb;
3843         acb->active_dcb = NULL;
3844         TRACEPRINTF("DISC *");
3845
3846         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
3847         clear_fifo(acb, "Disc");
3848         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT);
3849         if (srb->state & SRB_UNEXPECT_RESEL) {
3850                 dprintkl(KERN_ERR, "Disc: Unexpected Reselection (%i-%i)\n",
3851                        dcb->target_id, dcb->target_lun);
3852                 srb->state = 0;
3853                 waiting_process_next(acb);
3854         } else if (srb->state & SRB_ABORT_SENT) {
3855                 /*Scsi_Cmnd* cmd = srb->cmd; */
3856                 dcb->flag &= ~ABORT_DEV_;
3857                 acb->scsi_host->last_reset = jiffies + HZ / 2 + 1;
3858                 dprintkl(KERN_ERR, "Disc: SRB_ABORT_SENT!\n");
3859                 doing_srb_done(acb, DID_ABORT, srb->cmd, 1);
3860                 waiting_process_next(acb);
3861         } else {
3862                 if ((srb->state & (SRB_START_ + SRB_MSGOUT))
3863                     || !(srb->
3864                          state & (SRB_DISCONNECT + SRB_COMPLETED))) {
3865                         /*
3866                          * Selection time out 
3867                          * SRB_START_ || SRB_MSGOUT || (!SRB_DISCONNECT && !SRB_COMPLETED)
3868                          */
3869                         /* Unexp. Disc / Sel Timeout */
3870                         if (srb->state != SRB_START_
3871                             && srb->state != SRB_MSGOUT) {
3872                                 srb->state = SRB_READY;
3873                                 dprintkl(KERN_DEBUG, "Unexpected Disconnection (pid %li)!\n",
3874                                        srb->cmd->pid);
3875                                 srb->target_status = SCSI_STAT_SEL_TIMEOUT;
3876                                 TRACEPRINTF("UnExpD *");
3877                                 TRACEOUT("%s\n", srb->debugtrace);
3878                                 goto disc1;
3879                         } else {
3880                                 /* Normal selection timeout */
3881                                 TRACEPRINTF("SlTO *");
3882                                 dprintkdbg(DBG_KG,
3883                                        "Disc: SelTO (pid=%li) for dev %02i-%i\n",
3884                                        srb->cmd->pid, dcb->target_id,
3885                                        dcb->target_lun);
3886                                 if (srb->retry_count++ > DC395x_MAX_RETRIES
3887                                     || acb->scan_devices) {
3888                                         srb->target_status =
3889                                             SCSI_STAT_SEL_TIMEOUT;
3890                                         goto disc1;
3891                                 }
3892                                 free_tag(dcb, srb);
3893                                 move_srb_going_to_waiting(dcb, srb);
3894                                 dprintkdbg(DBG_KG, "Retry pid %li ...\n",
3895                                        srb->cmd->pid);
3896                                 waiting_set_timer(acb, HZ / 20);
3897                         }
3898                 } else if (srb->state & SRB_DISCONNECT) {
3899                         u8 bval = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
3900                         /*
3901                          * SRB_DISCONNECT (This is what we expect!)
3902                          */
3903                         /* dprintkl(KERN_DEBUG, "DoWaitingSRB (pid=%li)\n", srb->cmd->pid); */
3904                         TRACEPRINTF("+*");
3905                         if (bval & 0x40) {
3906                                 dprintkdbg(DBG_0, "Debug: DISC: SCSI bus stat %02x: ACK set! Other controllers?\n",
3907                                         bval);
3908                                 /* It could come from another initiator, therefore don't do much ! */
3909                                 TRACEPRINTF("ACK(%02x) *", bval);
3910                                 /*dump_register_info (acb, dcb, srb); */
3911                                 /*TRACEOUT (" %s\n", srb->debugtrace); */
3912                                 /*dcb->flag |= ABORT_DEV_; */
3913                                 /*enable_msgout_abort (acb, srb); */
3914                                 /*DC395x_write16 (TRM_S1040_SCSI_CONTROL, DO_CLRFIFO | DO_CLRATN | DO_HWRESELECT); */
3915                         } else
3916                                 waiting_process_next(acb);
3917                 } else if (srb->state & SRB_COMPLETED) {
3918                       disc1:
3919                         /*
3920                          ** SRB_COMPLETED
3921                          */
3922                         free_tag(dcb, srb);
3923                         dcb->active_srb = NULL;
3924                         srb->state = SRB_FREE;
3925                         /*dprintkl(KERN_DEBUG, "done (pid=%li)\n", srb->cmd->pid); */
3926                         srb_done(acb, dcb, srb);
3927                 }
3928         }
3929         return;
3930 }
3931
3932
3933 /*
3934  ********************************************************************
3935  * scsiio
3936  *              reselect
3937  ********************************************************************
3938  */
3939 static void reselect(struct AdapterCtlBlk *acb)
3940 {
3941         struct DeviceCtlBlk *dcb;
3942         struct ScsiReqBlk *srb = NULL;
3943         u16 rsel_tar_lun_id;
3944         u8 id, lun;
3945         u8 arblostflag = 0;
3946
3947         dprintkdbg(DBG_0, "reselect..............\n");
3948
3949         clear_fifo(acb, "Resel");
3950         /*DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT | DO_DATALATCH); */
3951         /* Read Reselected Target ID and LUN */
3952         rsel_tar_lun_id = DC395x_read16(acb, TRM_S1040_SCSI_TARGETID);
3953         dcb = acb->active_dcb;
3954         if (dcb) {              /* Arbitration lost but Reselection win */
3955                 srb = dcb->active_srb;
3956                 if (!srb) {
3957                         dprintkl(KERN_DEBUG, "Arb lost Resel won, but active_srb == NULL!\n");
3958                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3959                         return;
3960                 }
3961                 /* Why the if ? */
3962                 if (!(acb->scan_devices)) {
3963                         dprintkdbg(DBG_KG,
3964                                "Arb lost but Resel win pid %li (%02i-%i) Rsel %04x Stat %04x\n",
3965                                srb->cmd->pid, dcb->target_id,
3966                                dcb->target_lun, rsel_tar_lun_id,
3967                                DC395x_read16(acb, TRM_S1040_SCSI_STATUS));
3968                         TRACEPRINTF("ArbLResel!*");
3969                         /*TRACEOUT (" %s\n", srb->debugtrace); */
3970                         arblostflag = 1;
3971                         /*srb->state |= SRB_DISCONNECT; */
3972
3973                         srb->state = SRB_READY;
3974                         free_tag(dcb, srb);
3975                         move_srb_going_to_waiting(dcb, srb);
3976                         waiting_set_timer(acb, HZ / 20);
3977
3978                         /* return; */
3979                 }
3980         }
3981         /* Read Reselected Target Id and LUN */
3982         if (!(rsel_tar_lun_id & (IDENTIFY_BASE << 8)))
3983                 dprintkl(KERN_DEBUG, "Resel expects identify msg! Got %04x!\n",
3984                        rsel_tar_lun_id);
3985         id = rsel_tar_lun_id & 0xff;
3986         lun = (rsel_tar_lun_id >> 8) & 7;
3987         dcb = find_dcb(acb, id, lun);
3988         if (!dcb) {
3989                 dprintkl(KERN_ERR, "Reselect from non existing device (%02i-%i)\n",
3990                        id, lun);
3991                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3992                 return;
3993         }
3994
3995         acb->active_dcb = dcb;
3996
3997         if (!(dcb->dev_mode & NTC_DO_DISCONNECT))
3998                 dprintkl(KERN_DEBUG, "Reselection in spite of forbidden disconnection? (%02i-%i)\n",
3999                        dcb->target_id, dcb->target_lun);
4000
4001         if ((dcb->sync_mode & EN_TAG_QUEUEING) /*&& !arblostflag */ ) {
4002                 struct ScsiReqBlk *oldSRB = srb;
4003                 srb = acb->tmp_srb;
4004 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
4005                 srb->debugpos = 0;
4006                 srb->debugtrace[0] = 0;
4007 #endif
4008                 dcb->active_srb = srb;
4009                 if (oldSRB)
4010                         TRACEPRINTF("ArbLResel(%li):*", oldSRB->cmd->pid);
4011                 /*if (arblostflag) dprintkl(KERN_DEBUG, "Reselect: Wait for Tag ... \n"); */
4012         } else {
4013                 /* There can be only one! */
4014                 srb = dcb->active_srb;
4015                 if (srb)
4016                         TRACEPRINTF("RSel *");
4017                 if (!srb || !(srb->state & SRB_DISCONNECT)) {
4018                         /*
4019                          * abort command
4020                          */
4021                         dprintkl(KERN_DEBUG,
4022                                "Reselected w/o disconnected cmds from %02i-%i?\n",
4023                                dcb->target_id, dcb->target_lun);
4024                         srb = acb->tmp_srb;
4025                         srb->state = SRB_UNEXPECT_RESEL;
4026                         dcb->active_srb = srb;
4027                         enable_msgout_abort(acb, srb);
4028                 } else {
4029                         if (dcb->flag & ABORT_DEV_) {
4030                                 /*srb->state = SRB_ABORT_SENT; */
4031                                 enable_msgout_abort(acb, srb);
4032                         } else
4033                                 srb->state = SRB_DATA_XFER;
4034
4035                 }
4036                 /*if (arblostflag) TRACEOUT (" %s\n", srb->debugtrace); */
4037         }
4038         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
4039         /* 
4040          ***********************************************
4041          ** Program HA ID, target ID, period and offset
4042          ***********************************************
4043          */
4044         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);     /* host   ID */
4045         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);            /* target ID */
4046         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);            /* offset    */
4047         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);              /* sync period, wide */
4048         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);              /* it's important for atn stop */
4049         /* SCSI command */
4050         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
4051 }
4052
4053
4054 /* Dynamic device handling */
4055
4056 /* Remove dev (and DCB) */
4057 static
4058 void remove_dev(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb)
4059 {
4060         struct DeviceCtlBlk *pPrevDCB = acb->link_dcb;
4061
4062         dprintkdbg(DBG_0, "remove_dev\n");
4063         if (dcb->going_srb_count > 1) {
4064                 dprintkdbg(DBG_DCB, "Driver won't free DCB (ID %i, LUN %i): 0x%08x because of SRBCnt %i\n",
4065                           dcb->target_id, dcb->target_lun, (int) dcb,
4066                           dcb->going_srb_count);
4067                 return;
4068         }
4069         acb->dcb_map[dcb->target_id] &= ~(1 << dcb->target_lun);
4070         acb->children[dcb->target_id][dcb->target_lun] = NULL;
4071
4072         /* The first one */
4073         if (dcb == acb->link_dcb) {
4074                 /* The last one */
4075                 if (acb->last_dcb == dcb) {
4076                         dcb->next = NULL;
4077                         acb->last_dcb = NULL;
4078                 }
4079                 acb->link_dcb = dcb->next;
4080         } else {
4081                 while (pPrevDCB->next != dcb)
4082                         pPrevDCB = pPrevDCB->next;
4083                 pPrevDCB->next = dcb->next;
4084                 if (dcb == acb->last_dcb)
4085                         acb->last_dcb = pPrevDCB;
4086         }
4087
4088         dprintkdbg(DBG_DCB, "Driver about to free DCB (ID %i, LUN %i): %p\n",
4089                   dcb->target_id, dcb->target_lun, dcb);
4090         if (dcb == acb->active_dcb)
4091                 acb->active_dcb = NULL;
4092         if (dcb == acb->link_dcb)
4093                 acb->link_dcb = dcb->next;
4094         if (dcb == acb->dcb_run_robin)
4095                 acb->dcb_run_robin = dcb->next;
4096         acb->dcb_count--;
4097         dc395x_kfree(dcb);
4098 }
4099
4100
4101 static inline u8 tagq_blacklist(char *name)
4102 {
4103 #ifndef DC395x_NO_TAGQ
4104 #if 0
4105         u8 i;
4106         for (i = 0; i < BADDEVCNT; i++)
4107                 if (memcmp(name, DC395x_baddevname1[i], 28) == 0)
4108                         return 1;
4109 #endif
4110         return 0;
4111 #else
4112         return 1;
4113 #endif
4114 }
4115
4116
4117 static
4118 void disc_tagq_set(struct DeviceCtlBlk *dcb, struct ScsiInqData *ptr)
4119 {
4120         /* Check for SCSI format (ANSI and Response data format) */
4121         if ((ptr->Vers & 0x07) >= 2 || (ptr->RDF & 0x0F) == 2) {
4122                 if ((ptr->Flags & SCSI_INQ_CMDQUEUE)
4123                     && (dcb->dev_mode & NTC_DO_TAG_QUEUEING) &&
4124                     /*(dcb->dev_mode & NTC_DO_DISCONNECT) */
4125                     /* ((dcb->dev_type == TYPE_DISK) 
4126                        || (dcb->dev_type == TYPE_MOD)) && */
4127                     !tagq_blacklist(((char *) ptr) + 8)) {
4128                         if (dcb->max_command == 1)
4129                                 dcb->max_command =
4130                                     dcb->acb->tag_max_num;
4131                         dcb->sync_mode |= EN_TAG_QUEUEING;
4132                         /*dcb->tag_mask = 0; */
4133                 } else
4134                         dcb->max_command = 1;
4135         }
4136 }
4137
4138
4139 static
4140 void add_dev(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
4141              struct ScsiInqData *ptr)
4142 {
4143         u8 bval1 = ptr->DevType & SCSI_DEVTYPE;
4144         dcb->dev_type = bval1;
4145         /* if (bval1 == TYPE_DISK || bval1 == TYPE_MOD) */
4146         disc_tagq_set(dcb, ptr);
4147 }
4148
4149
4150 /* 
4151  ********************************************************************
4152  * unmap mapped pci regions from SRB
4153  ********************************************************************
4154  */
4155 static
4156 void pci_unmap_srb(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
4157 {
4158         int dir;
4159         Scsi_Cmnd *cmd = srb->cmd;
4160         dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
4161         if (cmd->use_sg && dir != PCI_DMA_NONE) {
4162                 /* unmap DC395x SG list */
4163                 dprintkdbg(DBG_SGPARANOIA,
4164                        "Unmap SG descriptor list %08x (%05x)\n",
4165                        srb->sg_bus_addr,
4166                        sizeof(struct SGentry) * DC395x_MAX_SG_LISTENTRY);
4167                 pci_unmap_single(acb->dev, srb->sg_bus_addr,
4168                                  sizeof(struct SGentry) *
4169                                  DC395x_MAX_SG_LISTENTRY,
4170                                  PCI_DMA_TODEVICE);
4171                 dprintkdbg(DBG_SGPARANOIA, "Unmap %i SG segments from %p\n",
4172                        cmd->use_sg, cmd->request_buffer);
4173                 /* unmap the sg segments */
4174                 pci_unmap_sg(acb->dev,
4175                              (struct scatterlist *) cmd->request_buffer,
4176                              cmd->use_sg, dir);
4177         } else if (cmd->request_buffer && dir != PCI_DMA_NONE) {
4178                 dprintkdbg(DBG_SGPARANOIA, "Unmap buffer at %08x (%05x)\n",
4179                        srb->segment_x[0].address, cmd->request_bufflen);
4180                 pci_unmap_single(acb->dev, srb->segment_x[0].address,
4181                                  cmd->request_bufflen, dir);
4182         }
4183 }
4184
4185
4186 /* 
4187  ********************************************************************
4188  * unmap mapped pci sense buffer from SRB
4189  ********************************************************************
4190  */
4191 static
4192 void pci_unmap_srb_sense(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
4193 {
4194         if (!(srb->flag & AUTO_REQSENSE))
4195                 return;
4196         /* Unmap sense buffer */
4197         dprintkdbg(DBG_SGPARANOIA, "Unmap sense buffer from %08x\n",
4198                srb->segment_x[0].address);
4199         pci_unmap_single(acb->dev, srb->segment_x[0].address,
4200                          srb->segment_x[0].length, PCI_DMA_FROMDEVICE);
4201         /* Restore SG stuff */
4202         /*printk ("Auto_ReqSense finished: Restore Counters ...\n"); */
4203         srb->total_xfer_length = srb->xferred;
4204         srb->segment_x[0].address =
4205             srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].address;
4206         srb->segment_x[0].length =
4207             srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].length;
4208 }
4209
4210
4211 /*
4212  ********************************************************************
4213  * scsiio
4214  *              disconnect
4215  *      Complete execution of a SCSI command
4216  *      Signal completion to the generic SCSI driver  
4217  ********************************************************************
4218  */
4219 static
4220 void srb_done(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
4221               struct ScsiReqBlk *srb)
4222 {
4223         u8 tempcnt, status;
4224         Scsi_Cmnd *cmd;
4225         struct ScsiInqData *ptr;
4226         /*u32              drv_flags=0; */
4227         int dir;
4228
4229         cmd = srb->cmd;
4230         TRACEPRINTF("DONE *");
4231
4232         dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
4233         ptr = (struct ScsiInqData *) (cmd->request_buffer);
4234         if (cmd->use_sg)
4235                 ptr =
4236                     (struct ScsiInqData *) CPU_ADDR(*(struct scatterlist *)
4237                                                     ptr);
4238         dprintkdbg(DBG_SGPARANOIA, 
4239                "SRBdone SG=%i (%i/%i), req_buf = %p, adr = %p\n",
4240                cmd->use_sg, srb->sg_index, srb->sg_count,
4241                cmd->request_buffer, ptr);
4242         dprintkdbg(DBG_KG,
4243                "SRBdone (pid %li, target %02i-%i): ", srb->cmd->pid,
4244                srb->cmd->device->id, srb->cmd->device->lun);
4245         status = srb->target_status;
4246         if (srb->flag & AUTO_REQSENSE) {
4247                 dprintkdbg(DBG_0, "AUTO_REQSENSE1..............\n");
4248                 pci_unmap_srb_sense(acb, srb);
4249                 /*
4250                  ** target status..........................
4251                  */
4252                 srb->flag &= ~AUTO_REQSENSE;
4253                 srb->adapter_status = 0;
4254                 srb->target_status = CHECK_CONDITION << 1;
4255                 if (debug_enabled(DBG_KG)) {
4256                         switch (cmd->sense_buffer[2] & 0x0f) {
4257                         case NOT_READY:
4258                                 dprintkl(KERN_DEBUG,
4259                                      "ReqSense: NOT_READY (Cmnd = 0x%02x, Dev = %i-%i, Stat = %i, Scan = %i) ",
4260                                      cmd->cmnd[0], dcb->target_id,
4261                                      dcb->target_lun, status, acb->scan_devices);
4262                                 break;
4263                         case UNIT_ATTENTION:
4264                                 dprintkl(KERN_DEBUG,
4265                                      "ReqSense: UNIT_ATTENTION (Cmnd = 0x%02x, Dev = %i-%i, Stat = %i, Scan = %i) ",
4266                                      cmd->cmnd[0], dcb->target_id,
4267                                      dcb->target_lun, status, acb->scan_devices);
4268                                 break;
4269                         case ILLEGAL_REQUEST:
4270                                 dprintkl(KERN_DEBUG,
4271                                      "ReqSense: ILLEGAL_REQUEST (Cmnd = 0x%02x, Dev = %i-%i, Stat = %i, Scan = %i) ",
4272                                      cmd->cmnd[0], dcb->target_id,
4273                                      dcb->target_lun, status, acb->scan_devices);
4274                                 break;
4275                         case MEDIUM_ERROR:
4276                                 dprintkl(KERN_DEBUG,
4277                                      "ReqSense: MEDIUM_ERROR (Cmnd = 0x%02x, Dev = %i-%i, Stat = %i, Scan = %i) ",
4278                                      cmd->cmnd[0], dcb->target_id,
4279                                      dcb->target_lun, status, acb->scan_devices);
4280                                 break;
4281                         case HARDWARE_ERROR:
4282                                 dprintkl(KERN_DEBUG,
4283                                      "ReqSense: HARDWARE_ERROR (Cmnd = 0x%02x, Dev = %i-%i, Stat = %i, Scan = %i) ",
4284                                      cmd->cmnd[0], dcb->target_id,
4285                                      dcb->target_lun, status, acb->scan_devices);
4286                                 break;
4287                         }
4288                         if (cmd->sense_buffer[7] >= 6)
4289                                 dprintkl(KERN_DEBUG, 
4290                                      "Sense=%02x, ASC=%02x, ASCQ=%02x (%08x %08x) ",
4291                                      cmd->sense_buffer[2], cmd->sense_buffer[12],
4292                                      cmd->sense_buffer[13],
4293                                      *((unsigned int *) (cmd->sense_buffer + 3)),
4294                                      *((unsigned int *) (cmd->sense_buffer + 8)));
4295                         else
4296                                 dprintkl(KERN_DEBUG,
4297                                      "Sense=%02x, No ASC/ASCQ (%08x) ",
4298                                      cmd->sense_buffer[2],
4299                                      *((unsigned int *) (cmd->sense_buffer + 3)));
4300                 }
4301
4302                 if (status == (CHECK_CONDITION << 1)) {
4303                         cmd->result = DID_BAD_TARGET << 16;
4304                         goto ckc_e;
4305                 }
4306                 dprintkdbg(DBG_0, "AUTO_REQSENSE2..............\n");
4307
4308                 if ((srb->total_xfer_length)
4309                     && (srb->total_xfer_length >= cmd->underflow))
4310                         cmd->result =
4311                             MK_RES_LNX(DRIVER_SENSE, DID_OK,
4312                                        srb->end_message, CHECK_CONDITION);
4313                 /*SET_RES_DID(cmd->result,DID_OK) */
4314                 else
4315                         cmd->result =
4316                             MK_RES_LNX(DRIVER_SENSE, DID_OK,
4317                                        srb->end_message, CHECK_CONDITION);
4318
4319                 goto ckc_e;
4320         }
4321
4322 /*************************************************************/
4323         if (status) {
4324                 /*
4325                  * target status..........................
4326                  */
4327                 if (status_byte(status) == CHECK_CONDITION) {
4328                         request_sense(acb, dcb, srb);
4329                         return;
4330                 } else if (status_byte(status) == QUEUE_FULL) {
4331                         tempcnt = (u8) dcb->going_srb_count;
4332                         printk
4333                             ("\nDC395x:  QUEUE_FULL for dev %02i-%i with %i cmnds\n",
4334                              dcb->target_id, dcb->target_lun, tempcnt);
4335                         if (tempcnt > 1)
4336                                 tempcnt--;
4337                         dcb->max_command = tempcnt;
4338                         free_tag(dcb, srb);
4339                         move_srb_going_to_waiting(dcb, srb);
4340                         waiting_set_timer(acb, HZ / 20);
4341                         srb->adapter_status = 0;
4342                         srb->target_status = 0;
4343                         return;
4344                 } else if (status == SCSI_STAT_SEL_TIMEOUT) {
4345                         srb->adapter_status = H_SEL_TIMEOUT;
4346                         srb->target_status = 0;
4347                         cmd->result = DID_NO_CONNECT << 16;
4348                 } else {
4349                         srb->adapter_status = 0;
4350                         SET_RES_DID(cmd->result, DID_ERROR);
4351                         SET_RES_MSG(cmd->result, srb->end_message);
4352                         SET_RES_TARGET(cmd->result, status);
4353
4354                 }
4355         } else {
4356                 /*
4357                  ** process initiator status..........................
4358                  */
4359                 status = srb->adapter_status;
4360                 if (status & H_OVER_UNDER_RUN) {
4361                         srb->target_status = 0;
4362                         SET_RES_DID(cmd->result, DID_OK);
4363                         SET_RES_MSG(cmd->result, srb->end_message);
4364                 } else if (srb->status & PARITY_ERROR) {
4365                         SET_RES_DID(cmd->result, DID_PARITY);
4366                         SET_RES_MSG(cmd->result, srb->end_message);
4367                 } else {        /* No error */
4368
4369                         srb->adapter_status = 0;
4370                         srb->target_status = 0;
4371                         SET_RES_DID(cmd->result, DID_OK);
4372                 }
4373         }
4374
4375         if (dir != PCI_DMA_NONE) {
4376                 if (cmd->use_sg)
4377                         pci_dma_sync_sg(acb->dev,
4378                                         (struct scatterlist *) cmd->
4379                                         request_buffer, cmd->use_sg, dir);
4380                 else if (cmd->request_buffer)
4381                         pci_dma_sync_single(acb->dev,
4382                                             srb->segment_x[0].address,
4383                                             cmd->request_bufflen, dir);
4384         }
4385
4386         if ((cmd->result & RES_DID) == 0 && cmd->cmnd[0] == INQUIRY
4387             && cmd->cmnd[2] == 0 && cmd->request_bufflen >= 8
4388             && dir != PCI_DMA_NONE && ptr && (ptr->Vers & 0x07) >= 2)
4389                 dcb->inquiry7 = ptr->Flags;
4390 /* Check Error Conditions */
4391       ckc_e:
4392
4393         /*if( srb->cmd->cmnd[0] == INQUIRY && */
4394         /*  (host_byte(cmd->result) == DID_OK || status_byte(cmd->result) & CHECK_CONDITION) ) */
4395         if (cmd->cmnd[0] == INQUIRY && (cmd->result == (DID_OK << 16)
4396                                          || status_byte(cmd->
4397                                                         result) &
4398                                          CHECK_CONDITION)) {
4399
4400                 if (!dcb->init_tcq_flag) {
4401                         add_dev(acb, dcb, ptr);
4402                         dcb->init_tcq_flag = 1;
4403                 }
4404
4405         }
4406
4407
4408         /* Here is the info for Doug Gilbert's sg3 ... */
4409         cmd->resid = srb->total_xfer_length;
4410         /* This may be interpreted by sb. or not ... */
4411         cmd->SCp.this_residual = srb->total_xfer_length;
4412         cmd->SCp.buffers_residual = 0;
4413         if (debug_enabled(DBG_KG)) {
4414                 if (srb->total_xfer_length)
4415                         dprintkdbg(DBG_KG, "pid %li: %02x (%02i-%i): Missed %i bytes\n",
4416                              cmd->pid, cmd->cmnd[0], cmd->device->id,
4417                              cmd->device->lun, srb->total_xfer_length);
4418         }
4419
4420         remove_srb_going(dcb, srb, 0);
4421         /* Add to free list */
4422         if (srb == acb->tmp_srb)
4423                 dprintkl(KERN_ERR, "ERROR! Completed Cmnd with tmp_srb!\n");
4424         else
4425                 insert_srb_free(acb, srb);
4426
4427         dprintkdbg(DBG_0, "SRBdone: done pid %li\n", cmd->pid);
4428         if (debug_enabled(DBG_KG)) {
4429                 printk(" 0x%08x\n", cmd->result);
4430         }
4431         TRACEPRINTF("%08x(%li)*", cmd->result, jiffies);
4432         pci_unmap_srb(acb, srb);
4433         /*DC395x_UNLOCK_ACB_NI; */
4434         cmd->scsi_done(cmd);
4435         /*DC395x_LOCK_ACB_NI; */
4436         TRACEOUTALL(KERN_INFO " %s\n", srb->debugtrace);
4437
4438         waiting_process_next(acb);
4439         return;
4440 }
4441
4442
4443 /*
4444  ********************************************************************
4445  * scsiio
4446  *              DC395x_reset
4447  * abort all cmds in our queues
4448  ********************************************************************
4449  */
4450 static
4451 void doing_srb_done(struct AdapterCtlBlk *acb, u8 did_flag,
4452                     Scsi_Cmnd * cmd, u8 force)
4453 {
4454         struct DeviceCtlBlk *dcb;
4455         struct ScsiReqBlk *srb;
4456         struct ScsiReqBlk *srb_temp;
4457         u16 cnt;
4458         Scsi_Cmnd *p;
4459
4460         dcb = acb->link_dcb;
4461         if (!dcb)
4462                 return;
4463         dprintkl(KERN_INFO, "doing_srb_done: pids ");
4464         do {
4465                 /* As the ML may queue cmnds again, cache old values */
4466                 struct ScsiReqBlk *waiting_srb = dcb->waiting_srb;
4467                 /*struct ScsiReqBlk* wait_list = dcb->wait_list; */
4468                 u16 waiting_srb_count = dcb->waiting_srb_count;
4469                 /* Going queue */
4470                 cnt = dcb->going_srb_count;
4471                 srb = dcb->going_srb;
4472                 while (cnt--) {
4473                         int result;
4474                         int dir;
4475                         srb_temp = srb->next;
4476                         p = srb->cmd;
4477                         dir = scsi_to_pci_dma_dir(p->sc_data_direction);
4478                         result = MK_RES(0, did_flag, 0, 0);
4479                         /*result = MK_RES(0,DID_RESET,0,0); */
4480                         TRACEPRINTF("Reset(%li):%08x*", jiffies, result);
4481                         printk(" (G)");
4482 #if 1                           /*ndef DC395x_DEBUGTRACE */
4483                         printk("%li(%02i-%i) ", p->pid,
4484                                p->device->id, p->device->lun);
4485 #endif
4486                         TRACEOUT("%s\n", srb->debugtrace);
4487                         dcb->going_srb = srb_temp;
4488                         dcb->going_srb_count--;
4489                         if (!srb_temp)
4490                                 dcb->going_last = NULL;
4491                         free_tag(dcb, srb);
4492                         insert_srb_free(acb, srb);
4493                         p->result = result;
4494                         pci_unmap_srb_sense(acb, srb);
4495                         pci_unmap_srb(acb, srb);
4496                         if (force) {
4497                                 /* For new EH, we normally don't need to give commands back,
4498                                  * as they all complete or all time out */
4499                                 p->scsi_done(p);
4500                         }
4501                         srb = srb_temp;
4502                 }
4503                 if (dcb->going_srb)
4504                         dprintkl(KERN_DEBUG, 
4505                                "How could the ML send cmnds to the Going queue? (%02i-%i)!!\n",
4506                                dcb->target_id, dcb->target_lun);
4507                 if (dcb->tag_mask)
4508                         dprintkl(KERN_DEBUG,
4509                                "tag_mask for %02i-%i should be empty, is %08x!\n",
4510                                dcb->target_id, dcb->target_lun,
4511                                dcb->tag_mask);
4512                 /*dcb->going_srb_count = 0;; */
4513                 /*dcb->going_srb = NULL; dcb->going_last = NULL; */
4514
4515                 /* Waiting queue */
4516                 cnt = waiting_srb_count;
4517                 srb = waiting_srb;
4518                 while (cnt--) {
4519                         int result;
4520                         srb_temp = srb->next;
4521                         p = srb->cmd;
4522                         result = MK_RES(0, did_flag, 0, 0);
4523                         TRACEPRINTF("Reset(%li):%08x*", jiffies, result);
4524                         printk(" (W)");
4525 #if 1                           /*ndef DC395x_DEBUGTRACE */
4526                         printk("%li(%i-%i)", p->pid, p->device->id,
4527                                p->device->lun);
4528 #endif
4529                         TRACEOUT("%s\n", srb->debugtrace);
4530                         dcb->waiting_srb = srb_temp;
4531                         dcb->waiting_srb_count--;
4532                         if (!srb_temp)
4533                                 dcb->wait_list = NULL;
4534                         insert_srb_free(acb, srb);
4535
4536                         p->result = result;
4537                         pci_unmap_srb_sense(acb, srb);
4538                         pci_unmap_srb(acb, srb);
4539                         if (force) {
4540                                 /* For new EH, we normally don't need to give commands back,
4541                                  * as they all complete or all time out */
4542                                 cmd->scsi_done(cmd);
4543                                 srb = srb_temp;
4544                         }
4545                 }
4546                 if (dcb->waiting_srb_count)
4547                         printk
4548                             ("\nDC395x: Debug: ML queued %i cmnds again to %02i-%i\n",
4549                              dcb->waiting_srb_count, dcb->target_id,
4550                              dcb->target_lun);
4551                 /* The ML could have queued the cmnds again! */
4552                 /*dcb->waiting_srb_count = 0;; */
4553                 /*dcb->waiting_srb = NULL; dcb->wait_list = NULL; */
4554                 dcb->flag &= ~ABORT_DEV_;
4555                 dcb = dcb->next;
4556         }
4557         while (dcb != acb->link_dcb && dcb);
4558         printk("\n");
4559 }
4560
4561
4562 /*
4563  ********************************************************************
4564  * scsiio
4565  *              DC395x_shutdown   DC395x_reset
4566  ********************************************************************
4567  */
4568 static void reset_scsi_bus(struct AdapterCtlBlk *acb)
4569 {
4570         /*u32  drv_flags=0; */
4571
4572         dprintkdbg(DBG_0, "reset_scsi_bus..............\n");
4573
4574         /*DC395x_DRV_LOCK(drv_flags); */
4575         acb->acb_flag |= RESET_DEV;     /* RESET_DETECT, RESET_DONE, RESET_DEV */
4576
4577         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_RSTSCSI);
4578         while (!(DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS) & INT_SCSIRESET));
4579
4580         /*DC395x_DRV_UNLOCK(drv_flags); */
4581         return;
4582 }
4583
4584
4585 /* Set basic config */
4586 static void set_basic_config(struct AdapterCtlBlk *acb)
4587 {
4588         u8 bval;
4589         u16 wval;
4590         DC395x_write8(acb, TRM_S1040_SCSI_TIMEOUT, acb->sel_timeout);
4591         if (acb->config & HCC_PARITY)
4592                 bval = PHASELATCH | INITIATOR | BLOCKRST | PARITYCHECK;
4593         else
4594                 bval = PHASELATCH | INITIATOR | BLOCKRST;
4595
4596         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG0, bval);
4597
4598         /* program configuration 1: Act_Neg (+ Act_Neg_Enh? + Fast_Filter? + DataDis?) */
4599         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG1, 0x03);       /* was 0x13: default */
4600         /* program Host ID                  */
4601         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);
4602         /* set ansynchronous transfer       */
4603         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, 0x00);
4604         /* Turn LED control off */
4605         wval = DC395x_read16(acb, TRM_S1040_GEN_CONTROL) & 0x7F;
4606         DC395x_write16(acb, TRM_S1040_GEN_CONTROL, wval);
4607         /* DMA config          */
4608         wval = DC395x_read16(acb, TRM_S1040_DMA_CONFIG) & ~DMA_FIFO_CTRL;
4609         wval |=
4610             DMA_FIFO_HALF_HALF | DMA_ENHANCE /*| DMA_MEM_MULTI_READ */ ;
4611         /*dprintkl(KERN_INFO, "DMA_Config: %04x\n", wval); */
4612         DC395x_write16(acb, TRM_S1040_DMA_CONFIG, wval);
4613         /* Clear pending interrupt status */
4614         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
4615         /* Enable SCSI interrupt    */
4616         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x7F);
4617         DC395x_write8(acb, TRM_S1040_DMA_INTEN, EN_SCSIINTR | EN_DMAXFERERROR
4618                       /*| EN_DMAXFERABORT | EN_DMAXFERCOMP | EN_FORCEDMACOMP */
4619                       );
4620 }
4621
4622
4623 /*
4624  ********************************************************************
4625  * scsiio
4626  *              dc395x_interrupt
4627  ********************************************************************
4628  */
4629 static void scsi_reset_detect(struct AdapterCtlBlk *acb)
4630 {
4631         dprintkl(KERN_INFO, "scsi_reset_detect\n");
4632         /* delay half a second */
4633         if (timer_pending(&acb->waiting_timer))
4634                 del_timer(&acb->waiting_timer);
4635
4636         DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
4637         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
4638         /*DC395x_write8(acb, TRM_S1040_DMA_CONTROL,STOPDMAXFER); */
4639         udelay(500);
4640         /* Maybe we locked up the bus? Then lets wait even longer ... */
4641         acb->scsi_host->last_reset =
4642             jiffies + 5 * HZ / 2 +
4643             HZ * eeprom_buf[acb->adapter_index].delay_time;
4644
4645         clear_fifo(acb, "RstDet");
4646         set_basic_config(acb);
4647         /*1.25 */
4648         /*DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT); */
4649
4650         if (acb->acb_flag & RESET_DEV) {        /* RESET_DETECT, RESET_DONE, RESET_DEV */
4651                 acb->acb_flag |= RESET_DONE;
4652         } else {
4653                 acb->acb_flag |= RESET_DETECT;
4654                 reset_dev_param(acb);
4655                 doing_srb_done(acb, DID_RESET, 0, 1);
4656                 /*DC395x_RecoverSRB( acb ); */
4657                 acb->active_dcb = NULL;
4658                 acb->acb_flag = 0;
4659                 waiting_process_next(acb);
4660         }
4661
4662         return;
4663 }
4664
4665
4666 /*
4667  ********************************************************************
4668  * scsiio
4669  *              srb_done
4670  ********************************************************************
4671  */
4672 static
4673 void request_sense(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
4674                    struct ScsiReqBlk *srb)
4675 {
4676         Scsi_Cmnd *cmd;
4677
4678         cmd = srb->cmd;
4679         dprintkdbg(DBG_KG,
4680                "request_sense for pid %li, target %02i-%i\n",
4681                cmd->pid, cmd->device->id, cmd->device->lun);
4682         TRACEPRINTF("RqSn*");
4683         srb->flag |= AUTO_REQSENSE;
4684         srb->adapter_status = 0;
4685         srb->target_status = 0;
4686
4687         /* KG: Can this prevent crap sense data ? */
4688         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
4689
4690         /* Save some data */
4691         srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].address =
4692             srb->segment_x[0].address;
4693         srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].length =
4694             srb->segment_x[0].length;
4695         srb->xferred = srb->total_xfer_length;
4696         /* srb->segment_x : a one entry of S/G list table */
4697         srb->total_xfer_length = sizeof(cmd->sense_buffer);
4698         srb->segment_x[0].length = sizeof(cmd->sense_buffer);
4699         /* Map sense buffer */
4700         srb->segment_x[0].address =
4701             pci_map_single(acb->dev, cmd->sense_buffer,
4702                            sizeof(cmd->sense_buffer), PCI_DMA_FROMDEVICE);
4703         dprintkdbg(DBG_SGPARANOIA, "Map sense buffer at %p (%05x) to %08x\n",
4704                cmd->sense_buffer, sizeof(cmd->sense_buffer),
4705                srb->segment_x[0].address);
4706         srb->sg_count = 1;
4707         srb->sg_index = 0;
4708
4709         if (start_scsi(acb, dcb, srb)) {        /* Should only happen, if sb. else grabs the bus */
4710                 dprintkl(KERN_DEBUG,
4711                        "Request Sense failed for pid %li (%02i-%i)!\n",
4712                        srb->cmd->pid, dcb->target_id, dcb->target_lun);
4713                 TRACEPRINTF("?*");
4714                 move_srb_going_to_waiting(dcb, srb);
4715                 waiting_set_timer(acb, HZ / 100);
4716         }
4717         TRACEPRINTF(".*");
4718 }
4719
4720
4721 /*
4722  *********************************************************************
4723  *              dc395x_queue_command
4724  *
4725  * Function : void init_dcb
4726  *  Purpose : initialize the internal structures for a given DCB
4727  *   Inputs : cmd - pointer to this scsi cmd request block structure
4728  *********************************************************************
4729  */
4730 static
4731 void init_dcb(struct AdapterCtlBlk *acb, struct DeviceCtlBlk **pdcb,
4732               u8 target, u8 lun)
4733 {
4734         struct NvRamType *eeprom;
4735         u8 period_index;
4736         u16 index;
4737         struct DeviceCtlBlk *dcb;
4738         struct DeviceCtlBlk *dcb2;
4739
4740         dprintkdbg(DBG_0, "init_dcb..............\n");
4741         dcb = dc395x_kmalloc(sizeof(struct DeviceCtlBlk), GFP_ATOMIC);
4742         /*dcb = find_dcb (acb, target, lun); */
4743         *pdcb = dcb;
4744         dcb2 = NULL;
4745         if (!dcb)
4746                 return;
4747
4748         if (acb->dcb_count == 0) {
4749                 acb->link_dcb = dcb;
4750                 acb->dcb_run_robin = dcb;
4751         } else {
4752                 acb->last_dcb->next = dcb;
4753         }
4754
4755         acb->dcb_count++;
4756         dcb->next = acb->link_dcb;
4757         acb->last_dcb = dcb;
4758
4759         /* $$$$$$$ */
4760         dcb->acb = acb;
4761         dcb->target_id = target;
4762         dcb->target_lun = lun;
4763         /* $$$$$$$ */
4764         dcb->waiting_srb = NULL;
4765         dcb->going_srb = NULL;
4766         dcb->going_srb_count = 0;
4767         dcb->waiting_srb_count = 0;
4768         dcb->active_srb = NULL;
4769         /* $$$$$$$ */
4770         dcb->tag_mask = 0;
4771         dcb->flag = 0;
4772         dcb->max_command = 1;
4773         /* $$$$$$$ */
4774         index = acb->adapter_index;
4775         eeprom = &eeprom_buf[index];
4776         dcb->dev_mode = eeprom->target[target].cfg0;
4777         /*dcb->AdpMode = eeprom->channel_cfg; */
4778         dcb->inquiry7 = 0;
4779         dcb->sync_mode = 0;
4780         /* $$$$$$$ */
4781         dcb->sync_period = 0;
4782         dcb->sync_offset = 0;
4783         period_index = eeprom->target[target].period & 0x07;
4784         dcb->min_nego_period = clock_period[period_index];
4785
4786 #ifndef DC395x_NO_WIDE
4787         if ((dcb->dev_mode & NTC_DO_WIDE_NEGO)
4788             && (acb->config & HCC_WIDE_CARD))
4789                 dcb->sync_mode |= WIDE_NEGO_ENABLE;
4790 #endif
4791 #ifndef DC395x_NO_SYNC
4792         if (dcb->dev_mode & NTC_DO_SYNC_NEGO)
4793                 if (!(lun) || current_sync_offset)
4794                         dcb->sync_mode |= SYNC_NEGO_ENABLE;
4795 #endif
4796         /* $$$$$$$ */
4797 #ifndef DC395x_NO_DISCONNECT
4798         dcb->identify_msg =
4799             IDENTIFY(dcb->dev_mode & NTC_DO_DISCONNECT, lun);
4800 #else
4801         dcb->identify_msg = IDENTIFY(0, lun);
4802 #endif
4803         /* $$$$$$$ */
4804         if (dcb->target_lun != 0) {
4805                 /* Copy settings */
4806                 struct DeviceCtlBlk *prevDCB = acb->link_dcb;
4807                 while (prevDCB->target_id != dcb->target_id)
4808                         prevDCB = prevDCB->next;
4809                 dprintkdbg(DBG_KG,
4810                        "Copy settings from %02i-%02i to %02i-%02i\n",
4811                        prevDCB->target_id, prevDCB->target_lun,
4812                        dcb->target_id, dcb->target_lun);
4813                 dcb->sync_mode = prevDCB->sync_mode;
4814                 dcb->sync_period = prevDCB->sync_period;
4815                 dcb->min_nego_period = prevDCB->min_nego_period;
4816                 dcb->sync_offset = prevDCB->sync_offset;
4817                 dcb->inquiry7 = prevDCB->inquiry7;
4818         };
4819
4820         acb->dcb_map[target] |= (1 << lun);
4821         acb->children[target][lun] = dcb;
4822 }
4823
4824
4825 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
4826 /*
4827  * Memory for trace buffers
4828  */
4829 static
4830 void free_tracebufs(struct AdapterCtlBlk *acb, int srb_idx)
4831 {
4832         int i;
4833         const unsigned bufs_per_page = PAGE_SIZE / DEBUGTRACEBUFSZ;
4834         for (i = 0; i < srb_idx; i += bufs_per_page) {
4835                 /*dprintkl(KERN_DEBUG, "Free tracebuf %p (for %i)\n", */
4836                 /*      acb->srb_array[i].debugtrace, i); */
4837                 dc395x_kfree(acb->srb_array[i].debugtrace);
4838         }
4839 }
4840
4841
4842 static
4843 int alloc_tracebufs(struct AdapterCtlBlk *acb)
4844 {
4845         const unsigned mem_needed =
4846             (DC395x_MAX_SRB_CNT + 1) * DEBUGTRACEBUFSZ;
4847         int pages = (mem_needed + (PAGE_SIZE - 1)) / PAGE_SIZE;
4848         const unsigned bufs_per_page = PAGE_SIZE / DEBUGTRACEBUFSZ;
4849         int srb_idx = 0;
4850         unsigned i = 0;
4851         unsigned char *ptr;
4852         /*dprintkl(KERN_DEBUG, "Alloc %i pages for tracebufs\n", pages); */
4853         while (pages--) {
4854                 ptr = dc395x_kmalloc(PAGE_SIZE, GFP_KERNEL);
4855                 if (!ptr) {
4856                         free_tracebufs(acb, srb_idx);
4857                         return 1;
4858                 }
4859                 /*dprintkl(KERN_DEBUG, "Alloc %li bytes at %p for tracebuf %i\n", */
4860                 /*      PAGE_SIZE, ptr, srb_idx); */
4861                 i = 0;
4862                 while (i < bufs_per_page && srb_idx < DC395x_MAX_SRB_CNT)
4863                         acb->srb_array[srb_idx++].debugtrace =
4864                             ptr + (i++ * DEBUGTRACEBUFSZ);
4865         }
4866         if (i < bufs_per_page) {
4867                 acb->srb.debugtrace = ptr + (i * DEBUGTRACEBUFSZ);
4868                 acb->srb.debugtrace[0] = 0;
4869         } else
4870                 dprintkl(KERN_DEBUG, "No space for tmsrb tracebuf reserved?!\n");
4871         return 0;
4872 }
4873 #endif
4874
4875
4876 /* Free SG tables */
4877 static void free_sg_tables(struct AdapterCtlBlk *acb, int srb_idx)
4878 {
4879         int i;
4880         const unsigned srbs_per_page =
4881             PAGE_SIZE / (DC395x_MAX_SG_LISTENTRY * sizeof(struct SGentry));
4882         for (i = 0; i < srb_idx; i += srbs_per_page) {
4883                 /*dprintkl(KERN_DEBUG, "Free SG segs %p (for %i)\n", */
4884                 /*      acb->srb_array[i].segment_x, i); */
4885                 dc395x_kfree(acb->srb_array[i].segment_x);
4886         }
4887 }
4888
4889
4890 /*
4891  * Allocate SG tables; as we have to pci_map them, an SG list (struct SGentry*)
4892  * should never cross a page boundary */
4893 static int alloc_sg_tables(struct AdapterCtlBlk *acb)
4894 {
4895         const unsigned mem_needed =
4896             (DC395x_MAX_SRB_CNT +
4897              1) * DC395x_MAX_SG_LISTENTRY * sizeof(struct SGentry);
4898         int pages = (mem_needed + (PAGE_SIZE - 1)) / PAGE_SIZE;
4899         const unsigned srbs_per_page =
4900             PAGE_SIZE / (DC395x_MAX_SG_LISTENTRY * sizeof(struct SGentry));
4901         int srb_idx = 0;
4902         unsigned i = 0;
4903         struct SGentry *ptr;
4904         /*dprintkl(KERN_DEBUG, "Alloc %i pages for SG tables\n", pages); */
4905         while (pages--) {
4906                 ptr = (struct SGentry *) dc395x_kmalloc(PAGE_SIZE, GFP_KERNEL);
4907                 if (!ptr) {
4908                         free_sg_tables(acb, srb_idx);
4909                         return 1;
4910                 }
4911                 /*dprintkl(KERN_DEBUG, "Alloc %li bytes at %p for SG segments %i\n", */
4912                 /*      PAGE_SIZE, ptr, srb_idx); */
4913                 i = 0;
4914                 while (i < srbs_per_page && srb_idx < DC395x_MAX_SRB_CNT)
4915                         acb->srb_array[srb_idx++].segment_x =
4916                             ptr + (i++ * DC395x_MAX_SG_LISTENTRY);
4917         }
4918         if (i < srbs_per_page)
4919                 acb->srb.segment_x =
4920                     ptr + (i * DC395x_MAX_SG_LISTENTRY);
4921         else
4922                 dprintkl(KERN_DEBUG, "No space for tmsrb SG table reserved?!\n");
4923         return 0;
4924 }
4925
4926
4927 /*
4928  ********************************************************************
4929  * scsiio
4930  *              init_acb
4931  ********************************************************************
4932  */
4933 static void __init link_srb(struct AdapterCtlBlk *acb)
4934 {
4935         int i;
4936
4937         for (i = 0; i < acb->srb_count - 1; i++)
4938                 acb->srb_array[i].next = &acb->srb_array[i + 1];
4939         acb->srb_array[i].next = NULL;
4940         /*DC395x_Free_integrity (acb);     */
4941 }
4942
4943
4944 /*
4945  ***********************************************************************
4946  *              host_init
4947  *
4948  * Function : static void init_acb
4949  *  Purpose :  initialize the internal structures for a given SCSI host
4950  *   Inputs : host - pointer to this host adapter's structure
4951  ***********************************************************************
4952  */
4953 static
4954 int __init init_acb(struct Scsi_Host *host, u32 io_port, u8 irq, u16 index)
4955 {
4956         struct NvRamType *eeprom;
4957         struct AdapterCtlBlk *acb;
4958         u16 i;
4959
4960         eeprom = &eeprom_buf[index];
4961         host->max_cmd_len = 24;
4962         host->can_queue = DC395x_MAX_CMD_QUEUE;
4963         host->cmd_per_lun = DC395x_MAX_CMD_PER_LUN;
4964         host->this_id = (int) eeprom->scsi_id;
4965         host->io_port = io_port;
4966         host->n_io_port = 0x80;
4967         host->dma_channel = -1;
4968         host->unique_id = io_port;
4969         host->irq = irq;
4970         host->last_reset = jiffies;
4971
4972         acb = (struct AdapterCtlBlk *) host->hostdata;
4973
4974         host->max_id = 16;
4975         if (host->max_id - 1 == eeprom->scsi_id)
4976                 host->max_id--;
4977 #ifdef  CONFIG_SCSI_MULTI_LUN
4978         if (eeprom->channel_cfg & NAC_SCANLUN)
4979                 host->max_lun = 8;
4980         else
4981                 host->max_lun = 1;
4982 #else
4983         host->max_lun = 1;
4984 #endif
4985         /*
4986          ********************************
4987          */
4988         acb->scsi_host = host;
4989         acb->IOPortBase = (u16) io_port;
4990         acb->link_dcb = NULL;
4991         acb->dcb_run_robin = NULL;
4992         acb->active_dcb = NULL;
4993         acb->srb_count = DC395x_MAX_SRB_CNT;
4994         acb->adapter_index = index;
4995         acb->scsi_host->this_id = eeprom->scsi_id;
4996         acb->hostid_bit = (1 << acb->scsi_host->this_id);
4997         /*acb->scsi_host->this_lun = 0; */
4998         acb->dcb_count = 0;
4999         acb->irq_level = irq;
5000         acb->tag_max_num = 1 << eeprom->max_tag;
5001         if (acb->tag_max_num > 30)
5002                 acb->tag_max_num = 30;
5003         acb->acb_flag = 0;      /* RESET_DETECT, RESET_DONE, RESET_DEV */
5004         acb->scan_devices = 1;
5005         acb->msg_len = 0;
5006         acb->gmode2 = eeprom->channel_cfg;
5007         if (eeprom->channel_cfg & NAC_SCANLUN)
5008                 acb->lun_chk = 1;
5009         /* 
5010          * link all device's SRB Q of this adapter 
5011          */
5012         if (alloc_sg_tables(acb)) {
5013                 dprintkl(KERN_DEBUG, "SG table allocation failed!\n");
5014                 return 1;
5015         }
5016 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
5017         if (alloc_tracebufs(acb)) {
5018                 dprintkl(KERN_DEBUG, "SG trace buffer allocation failed!\n");
5019                 free_sg_tables(acb, DC395x_MAX_SRB_CNT);
5020                 return 1;
5021         }
5022 #endif
5023         link_srb(acb);
5024         acb->free_srb = acb->srb_array;
5025         /* 
5026          * temp SRB for Q tag used or abort command used 
5027          */
5028         acb->tmp_srb = &acb->srb;
5029         acb->srb.dcb = NULL;
5030         acb->srb.next = NULL;
5031         init_timer(&acb->waiting_timer);
5032
5033         for (i = 0; i < DC395x_MAX_SCSI_ID; i++)
5034                 acb->dcb_map[i] = 0;
5035         dprintkdbg(DBG_0, "acb = %p, pdcb_map = %p, psrb_array = %p\n", acb,
5036                acb->dcb_map, acb->srb_array);
5037         dprintkdbg(DBG_0, "ACB size= %04x, DCB size= %04x, SRB size= %04x\n",
5038                sizeof(struct AdapterCtlBlk), sizeof(struct DeviceCtlBlk),
5039                sizeof(struct ScsiReqBlk));
5040         return 0;
5041 }
5042
5043
5044 /*===========================================================================
5045                                 Init
5046   ===========================================================================*/
5047 /**
5048  * init_adapter - Initialize the SCSI chip control registers
5049  *
5050  * @host:       This hosts adapter strcuture
5051  * @io_port:    The base I/O port
5052  * @irq:        IRQ
5053  * @index:      Card instance number
5054  *
5055  * Returns 0 if the initialization succeeds, any other value on failure.
5056  **/
5057 static
5058 int __init init_adapter(struct Scsi_Host *host, u32 io_port,
5059                         u8 irq, u16 index)
5060 {
5061         struct NvRamType *eeprom = &eeprom_buf[index];
5062         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)host->hostdata;
5063
5064         if (!request_region(io_port, host->n_io_port, DC395X_NAME)) {
5065                 dprintkl(KERN_ERR, "Failed to reserve IO region 0x%x\n", io_port);
5066                 return -1;
5067         }
5068         if (request_irq(irq, dc395x_interrupt, SA_SHIRQ, DC395X_NAME, acb)) {
5069                 /* release the region we just claimed */
5070                 release_region(io_port, host->n_io_port);
5071                 dprintkl(KERN_INFO, "Failed to register IRQ!\n");
5072                 return -1;
5073         }
5074
5075         acb->IOPortBase = io_port;
5076
5077         /* selection timeout = 250 ms */
5078         acb->sel_timeout = DC395x_SEL_TIMEOUT;
5079
5080         /* Mask all the interrupt */
5081         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0x00);
5082         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x00);
5083
5084         /* Reset SCSI module */
5085         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
5086
5087         /* Reset PCI/DMA module */
5088         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
5089         udelay(20);
5090
5091         /* program configuration 0 */
5092         acb->config = HCC_AUTOTERM | HCC_PARITY;
5093         if (DC395x_read8(acb, TRM_S1040_GEN_STATUS) & WIDESCSI)
5094                 acb->config |= HCC_WIDE_CARD;
5095
5096         if (eeprom->channel_cfg & NAC_POWERON_SCSI_RESET)
5097                 acb->config |= HCC_SCSI_RESET;
5098
5099         if (acb->config & HCC_SCSI_RESET) {
5100                 dprintkl(KERN_INFO, "Performing initial SCSI bus reset\n");
5101                 DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTSCSI);
5102
5103                 /*while (!( DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS) & INT_SCSIRESET )); */
5104                 /*spin_unlock_irq (&io_request_lock); */
5105                 udelay(500);
5106
5107                 acb->scsi_host->last_reset =
5108                     jiffies + HZ / 2 +
5109                     HZ *
5110                     eeprom_buf[acb->adapter_index].
5111                     delay_time;
5112
5113                 /*spin_lock_irq (&io_request_lock); */
5114         }
5115         set_basic_config(acb);
5116         return 0;
5117 }
5118
5119
5120 /**
5121  * trms1040_wait_30us: wait for 30 us
5122  *
5123  * Waits for 30us (using the chip by the looks of it..)
5124  *
5125  * @io_port: base I/O address
5126  **/
5127 static
5128 void __init trms1040_wait_30us(u16 io_port)
5129 {
5130         /* ScsiPortStallExecution(30); wait 30 us */
5131         outb(5, io_port + TRM_S1040_GEN_TIMER);
5132         while (!(inb(io_port + TRM_S1040_GEN_STATUS) & GTIMEOUT))
5133                 /* nothing */ ;
5134         return;
5135 }
5136
5137
5138 /**
5139  * trms1040_write_cmd - write the secified command and address to
5140  * chip
5141  *
5142  * @io_port:    base I/O address
5143  * @cmd:        SB + op code (command) to send
5144  * @addr:       address to send
5145  **/
5146 static
5147 void __init trms1040_write_cmd(u16 io_port, u8 cmd, u8 addr)
5148 {
5149         int i;
5150         u8 send_data;
5151
5152         /* program SB + OP code */
5153         for (i = 0; i < 3; i++, cmd <<= 1) {
5154                 send_data = NVR_SELECT;
5155                 if (cmd & 0x04) /* Start from bit 2 */
5156                         send_data |= NVR_BITOUT;
5157
5158                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
5159                 trms1040_wait_30us(io_port);
5160                 outb((send_data | NVR_CLOCK),
5161                      io_port + TRM_S1040_GEN_NVRAM);
5162                 trms1040_wait_30us(io_port);
5163         }
5164
5165         /* send address */
5166         for (i = 0; i < 7; i++, addr <<= 1) {
5167                 send_data = NVR_SELECT;
5168                 if (addr & 0x40)        /* Start from bit 6 */
5169                         send_data |= NVR_BITOUT;
5170
5171                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
5172                 trms1040_wait_30us(io_port);
5173                 outb((send_data | NVR_CLOCK),
5174                      io_port + TRM_S1040_GEN_NVRAM);
5175                 trms1040_wait_30us(io_port);
5176         }
5177         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
5178         trms1040_wait_30us(io_port);
5179 }
5180
5181
5182 /**
5183  * trms1040_set_data - store a single byte in the eeprom
5184  *
5185  * Called from write all to write a single byte into the SSEEPROM
5186  * Which is done one bit at a time.
5187  *
5188  * @io_port:    base I/O address
5189  * @addr:       offset into EEPROM
5190  * @byte:       bytes to write
5191  **/
5192 static
5193 void __init trms1040_set_data(u16 io_port, u8 addr, u8 byte)
5194 {
5195         int i;
5196         u8 send_data;
5197
5198         /* Send write command & address */
5199         trms1040_write_cmd(io_port, 0x05, addr);
5200
5201         /* Write data */
5202         for (i = 0; i < 8; i++, byte <<= 1) {
5203                 send_data = NVR_SELECT;
5204                 if (byte & 0x80)        /* Start from bit 7 */
5205                         send_data |= NVR_BITOUT;
5206
5207                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
5208                 trms1040_wait_30us(io_port);
5209                 outb((send_data | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
5210                 trms1040_wait_30us(io_port);
5211         }
5212         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
5213         trms1040_wait_30us(io_port);
5214
5215         /* Disable chip select */
5216         outb(0, io_port + TRM_S1040_GEN_NVRAM);
5217         trms1040_wait_30us(io_port);
5218
5219         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
5220         trms1040_wait_30us(io_port);
5221
5222         /* Wait for write ready */
5223         while (1) {
5224                 outb((NVR_SELECT | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
5225                 trms1040_wait_30us(io_port);
5226
5227                 outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
5228                 trms1040_wait_30us(io_port);
5229
5230                 if (inb(io_port + TRM_S1040_GEN_NVRAM) & NVR_BITIN)
5231                         break;
5232         }
5233
5234         /*  Disable chip select */
5235         outb(0, io_port + TRM_S1040_GEN_NVRAM);
5236 }
5237
5238
5239 /**
5240  * trms1040_write_all - write 128 bytes to the eeprom
5241  *
5242  * Write the supplied 128 bytes to the chips SEEPROM
5243  *
5244  * @eeprom:     the data to write
5245  * @io_port:    the base io port
5246  **/
5247 static
5248 void __init trms1040_write_all(struct NvRamType *eeprom, u16 io_port)
5249 {
5250         u8 *b_eeprom = (u8 *) eeprom;
5251         u8 addr;
5252
5253         /* Enable SEEPROM */
5254         outb((inb(io_port + TRM_S1040_GEN_CONTROL) | EN_EEPROM),
5255              io_port + TRM_S1040_GEN_CONTROL);
5256
5257         /* write enable */
5258         trms1040_write_cmd(io_port, 0x04, 0xFF);
5259         outb(0, io_port + TRM_S1040_GEN_NVRAM);
5260         trms1040_wait_30us(io_port);
5261
5262         /* write */
5263         for (addr = 0; addr < 128; addr++, b_eeprom++) {
5264                 trms1040_set_data(io_port, addr, *b_eeprom);
5265         }
5266
5267         /* write disable */
5268         trms1040_write_cmd(io_port, 0x04, 0x00);
5269         outb(0, io_port + TRM_S1040_GEN_NVRAM);
5270         trms1040_wait_30us(io_port);
5271
5272         /* Disable SEEPROM */
5273         outb((inb(io_port + TRM_S1040_GEN_CONTROL) & ~EN_EEPROM),
5274              io_port + TRM_S1040_GEN_CONTROL);
5275 }
5276
5277
5278 /**
5279  * trms1040_get_data - get a single byte from the eeprom
5280  *
5281  * Called from read all to read a single byte into the SSEEPROM
5282  * Which is done one bit at a time.
5283  *
5284  * @io_port:    base I/O address
5285  * @addr:       offset into SEEPROM
5286  *
5287  * Returns the the byte read.
5288  **/
5289 static
5290 u8 __init trms1040_get_data(u16 io_port, u8 addr)
5291 {
5292         int i;
5293         u8 read_byte;
5294         u8 result = 0;
5295
5296         /* Send read command & address */
5297         trms1040_write_cmd(io_port, 0x06, addr);
5298
5299         /* read data */
5300         for (i = 0; i < 8; i++) {
5301                 outb((NVR_SELECT | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
5302                 trms1040_wait_30us(io_port);
5303                 outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
5304
5305                 /* Get data bit while falling edge */
5306                 read_byte = inb(io_port + TRM_S1040_GEN_NVRAM);
5307                 result <<= 1;
5308                 if (read_byte & NVR_BITIN)
5309                         result |= 1;
5310
5311                 trms1040_wait_30us(io_port);
5312         }
5313
5314         /* Disable chip select */
5315         outb(0, io_port + TRM_S1040_GEN_NVRAM);
5316         return result;
5317 }
5318
5319
5320 /**
5321  * trms1040_read_all - read all bytes from the eeprom
5322  *
5323  * Read the 128 bytes from the SEEPROM.
5324  *
5325  * @eeprom:     where to store the data
5326  * @io_port:    the base io port
5327  **/
5328 static
5329 void __init trms1040_read_all(struct NvRamType *eeprom, u16 io_port)
5330 {
5331         u8 *b_eeprom = (u8 *) eeprom;
5332         u8 addr;
5333
5334         /* Enable SEEPROM */
5335         outb((inb(io_port + TRM_S1040_GEN_CONTROL) | EN_EEPROM),
5336              io_port + TRM_S1040_GEN_CONTROL);
5337
5338         /* read details */
5339         for (addr = 0; addr < 128; addr++, b_eeprom++) {
5340                 *b_eeprom = trms1040_get_data(io_port, addr);
5341         }
5342
5343         /* Disable SEEPROM */
5344         outb((inb(io_port + TRM_S1040_GEN_CONTROL) & ~EN_EEPROM),
5345              io_port + TRM_S1040_GEN_CONTROL);
5346 }
5347
5348
5349
5350 /**
5351  * check_eeprom - get and check contents of the eeprom
5352  *
5353  * Read seeprom 128 bytes into the memory provider in eeprom.
5354  * Checks the checksum and if it's not correct it uses a set of default
5355  * values.
5356  *
5357  * @eeprom:     caller allocated strcuture to read the eeprom data into
5358  * @io_port:    io port to read from
5359  **/
5360 static
5361 void __init check_eeprom(struct NvRamType *eeprom, u16 io_port)
5362 {
5363         u16 *w_eeprom = (u16 *) eeprom;
5364         u16 w_addr;
5365         u16 cksum;
5366         u32 d_addr;
5367         u32 *d_eeprom;
5368
5369         trms1040_read_all(eeprom, io_port);     /* read eeprom */
5370
5371         cksum = 0;
5372         for (w_addr = 0, w_eeprom = (u16 *) eeprom; w_addr < 64;
5373              w_addr++, w_eeprom++)
5374                 cksum += *w_eeprom;
5375         if (cksum != 0x1234) {
5376                 /*
5377                  * Checksum is wrong.
5378                  * Load a set of defaults into the eeprom buffer
5379                  */
5380                 dprintkl(KERN_WARNING,
5381                        "EEProm checksum error: using default values and options.\n");
5382                 eeprom->sub_vendor_id[0] = (u8) PCI_VENDOR_ID_TEKRAM;
5383                 eeprom->sub_vendor_id[1] = (u8) (PCI_VENDOR_ID_TEKRAM >> 8);
5384                 eeprom->sub_sys_id[0] = (u8) PCI_DEVICE_ID_TEKRAM_TRMS1040;
5385                 eeprom->sub_sys_id[1] =
5386                     (u8) (PCI_DEVICE_ID_TEKRAM_TRMS1040 >> 8);
5387                 eeprom->sub_class = 0x00;
5388                 eeprom->vendor_id[0] = (u8) PCI_VENDOR_ID_TEKRAM;
5389                 eeprom->vendor_id[1] = (u8) (PCI_VENDOR_ID_TEKRAM >> 8);
5390                 eeprom->device_id[0] = (u8) PCI_DEVICE_ID_TEKRAM_TRMS1040;
5391                 eeprom->device_id[1] =
5392                     (u8) (PCI_DEVICE_ID_TEKRAM_TRMS1040 >> 8);
5393                 eeprom->reserved = 0x00;
5394
5395                 for (d_addr = 0, d_eeprom = (u32 *) eeprom->target;
5396                      d_addr < 16; d_addr++, d_eeprom++)
5397                         *d_eeprom = 0x00000077; /* cfg3,cfg2,period,cfg0 */
5398
5399                 *d_eeprom++ = 0x04000F07;       /* max_tag,delay_time,channel_cfg,scsi_id */
5400                 *d_eeprom++ = 0x00000015;       /* reserved1,boot_lun,boot_target,reserved0 */
5401                 for (d_addr = 0; d_addr < 12; d_addr++, d_eeprom++)
5402                         *d_eeprom = 0x00;
5403
5404                 /* Now load defaults (maybe set by boot/module params) */
5405                 set_safe_settings();
5406                 fix_settings();
5407                 eeprom_override(eeprom);
5408
5409                 eeprom->cksum = 0x00;
5410                 for (w_addr = 0, cksum = 0, w_eeprom = (u16 *) eeprom;
5411                      w_addr < 63; w_addr++, w_eeprom++)
5412                         cksum += *w_eeprom;
5413
5414                 *w_eeprom = 0x1234 - cksum;
5415                 trms1040_write_all(eeprom, io_port);
5416                 eeprom->delay_time = cfg_data[CFG_RESET_DELAY].value;
5417         } else {
5418                 set_safe_settings();
5419                 eeprom_index_to_delay(eeprom);
5420                 eeprom_override(eeprom);
5421         }
5422 }
5423
5424
5425 /**
5426  * print_config - print adapter connection and termination
5427  * config
5428  *
5429  * @acb:        adapter control block
5430  **/
5431 static
5432 void __init print_config(struct AdapterCtlBlk *acb)
5433 {
5434         u8 bval;
5435
5436         bval = DC395x_read8(acb, TRM_S1040_GEN_STATUS);
5437         dprintkl(KERN_INFO, "%c: Connectors: ",
5438                ((bval & WIDESCSI) ? 'W' : ' '));
5439         if (!(bval & CON5068))
5440                 printk("ext%s ", !(bval & EXT68HIGH) ? "68" : "50");
5441         if (!(bval & CON68))
5442                 printk("int68%s ", !(bval & INT68HIGH) ? "" : "(50)");
5443         if (!(bval & CON50))
5444                 printk("int50 ");
5445         if ((bval & (CON5068 | CON50 | CON68)) ==
5446             0 /*(CON5068 | CON50 | CON68) */ )
5447                 printk(" Oops! (All 3?) ");
5448         bval = DC395x_read8(acb, TRM_S1040_GEN_CONTROL);
5449         printk(" Termination: ");
5450         if (bval & DIS_TERM)
5451                 printk("Disabled\n");
5452         else {
5453                 if (bval & AUTOTERM)
5454                         printk("Auto ");
5455                 if (bval & LOW8TERM)
5456                         printk("Low ");
5457                 if (bval & UP8TERM)
5458                         printk("High ");
5459                 printk("\n");
5460         }
5461 }
5462
5463
5464 /**
5465  * print_eeprom_settings - output the eeprom settings
5466  * to the kernel log so people can see what they were.
5467  *
5468  * @index: Adapter number
5469  **/
5470 static
5471 void __init print_eeprom_settings(u16 index)
5472 {
5473         dprintkl(KERN_INFO, "Used settings: AdapterID=%02i, Speed=%i(%02i.%01iMHz), dev_mode=0x%02x\n",
5474                eeprom_buf[index].scsi_id,
5475                eeprom_buf[index].target[0].period,
5476                clock_speed[eeprom_buf[index].target[0].period] / 10,
5477                clock_speed[eeprom_buf[index].target[0].period] % 10,
5478                eeprom_buf[index].target[0].cfg0);
5479         dprintkl(KERN_INFO, "               AdaptMode=0x%02x, Tags=%i(%02i), DelayReset=%is\n",
5480                eeprom_buf[index].channel_cfg,
5481                eeprom_buf[index].max_tag,
5482                1 << eeprom_buf[index].max_tag,
5483                eeprom_buf[index].delay_time);
5484 }
5485
5486
5487 /*
5488  *********************************************************************
5489  *                      DC395x_detect
5490  *
5491  *      Function : static int host_init (struct Scsi_Host *host)
5492  *       Purpose : initialize the internal structures for a given SCSI host
5493  *        Inputs : host - pointer to this host adapter's structure/
5494  * Preconditions : when this function is called, the chip_type
5495  *                 field of the acb structure MUST have been set.
5496  *********************************************************************
5497  */
5498 static
5499 struct Scsi_Host *__init host_init(Scsi_Host_Template * host_template,
5500                                    u32 io_port, u8 irq,
5501                                    u16 index)
5502 {
5503         struct Scsi_Host *host;
5504         struct AdapterCtlBlk *acb;
5505
5506         /*
5507          * Read the eeprom contents info the buffer we supply. Use
5508          * defaults is eeprom checksum is wrong.
5509          */
5510         check_eeprom(&eeprom_buf[index], (u16) io_port);
5511
5512         /*
5513          *$$$$$$$$$$$  MEMORY ALLOCATE FOR ADAPTER CONTROL BLOCK $$$$$$$$$$$$
5514          */
5515         host = scsi_host_alloc(host_template, sizeof(struct AdapterCtlBlk));
5516         if (!host) {
5517                 dprintkl(KERN_INFO, "pSH scsi_host_alloc ERROR\n");
5518                 return 0;
5519         }
5520         print_eeprom_settings(index);
5521
5522         acb = (struct AdapterCtlBlk *) host->hostdata;
5523         if (init_acb(host, io_port, irq, index)) {
5524                 scsi_host_put(host);
5525                 return 0;
5526         }
5527         print_config(acb);
5528
5529        /*
5530         *$$$$$$$$$$$$$$$$$ INITIAL ADAPTER $$$$$$$$$$$$$$$$$
5531         */
5532         if (!init_adapter(host, io_port, irq, index)) {
5533                 if (!acb_list_head) {
5534                         acb_list_head = acb;
5535                 } else {
5536                         acb_list_tail->next_acb = acb;
5537                 }
5538                 acb_list_tail = acb;
5539                 acb->next_acb = NULL;
5540         } else {
5541                 dprintkl(KERN_INFO, "DC395x_initAdapter initial ERROR\n");
5542                 scsi_host_put(host);
5543                 host = NULL;
5544         }
5545         return host;
5546 }
5547
5548 #undef SEARCH
5549 #undef YESNO
5550 #undef SCANF
5551
5552
5553 /*
5554  ******************************************************************
5555  * Function: dc395x_proc_info(char* buffer, char **start,
5556  *                       off_t offset, int length, int hostno, int inout)
5557  *  Purpose: return SCSI Adapter/Device Info
5558  *    Input:
5559  *          buffer: Pointer to a buffer where to write info
5560  *               start :
5561  *               offset:
5562  *               hostno: Host adapter index
5563  *               inout : Read (=0) or set(!=0) info
5564  *   Output:
5565  *          buffer: contains info length 
5566  *                       
5567  *    return value: length of info in buffer
5568  *
5569  ******************************************************************
5570  */
5571
5572 /* KG: dc395x_proc_info taken from driver aha152x.c */
5573
5574 #undef SPRINTF
5575 #define SPRINTF(args...) pos += sprintf(pos, args)
5576
5577 #define YESNO(YN) \
5578  if (YN) SPRINTF(" Yes ");\
5579  else SPRINTF(" No  ")
5580
5581 static
5582 int dc395x_proc_info(struct Scsi_Host *shpnt, char *buffer, char **start, off_t offset, int length,
5583                      int inout)
5584 {
5585         int dev, spd, spd1;
5586         char *pos = buffer;
5587         struct AdapterCtlBlk *acb;
5588         struct DeviceCtlBlk *dcb;
5589         unsigned long flags;
5590
5591         acb = acb_list_head;
5592
5593         while (acb) {
5594                 if (acb->scsi_host == shpnt)
5595                         break;
5596                 acb = acb->next_acb;
5597         }
5598         if (!acb)
5599                 return -ESRCH;
5600
5601         if (inout)              /* Has data been written to the file ? */
5602                 return -EPERM;
5603
5604         SPRINTF(DC395X_BANNER " PCI SCSI Host Adapter\n");
5605         SPRINTF(" Driver Version " DC395X_VERSION "\n");
5606
5607         DC395x_LOCK_IO(acb->scsi_host, flags);
5608
5609         SPRINTF("SCSI Host Nr %i, ", shpnt->host_no);
5610         SPRINTF("DC395U/UW/F DC315/U %s Adapter Nr %i\n",
5611                 (acb->config & HCC_WIDE_CARD) ? "Wide" : "",
5612                 acb->adapter_index);
5613         SPRINTF("IOPortBase 0x%04x, ", acb->IOPortBase);
5614         SPRINTF("irq_level 0x%02x, ", acb->irq_level);
5615         SPRINTF(" SelTimeout %ims\n", (1638 * acb->sel_timeout) / 1000);
5616
5617         SPRINTF("MaxID %i, MaxLUN %i, ", shpnt->max_id, shpnt->max_lun);
5618         SPRINTF("AdapterID %i\n", shpnt->this_id);
5619
5620         SPRINTF("tag_max_num %i", acb->tag_max_num);
5621         /*SPRINTF(", DMA_Status %i\n", DC395x_read8(acb, TRM_S1040_DMA_STATUS)); */
5622         SPRINTF(", FilterCfg 0x%02x",
5623                 DC395x_read8(acb, TRM_S1040_SCSI_CONFIG1));
5624         SPRINTF(", DelayReset %is\n",
5625                 eeprom_buf[acb->adapter_index].delay_time);
5626         /*SPRINTF("\n"); */
5627
5628         SPRINTF("Nr of DCBs: %i\n", acb->dcb_count);
5629         SPRINTF
5630             ("Map of attached LUNs: %02x %02x %02x %02x %02x %02x %02x %02x\n",
5631              acb->dcb_map[0], acb->dcb_map[1], acb->dcb_map[2],
5632              acb->dcb_map[3], acb->dcb_map[4], acb->dcb_map[5],
5633              acb->dcb_map[6], acb->dcb_map[7]);
5634         SPRINTF
5635             ("                      %02x %02x %02x %02x %02x %02x %02x %02x\n",
5636              acb->dcb_map[8], acb->dcb_map[9], acb->dcb_map[10],
5637              acb->dcb_map[11], acb->dcb_map[12], acb->dcb_map[13],
5638              acb->dcb_map[14], acb->dcb_map[15]);
5639
5640         SPRINTF
5641             ("Un ID LUN Prty Sync Wide DsCn SndS TagQ nego_period SyncFreq SyncOffs MaxCmd\n");
5642
5643         dcb = acb->link_dcb;
5644         for (dev = 0; dev < acb->dcb_count; dev++) {
5645                 int nego_period;
5646                 SPRINTF("%02i %02i  %02i ", dev, dcb->target_id,
5647                         dcb->target_lun);
5648                 YESNO(dcb->dev_mode & NTC_DO_PARITY_CHK);
5649                 YESNO(dcb->sync_offset);
5650                 YESNO(dcb->sync_period & WIDE_SYNC);
5651                 YESNO(dcb->dev_mode & NTC_DO_DISCONNECT);
5652                 YESNO(dcb->dev_mode & NTC_DO_SEND_START);
5653                 YESNO(dcb->sync_mode & EN_TAG_QUEUEING);
5654                 nego_period =
5655                     clock_period[dcb->sync_period & 0x07] << 2;
5656                 if (dcb->sync_offset)
5657                         SPRINTF("  %03i ns ", nego_period);
5658                 else
5659                         SPRINTF(" (%03i ns)", (dcb->min_nego_period << 2));
5660
5661                 if (dcb->sync_offset & 0x0f) {
5662                         spd = 1000 / (nego_period);
5663                         spd1 = 1000 % (nego_period);
5664                         spd1 = (spd1 * 10 + nego_period / 2) / (nego_period);
5665                         SPRINTF("   %2i.%1i M     %02i ", spd, spd1,
5666                                 (dcb->sync_offset & 0x0f));
5667                 } else
5668                         SPRINTF("                 ");
5669
5670                 /* Add more info ... */
5671                 SPRINTF("     %02i\n", dcb->max_command);
5672                 dcb = dcb->next;
5673         }
5674
5675         if (timer_pending(&acb->waiting_timer))
5676                 SPRINTF("Waiting queue timer running\n");
5677         else
5678                 SPRINTF("\n");
5679         dcb = acb->link_dcb;
5680
5681         for (dev = 0; dev < acb->dcb_count; dev++) {
5682                 struct ScsiReqBlk *srb;
5683                 if (dcb->waiting_srb_count)
5684                         SPRINTF("DCB (%02i-%i): Waiting: %i:",
5685                                 dcb->target_id, dcb->target_lun,
5686                                 dcb->waiting_srb_count);
5687                 for (srb = dcb->waiting_srb; srb; srb = srb->next)
5688                         SPRINTF(" %li", srb->cmd->pid);
5689                 if (dcb->going_srb_count)
5690                         SPRINTF("\nDCB (%02i-%i): Going  : %i:",
5691                                 dcb->target_id, dcb->target_lun,
5692                                 dcb->going_srb_count);
5693                 for (srb = dcb->going_srb; srb; srb = srb->next)
5694 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
5695                         SPRINTF("\n  %s", srb->debugtrace);
5696 #else
5697                         SPRINTF(" %li", srb->cmd->pid);
5698 #endif
5699                 if (dcb->waiting_srb_count || dcb->going_srb_count)
5700                         SPRINTF("\n");
5701                 dcb = dcb->next;
5702         }
5703
5704         if (debug_enabled(DBG_DCB)) {
5705                 SPRINTF("DCB list for ACB %p:\n", acb);
5706                 dcb = acb->link_dcb;
5707                 SPRINTF("%p", dcb);
5708                 for (dev = 0; dev < acb->dcb_count; dev++, dcb = dcb->next)
5709                         SPRINTF("->%p", dcb->next);
5710                 SPRINTF("\n");
5711         }
5712
5713         *start = buffer + offset;
5714         DC395x_UNLOCK_IO(acb->scsi_host, flags);
5715
5716         if (pos - buffer < offset)
5717                 return 0;
5718         else if (pos - buffer - offset < length)
5719                 return pos - buffer - offset;
5720         else
5721                 return length;
5722 }
5723
5724
5725 /**
5726  * chip_shutdown - cleanly shut down the scsi controller chip,
5727  * stopping all operations and disablig interrupt generation on the
5728  * card.
5729  *
5730  * @acb: The scsi adapter control block of the adapter to shut down.
5731  **/
5732 static
5733 void chip_shutdown(struct AdapterCtlBlk *acb)
5734 {
5735         /* disable interrupt */
5736         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0);
5737         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0);
5738
5739         /* remove timers */
5740         if (timer_pending(&acb->waiting_timer))
5741                 del_timer(&acb->waiting_timer);
5742         if (timer_pending(&acb->selto_timer))
5743                 del_timer(&acb->selto_timer);
5744
5745         /* reset the scsi bus */
5746         if (acb->config & HCC_SCSI_RESET)
5747                 reset_scsi_bus(acb);
5748
5749         /* clear any pending interupt state */
5750         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
5751
5752         /* release chip resources */
5753 #if debug_enabled(DBG_TRACE|DBG_TRACEALL)
5754         free_tracebufs(acb, DC395x_MAX_SRB_CNT);
5755 #endif
5756         free_sg_tables(acb, DC395x_MAX_SRB_CNT);
5757 }
5758
5759
5760 /**
5761  * free_dcbs - Free all of the DCBs.
5762  *
5763  * @acb: Adapter to remove the DCBs for.
5764  **/
5765 static
5766 void free_dcbs(struct AdapterCtlBlk* acb)
5767 {
5768         struct DeviceCtlBlk *dcb;
5769         struct DeviceCtlBlk *dcb_next;
5770
5771         dprintkdbg(DBG_DCB, "Free %i DCBs\n", acb->dcb_count);
5772
5773         for (dcb = acb->link_dcb; dcb != NULL; dcb = dcb_next)
5774         {
5775                 dcb_next = dcb->next;
5776                 dprintkdbg(DBG_DCB, "Free DCB (ID %i, LUN %i): %p\n",
5777                                      dcb->target_id, dcb->target_lun, dcb);
5778                 /*
5779                  * Free the DCB. This removes the entry from the
5780                  * link_dcb list and decrements the count in dcb_count
5781                  */
5782                 remove_dev(acb, dcb);
5783         }
5784 }
5785
5786 /**
5787  * host_release - shutdown device and release resources that were
5788  * allocate for it. Called once for each card as it is shutdown.
5789  *
5790  * @host: The adapter instance to shutdown.
5791  **/
5792 static
5793 void host_release(struct Scsi_Host *host)
5794 {
5795         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)(host->hostdata);
5796         unsigned long flags;
5797
5798         dprintkl(KERN_DEBUG, "DC395x release\n");
5799
5800         DC395x_LOCK_IO(acb->scsi_host, flags);
5801         chip_shutdown(acb);
5802         free_dcbs(acb);
5803
5804         free_irq(host->irq, acb);
5805         release_region(host->io_port, host->n_io_port);
5806
5807         DC395x_UNLOCK_IO(acb->scsi_host, flags);
5808 }
5809
5810
5811 /*
5812  * SCSI host template
5813  */
5814 static Scsi_Host_Template dc395x_driver_template = {
5815         .module                 = THIS_MODULE,
5816         .proc_name              = DC395X_NAME,
5817         .proc_info              = dc395x_proc_info,
5818         .name                   = DC395X_BANNER " " DC395X_VERSION,
5819         .queuecommand           = dc395x_queue_command,
5820         .bios_param             = dc395x_bios_param,
5821         .slave_alloc            = dc395x_slave_alloc,
5822         .slave_destroy          = dc395x_slave_destroy,
5823         .can_queue              = DC395x_MAX_CAN_QUEUE,
5824         .this_id                = 7,
5825         .sg_tablesize           = DC395x_MAX_SG_TABLESIZE,
5826         .cmd_per_lun            = DC395x_MAX_CMD_PER_LUN,
5827         .eh_abort_handler       = dc395x_eh_abort,
5828         .eh_bus_reset_handler   = dc395x_eh_bus_reset,
5829         .unchecked_isa_dma      = 0,
5830         .use_clustering         = DISABLE_CLUSTERING,
5831 };
5832
5833
5834 /**
5835  * dc395x_init_one - Initialise a single instance of the adapter.
5836  *
5837  * The PCI layer will call this once for each instance of the adapter
5838  * that it finds in the system. The pci_dev strcuture indicates which
5839  * instance we are being called from.
5840  * 
5841  * @dev: The PCI device to intialize.
5842  * @id: Looks like a pointer to the entry in our pci device table
5843  * that was actually matched by the PCI subsystem.
5844  *
5845  * Returns 0 on success, or an error code (-ve) on failure.
5846  **/
5847 static
5848 int __devinit dc395x_init_one(struct pci_dev *dev,
5849                               const struct pci_device_id *id)
5850 {
5851         unsigned int io_port;
5852         u8 irq;
5853         struct Scsi_Host *scsi_host;
5854         static int banner_done = 0;
5855
5856         dprintkdbg(DBG_0, "Init one instance of the dc395x\n");
5857         if (!banner_done)
5858         {
5859                 dprintkl(KERN_INFO, "%s %s\n", DC395X_BANNER, DC395X_VERSION);
5860                 banner_done = 1;
5861         }
5862
5863         if (pci_enable_device(dev))
5864         {
5865                 dprintkl(KERN_INFO, "PCI Enable device failed.\n");
5866                 return -ENODEV;
5867         }
5868
5869         dprintkdbg(DBG_0, "Get resources...\n");
5870         io_port = pci_resource_start(dev, 0) & PCI_BASE_ADDRESS_IO_MASK;
5871         irq = dev->irq;
5872         dprintkdbg(DBG_0, "IO_PORT=%04x,IRQ=%x\n", (unsigned int) io_port, irq);
5873
5874         scsi_host = host_init(&dc395x_driver_template, io_port, irq, adapter_count);
5875         if (!scsi_host)
5876         {
5877                 dprintkdbg(DBG_0, "host_init failed\n");
5878                 return -ENOMEM;
5879         }
5880
5881         pci_set_master(dev);
5882
5883         /* store pci devices in out host data object. */
5884         ((struct AdapterCtlBlk *)(scsi_host->hostdata))->dev = dev;
5885
5886         /* increment adaptor count */
5887         adapter_count++;
5888
5889         /* store ptr to scsi host in the PCI device structure */
5890         pci_set_drvdata(dev, scsi_host);
5891
5892         /* get the scsi mid level to scan for new devices on the bus */
5893         scsi_add_host(scsi_host, &dev->dev);    /* XXX handle failure */
5894         scsi_scan_host(scsi_host);
5895
5896         return 0;
5897 }
5898
5899
5900 /**
5901  * dc395x_remove_one - Called to remove a single instance of the
5902  * adapter.
5903  *
5904  * @dev: The PCI device to intialize.
5905  **/
5906 static void __devexit dc395x_remove_one(struct pci_dev *dev)
5907 {
5908         struct Scsi_Host *host = pci_get_drvdata(dev);
5909         dprintkdbg(DBG_0, "Removing instance\n");
5910         scsi_remove_host(host);
5911         host_release(host);
5912         pci_set_drvdata(dev, NULL);
5913 }
5914
5915
5916 /*
5917  * Table which identifies the PCI devices which
5918  * are handled by this device driver.
5919  */
5920 static struct pci_device_id dc395x_pci_table[] = {
5921         {
5922                 .vendor         = PCI_VENDOR_ID_TEKRAM,
5923                 .device         = PCI_DEVICE_ID_TEKRAM_TRMS1040,
5924                 .subvendor      = PCI_ANY_ID,
5925                 .subdevice      = PCI_ANY_ID,
5926          },
5927         {}                      /* Terminating entry */
5928 };
5929 MODULE_DEVICE_TABLE(pci, dc395x_pci_table);
5930
5931
5932 /*
5933  * PCI driver operations.
5934  * Tells the PCI sub system what can be done with the card.
5935  */
5936 static struct pci_driver dc395x_driver = {
5937         .name           = DC395X_NAME,
5938         .id_table       = dc395x_pci_table,
5939         .probe          = dc395x_init_one,
5940         .remove         = __devexit_p(dc395x_remove_one),
5941 };
5942
5943
5944 /**
5945  * dc395x_module_init - Module initialization function
5946  *
5947  * Used by both module and built-in driver to initialise this driver.
5948  **/
5949 static
5950 int __init dc395x_module_init(void)
5951 {
5952         return pci_module_init(&dc395x_driver);
5953 }
5954
5955
5956 /**
5957  * dc395x_module_exit - Module cleanup function.
5958  **/
5959 static
5960 void __exit dc395x_module_exit(void)
5961 {
5962         pci_unregister_driver(&dc395x_driver);
5963 }
5964
5965
5966 module_init(dc395x_module_init);
5967 module_exit(dc395x_module_exit);
5968
5969 MODULE_AUTHOR("C.L. Huang / Erich Chen / Kurt Garloff");
5970 MODULE_DESCRIPTION("SCSI host adapter driver for Tekram TRM-S1040 based adapters: Tekram DC395 and DC315 series");
5971 MODULE_LICENSE("GPL");