VServer 1.9.2 (patch-2.6.8.1-vs1.9.2.diff)
[linux-2.6.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 <linux/interrupt.h>
55 #include <linux/init.h>
56 #include <linux/spinlock.h>
57 #include <linux/pci.h>
58 #include <linux/list.h>
59 #include <asm/io.h>
60
61 #include <scsi/scsi.h>
62 #include <scsi/scsicam.h>       /* needed for scsicam_bios_param */
63 #include <scsi/scsi_cmnd.h>
64 #include <scsi/scsi_device.h>
65 #include <scsi/scsi_host.h>
66
67 #include "dc395x.h"
68
69 #define DC395X_NAME     "dc395x"
70 #define DC395X_BANNER   "Tekram DC395(U/UW/F), DC315(U) - ASIC TRM-S1040"
71 #define DC395X_VERSION  "v2.05, 2004/03/08"
72
73 /*---------------------------------------------------------------------------
74                                   Features
75  ---------------------------------------------------------------------------*/
76 /*
77  * Set to disable parts of the driver
78  */
79 /*#define DC395x_NO_DISCONNECT*/
80 /*#define DC395x_NO_TAGQ*/
81 /*#define DC395x_NO_SYNC*/
82 /*#define DC395x_NO_WIDE*/
83
84 /*---------------------------------------------------------------------------
85                                   Debugging
86  ---------------------------------------------------------------------------*/
87 /*
88  * Types of debugging that can be enabled and disabled
89  */
90 #define DBG_KG          0x0001
91 #define DBG_0           0x0002
92 #define DBG_1           0x0004
93 #define DBG_SG          0x0020
94 #define DBG_FIFO        0x0040
95 #define DBG_PIO         0x0080
96
97
98 /*
99  * Set set of things to output debugging for.
100  * Undefine to remove all debugging
101  */
102 /*#define DEBUG_MASK (DBG_0|DBG_1|DBG_SG|DBG_FIFO|DBG_PIO)*/
103 /*#define  DEBUG_MASK   DBG_0*/
104
105
106 /*
107  * Output a kernel mesage at the specified level and append the
108  * driver name and a ": " to the start of the message
109  */
110 #define dprintkl(level, format, arg...)  \
111     printk(level DC395X_NAME ": " format , ## arg)
112
113
114 #ifdef DEBUG_MASK
115 /*
116  * print a debug message - this is formated with KERN_DEBUG, then the
117  * driver name followed by a ": " and then the message is output. 
118  * This also checks that the specified debug level is enabled before
119  * outputing the message
120  */
121 #define dprintkdbg(type, format, arg...) \
122         do { \
123                 if ((type) & (DEBUG_MASK)) \
124                         dprintkl(KERN_DEBUG , format , ## arg); \
125         } while (0)
126
127 /*
128  * Check if the specified type of debugging is enabled
129  */
130 #define debug_enabled(type)     ((DEBUG_MASK) & (type))
131
132 #else
133 /*
134  * No debugging. Do nothing
135  */
136 #define dprintkdbg(type, format, arg...) \
137         do {} while (0)
138 #define debug_enabled(type)     (0)
139
140 #endif
141
142
143 #ifndef PCI_VENDOR_ID_TEKRAM
144 #define PCI_VENDOR_ID_TEKRAM                    0x1DE1  /* Vendor ID    */
145 #endif
146 #ifndef PCI_DEVICE_ID_TEKRAM_TRMS1040
147 #define PCI_DEVICE_ID_TEKRAM_TRMS1040           0x0391  /* Device ID    */
148 #endif
149
150
151 #define DC395x_LOCK_IO(dev,flags)               spin_lock_irqsave(((struct Scsi_Host *)dev)->host_lock, flags)
152 #define DC395x_UNLOCK_IO(dev,flags)             spin_unlock_irqrestore(((struct Scsi_Host *)dev)->host_lock, flags)
153
154 #define DC395x_read8(acb,address)               (u8)(inb(acb->io_port_base + (address)))
155 #define DC395x_read16(acb,address)              (u16)(inw(acb->io_port_base + (address)))
156 #define DC395x_read32(acb,address)              (u32)(inl(acb->io_port_base + (address)))
157 #define DC395x_write8(acb,address,value)        outb((value), acb->io_port_base + (address))
158 #define DC395x_write16(acb,address,value)       outw((value), acb->io_port_base + (address))
159 #define DC395x_write32(acb,address,value)       outl((value), acb->io_port_base + (address))
160
161 /* cmd->result */
162 #define RES_TARGET              0x000000FF      /* Target State */
163 #define RES_TARGET_LNX  STATUS_MASK     /* Only official ... */
164 #define RES_ENDMSG              0x0000FF00      /* End Message */
165 #define RES_DID                 0x00FF0000      /* DID_ codes */
166 #define RES_DRV                 0xFF000000      /* DRIVER_ codes */
167
168 #define MK_RES(drv,did,msg,tgt) ((int)(drv)<<24 | (int)(did)<<16 | (int)(msg)<<8 | (int)(tgt))
169 #define MK_RES_LNX(drv,did,msg,tgt) ((int)(drv)<<24 | (int)(did)<<16 | (int)(msg)<<8 | (int)(tgt)<<1)
170
171 #define SET_RES_TARGET(who,tgt) { who &= ~RES_TARGET; who |= (int)(tgt); }
172 #define SET_RES_TARGET_LNX(who,tgt) { who &= ~RES_TARGET_LNX; who |= (int)(tgt) << 1; }
173 #define SET_RES_MSG(who,msg) { who &= ~RES_ENDMSG; who |= (int)(msg) << 8; }
174 #define SET_RES_DID(who,did) { who &= ~RES_DID; who |= (int)(did) << 16; }
175 #define SET_RES_DRV(who,drv) { who &= ~RES_DRV; who |= (int)(drv) << 24; }
176
177 #define TAG_NONE 255
178
179 /*
180  * srb->segement_x is the hw sg list. It is always allocated as a
181  * DC395x_MAX_SG_LISTENTRY entries in a linear block which does not
182  * cross a page boundy.
183  */
184 #define SEGMENTX_LEN    (sizeof(struct SGentry)*DC395x_MAX_SG_LISTENTRY)
185
186
187 struct SGentry {
188         u32 address;            /* bus! address */
189         u32 length;
190 };
191
192 /* The SEEPROM structure for TRM_S1040 */
193 struct NVRamTarget {
194         u8 cfg0;                /* Target configuration byte 0  */
195         u8 period;              /* Target period                */
196         u8 cfg2;                /* Target configuration byte 2  */
197         u8 cfg3;                /* Target configuration byte 3  */
198 };
199
200 struct NvRamType {
201         u8 sub_vendor_id[2];    /* 0,1  Sub Vendor ID   */
202         u8 sub_sys_id[2];       /* 2,3  Sub System ID   */
203         u8 sub_class;           /* 4    Sub Class       */
204         u8 vendor_id[2];        /* 5,6  Vendor ID       */
205         u8 device_id[2];        /* 7,8  Device ID       */
206         u8 reserved;            /* 9    Reserved        */
207         struct NVRamTarget target[DC395x_MAX_SCSI_ID];
208                                                 /** 10,11,12,13
209                                                  ** 14,15,16,17
210                                                  ** ....
211                                                  ** ....
212                                                  ** 70,71,72,73
213                                                  */
214         u8 scsi_id;             /* 74 Host Adapter SCSI ID      */
215         u8 channel_cfg;         /* 75 Channel configuration     */
216         u8 delay_time;          /* 76 Power on delay time       */
217         u8 max_tag;             /* 77 Maximum tags              */
218         u8 reserved0;           /* 78  */
219         u8 boot_target;         /* 79  */
220         u8 boot_lun;            /* 80  */
221         u8 reserved1;           /* 81  */
222         u16 reserved2[22];      /* 82,..125 */
223         u16 cksum;              /* 126,127 */
224 };
225
226 struct ScsiReqBlk {
227         struct list_head list;          /* next/prev ptrs for srb lists */
228         struct DeviceCtlBlk *dcb;
229         struct scsi_cmnd *cmd;
230
231         struct SGentry *segment_x;      /* Linear array of hw sg entries (up to 64 entries) */
232         u32 sg_bus_addr;                /* Bus address of sg list (ie, of segment_x) */
233
234         u8 sg_count;                    /* No of HW sg entries for this request */
235         u8 sg_index;                    /* Index of HW sg entry for this request */
236         u32 total_xfer_length;          /* Total number of bytes remaining to be transfered */
237         unsigned char *virt_addr;       /* Virtual address of current transfer position */
238
239         /*
240          * The sense buffer handling function, request_sense, uses
241          * the first hw sg entry (segment_x[0]) and the transfer
242          * length (total_xfer_length). While doing this it stores the
243          * original values into the last sg hw list
244          * (srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1] and the
245          * total_xfer_length in xferred. These values are restored in
246          * pci_unmap_srb_sense. This is the only place xferred is used.
247          */
248         u32 xferred;                    /* Saved copy of total_xfer_length */
249
250         u16 state;
251
252         u8 msgin_buf[6];
253         u8 msgout_buf[6];
254
255         u8 adapter_status;
256         u8 target_status;
257         u8 msg_count;
258         u8 end_message;
259
260         u8 tag_number;
261         u8 status;
262         u8 retry_count;
263         u8 flag;
264
265         u8 scsi_phase;
266 };
267
268 struct DeviceCtlBlk {
269         struct list_head list;          /* next/prev ptrs for the dcb list */
270         struct AdapterCtlBlk *acb;
271         struct list_head srb_going_list;        /* head of going srb list */
272         struct list_head srb_waiting_list;      /* head of waiting srb list */
273
274         struct ScsiReqBlk *active_srb;
275         u32 tag_mask;
276
277         u16 max_command;
278
279         u8 target_id;           /* SCSI Target ID  (SCSI Only) */
280         u8 target_lun;          /* SCSI Log.  Unit (SCSI Only) */
281         u8 identify_msg;
282         u8 dev_mode;
283
284         u8 inquiry7;            /* To store Inquiry flags */
285         u8 sync_mode;           /* 0:async mode */
286         u8 min_nego_period;     /* for nego. */
287         u8 sync_period;         /* for reg.  */
288
289         u8 sync_offset;         /* for reg. and nego.(low nibble) */
290         u8 flag;
291         u8 dev_type;
292         u8 init_tcq_flag;
293 };
294
295 struct AdapterCtlBlk {
296         struct Scsi_Host *scsi_host;
297
298         u16 io_port_base;
299         u16 io_port_len;
300
301         struct list_head dcb_list;              /* head of going dcb list */
302         struct DeviceCtlBlk *dcb_run_robin;
303         struct DeviceCtlBlk *active_dcb;
304
305         struct list_head srb_free_list;         /* head of free srb list */
306         struct ScsiReqBlk *tmp_srb;
307         struct timer_list waiting_timer;
308         struct timer_list selto_timer;
309
310         u16 srb_count;
311
312         u8 sel_timeout;
313
314         u8 irq_level;
315         u8 tag_max_num;
316         u8 acb_flag;
317         u8 gmode2;
318
319         u8 config;
320         u8 lun_chk;
321         u8 scan_devices;
322         u8 hostid_bit;
323
324         u8 dcb_map[DC395x_MAX_SCSI_ID];
325         struct DeviceCtlBlk *children[DC395x_MAX_SCSI_ID][32];
326
327         struct pci_dev *dev;
328
329         u8 msg_len;
330
331         struct ScsiReqBlk srb_array[DC395x_MAX_SRB_CNT];
332         struct ScsiReqBlk srb;
333
334         struct NvRamType eeprom;        /* eeprom settings for this adapter */
335 };
336
337
338 /*---------------------------------------------------------------------------
339                             Forward declarations
340  ---------------------------------------------------------------------------*/
341 static void data_out_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
342                 u16 *pscsi_status);
343 static void data_in_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
344                 u16 *pscsi_status);
345 static void command_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
346                 u16 *pscsi_status);
347 static void status_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
348                 u16 *pscsi_status);
349 static void msgout_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
350                 u16 *pscsi_status);
351 static void msgin_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
352                 u16 *pscsi_status);
353 static void data_out_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
354                 u16 *pscsi_status);
355 static void data_in_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
356                 u16 *pscsi_status);
357 static void command_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
358                 u16 *pscsi_status);
359 static void status_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
360                 u16 *pscsi_status);
361 static void msgout_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
362                 u16 *pscsi_status);
363 static void msgin_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
364                 u16 *pscsi_status);
365 static void nop0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
366                 u16 *pscsi_status);
367 static void nop1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb, 
368                 u16 *pscsi_status);
369 static void set_basic_config(struct AdapterCtlBlk *acb);
370 static void cleanup_after_transfer(struct AdapterCtlBlk *acb,
371                 struct ScsiReqBlk *srb);
372 static void reset_scsi_bus(struct AdapterCtlBlk *acb);
373 static void data_io_transfer(struct AdapterCtlBlk *acb,
374                 struct ScsiReqBlk *srb, u16 io_dir);
375 static void disconnect(struct AdapterCtlBlk *acb);
376 static void reselect(struct AdapterCtlBlk *acb);
377 static u8 start_scsi(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
378                 struct ScsiReqBlk *srb);
379 static void build_srb(struct scsi_cmnd *cmd, struct DeviceCtlBlk *dcb,
380                 struct ScsiReqBlk *srb);
381 static void doing_srb_done(struct AdapterCtlBlk *acb, u8 did_code,
382                 struct scsi_cmnd *cmd, u8 force);
383 static void scsi_reset_detect(struct AdapterCtlBlk *acb);
384 static void pci_unmap_srb(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb);
385 static void pci_unmap_srb_sense(struct AdapterCtlBlk *acb,
386                 struct ScsiReqBlk *srb);
387 static inline void enable_msgout_abort(struct AdapterCtlBlk *acb,
388                 struct ScsiReqBlk *srb);
389 static void srb_done(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
390                 struct ScsiReqBlk *srb);
391 static void request_sense(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
392                 struct ScsiReqBlk *srb);
393 static inline void set_xfer_rate(struct AdapterCtlBlk *acb,
394                 struct DeviceCtlBlk *dcb);
395 static void waiting_timeout(unsigned long ptr);
396
397
398 /*---------------------------------------------------------------------------
399                                  Static Data
400  ---------------------------------------------------------------------------*/
401 static u16 current_sync_offset = 0;
402
403 static void *dc395x_scsi_phase0[] = {
404         data_out_phase0,/* phase:0 */
405         data_in_phase0, /* phase:1 */
406         command_phase0, /* phase:2 */
407         status_phase0,  /* phase:3 */
408         nop0,           /* phase:4 PH_BUS_FREE .. initial phase */
409         nop0,           /* phase:5 PH_BUS_FREE .. initial phase */
410         msgout_phase0,  /* phase:6 */
411         msgin_phase0,   /* phase:7 */
412 };
413
414 static void *dc395x_scsi_phase1[] = {
415         data_out_phase1,/* phase:0 */
416         data_in_phase1, /* phase:1 */
417         command_phase1, /* phase:2 */
418         status_phase1,  /* phase:3 */
419         nop1,           /* phase:4 PH_BUS_FREE .. initial phase */
420         nop1,           /* phase:5 PH_BUS_FREE .. initial phase */
421         msgout_phase1,  /* phase:6 */
422         msgin_phase1,   /* phase:7 */
423 };
424
425 /*
426  *Fast20:       000      50ns, 20.0 MHz
427  *              001      75ns, 13.3 MHz
428  *              010     100ns, 10.0 MHz
429  *              011     125ns,  8.0 MHz
430  *              100     150ns,  6.6 MHz
431  *              101     175ns,  5.7 MHz
432  *              110     200ns,  5.0 MHz
433  *              111     250ns,  4.0 MHz
434  *
435  *Fast40(LVDS): 000      25ns, 40.0 MHz
436  *              001      50ns, 20.0 MHz
437  *              010      75ns, 13.3 MHz
438  *              011     100ns, 10.0 MHz
439  *              100     125ns,  8.0 MHz
440  *              101     150ns,  6.6 MHz
441  *              110     175ns,  5.7 MHz
442  *              111     200ns,  5.0 MHz
443  */
444 /*static u8     clock_period[] = {12,19,25,31,37,44,50,62};*/
445
446 /* real period:48ns,76ns,100ns,124ns,148ns,176ns,200ns,248ns */
447 static u8 clock_period[] = { 12, 18, 25, 31, 37, 43, 50, 62 };
448 static u16 clock_speed[] = { 200, 133, 100, 80, 67, 58, 50, 40 };
449
450
451 /*---------------------------------------------------------------------------
452                                 Configuration
453   ---------------------------------------------------------------------------*/
454 /*
455  * Module/boot parameters currently effect *all* instances of the
456  * card in the system.
457  */
458
459 /*
460  * Command line parameters are stored in a structure below.
461  * These are the index's into the structure for the various
462  * command line options.
463  */
464 #define CFG_ADAPTER_ID          0
465 #define CFG_MAX_SPEED           1
466 #define CFG_DEV_MODE            2
467 #define CFG_ADAPTER_MODE        3
468 #define CFG_TAGS                4
469 #define CFG_RESET_DELAY         5
470
471 #define CFG_NUM                 6       /* number of configuration items */
472
473
474 /*
475  * Value used to indicate that a command line override
476  * hasn't been used to modify the value.
477  */
478 #define CFG_PARAM_UNSET -1
479
480
481 /*
482  * Hold command line parameters.
483  */
484 struct ParameterData {
485         int value;              /* value of this setting */
486         int min;                /* minimum value */
487         int max;                /* maximum value */
488         int def;                /* default value */
489         int safe;               /* safe value */
490 };
491 static struct ParameterData __initdata cfg_data[] = {
492         { /* adapter id */
493                 CFG_PARAM_UNSET,
494                 0,
495                 15,
496                 7,
497                 7
498         },
499         { /* max speed */
500                 CFG_PARAM_UNSET,
501                   0,
502                   7,
503                   1,    /* 13.3Mhz */
504                   4,    /*  6.7Hmz */
505         },
506         { /* dev mode */
507                 CFG_PARAM_UNSET,
508                 0,
509                 0x3f,
510                 NTC_DO_PARITY_CHK | NTC_DO_DISCONNECT | NTC_DO_SYNC_NEGO |
511                         NTC_DO_WIDE_NEGO | NTC_DO_TAG_QUEUEING |
512                         NTC_DO_SEND_START,
513                 NTC_DO_PARITY_CHK | NTC_DO_SEND_START
514         },
515         { /* adapter mode */
516                 CFG_PARAM_UNSET,
517                 0,
518                 0x2f,
519 #ifdef CONFIG_SCSI_MULTI_LUN
520                         NAC_SCANLUN |
521 #endif
522                 NAC_GT2DRIVES | NAC_GREATER_1G | NAC_POWERON_SCSI_RESET
523                         /*| NAC_ACTIVE_NEG*/,
524                 NAC_GT2DRIVES | NAC_GREATER_1G | NAC_POWERON_SCSI_RESET | 0x08
525         },
526         { /* tags */
527                 CFG_PARAM_UNSET,
528                 0,
529                 5,
530                 3,      /* 16 tags (??) */
531                 2,
532         },
533         { /* reset delay */
534                 CFG_PARAM_UNSET,
535                 0,
536                 180,
537                 1,      /* 1 second */
538                 10,     /* 10 seconds */
539         }
540 };
541
542
543 /*
544  * Safe settings. If set to zero the the BIOS/default values with
545  * command line overrides will be used. If set to 1 then safe and
546  * slow settings will be used.
547  */
548 static int use_safe_settings = 0;
549 module_param_named(safe, use_safe_settings, bool, 0);
550 MODULE_PARM_DESC(safe, "Use safe and slow settings only. Default: false");
551
552
553 module_param_named(adapter_id, cfg_data[CFG_ADAPTER_ID].value, int, 0);
554 MODULE_PARM_DESC(adapter_id, "Adapter SCSI ID. Default 7 (0-15)");
555
556 module_param_named(max_speed, cfg_data[CFG_MAX_SPEED].value, int, 0);
557 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");
558
559 module_param_named(dev_mode, cfg_data[CFG_DEV_MODE].value, int, 0);
560 MODULE_PARM_DESC(dev_mode, "Device mode.");
561
562 module_param_named(adapter_mode, cfg_data[CFG_ADAPTER_MODE].value, int, 0);
563 MODULE_PARM_DESC(adapter_mode, "Adapter mode.");
564
565 module_param_named(tags, cfg_data[CFG_TAGS].value, int, 0);
566 MODULE_PARM_DESC(tags, "Number of tags (1<<x). Default 3 (0-5)");
567
568 module_param_named(reset_delay, cfg_data[CFG_RESET_DELAY].value, int, 0);
569 MODULE_PARM_DESC(reset_delay, "Reset delay in seconds. Default 1 (0-180)");
570
571
572 /**
573  * set_safe_settings - if the use_safe_settings option is set then
574  * set all values to the safe and slow values.
575  **/
576 static void __init set_safe_settings(void)
577 {
578         if (use_safe_settings)
579         {
580                 int i;
581
582                 dprintkl(KERN_INFO, "Using safe settings.\n");
583                 for (i = 0; i < CFG_NUM; i++)
584                 {
585                         cfg_data[i].value = cfg_data[i].safe;
586                 }
587         }
588 }
589
590
591 /**
592  * fix_settings - reset any boot parameters which are out of range
593  * back to the default values.
594  **/
595 static void __init fix_settings(void)
596 {
597         int i;
598
599         dprintkdbg(DBG_1,
600                 "setup: AdapterId=%08x MaxSpeed=%08x DevMode=%08x "
601                 "AdapterMode=%08x Tags=%08x ResetDelay=%08x\n",
602                 cfg_data[CFG_ADAPTER_ID].value,
603                 cfg_data[CFG_MAX_SPEED].value,
604                 cfg_data[CFG_DEV_MODE].value,
605                 cfg_data[CFG_ADAPTER_MODE].value,
606                 cfg_data[CFG_TAGS].value,
607                 cfg_data[CFG_RESET_DELAY].value);
608         for (i = 0; i < CFG_NUM; i++)
609         {
610                 if (cfg_data[i].value < cfg_data[i].min
611                     || cfg_data[i].value > cfg_data[i].max)
612                         cfg_data[i].value = cfg_data[i].def;
613         }
614 }
615
616
617
618 /*
619  * Mapping from the eeprom delay index value (index into this array)
620  * to the the number of actual seconds that the delay should be for.
621  */
622 static char __initdata eeprom_index_to_delay_map[] = 
623         { 1, 3, 5, 10, 16, 30, 60, 120 };
624
625
626 /**
627  * eeprom_index_to_delay - Take the eeprom delay setting and convert it
628  * into a number of seconds.
629  *
630  * @eeprom: The eeprom structure in which we find the delay index to map.
631  **/
632 static void __init eeprom_index_to_delay(struct NvRamType *eeprom)
633 {
634         eeprom->delay_time = eeprom_index_to_delay_map[eeprom->delay_time];
635 }
636
637
638 /**
639  * delay_to_eeprom_index - Take a delay in seconds and return the
640  * closest eeprom index which will delay for at least that amount of
641  * seconds.
642  *
643  * @delay: The delay, in seconds, to find the eeprom index for.
644  **/
645 static int __init delay_to_eeprom_index(int delay)
646 {
647         u8 idx = 0;
648         while (idx < 7 && eeprom_index_to_delay_map[idx] < delay)
649                 idx++;
650         return idx;
651 }
652
653
654 /**
655  * eeprom_override - Override the eeprom settings, in the provided
656  * eeprom structure, with values that have been set on the command
657  * line.
658  *
659  * @eeprom: The eeprom data to override with command line options.
660  **/
661 static void __init eeprom_override(struct NvRamType *eeprom)
662 {
663         u8 id;
664
665         /* Adapter Settings */
666         if (cfg_data[CFG_ADAPTER_ID].value != CFG_PARAM_UNSET)
667                 eeprom->scsi_id = (u8)cfg_data[CFG_ADAPTER_ID].value;
668
669         if (cfg_data[CFG_ADAPTER_MODE].value != CFG_PARAM_UNSET)
670                 eeprom->channel_cfg = (u8)cfg_data[CFG_ADAPTER_MODE].value;
671
672         if (cfg_data[CFG_RESET_DELAY].value != CFG_PARAM_UNSET)
673                 eeprom->delay_time = delay_to_eeprom_index(
674                                         cfg_data[CFG_RESET_DELAY].value);
675
676         if (cfg_data[CFG_TAGS].value != CFG_PARAM_UNSET)
677                 eeprom->max_tag = (u8)cfg_data[CFG_TAGS].value;
678
679         /* Device Settings */
680         for (id = 0; id < DC395x_MAX_SCSI_ID; id++) {
681                 if (cfg_data[CFG_DEV_MODE].value != CFG_PARAM_UNSET)
682                         eeprom->target[id].cfg0 =
683                                 (u8)cfg_data[CFG_DEV_MODE].value;
684
685                 if (cfg_data[CFG_MAX_SPEED].value != CFG_PARAM_UNSET)
686                         eeprom->target[id].period =
687                                 (u8)cfg_data[CFG_MAX_SPEED].value;
688
689         }
690 }
691
692
693 /*---------------------------------------------------------------------------
694  ---------------------------------------------------------------------------*/
695
696 static unsigned int list_size(struct list_head *head)
697 {
698         unsigned int count = 0;
699         struct list_head *pos;
700         list_for_each(pos, head)
701                 count++;
702         return count;
703 }
704
705
706 static struct DeviceCtlBlk *dcb_get_next(struct list_head *head,
707                 struct DeviceCtlBlk *pos)
708 {
709         int use_next = 0;
710         struct DeviceCtlBlk* next = NULL;
711         struct DeviceCtlBlk* i;
712
713         if (list_empty(head))
714                 return NULL;
715
716         /* find supplied dcb and then select the next one */
717         list_for_each_entry(i, head, list)
718                 if (use_next) {
719                         next = i;
720                         break;
721                 } else if (i == pos) {
722                         use_next = 1;
723                 }
724         /* if no next one take the head one (ie, wraparound) */
725         if (!next)
726                 list_for_each_entry(i, head, list) {
727                         next = i;
728                         break;
729                 }
730
731         return next;
732 }
733
734
735 static void free_tag(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
736 {
737         if (srb->tag_number < 255) {
738                 dcb->tag_mask &= ~(1 << srb->tag_number);       /* free tag mask */
739                 srb->tag_number = 255;
740         }
741 }
742
743
744 /* Find cmd in SRB list */
745 inline static struct ScsiReqBlk *find_cmd(struct scsi_cmnd *cmd, 
746                 struct list_head *head)
747 {
748         struct ScsiReqBlk *i;
749         list_for_each_entry(i, head, list)
750                 if (i->cmd == cmd)
751                         return i;
752         return NULL;
753 }
754
755
756 static struct ScsiReqBlk *srb_get_free(struct AdapterCtlBlk *acb)
757 {
758         struct list_head *head = &acb->srb_free_list;
759         struct ScsiReqBlk *srb = NULL;
760
761         if (!list_empty(head)) {
762                 srb = list_entry(head->next, struct ScsiReqBlk, list);
763                 list_del(head->next);
764                 dprintkdbg(DBG_0, "srb_get_free: srb=%p\n", srb);
765         }
766         return srb;
767 }
768
769
770 static void srb_free_insert(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
771 {
772         dprintkdbg(DBG_0, "srb_free_insert: srb=%p\n", srb);
773         list_add_tail(&srb->list, &acb->srb_free_list);
774 }
775
776
777 static void srb_waiting_insert(struct DeviceCtlBlk *dcb,
778                 struct ScsiReqBlk *srb)
779 {
780         dprintkdbg(DBG_0, "srb_waiting_insert: (pid#%li) <%02i-%i> srb=%p\n",
781                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
782         list_add(&srb->list, &dcb->srb_waiting_list);
783 }
784
785
786 static void srb_waiting_append(struct DeviceCtlBlk *dcb,
787                 struct ScsiReqBlk *srb)
788 {
789         dprintkdbg(DBG_0, "srb_waiting_append: (pid#%li) <%02i-%i> srb=%p\n",
790                  srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
791         list_add_tail(&srb->list, &dcb->srb_waiting_list);
792 }
793
794
795 static void srb_going_append(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
796 {
797         dprintkdbg(DBG_0, "srb_going_append: (pid#%li) <%02i-%i> srb=%p\n",
798                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
799         list_add_tail(&srb->list, &dcb->srb_going_list);
800 }
801
802
803 static void srb_going_remove(struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
804 {
805         struct ScsiReqBlk *i;
806         struct ScsiReqBlk *tmp;
807         dprintkdbg(DBG_0, "srb_going_remove: (pid#%li) <%02i-%i> srb=%p\n",
808                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
809
810         list_for_each_entry_safe(i, tmp, &dcb->srb_going_list, list)
811                 if (i == srb) {
812                         list_del(&srb->list);
813                         break;
814                 }
815 }
816
817
818 static void srb_waiting_remove(struct DeviceCtlBlk *dcb,
819                 struct ScsiReqBlk *srb)
820 {
821         struct ScsiReqBlk *i;
822         struct ScsiReqBlk *tmp;
823         dprintkdbg(DBG_0, "srb_waiting_remove: (pid#%li) <%02i-%i> srb=%p\n",
824                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
825
826         list_for_each_entry_safe(i, tmp, &dcb->srb_waiting_list, list)
827                 if (i == srb) {
828                         list_del(&srb->list);
829                         break;
830                 }
831 }
832
833
834 static void srb_going_to_waiting_move(struct DeviceCtlBlk *dcb,
835                 struct ScsiReqBlk *srb)
836 {
837         dprintkdbg(DBG_0,
838                 "srb_going_to_waiting_move: (pid#%li) <%02i-%i> srb=%p\n",
839                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
840         list_move(&srb->list, &dcb->srb_waiting_list);
841 }
842
843
844 static void srb_waiting_to_going_move(struct DeviceCtlBlk *dcb,
845                 struct ScsiReqBlk *srb)
846 {
847         dprintkdbg(DBG_0,
848                 "srb_waiting_to_going_move: (pid#%li) <%02i-%i> srb=%p\n",
849                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
850         list_move(&srb->list, &dcb->srb_going_list);
851 }
852
853
854 /* Sets the timer to wake us up */
855 static void waiting_set_timer(struct AdapterCtlBlk *acb, unsigned long to)
856 {
857         if (timer_pending(&acb->waiting_timer))
858                 return;
859         init_timer(&acb->waiting_timer);
860         acb->waiting_timer.function = waiting_timeout;
861         acb->waiting_timer.data = (unsigned long) acb;
862         if (time_before(jiffies + to, acb->scsi_host->last_reset - HZ / 2))
863                 acb->waiting_timer.expires =
864                     acb->scsi_host->last_reset - HZ / 2 + 1;
865         else
866                 acb->waiting_timer.expires = jiffies + to + 1;
867         add_timer(&acb->waiting_timer);
868 }
869
870
871 /* Send the next command from the waiting list to the bus */
872 static void waiting_process_next(struct AdapterCtlBlk *acb)
873 {
874         struct DeviceCtlBlk *start = NULL;
875         struct DeviceCtlBlk *pos;
876         struct DeviceCtlBlk *dcb;
877         struct ScsiReqBlk *srb;
878         struct list_head *dcb_list_head = &acb->dcb_list;
879
880         if (acb->active_dcb
881             || (acb->acb_flag & (RESET_DETECT + RESET_DONE + RESET_DEV)))
882                 return;
883
884         if (timer_pending(&acb->waiting_timer))
885                 del_timer(&acb->waiting_timer);
886
887         if (list_empty(dcb_list_head))
888                 return;
889
890         /*
891          * Find the starting dcb. Need to find it again in the list
892          * since the list may have changed since we set the ptr to it
893          */
894         list_for_each_entry(dcb, dcb_list_head, list)
895                 if (dcb == acb->dcb_run_robin) {
896                         start = dcb;
897                         break;
898                 }
899         if (!start) {
900                 /* This can happen! */
901                 start = list_entry(dcb_list_head->next, typeof(*start), list);
902                 acb->dcb_run_robin = start;
903         }
904
905
906         /*
907          * Loop over the dcb, but we start somewhere (potentially) in
908          * the middle of the loop so we need to manully do this.
909          */
910         pos = start;
911         do {
912                 struct list_head *waiting_list_head = &pos->srb_waiting_list;
913
914                 /* Make sure, the next another device gets scheduled ... */
915                 acb->dcb_run_robin = dcb_get_next(dcb_list_head,
916                                                   acb->dcb_run_robin);
917
918                 if (list_empty(waiting_list_head) ||
919                     pos->max_command <= list_size(&pos->srb_going_list)) {
920                         /* move to next dcb */
921                         pos = dcb_get_next(dcb_list_head, pos);
922                 } else {
923                         srb = list_entry(waiting_list_head->next,
924                                          struct ScsiReqBlk, list);
925
926                         /* Try to send to the bus */
927                         if (!start_scsi(acb, pos, srb))
928                                 srb_waiting_to_going_move(pos, srb);
929                         else
930                                 waiting_set_timer(acb, HZ/50);
931                         break;
932                 }
933         } while (pos != start);
934 }
935
936
937 /* Wake up waiting queue */
938 static void waiting_timeout(unsigned long ptr)
939 {
940         unsigned long flags;
941         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)ptr;
942         dprintkdbg(DBG_1,
943                 "waiting_timeout: Queue woken up by timer. acb=%p\n", acb);
944         DC395x_LOCK_IO(acb->scsi_host, flags);
945         waiting_process_next(acb);
946         DC395x_UNLOCK_IO(acb->scsi_host, flags);
947 }
948
949
950 /* Get the DCB for a given ID/LUN combination */
951 static struct DeviceCtlBlk *find_dcb(struct AdapterCtlBlk *acb, u8 id, u8 lun)
952 {
953         return acb->children[id][lun];
954 }
955
956
957 /* Send SCSI Request Block (srb) to adapter (acb) */
958 static void send_srb(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
959 {
960         struct DeviceCtlBlk *dcb = srb->dcb;
961
962         if (dcb->max_command <= list_size(&dcb->srb_going_list) ||
963             acb->active_dcb ||
964             (acb->acb_flag & (RESET_DETECT + RESET_DONE + RESET_DEV))) {
965                 srb_waiting_append(dcb, srb);
966                 waiting_process_next(acb);
967                 return;
968         }
969
970         if (!start_scsi(acb, dcb, srb))
971                 srb_going_append(dcb, srb);
972         else {
973                 srb_waiting_insert(dcb, srb);
974                 waiting_set_timer(acb, HZ / 50);
975         }
976 }
977
978
979 /* Prepare SRB for being sent to Device DCB w/ command *cmd */
980 static void build_srb(struct scsi_cmnd *cmd, struct DeviceCtlBlk *dcb,
981                 struct ScsiReqBlk *srb)
982 {
983         enum dma_data_direction dir = cmd->sc_data_direction;
984         dprintkdbg(DBG_0, "build_srb: (pid#%li) <%02i-%i>\n",
985                 cmd->pid, dcb->target_id, dcb->target_lun);
986
987         srb->dcb = dcb;
988         srb->cmd = cmd;
989         srb->sg_count = 0;
990         srb->total_xfer_length = 0;
991         srb->sg_bus_addr = 0;
992         srb->virt_addr = 0;
993         srb->sg_index = 0;
994         srb->adapter_status = 0;
995         srb->target_status = 0;
996         srb->msg_count = 0;
997         srb->status = 0;
998         srb->flag = 0;
999         srb->state = 0;
1000         srb->retry_count = 0;
1001         srb->tag_number = TAG_NONE;
1002         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
1003         srb->end_message = 0;
1004
1005         if (dir == PCI_DMA_NONE || !cmd->request_buffer) {
1006                 dprintkdbg(DBG_0,
1007                         "build_srb: [0] len=%d buf=%p use_sg=%d !MAP=%08x\n",
1008                         cmd->bufflen, cmd->request_buffer,
1009                         cmd->use_sg, srb->segment_x[0].address);
1010         } else if (cmd->use_sg) {
1011                 int i;
1012                 u32 reqlen = cmd->request_bufflen;
1013                 struct scatterlist *sl = (struct scatterlist *)
1014                                          cmd->request_buffer;
1015                 struct SGentry *sgp = srb->segment_x;
1016                 srb->sg_count = pci_map_sg(dcb->acb->dev, sl, cmd->use_sg,
1017                                            dir);
1018                 dprintkdbg(DBG_0,
1019                         "build_srb: [n] len=%d buf=%p use_sg=%d segs=%d\n",
1020                         reqlen, cmd->request_buffer, cmd->use_sg,
1021                         srb->sg_count);
1022
1023                 srb->virt_addr = page_address(sl->page);
1024                 for (i = 0; i < srb->sg_count; i++) {
1025                         u32 busaddr = (u32)sg_dma_address(&sl[i]);
1026                         u32 seglen = (u32)sl[i].length;
1027                         sgp[i].address = busaddr;
1028                         sgp[i].length = seglen;
1029                         srb->total_xfer_length += seglen;
1030                 }
1031                 sgp += srb->sg_count - 1;
1032
1033                 /*
1034                  * adjust last page if too big as it is allocated
1035                  * on even page boundaries
1036                  */
1037                 if (srb->total_xfer_length > reqlen) {
1038                         sgp->length -= (srb->total_xfer_length - reqlen);
1039                         srb->total_xfer_length = reqlen;
1040                 }
1041
1042                 /* Fixup for WIDE padding - make sure length is even */
1043                 if (dcb->sync_period & WIDE_SYNC &&
1044                     srb->total_xfer_length % 2) {
1045                         srb->total_xfer_length++;
1046                         sgp->length++;
1047                 }
1048
1049                 srb->sg_bus_addr = pci_map_single(dcb->acb->dev,
1050                                                 srb->segment_x,
1051                                                 SEGMENTX_LEN,
1052                                                 PCI_DMA_TODEVICE);
1053
1054                 dprintkdbg(DBG_SG, "build_srb: [n] map sg %p->%08x(%05x)\n",
1055                         srb->segment_x, srb->sg_bus_addr, SEGMENTX_LEN);
1056         } else {
1057                 srb->total_xfer_length = cmd->request_bufflen;
1058                 srb->sg_count = 1;
1059                 srb->segment_x[0].address =
1060                         pci_map_single(dcb->acb->dev, cmd->request_buffer,
1061                                        srb->total_xfer_length, dir);
1062
1063                 /* Fixup for WIDE padding - make sure length is even */
1064                 if (dcb->sync_period & WIDE_SYNC && srb->total_xfer_length % 2)
1065                         srb->total_xfer_length++;
1066
1067                 srb->segment_x[0].length = srb->total_xfer_length;
1068                 srb->virt_addr = cmd->request_buffer;
1069                 dprintkdbg(DBG_0,
1070                         "build_srb: [1] len=%d buf=%p use_sg=%d map=%08x\n",
1071                         srb->total_xfer_length, cmd->request_buffer,
1072                         cmd->use_sg, srb->segment_x[0].address);
1073         }
1074 }
1075
1076
1077 /**
1078  * dc395x_queue_command - queue scsi command passed from the mid
1079  * layer, invoke 'done' on completion
1080  *
1081  * @cmd: pointer to scsi command object
1082  * @done: function pointer to be invoked on completion
1083  *
1084  * Returns 1 if the adapter (host) is busy, else returns 0. One
1085  * reason for an adapter to be busy is that the number
1086  * of outstanding queued commands is already equal to
1087  * struct Scsi_Host::can_queue .
1088  *
1089  * Required: if struct Scsi_Host::can_queue is ever non-zero
1090  *           then this function is required.
1091  *
1092  * Locks: struct Scsi_Host::host_lock held on entry (with "irqsave")
1093  *        and is expected to be held on return.
1094  *
1095  **/
1096 static int dc395x_queue_command(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
1097 {
1098         struct DeviceCtlBlk *dcb;
1099         struct ScsiReqBlk *srb;
1100         struct AdapterCtlBlk *acb =
1101             (struct AdapterCtlBlk *)cmd->device->host->hostdata;
1102         dprintkdbg(DBG_0, "queue_command: (pid#%li) <%02i-%i> cmnd=0x%02x\n",
1103                 cmd->pid, cmd->device->id, cmd->device->lun, cmd->cmnd[0]);
1104
1105         /* Assume BAD_TARGET; will be cleared later */
1106         cmd->result = DID_BAD_TARGET << 16;
1107
1108         /* ignore invalid targets */
1109         if (cmd->device->id >= acb->scsi_host->max_id ||
1110             cmd->device->lun >= acb->scsi_host->max_lun ||
1111             cmd->device->lun >31) {
1112                 goto complete;
1113         }
1114
1115         /* does the specified lun on the specified device exist */
1116         if (!(acb->dcb_map[cmd->device->id] & (1 << cmd->device->lun))) {
1117                 dprintkl(KERN_INFO, "queue_command: Ignore target <%02i-%i>\n",
1118                         cmd->device->id, cmd->device->lun);
1119                 goto complete;
1120         }
1121
1122         /* do we have a DCB for the device */
1123         dcb = find_dcb(acb, cmd->device->id, cmd->device->lun);
1124         if (!dcb) {
1125                 /* should never happen */
1126                 dprintkl(KERN_ERR, "queue_command: No such device <%02i-%i>",
1127                         cmd->device->id, cmd->device->lun);
1128                 goto complete;
1129         }
1130
1131         /* set callback and clear result in the command */
1132         cmd->scsi_done = done;
1133         cmd->result = 0;
1134
1135         srb = srb_get_free(acb);
1136         if (!srb)
1137         {
1138                 /*
1139                  * Return 1 since we are unable to queue this command at this
1140                  * point in time.
1141                  */
1142                 dprintkdbg(DBG_0, "queue_command: No free srb's\n");
1143                 return 1;
1144         }
1145
1146         build_srb(cmd, dcb, srb);
1147
1148         if (!list_empty(&dcb->srb_waiting_list)) {
1149                 /* append to waiting queue */
1150                 srb_waiting_append(dcb, srb);
1151                 waiting_process_next(acb);
1152         } else {
1153                 /* process immediately */
1154                 send_srb(acb, srb);
1155         }
1156         dprintkdbg(DBG_1, "queue_command: (pid#%li) done\n", cmd->pid);
1157         return 0;
1158
1159 complete:
1160         /*
1161          * Complete the command immediatey, and then return 0 to
1162          * indicate that we have handled the command. This is usually
1163          * done when the commad is for things like non existent
1164          * devices.
1165          */
1166         done(cmd);
1167         return 0;
1168 }
1169
1170
1171 /*
1172  * Return the disk geometry for the given SCSI device.
1173  */
1174 static int dc395x_bios_param(struct scsi_device *sdev,
1175                 struct block_device *bdev, sector_t capacity, int *info)
1176 {
1177 #ifdef CONFIG_SCSI_DC395x_TRMS1040_TRADMAP
1178         int heads, sectors, cylinders;
1179         struct AdapterCtlBlk *acb;
1180         int size = capacity;
1181
1182         dprintkdbg(DBG_0, "dc395x_bios_param..............\n");
1183         acb = (struct AdapterCtlBlk *)sdev->host->hostdata;
1184         heads = 64;
1185         sectors = 32;
1186         cylinders = size / (heads * sectors);
1187
1188         if ((acb->gmode2 & NAC_GREATER_1G) && (cylinders > 1024)) {
1189                 heads = 255;
1190                 sectors = 63;
1191                 cylinders = size / (heads * sectors);
1192         }
1193         geom[0] = heads;
1194         geom[1] = sectors;
1195         geom[2] = cylinders;
1196         return 0;
1197 #else
1198         return scsicam_bios_param(bdev, capacity, info);
1199 #endif
1200 }
1201
1202
1203 static void dump_register_info(struct AdapterCtlBlk *acb,
1204                 struct DeviceCtlBlk *dcb, struct ScsiReqBlk *srb)
1205 {
1206         u16 pstat;
1207         struct pci_dev *dev = acb->dev;
1208         pci_read_config_word(dev, PCI_STATUS, &pstat);
1209         if (!dcb)
1210                 dcb = acb->active_dcb;
1211         if (!srb && dcb)
1212                 srb = dcb->active_srb;
1213         if (srb) {
1214                 if (!srb->cmd)
1215                         dprintkl(KERN_INFO, "dump: srb=%p cmd=%p OOOPS!\n",
1216                                 srb, srb->cmd);
1217                 else
1218                         dprintkl(KERN_INFO, "dump: srb=%p cmd=%p (pid#%li) "
1219                                  "cmnd=0x%02x <%02i-%i>\n",
1220                                 srb, srb->cmd, srb->cmd->pid,
1221                                 srb->cmd->cmnd[0], srb->cmd->device->id,
1222                                 srb->cmd->device->lun);
1223                 printk("  sglist=%p cnt=%i idx=%i len=%i\n",
1224                        srb->segment_x, srb->sg_count, srb->sg_index,
1225                        srb->total_xfer_length);
1226                 printk("  state=0x%04x status=0x%02x phase=0x%02x (%sconn.)\n",
1227                        srb->state, srb->status, srb->scsi_phase,
1228                        (acb->active_dcb) ? "" : "not");
1229         }
1230         dprintkl(KERN_INFO, "dump: SCSI{status=0x%04x fifocnt=0x%02x "
1231                 "signals=0x%02x irqstat=0x%02x sync=0x%02x target=0x%02x "
1232                 "rselid=0x%02x ctr=0x%08x irqen=0x%02x config=0x%04x "
1233                 "config2=0x%02x cmd=0x%02x selto=0x%02x}\n",
1234                 DC395x_read16(acb, TRM_S1040_SCSI_STATUS),
1235                 DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
1236                 DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL),
1237                 DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS),
1238                 DC395x_read8(acb, TRM_S1040_SCSI_SYNC),
1239                 DC395x_read8(acb, TRM_S1040_SCSI_TARGETID),
1240                 DC395x_read8(acb, TRM_S1040_SCSI_IDMSG),
1241                 DC395x_read32(acb, TRM_S1040_SCSI_COUNTER),
1242                 DC395x_read8(acb, TRM_S1040_SCSI_INTEN),
1243                 DC395x_read16(acb, TRM_S1040_SCSI_CONFIG0),
1244                 DC395x_read8(acb, TRM_S1040_SCSI_CONFIG2),
1245                 DC395x_read8(acb, TRM_S1040_SCSI_COMMAND),
1246                 DC395x_read8(acb, TRM_S1040_SCSI_TIMEOUT));
1247         dprintkl(KERN_INFO, "dump: DMA{cmd=0x%04x fifocnt=0x%02x fstat=0x%02x "
1248                 "irqstat=0x%02x irqen=0x%02x cfg=0x%04x tctr=0x%08x "
1249                 "ctctr=0x%08x addr=0x%08x:0x%08x}\n",
1250                 DC395x_read16(acb, TRM_S1040_DMA_COMMAND),
1251                 DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
1252                 DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
1253                 DC395x_read8(acb, TRM_S1040_DMA_STATUS),
1254                 DC395x_read8(acb, TRM_S1040_DMA_INTEN),
1255                 DC395x_read16(acb, TRM_S1040_DMA_CONFIG),
1256                 DC395x_read32(acb, TRM_S1040_DMA_XCNT),
1257                 DC395x_read32(acb, TRM_S1040_DMA_CXCNT),
1258                 DC395x_read32(acb, TRM_S1040_DMA_XHIGHADDR),
1259                 DC395x_read32(acb, TRM_S1040_DMA_XLOWADDR));
1260         dprintkl(KERN_INFO, "dump: gen{gctrl=0x%02x gstat=0x%02x gtmr=0x%02x} "
1261                 "pci{status=0x%04x}\n",
1262                 DC395x_read8(acb, TRM_S1040_GEN_CONTROL),
1263                 DC395x_read8(acb, TRM_S1040_GEN_STATUS),
1264                 DC395x_read8(acb, TRM_S1040_GEN_TIMER),
1265                 pstat);
1266 }
1267
1268
1269 static inline void clear_fifo(struct AdapterCtlBlk *acb, char *txt)
1270 {
1271 #if debug_enabled(DBG_FIFO)
1272         u8 lines = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
1273         u8 fifocnt = DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT);
1274         if (!(fifocnt & 0x40))
1275                 dprintkdbg(DBG_FIFO,
1276                         "clear_fifo: (%i bytes) on phase %02x in %s\n",
1277                         fifocnt & 0x3f, lines, txt);
1278 #endif
1279         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_CLRFIFO);
1280 }
1281
1282
1283 static void reset_dev_param(struct AdapterCtlBlk *acb)
1284 {
1285         struct DeviceCtlBlk *dcb;
1286         struct NvRamType *eeprom = &acb->eeprom;
1287         dprintkdbg(DBG_0, "reset_dev_param: acb=%p\n", acb);
1288
1289         list_for_each_entry(dcb, &acb->dcb_list, list) {
1290                 u8 period_index;
1291
1292                 dcb->sync_mode &= ~(SYNC_NEGO_DONE + WIDE_NEGO_DONE);
1293                 dcb->sync_period = 0;
1294                 dcb->sync_offset = 0;
1295
1296                 dcb->dev_mode = eeprom->target[dcb->target_id].cfg0;
1297                 period_index = eeprom->target[dcb->target_id].period & 0x07;
1298                 dcb->min_nego_period = clock_period[period_index];
1299                 if (!(dcb->dev_mode & NTC_DO_WIDE_NEGO)
1300                     || !(acb->config & HCC_WIDE_CARD))
1301                         dcb->sync_mode &= ~WIDE_NEGO_ENABLE;
1302         }
1303 }
1304
1305
1306 /*
1307  * perform a hard reset on the SCSI bus
1308  * @cmd - some command for this host (for fetching hooks)
1309  * Returns: SUCCESS (0x2002) on success, else FAILED (0x2003).
1310  */
1311 static int dc395x_eh_bus_reset(struct scsi_cmnd *cmd)
1312 {
1313         struct AdapterCtlBlk *acb =
1314                 (struct AdapterCtlBlk *)cmd->device->host->hostdata;
1315         dprintkl(KERN_INFO,
1316                 "eh_bus_reset: (pid#%li) target=<%02i-%i> cmd=%p\n",
1317                 cmd->pid, cmd->device->id, cmd->device->lun, cmd);
1318
1319         if (timer_pending(&acb->waiting_timer))
1320                 del_timer(&acb->waiting_timer);
1321
1322         /*
1323          * disable interrupt    
1324          */
1325         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0x00);
1326         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x00);
1327         DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
1328         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
1329
1330         reset_scsi_bus(acb);
1331         udelay(500);
1332
1333         /* We may be in serious trouble. Wait some seconds */
1334         acb->scsi_host->last_reset =
1335             jiffies + 3 * HZ / 2 +
1336             HZ * acb->eeprom.delay_time;
1337
1338         /*
1339          * re-enable interrupt      
1340          */
1341         /* Clear SCSI FIFO          */
1342         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
1343         clear_fifo(acb, "eh_bus_reset");
1344         /* Delete pending IRQ */
1345         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
1346         set_basic_config(acb);
1347
1348         reset_dev_param(acb);
1349         doing_srb_done(acb, DID_RESET, cmd, 0);
1350         acb->active_dcb = NULL;
1351         acb->acb_flag = 0;      /* RESET_DETECT, RESET_DONE ,RESET_DEV */
1352         waiting_process_next(acb);
1353
1354         return SUCCESS;
1355 }
1356
1357
1358 /*
1359  * abort an errant SCSI command
1360  * @cmd - command to be aborted
1361  * Returns: SUCCESS (0x2002) on success, else FAILED (0x2003).
1362  */
1363 static int dc395x_eh_abort(struct scsi_cmnd *cmd)
1364 {
1365         /*
1366          * Look into our command queues: If it has not been sent already,
1367          * we remove it and return success. Otherwise fail.
1368          */
1369         struct AdapterCtlBlk *acb =
1370             (struct AdapterCtlBlk *)cmd->device->host->hostdata;
1371         struct DeviceCtlBlk *dcb;
1372         struct ScsiReqBlk *srb;
1373         dprintkl(KERN_INFO, "eh_abort: (pid#%li) target=<%02i-%i> cmd=%p\n",
1374                 cmd->pid, cmd->device->id, cmd->device->lun, cmd);
1375
1376         dcb = find_dcb(acb, cmd->device->id, cmd->device->lun);
1377         if (!dcb) {
1378                 dprintkl(KERN_DEBUG, "eh_abort: No such device\n");
1379                 return FAILED;
1380         }
1381
1382         srb = find_cmd(cmd, &dcb->srb_waiting_list);
1383         if (srb) {
1384                 srb_waiting_remove(dcb, srb);
1385                 pci_unmap_srb_sense(acb, srb);
1386                 pci_unmap_srb(acb, srb);
1387                 free_tag(dcb, srb);
1388                 srb_free_insert(acb, srb);
1389                 dprintkl(KERN_DEBUG, "eh_abort: Command was waiting\n");
1390                 cmd->result = DID_ABORT << 16;
1391                 return SUCCESS;
1392         }
1393         srb = find_cmd(cmd, &dcb->srb_going_list);
1394         if (srb) {
1395                 dprintkl(KERN_DEBUG, "eh_abort: Command in progress");
1396                 /* XXX: Should abort the command here */
1397         } else {
1398                 dprintkl(KERN_DEBUG, "eh_abort: Command not found");
1399         }
1400         return FAILED;
1401 }
1402
1403
1404 /* SDTR */
1405 static void build_sdtr(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
1406                 struct ScsiReqBlk *srb)
1407 {
1408         u8 *ptr = srb->msgout_buf + srb->msg_count;
1409         if (srb->msg_count > 1) {
1410                 dprintkl(KERN_INFO,
1411                         "build_sdtr: msgout_buf BUSY (%i: %02x %02x)\n",
1412                         srb->msg_count, srb->msgout_buf[0],
1413                         srb->msgout_buf[1]);
1414                 return;
1415         }
1416         if (!(dcb->dev_mode & NTC_DO_SYNC_NEGO)) {
1417                 dcb->sync_offset = 0;
1418                 dcb->min_nego_period = 200 >> 2;
1419         } else if (dcb->sync_offset == 0)
1420                 dcb->sync_offset = SYNC_NEGO_OFFSET;
1421
1422         *ptr++ = MSG_EXTENDED;  /* (01h) */
1423         *ptr++ = 3;             /* length */
1424         *ptr++ = EXTENDED_SDTR; /* (01h) */
1425         *ptr++ = dcb->min_nego_period;  /* Transfer period (in 4ns) */
1426         *ptr++ = dcb->sync_offset;      /* Transfer period (max. REQ/ACK dist) */
1427         srb->msg_count += 5;
1428         srb->state |= SRB_DO_SYNC_NEGO;
1429 }
1430
1431
1432 /* WDTR */
1433 static void build_wdtr(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
1434                 struct ScsiReqBlk *srb)
1435 {
1436         u8 wide = ((dcb->dev_mode & NTC_DO_WIDE_NEGO) &
1437                    (acb->config & HCC_WIDE_CARD)) ? 1 : 0;
1438         u8 *ptr = srb->msgout_buf + srb->msg_count;
1439         if (srb->msg_count > 1) {
1440                 dprintkl(KERN_INFO,
1441                         "build_wdtr: msgout_buf BUSY (%i: %02x %02x)\n",
1442                         srb->msg_count, srb->msgout_buf[0],
1443                         srb->msgout_buf[1]);
1444                 return;
1445         }
1446         *ptr++ = MSG_EXTENDED;  /* (01h) */
1447         *ptr++ = 2;             /* length */
1448         *ptr++ = EXTENDED_WDTR; /* (03h) */
1449         *ptr++ = wide;
1450         srb->msg_count += 4;
1451         srb->state |= SRB_DO_WIDE_NEGO;
1452 }
1453
1454
1455 #if 0
1456 /* Timer to work around chip flaw: When selecting and the bus is 
1457  * busy, we sometimes miss a Selection timeout IRQ */
1458 void selection_timeout_missed(unsigned long ptr);
1459 /* Sets the timer to wake us up */
1460 static void selto_timer(struct AdapterCtlBlk *acb)
1461 {
1462         if (timer_pending(&acb->selto_timer))
1463                 return;
1464         acb->selto_timer.function = selection_timeout_missed;
1465         acb->selto_timer.data = (unsigned long) acb;
1466         if (time_before
1467             (jiffies + HZ, acb->scsi_host->last_reset + HZ / 2))
1468                 acb->selto_timer.expires =
1469                     acb->scsi_host->last_reset + HZ / 2 + 1;
1470         else
1471                 acb->selto_timer.expires = jiffies + HZ + 1;
1472         add_timer(&acb->selto_timer);
1473 }
1474
1475
1476 void selection_timeout_missed(unsigned long ptr)
1477 {
1478         unsigned long flags;
1479         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)ptr;
1480         struct ScsiReqBlk *srb;
1481         dprintkl(KERN_DEBUG, "Chip forgot to produce SelTO IRQ!\n");
1482         if (!acb->active_dcb || !acb->active_dcb->active_srb) {
1483                 dprintkl(KERN_DEBUG, "... but no cmd pending? Oops!\n");
1484                 return;
1485         }
1486         DC395x_LOCK_IO(acb->scsi_host, flags);
1487         srb = acb->active_dcb->active_srb;
1488         disconnect(acb);
1489         DC395x_UNLOCK_IO(acb->scsi_host, flags);
1490 }
1491 #endif
1492
1493
1494 static u8 start_scsi(struct AdapterCtlBlk* acb, struct DeviceCtlBlk* dcb,
1495                 struct ScsiReqBlk* srb)
1496 {
1497         u16 s_stat2, return_code;
1498         u8 s_stat, scsicommand, i, identify_message;
1499         u8 *ptr;
1500         dprintkdbg(DBG_0, "start_scsi: (pid#%li) <%02i-%i> srb=%p\n",
1501                 srb->cmd->pid, dcb->target_id, dcb->target_lun, srb);
1502
1503         srb->tag_number = TAG_NONE;     /* acb->tag_max_num: had error read in eeprom */
1504
1505         s_stat = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
1506         s_stat2 = 0;
1507         s_stat2 = DC395x_read16(acb, TRM_S1040_SCSI_STATUS);
1508 #if 1
1509         if (s_stat & 0x20 /* s_stat2 & 0x02000 */ ) {
1510                 dprintkdbg(DBG_KG, "start_scsi: (pid#%li) BUSY %02x %04x\n",
1511                         srb->cmd->pid, s_stat, s_stat2);
1512                 /*
1513                  * Try anyway?
1514                  *
1515                  * We could, BUT: Sometimes the TRM_S1040 misses to produce a Selection
1516                  * Timeout, a Disconnect or a Reselction IRQ, so we would be screwed!
1517                  * (This is likely to be a bug in the hardware. Obviously, most people
1518                  *  only have one initiator per SCSI bus.)
1519                  * Instead let this fail and have the timer make sure the command is 
1520                  * tried again after a short time
1521                  */
1522                 /*selto_timer (acb); */
1523                 return 1;
1524         }
1525 #endif
1526         if (acb->active_dcb) {
1527                 dprintkl(KERN_DEBUG, "start_scsi: (pid#%li) Attempt to start a"
1528                         "command while another command (pid#%li) is active.",
1529                         srb->cmd->pid,
1530                         acb->active_dcb->active_srb ?
1531                             acb->active_dcb->active_srb->cmd->pid : 0);
1532                 return 1;
1533         }
1534         if (DC395x_read16(acb, TRM_S1040_SCSI_STATUS) & SCSIINTERRUPT) {
1535                 dprintkdbg(DBG_KG, "start_scsi: (pid#%li) Failed (busy)\n",
1536                         srb->cmd->pid);
1537                 return 1;
1538         }
1539         /* Allow starting of SCSI commands half a second before we allow the mid-level
1540          * to queue them again after a reset */
1541         if (time_before(jiffies, acb->scsi_host->last_reset - HZ / 2)) {
1542                 dprintkdbg(DBG_KG, "start_scsi: Refuse cmds (reset wait)\n");
1543                 return 1;
1544         }
1545
1546         /* Flush FIFO */
1547         clear_fifo(acb, "start_scsi");
1548         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);
1549         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);
1550         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);
1551         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);
1552         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
1553
1554         identify_message = dcb->identify_msg;
1555         /*DC395x_TRM_write8(TRM_S1040_SCSI_IDMSG, identify_message); */
1556         /* Don't allow disconnection for AUTO_REQSENSE: Cont.All.Cond.! */
1557         if (srb->flag & AUTO_REQSENSE)
1558                 identify_message &= 0xBF;
1559
1560         if (((srb->cmd->cmnd[0] == INQUIRY)
1561              || (srb->cmd->cmnd[0] == REQUEST_SENSE)
1562              || (srb->flag & AUTO_REQSENSE))
1563             && (((dcb->sync_mode & WIDE_NEGO_ENABLE)
1564                  && !(dcb->sync_mode & WIDE_NEGO_DONE))
1565                 || ((dcb->sync_mode & SYNC_NEGO_ENABLE)
1566                     && !(dcb->sync_mode & SYNC_NEGO_DONE)))
1567             && (dcb->target_lun == 0)) {
1568                 srb->msgout_buf[0] = identify_message;
1569                 srb->msg_count = 1;
1570                 scsicommand = SCMD_SEL_ATNSTOP;
1571                 srb->state = SRB_MSGOUT;
1572 #ifndef SYNC_FIRST
1573                 if (dcb->sync_mode & WIDE_NEGO_ENABLE
1574                     && dcb->inquiry7 & SCSI_INQ_WBUS16) {
1575                         build_wdtr(acb, dcb, srb);
1576                         goto no_cmd;
1577                 }
1578 #endif
1579                 if (dcb->sync_mode & SYNC_NEGO_ENABLE
1580                     && dcb->inquiry7 & SCSI_INQ_SYNC) {
1581                         build_sdtr(acb, dcb, srb);
1582                         goto no_cmd;
1583                 }
1584                 if (dcb->sync_mode & WIDE_NEGO_ENABLE
1585                     && dcb->inquiry7 & SCSI_INQ_WBUS16) {
1586                         build_wdtr(acb, dcb, srb);
1587                         goto no_cmd;
1588                 }
1589                 srb->msg_count = 0;
1590         }
1591         /* Send identify message */
1592         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, identify_message);
1593
1594         scsicommand = SCMD_SEL_ATN;
1595         srb->state = SRB_START_;
1596 #ifndef DC395x_NO_TAGQ
1597         if ((dcb->sync_mode & EN_TAG_QUEUEING)
1598             && (identify_message & 0xC0)) {
1599                 /* Send Tag message */
1600                 u32 tag_mask = 1;
1601                 u8 tag_number = 0;
1602                 while (tag_mask & dcb->tag_mask
1603                        && tag_number <= dcb->max_command) {
1604                         tag_mask = tag_mask << 1;
1605                         tag_number++;
1606                 }
1607                 if (tag_number >= dcb->max_command) {
1608                         dprintkl(KERN_WARNING, "start_scsi: (pid#%li) "
1609                                 "Out of tags target=<%02i-%i>)\n",
1610                                 srb->cmd->pid, srb->cmd->device->id,
1611                                 srb->cmd->device->lun);
1612                         srb->state = SRB_READY;
1613                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
1614                                        DO_HWRESELECT);
1615                         return 1;
1616                 }
1617                 /* Send Tag id */
1618                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, MSG_SIMPLE_QTAG);
1619                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, tag_number);
1620                 dcb->tag_mask |= tag_mask;
1621                 srb->tag_number = tag_number;
1622                 scsicommand = SCMD_SEL_ATN3;
1623                 srb->state = SRB_START_;
1624         }
1625 #endif
1626 /*polling:*/
1627         /* Send CDB ..command block ......... */
1628         dprintkdbg(DBG_KG, "start_scsi: (pid#%li) <%02i-%i> cmnd=0x%02x tag=%i\n",
1629                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun,
1630                 srb->cmd->cmnd[0], srb->tag_number);
1631         if (srb->flag & AUTO_REQSENSE) {
1632                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, REQUEST_SENSE);
1633                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, (dcb->target_lun << 5));
1634                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1635                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1636                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
1637                               sizeof(srb->cmd->sense_buffer));
1638                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1639         } else {
1640                 ptr = (u8 *)srb->cmd->cmnd;
1641                 for (i = 0; i < srb->cmd->cmd_len; i++)
1642                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr++);
1643         }
1644       no_cmd:
1645         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
1646                        DO_HWRESELECT | DO_DATALATCH);
1647         if (DC395x_read16(acb, TRM_S1040_SCSI_STATUS) & SCSIINTERRUPT) {
1648                 /* 
1649                  * If start_scsi return 1:
1650                  * we caught an interrupt (must be reset or reselection ... )
1651                  * : Let's process it first!
1652                  */
1653                 dprintkdbg(DBG_0, "start_scsi: (pid#%li) <%02i-%i> Failed - busy\n",
1654                         srb->cmd->pid, dcb->target_id, dcb->target_lun);
1655                 srb->state = SRB_READY;
1656                 free_tag(dcb, srb);
1657                 srb->msg_count = 0;
1658                 return_code = 1;
1659                 /* This IRQ should NOT get lost, as we did not acknowledge it */
1660         } else {
1661                 /* 
1662                  * If start_scsi returns 0:
1663                  * we know that the SCSI processor is free
1664                  */
1665                 srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
1666                 dcb->active_srb = srb;
1667                 acb->active_dcb = dcb;
1668                 return_code = 0;
1669                 /* it's important for atn stop */
1670                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
1671                                DO_DATALATCH | DO_HWRESELECT);
1672                 /* SCSI command */
1673                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, scsicommand);
1674         }
1675         return return_code;
1676 }
1677
1678
1679 /**
1680  * dc395x_handle_interrupt - Handle an interrupt that has been confirmed to
1681  *                           have been triggered for this card.
1682  *
1683  * @acb:         a pointer to the adpter control block
1684  * @scsi_status: the status return when we checked the card
1685  **/
1686 static void dc395x_handle_interrupt(struct AdapterCtlBlk *acb,
1687                 u16 scsi_status)
1688 {
1689         struct DeviceCtlBlk *dcb;
1690         struct ScsiReqBlk *srb;
1691         u16 phase;
1692         u8 scsi_intstatus;
1693         unsigned long flags;
1694         void (*dc395x_statev)(struct AdapterCtlBlk *, struct ScsiReqBlk *, 
1695                               u16 *);
1696
1697         DC395x_LOCK_IO(acb->scsi_host, flags);
1698
1699         /* This acknowledges the IRQ */
1700         scsi_intstatus = DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
1701         if ((scsi_status & 0x2007) == 0x2002)
1702                 dprintkl(KERN_DEBUG,
1703                         "COP after COP completed? %04x\n", scsi_status);
1704         if (debug_enabled(DBG_KG)) {
1705                 if (scsi_intstatus & INT_SELTIMEOUT)
1706                         dprintkdbg(DBG_KG, "handle_interrupt: Selection timeout\n");
1707         }
1708         /*dprintkl(KERN_DEBUG, "handle_interrupt: intstatus = 0x%02x ", scsi_intstatus); */
1709
1710         if (timer_pending(&acb->selto_timer))
1711                 del_timer(&acb->selto_timer);
1712
1713         if (scsi_intstatus & (INT_SELTIMEOUT | INT_DISCONNECT)) {
1714                 disconnect(acb);        /* bus free interrupt  */
1715                 goto out_unlock;
1716         }
1717         if (scsi_intstatus & INT_RESELECTED) {
1718                 reselect(acb);
1719                 goto out_unlock;
1720         }
1721         if (scsi_intstatus & INT_SELECT) {
1722                 dprintkl(KERN_INFO, "Host does not support target mode!\n");
1723                 goto out_unlock;
1724         }
1725         if (scsi_intstatus & INT_SCSIRESET) {
1726                 scsi_reset_detect(acb);
1727                 goto out_unlock;
1728         }
1729         if (scsi_intstatus & (INT_BUSSERVICE | INT_CMDDONE)) {
1730                 dcb = acb->active_dcb;
1731                 if (!dcb) {
1732                         dprintkl(KERN_DEBUG,
1733                                 "Oops: BusService (%04x %02x) w/o ActiveDCB!\n",
1734                                 scsi_status, scsi_intstatus);
1735                         goto out_unlock;
1736                 }
1737                 srb = dcb->active_srb;
1738                 if (dcb->flag & ABORT_DEV_) {
1739                         dprintkdbg(DBG_0, "MsgOut Abort Device.....\n");
1740                         enable_msgout_abort(acb, srb);
1741                 }
1742
1743                 /* software sequential machine */
1744                 phase = (u16)srb->scsi_phase;
1745
1746                 /* 
1747                  * 62037 or 62137
1748                  * call  dc395x_scsi_phase0[]... "phase entry"
1749                  * handle every phase before start transfer
1750                  */
1751                 /* data_out_phase0,     phase:0 */
1752                 /* data_in_phase0,      phase:1 */
1753                 /* command_phase0,      phase:2 */
1754                 /* status_phase0,       phase:3 */
1755                 /* nop0,                phase:4 PH_BUS_FREE .. initial phase */
1756                 /* nop0,                phase:5 PH_BUS_FREE .. initial phase */
1757                 /* msgout_phase0,       phase:6 */
1758                 /* msgin_phase0,        phase:7 */
1759                 dc395x_statev = dc395x_scsi_phase0[phase];
1760                 dc395x_statev(acb, srb, &scsi_status);
1761
1762                 /* 
1763                  * if there were any exception occured scsi_status
1764                  * will be modify to bus free phase new scsi_status
1765                  * transfer out from ... previous dc395x_statev
1766                  */
1767                 srb->scsi_phase = scsi_status & PHASEMASK;
1768                 phase = (u16)scsi_status & PHASEMASK;
1769
1770                 /* 
1771                  * call  dc395x_scsi_phase1[]... "phase entry" handle
1772                  * every phase to do transfer
1773                  */
1774                 /* data_out_phase1,     phase:0 */
1775                 /* data_in_phase1,      phase:1 */
1776                 /* command_phase1,      phase:2 */
1777                 /* status_phase1,       phase:3 */
1778                 /* nop1,                phase:4 PH_BUS_FREE .. initial phase */
1779                 /* nop1,                phase:5 PH_BUS_FREE .. initial phase */
1780                 /* msgout_phase1,       phase:6 */
1781                 /* msgin_phase1,        phase:7 */
1782                 dc395x_statev = dc395x_scsi_phase1[phase];
1783                 dc395x_statev(acb, srb, &scsi_status);
1784         }
1785       out_unlock:
1786         DC395x_UNLOCK_IO(acb->scsi_host, flags);
1787 }
1788
1789
1790 static irqreturn_t dc395x_interrupt(int irq, void *dev_id,
1791                 struct pt_regs *regs)
1792 {
1793         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)dev_id;
1794         u16 scsi_status;
1795         u8 dma_status;
1796         irqreturn_t handled = IRQ_NONE;
1797
1798         /*
1799          * Check for pending interupt
1800          */
1801         scsi_status = DC395x_read16(acb, TRM_S1040_SCSI_STATUS);
1802         dma_status = DC395x_read8(acb, TRM_S1040_DMA_STATUS);
1803         if (scsi_status & SCSIINTERRUPT) {
1804                 /* interupt pending - let's process it! */
1805                 dc395x_handle_interrupt(acb, scsi_status);
1806                 handled = IRQ_HANDLED;
1807         }
1808         else if (dma_status & 0x20) {
1809                 /* Error from the DMA engine */
1810                 dprintkl(KERN_INFO, "Interrupt from DMA engine: 0x%02x!\n", dma_status);
1811 #if 0
1812                 dprintkl(KERN_INFO, "This means DMA error! Try to handle ...\n");
1813                 if (acb->active_dcb) {
1814                         acb->active_dcb-> flag |= ABORT_DEV_;
1815                         if (acb->active_dcb->active_srb)
1816                                 enable_msgout_abort(acb, acb->active_dcb->active_srb);
1817                 }
1818                 DC395x_write8(acb, TRM_S1040_DMA_CONTROL, ABORTXFER | CLRXFIFO);
1819 #else
1820                 dprintkl(KERN_INFO, "Ignoring DMA error (probably a bad thing) ...\n");
1821                 acb = NULL;
1822 #endif
1823                 handled = IRQ_HANDLED;
1824         }
1825
1826         return handled;
1827 }
1828
1829
1830 static void msgout_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
1831                 u16 *pscsi_status)
1832 {
1833         dprintkdbg(DBG_0, "msgout_phase0: (pid#%li)\n", srb->cmd->pid);
1834         if (srb->state & (SRB_UNEXPECT_RESEL + SRB_ABORT_SENT))
1835                 *pscsi_status = PH_BUS_FREE;    /*.. initial phase */
1836
1837         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
1838         srb->state &= ~SRB_MSGOUT;
1839 }
1840
1841
1842 static void msgout_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
1843                 u16 *pscsi_status)
1844 {
1845         u16 i;
1846         u8 *ptr;
1847         dprintkdbg(DBG_0, "msgout_phase1: (pid#%li)\n", srb->cmd->pid);
1848
1849         clear_fifo(acb, "msgout_phase1");
1850         if (!(srb->state & SRB_MSGOUT)) {
1851                 srb->state |= SRB_MSGOUT;
1852                 dprintkl(KERN_DEBUG,
1853                         "msgout_phase1: (pid#%li) Phase unexpected\n",
1854                         srb->cmd->pid); /* So what ? */
1855         }
1856         if (!srb->msg_count) {
1857                 dprintkdbg(DBG_0, "msgout_phase1: (pid#%li) NOP msg\n",
1858                         srb->cmd->pid);
1859                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, MSG_NOP);
1860                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
1861                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
1862                 return;
1863         }
1864         ptr = (u8 *)srb->msgout_buf;
1865         for (i = 0; i < srb->msg_count; i++)
1866                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr++);
1867         srb->msg_count = 0;
1868         if (srb->msgout_buf[0] == MSG_ABORT)
1869                 srb->state = SRB_ABORT_SENT;
1870
1871         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
1872 }
1873
1874
1875 static void command_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
1876                 u16 *pscsi_status)
1877 {
1878         dprintkdbg(DBG_0, "command_phase0: (pid#%li)\n", srb->cmd->pid);
1879         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
1880 }
1881
1882
1883 static void command_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
1884                 u16 *pscsi_status)
1885 {
1886         struct DeviceCtlBlk *dcb;
1887         u8 *ptr;
1888         u16 i;
1889         dprintkdbg(DBG_0, "command_phase1: (pid#%li)\n", srb->cmd->pid);
1890
1891         clear_fifo(acb, "command_phase1");
1892         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_CLRATN);
1893         if (!(srb->flag & AUTO_REQSENSE)) {
1894                 ptr = (u8 *)srb->cmd->cmnd;
1895                 for (i = 0; i < srb->cmd->cmd_len; i++) {
1896                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, *ptr);
1897                         ptr++;
1898                 }
1899         } else {
1900                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, REQUEST_SENSE);
1901                 dcb = acb->active_dcb;
1902                 /* target id */
1903                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, (dcb->target_lun << 5));
1904                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1905                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1906                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO,
1907                               sizeof(srb->cmd->sense_buffer));
1908                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
1909         }
1910         srb->state |= SRB_COMMAND;
1911         /* it's important for atn stop */
1912         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
1913         /* SCSI command */
1914         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_OUT);
1915 }
1916
1917
1918 /*
1919  * Verify that the remaining space in the hw sg lists is the same as
1920  * the count of remaining bytes in srb->total_xfer_length
1921  */
1922 static void sg_verify_length(struct ScsiReqBlk *srb)
1923 {
1924         if (debug_enabled(DBG_SG)) {
1925                 unsigned len = 0;
1926                 unsigned idx = srb->sg_index;
1927                 struct SGentry *psge = srb->segment_x + idx;
1928                 for (; idx < srb->sg_count; psge++, idx++)
1929                         len += psge->length;
1930                 if (len != srb->total_xfer_length)
1931                         dprintkdbg(DBG_SG,
1932                                "Inconsistent SRB S/G lengths (Tot=%i, Count=%i) !!\n",
1933                                srb->total_xfer_length, len);
1934         }                              
1935 }
1936
1937
1938 /*
1939  * Compute the next Scatter Gather list index and adjust its length
1940  * and address if necessary; also compute virt_addr
1941  */
1942 static void sg_update_list(struct ScsiReqBlk *srb, u32 left)
1943 {
1944         u8 idx;
1945         struct scatterlist *sg;
1946         struct scsi_cmnd *cmd = srb->cmd;
1947         int segment = cmd->use_sg;
1948         u32 xferred = srb->total_xfer_length - left; /* bytes transfered */
1949         struct SGentry *psge = srb->segment_x + srb->sg_index;
1950
1951         dprintkdbg(DBG_0,
1952                 "sg_update_list: Transfered %i of %i bytes, %i remain\n",
1953                 xferred, srb->total_xfer_length, left);
1954         if (xferred == 0) {
1955                 /* nothing to update since we did not transfer any data */
1956                 return;
1957         }
1958
1959         sg_verify_length(srb);
1960         srb->total_xfer_length = left;  /* update remaining count */
1961         for (idx = srb->sg_index; idx < srb->sg_count; idx++) {
1962                 if (xferred >= psge->length) {
1963                         /* Complete SG entries done */
1964                         xferred -= psge->length;
1965                 } else {
1966                         /* Partial SG entry done */
1967                         psge->length -= xferred;
1968                         psge->address += xferred;
1969                         srb->sg_index = idx;
1970                         pci_dma_sync_single_for_device(srb->dcb->
1971                                             acb->dev,
1972                                             srb->sg_bus_addr,
1973                                             SEGMENTX_LEN,
1974                                             PCI_DMA_TODEVICE);
1975                         break;
1976                 }
1977                 psge++;
1978         }
1979         sg_verify_length(srb);
1980
1981         /* we need the corresponding virtual address */
1982         if (!segment) {
1983                 srb->virt_addr += xferred;
1984                 return;
1985         }
1986
1987         /* We have to walk the scatterlist to find it */
1988         sg = (struct scatterlist *)cmd->request_buffer;
1989         while (segment--) {
1990                 unsigned long mask =
1991                     ~((unsigned long)sg->length - 1) & PAGE_MASK;
1992                 if ((sg_dma_address(sg) & mask) == (psge->address & mask)) {
1993                         srb->virt_addr = (page_address(sg->page)
1994                                            + psge->address -
1995                                            (psge->address & PAGE_MASK));
1996                         return;
1997                 }
1998                 ++sg;
1999         }
2000
2001         dprintkl(KERN_ERR, "sg_update_list: sg_to_virt failed\n");
2002         srb->virt_addr = 0;
2003 }
2004
2005
2006 /*
2007  * We have transfered a single byte (PIO mode?) and need to update
2008  * the count of bytes remaining (total_xfer_length) and update the sg
2009  * entry to either point to next byte in the current sg entry, or of
2010  * already at the end to point to the start of the next sg entry
2011  */
2012 static void sg_subtract_one(struct ScsiReqBlk *srb)
2013 {
2014         srb->total_xfer_length--;
2015         srb->segment_x[srb->sg_index].length--;
2016         if (srb->total_xfer_length &&
2017             !srb->segment_x[srb->sg_index].length) {
2018                 if (debug_enabled(DBG_PIO))
2019                         printk(" (next segment)");
2020                 srb->sg_index++;
2021                 sg_update_list(srb, srb->total_xfer_length);
2022         }
2023 }
2024
2025
2026 /* 
2027  * cleanup_after_transfer
2028  * 
2029  * Makes sure, DMA and SCSI engine are empty, after the transfer has finished
2030  * KG: Currently called from  StatusPhase1 ()
2031  * Should probably also be called from other places
2032  * Best might be to call it in DataXXPhase0, if new phase will differ 
2033  */
2034 static void cleanup_after_transfer(struct AdapterCtlBlk *acb,
2035                 struct ScsiReqBlk *srb)
2036 {
2037         /*DC395x_write8 (TRM_S1040_DMA_STATUS, FORCEDMACOMP); */
2038         if (DC395x_read16(acb, TRM_S1040_DMA_COMMAND) & 0x0001) {       /* read */
2039                 if (!(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x40))
2040                         clear_fifo(acb, "cleanup/in");
2041                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80))
2042                         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
2043         } else {                /* write */
2044                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80))
2045                         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
2046                 if (!(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x40))
2047                         clear_fifo(acb, "cleanup/out");
2048         }
2049         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);
2050 }
2051
2052
2053 /*
2054  * Those no of bytes will be transfered w/ PIO through the SCSI FIFO
2055  * Seems to be needed for unknown reasons; could be a hardware bug :-(
2056  */
2057 #define DC395x_LASTPIO 4
2058
2059
2060 static void data_out_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2061                 u16 *pscsi_status)
2062 {
2063         struct DeviceCtlBlk *dcb = srb->dcb;
2064         u16 scsi_status = *pscsi_status;
2065         u32 d_left_counter = 0;
2066         dprintkdbg(DBG_0, "data_out_phase0: (pid#%li) <%02i-%i>\n",
2067                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2068
2069         /*
2070          * KG: We need to drain the buffers before we draw any conclusions!
2071          * This means telling the DMA to push the rest into SCSI, telling
2072          * SCSI to push the rest to the bus.
2073          * However, the device might have been the one to stop us (phase
2074          * change), and the data in transit just needs to be accounted so
2075          * it can be retransmitted.)
2076          */
2077         /* 
2078          * KG: Stop DMA engine pushing more data into the SCSI FIFO
2079          * If we need more data, the DMA SG list will be freshly set up, anyway
2080          */
2081         dprintkdbg(DBG_PIO, "data_out_phase0: "
2082                 "DMA{fifcnt=0x%02x fifostat=0x%02x} "
2083                 "SCSI{fifocnt=0x%02x cnt=0x%06x status=0x%04x} total=0x%06x\n",
2084                 DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2085                 DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2086                 DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2087                 DC395x_read32(acb, TRM_S1040_SCSI_COUNTER), scsi_status,
2088                 srb->total_xfer_length);
2089         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, STOPDMAXFER | CLRXFIFO);
2090
2091         if (!(srb->state & SRB_XFERPAD)) {
2092                 if (scsi_status & PARITYERROR)
2093                         srb->status |= PARITY_ERROR;
2094
2095                 /*
2096                  * KG: Right, we can't just rely on the SCSI_COUNTER, because this
2097                  * is the no of bytes it got from the DMA engine not the no it 
2098                  * transferred successfully to the device. (And the difference could
2099                  * be as much as the FIFO size, I guess ...)
2100                  */
2101                 if (!(scsi_status & SCSIXFERDONE)) {
2102                         /*
2103                          * when data transfer from DMA FIFO to SCSI FIFO
2104                          * if there was some data left in SCSI FIFO
2105                          */
2106                         d_left_counter =
2107                             (u32)(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) &
2108                                   0x1F);
2109                         if (dcb->sync_period & WIDE_SYNC)
2110                                 d_left_counter <<= 1;
2111
2112                         dprintkdbg(DBG_KG, "data_out_phase0: FIFO contains %i %s\n"
2113                                 "SCSI{fifocnt=0x%02x cnt=0x%08x} "
2114                                 "DMA{fifocnt=0x%04x cnt=0x%02x ctr=0x%08x}\n",
2115                                 DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2116                                 (dcb->sync_period & WIDE_SYNC) ? "words" : "bytes",
2117                                 DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2118                                 DC395x_read32(acb, TRM_S1040_SCSI_COUNTER),
2119                                 DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2120                                 DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2121                                 DC395x_read32(acb, TRM_S1040_DMA_CXCNT));
2122                 }
2123                 /*
2124                  * calculate all the residue data that not yet tranfered
2125                  * SCSI transfer counter + left in SCSI FIFO data
2126                  *
2127                  * .....TRM_S1040_SCSI_COUNTER (24bits)
2128                  * The counter always decrement by one for every SCSI byte transfer.
2129                  * .....TRM_S1040_SCSI_FIFOCNT ( 5bits)
2130                  * The counter is SCSI FIFO offset counter (in units of bytes or! words)
2131                  */
2132                 if (srb->total_xfer_length > DC395x_LASTPIO)
2133                         d_left_counter +=
2134                             DC395x_read32(acb, TRM_S1040_SCSI_COUNTER);
2135
2136                 /* Is this a good idea? */
2137                 /*clear_fifo(acb, "DOP1"); */
2138                 /* KG: What is this supposed to be useful for? WIDE padding stuff? */
2139                 if (d_left_counter == 1 && dcb->sync_period & WIDE_SYNC
2140                     && srb->cmd->request_bufflen % 2) {
2141                         d_left_counter = 0;
2142                         dprintkl(KERN_INFO,
2143                                 "data_out_phase0: Discard 1 byte (0x%02x)\n",
2144                                 scsi_status);
2145                 }
2146                 /*
2147                  * KG: Oops again. Same thinko as above: The SCSI might have been
2148                  * faster than the DMA engine, so that it ran out of data.
2149                  * In that case, we have to do just nothing! 
2150                  * But: Why the interrupt: No phase change. No XFERCNT_2_ZERO. Or?
2151                  */
2152                 /*
2153                  * KG: This is nonsense: We have been WRITING data to the bus
2154                  * If the SCSI engine has no bytes left, how should the DMA engine?
2155                  */
2156                 if (d_left_counter == 0) {
2157                         srb->total_xfer_length = 0;
2158                 } else {
2159                         /*
2160                          * if transfer not yet complete
2161                          * there were some data residue in SCSI FIFO or
2162                          * SCSI transfer counter not empty
2163                          */
2164                         long oldxferred =
2165                             srb->total_xfer_length - d_left_counter;
2166                         const int diff =
2167                             (dcb->sync_period & WIDE_SYNC) ? 2 : 1;
2168                         sg_update_list(srb, d_left_counter);
2169                         /* KG: Most ugly hack! Apparently, this works around a chip bug */
2170                         if ((srb->segment_x[srb->sg_index].length ==
2171                              diff && srb->cmd->use_sg)
2172                             || ((oldxferred & ~PAGE_MASK) ==
2173                                 (PAGE_SIZE - diff))
2174                             ) {
2175                                 dprintkl(KERN_INFO, "data_out_phase0: "
2176                                         "Work around chip bug (%i)?\n", diff);
2177                                 d_left_counter =
2178                                     srb->total_xfer_length - diff;
2179                                 sg_update_list(srb, d_left_counter);
2180                                 /*srb->total_xfer_length -= diff; */
2181                                 /*srb->virt_addr += diff; */
2182                                 /*if (srb->cmd->use_sg) */
2183                                 /*      srb->sg_index++; */
2184                         }
2185                 }
2186         }
2187         if ((*pscsi_status & PHASEMASK) != PH_DATA_OUT) {
2188                 cleanup_after_transfer(acb, srb);
2189         }
2190 }
2191
2192
2193 static void data_out_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2194                 u16 *pscsi_status)
2195 {
2196         dprintkdbg(DBG_0, "data_out_phase1: (pid#%li) <%02i-%i>\n",
2197                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2198         clear_fifo(acb, "data_out_phase1");
2199         /* do prepare before transfer when data out phase */
2200         data_io_transfer(acb, srb, XFERDATAOUT);
2201 }
2202
2203
2204 static void data_in_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2205                 u16 *pscsi_status)
2206 {
2207         u16 scsi_status = *pscsi_status;
2208         u32 d_left_counter = 0;
2209         dprintkdbg(DBG_0, "data_in_phase0: (pid#%li) <%02i-%i>\n",
2210                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2211
2212         /*
2213          * KG: DataIn is much more tricky than DataOut. When the device is finished
2214          * and switches to another phase, the SCSI engine should be finished too.
2215          * But: There might still be bytes left in its FIFO to be fetched by the DMA
2216          * engine and transferred to memory.
2217          * We should wait for the FIFOs to be emptied by that (is there any way to 
2218          * enforce this?) and then stop the DMA engine, because it might think, that
2219          * there are more bytes to follow. Yes, the device might disconnect prior to
2220          * having all bytes transferred! 
2221          * Also we should make sure that all data from the DMA engine buffer's really
2222          * made its way to the system memory! Some documentation on this would not
2223          * seem to be a bad idea, actually.
2224          */
2225         if (!(srb->state & SRB_XFERPAD)) {
2226                 if (scsi_status & PARITYERROR) {
2227                         dprintkl(KERN_INFO, "data_in_phase0: (pid#%li) "
2228                                 "Parity Error\n", srb->cmd->pid);
2229                         srb->status |= PARITY_ERROR;
2230                 }
2231                 /*
2232                  * KG: We should wait for the DMA FIFO to be empty ...
2233                  * but: it would be better to wait first for the SCSI FIFO and then the
2234                  * the DMA FIFO to become empty? How do we know, that the device not already
2235                  * sent data to the FIFO in a MsgIn phase, eg.?
2236                  */
2237                 if (!(DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT) & 0x80)) {
2238 #if 0
2239                         int ctr = 6000000;
2240                         dprintkl(KERN_DEBUG,
2241                                 "DIP0: Wait for DMA FIFO to flush ...\n");
2242                         /*DC395x_write8  (TRM_S1040_DMA_CONTROL, STOPDMAXFER); */
2243                         /*DC395x_write32 (TRM_S1040_SCSI_COUNTER, 7); */
2244                         /*DC395x_write8  (TRM_S1040_SCSI_COMMAND, SCMD_DMA_IN); */
2245                         while (!
2246                                (DC395x_read16(acb, TRM_S1040_DMA_FIFOSTAT) &
2247                                 0x80) && --ctr);
2248                         if (ctr < 6000000 - 1)
2249                                 dprintkl(KERN_DEBUG
2250                                        "DIP0: Had to wait for DMA ...\n");
2251                         if (!ctr)
2252                                 dprintkl(KERN_ERR,
2253                                        "Deadlock in DIP0 waiting for DMA FIFO empty!!\n");
2254                         /*DC395x_write32 (TRM_S1040_SCSI_COUNTER, 0); */
2255 #endif
2256                         dprintkdbg(DBG_KG, "data_in_phase0: "
2257                                 "DMA{fifocnt=0x%02x fifostat=0x%02x}\n",
2258                                 DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2259                                 DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT));
2260                 }
2261                 /* Now: Check remainig data: The SCSI counters should tell us ... */
2262                 d_left_counter = DC395x_read32(acb, TRM_S1040_SCSI_COUNTER)
2263                     + ((DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x1f)
2264                        << ((srb->dcb->sync_period & WIDE_SYNC) ? 1 :
2265                            0));
2266                 dprintkdbg(DBG_KG, "data_in_phase0: "
2267                         "SCSI{fifocnt=0x%02x%s ctr=0x%08x} "
2268                         "DMA{fifocnt=0x%02x fifostat=0x%02x ctr=0x%08x} "
2269                         "Remain{totxfer=%i scsi_fifo+ctr=%i}\n",
2270                         DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT),
2271                         (srb->dcb->sync_period & WIDE_SYNC) ? "words" : "bytes",
2272                         DC395x_read32(acb, TRM_S1040_SCSI_COUNTER),
2273                         DC395x_read8(acb, TRM_S1040_DMA_FIFOCNT),
2274                         DC395x_read8(acb, TRM_S1040_DMA_FIFOSTAT),
2275                         DC395x_read32(acb, TRM_S1040_DMA_CXCNT),
2276                         srb->total_xfer_length, d_left_counter);
2277 #if DC395x_LASTPIO
2278                 /* KG: Less than or equal to 4 bytes can not be transfered via DMA, it seems. */
2279                 if (d_left_counter
2280                     && srb->total_xfer_length <= DC395x_LASTPIO) {
2281                         /*u32 addr = (srb->segment_x[srb->sg_index].address); */
2282                         /*sg_update_list (srb, d_left_counter); */
2283                         dprintkdbg(DBG_PIO, "data_in_phase0: PIO (%i %s) to "
2284                                 "%p for remaining %i bytes:",
2285                                 DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) & 0x1f,
2286                                 (srb->dcb->sync_period & WIDE_SYNC) ?
2287                                     "words" : "bytes",
2288                                 srb->virt_addr,
2289                                 srb->total_xfer_length);
2290                         if (srb->dcb->sync_period & WIDE_SYNC)
2291                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2,
2292                                               CFG2_WIDEFIFO);
2293                         while (DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) != 0x40) {
2294                                 u8 byte = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2295                                 *(srb->virt_addr)++ = byte;
2296                                 if (debug_enabled(DBG_PIO))
2297                                         printk(" %02x", byte);
2298                                 d_left_counter--;
2299                                 sg_subtract_one(srb);
2300                         }
2301                         if (srb->dcb->sync_period & WIDE_SYNC) {
2302 #if 1
2303                 /* Read the last byte ... */
2304                                 if (srb->total_xfer_length > 0) {
2305                                         u8 byte = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2306                                         *(srb->virt_addr)++ = byte;
2307                                         srb->total_xfer_length--;
2308                                         if (debug_enabled(DBG_PIO))
2309                                                 printk(" %02x", byte);
2310                                 }
2311 #endif
2312                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2, 0);
2313                         }
2314                         /*printk(" %08x", *(u32*)(bus_to_virt (addr))); */
2315                         /*srb->total_xfer_length = 0; */
2316                         if (debug_enabled(DBG_PIO))
2317                                 printk("\n");
2318                 }
2319 #endif                          /* DC395x_LASTPIO */
2320
2321 #if 0
2322                 /*
2323                  * KG: This was in DATAOUT. Does it also belong here?
2324                  * Nobody seems to know what counter and fifo_cnt count exactly ...
2325                  */
2326                 if (!(scsi_status & SCSIXFERDONE)) {
2327                         /*
2328                          * when data transfer from DMA FIFO to SCSI FIFO
2329                          * if there was some data left in SCSI FIFO
2330                          */
2331                         d_left_counter =
2332                             (u32)(DC395x_read8(acb, TRM_S1040_SCSI_FIFOCNT) &
2333                                   0x1F);
2334                         if (srb->dcb->sync_period & WIDE_SYNC)
2335                                 d_left_counter <<= 1;
2336                         /*
2337                          * if WIDE scsi SCSI FIFOCNT unit is word !!!
2338                          * so need to *= 2
2339                          * KG: Seems to be correct ...
2340                          */
2341                 }
2342 #endif
2343                 /* KG: This should not be needed any more! */
2344                 if (d_left_counter == 0
2345                     || (scsi_status & SCSIXFERCNT_2_ZERO)) {
2346 #if 0
2347                         int ctr = 6000000;
2348                         u8 TempDMAstatus;
2349                         do {
2350                                 TempDMAstatus =
2351                                     DC395x_read8(acb, TRM_S1040_DMA_STATUS);
2352                         } while (!(TempDMAstatus & DMAXFERCOMP) && --ctr);
2353                         if (!ctr)
2354                                 dprintkl(KERN_ERR,
2355                                        "Deadlock in DataInPhase0 waiting for DMA!!\n");
2356                         srb->total_xfer_length = 0;
2357 #endif
2358                         srb->total_xfer_length = d_left_counter;
2359                 } else {        /* phase changed */
2360                         /*
2361                          * parsing the case:
2362                          * when a transfer not yet complete 
2363                          * but be disconnected by target
2364                          * if transfer not yet complete
2365                          * there were some data residue in SCSI FIFO or
2366                          * SCSI transfer counter not empty
2367                          */
2368                         sg_update_list(srb, d_left_counter);
2369                 }
2370         }
2371         /* KG: The target may decide to disconnect: Empty FIFO before! */
2372         if ((*pscsi_status & PHASEMASK) != PH_DATA_IN) {
2373                 cleanup_after_transfer(acb, srb);
2374         }
2375 }
2376
2377
2378 static void data_in_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2379                 u16 *pscsi_status)
2380 {
2381         dprintkdbg(DBG_0, "data_in_phase1: (pid#%li) <%02i-%i>\n",
2382                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2383         data_io_transfer(acb, srb, XFERDATAIN);
2384 }
2385
2386
2387 static void data_io_transfer(struct AdapterCtlBlk *acb, 
2388                 struct ScsiReqBlk *srb, u16 io_dir)
2389 {
2390         struct DeviceCtlBlk *dcb = srb->dcb;
2391         u8 bval;
2392         dprintkdbg(DBG_0,
2393                 "data_io_transfer: (pid#%li) <%02i-%i> %c len=%i, sg=(%i/%i)\n",
2394                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun,
2395                 ((io_dir & DMACMD_DIR) ? 'r' : 'w'),
2396                 srb->total_xfer_length, srb->sg_index, srb->sg_count);
2397         if (srb == acb->tmp_srb)
2398                 dprintkl(KERN_ERR, "data_io_transfer: Using tmp_srb!\n");
2399         if (srb->sg_index >= srb->sg_count) {
2400                 /* can't happen? out of bounds error */
2401                 return;
2402         }
2403
2404         if (srb->total_xfer_length > DC395x_LASTPIO) {
2405                 u8 dma_status = DC395x_read8(acb, TRM_S1040_DMA_STATUS);
2406                 /*
2407                  * KG: What should we do: Use SCSI Cmd 0x90/0x92?
2408                  * Maybe, even ABORTXFER would be appropriate
2409                  */
2410                 if (dma_status & XFERPENDING) {
2411                         dprintkl(KERN_DEBUG, "data_io_transfer: Xfer pending! "
2412                                 "Expect trouble!\n");
2413                         dump_register_info(acb, dcb, srb);
2414                         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, CLRXFIFO);
2415                 }
2416                 /* clear_fifo(acb, "IO"); */
2417                 /* 
2418                  * load what physical address of Scatter/Gather list table
2419                  * want to be transfer
2420                  */
2421                 srb->state |= SRB_DATA_XFER;
2422                 DC395x_write32(acb, TRM_S1040_DMA_XHIGHADDR, 0);
2423                 if (srb->cmd->use_sg) { /* with S/G */
2424                         io_dir |= DMACMD_SG;
2425                         DC395x_write32(acb, TRM_S1040_DMA_XLOWADDR,
2426                                        srb->sg_bus_addr +
2427                                        sizeof(struct SGentry) *
2428                                        srb->sg_index);
2429                         /* load how many bytes in the sg list table */
2430                         DC395x_write32(acb, TRM_S1040_DMA_XCNT,
2431                                        ((u32)(srb->sg_count -
2432                                               srb->sg_index) << 3));
2433                 } else {        /* without S/G */
2434                         io_dir &= ~DMACMD_SG;
2435                         DC395x_write32(acb, TRM_S1040_DMA_XLOWADDR,
2436                                        srb->segment_x[0].address);
2437                         DC395x_write32(acb, TRM_S1040_DMA_XCNT,
2438                                        srb->segment_x[0].length);
2439                 }
2440                 /* load total transfer length (24bits) max value 16Mbyte */
2441                 DC395x_write32(acb, TRM_S1040_SCSI_COUNTER,
2442                                srb->total_xfer_length);
2443                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2444                 if (io_dir & DMACMD_DIR) {      /* read */
2445                         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
2446                                       SCMD_DMA_IN);
2447                         DC395x_write16(acb, TRM_S1040_DMA_COMMAND, io_dir);
2448                 } else {
2449                         DC395x_write16(acb, TRM_S1040_DMA_COMMAND, io_dir);
2450                         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
2451                                       SCMD_DMA_OUT);
2452                 }
2453
2454         }
2455 #if DC395x_LASTPIO
2456         else if (srb->total_xfer_length > 0) {  /* The last four bytes: Do PIO */
2457                 /* 
2458                  * load what physical address of Scatter/Gather list table
2459                  * want to be transfer
2460                  */
2461                 srb->state |= SRB_DATA_XFER;
2462                 /* load total transfer length (24bits) max value 16Mbyte */
2463                 DC395x_write32(acb, TRM_S1040_SCSI_COUNTER,
2464                                srb->total_xfer_length);
2465                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2466                 if (io_dir & DMACMD_DIR) {      /* read */
2467                         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
2468                                       SCMD_FIFO_IN);
2469                 } else {        /* write */
2470                         int ln = srb->total_xfer_length;
2471                         if (srb->dcb->sync_period & WIDE_SYNC)
2472                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2,
2473                                      CFG2_WIDEFIFO);
2474                         dprintkdbg(DBG_PIO,
2475                                 "data_io_transfer: PIO %i bytes from %p:",
2476                                 srb->total_xfer_length, srb->virt_addr);
2477
2478                         while (srb->total_xfer_length) {
2479                                 if (debug_enabled(DBG_PIO))
2480                                         printk(" %02x", (unsigned char) *(srb->virt_addr));
2481
2482                                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 
2483                                      *(srb->virt_addr)++);
2484
2485                                 sg_subtract_one(srb);
2486                         }
2487                         if (srb->dcb->sync_period & WIDE_SYNC) {
2488                                 if (ln % 2) {
2489                                         DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 0);
2490                                         if (debug_enabled(DBG_PIO))
2491                                                 printk(" |00");
2492                                 }
2493                                 DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2, 0);
2494                         }
2495                         /*DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, ln); */
2496                         if (debug_enabled(DBG_PIO))
2497                                 printk("\n");
2498                         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND,
2499                                           SCMD_FIFO_OUT);
2500                 }
2501         }
2502 #endif                          /* DC395x_LASTPIO */
2503         else {          /* xfer pad */
2504                 u8 data = 0, data2 = 0;
2505                 if (srb->sg_count) {
2506                         srb->adapter_status = H_OVER_UNDER_RUN;
2507                         srb->status |= OVER_RUN;
2508                 }
2509                 /*
2510                  * KG: despite the fact that we are using 16 bits I/O ops
2511                  * the SCSI FIFO is only 8 bits according to the docs
2512                  * (we can set bit 1 in 0x8f to serialize FIFO access ...)
2513                  */
2514                 if (dcb->sync_period & WIDE_SYNC) {
2515                         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 2);
2516                         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2,
2517                                       CFG2_WIDEFIFO);
2518                         if (io_dir & DMACMD_DIR) {
2519                                 data = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2520                                 data2 = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2521                         } else {
2522                                 /* Danger, Robinson: If you find KGs
2523                                  * scattered over the wide disk, the driver
2524                                  * or chip is to blame :-( */
2525                                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 'K');
2526                                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 'G');
2527                         }
2528                         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG2, 0);
2529                 } else {
2530                         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 1);
2531                         /* Danger, Robinson: If you find a collection of Ks on your disk
2532                          * something broke :-( */
2533                         if (io_dir & DMACMD_DIR)
2534                                 data = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2535                         else
2536                                 DC395x_write8(acb, TRM_S1040_SCSI_FIFO, 'K');
2537                 }
2538                 srb->state |= SRB_XFERPAD;
2539                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2540                 /* SCSI command */
2541                 bval = (io_dir & DMACMD_DIR) ? SCMD_FIFO_IN : SCMD_FIFO_OUT;
2542                 DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, bval);
2543         }
2544 }
2545
2546
2547 static void status_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2548                 u16 *pscsi_status)
2549 {
2550         dprintkdbg(DBG_0, "status_phase0: (pid#%li) <%02i-%i>\n",
2551                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2552         srb->target_status = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2553         srb->end_message = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);      /* get message */
2554         srb->state = SRB_COMPLETED;
2555         *pscsi_status = PH_BUS_FREE;    /*.. initial phase */
2556         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2557         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
2558 }
2559
2560
2561 static void status_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2562                 u16 *pscsi_status)
2563 {
2564         dprintkdbg(DBG_0, "status_phase1: (pid#%li) <%02i-%i>\n",
2565                 srb->cmd->pid, srb->cmd->device->id, srb->cmd->device->lun);
2566         srb->state = SRB_STATUS;
2567         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2568         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_COMP);
2569 }
2570
2571
2572 /* Check if the message is complete */
2573 static inline u8 msgin_completed(u8 * msgbuf, u32 len)
2574 {
2575         if (*msgbuf == EXTENDED_MESSAGE) {
2576                 if (len < 2)
2577                         return 0;
2578                 if (len < msgbuf[1] + 2)
2579                         return 0;
2580         } else if (*msgbuf >= 0x20 && *msgbuf <= 0x2f)  /* two byte messages */
2581                 if (len < 2)
2582                         return 0;
2583         return 1;
2584 }
2585
2586 #define DC395x_ENABLE_MSGOUT \
2587  DC395x_write16 (acb, TRM_S1040_SCSI_CONTROL, DO_SETATN); \
2588  srb->state |= SRB_MSGOUT
2589
2590
2591 /* reject_msg */
2592 static inline void msgin_reject(struct AdapterCtlBlk *acb,
2593                 struct ScsiReqBlk *srb)
2594 {
2595         srb->msgout_buf[0] = MESSAGE_REJECT;
2596         srb->msg_count = 1;
2597         DC395x_ENABLE_MSGOUT;
2598         srb->state &= ~SRB_MSGIN;
2599         srb->state |= SRB_MSGOUT;
2600         dprintkl(KERN_INFO, "msgin_reject: 0x%02x <%02i-%i>\n",
2601                 srb->msgin_buf[0],
2602                 srb->dcb->target_id, srb->dcb->target_lun);
2603 }
2604
2605
2606 /* abort command */
2607 static inline void enable_msgout_abort(struct AdapterCtlBlk *acb,
2608                 struct ScsiReqBlk *srb)
2609 {
2610         srb->msgout_buf[0] = ABORT;
2611         srb->msg_count = 1;
2612         DC395x_ENABLE_MSGOUT;
2613         srb->state &= ~SRB_MSGIN;
2614         srb->state |= SRB_MSGOUT;
2615 }
2616
2617
2618 static struct ScsiReqBlk *msgin_qtag(struct AdapterCtlBlk *acb,
2619                 struct DeviceCtlBlk *dcb, u8 tag)
2620 {
2621         struct ScsiReqBlk *srb = NULL;
2622         struct ScsiReqBlk *i;
2623         dprintkdbg(DBG_0, "msgin_qtag: (pid#%li) tag=%i srb=%p\n",
2624                    srb->cmd->pid, tag, srb);
2625
2626         if (!(dcb->tag_mask & (1 << tag)))
2627                 dprintkl(KERN_DEBUG,
2628                         "msgin_qtag: tag_mask=0x%08x does not reserve tag %i!\n",
2629                         dcb->tag_mask, tag);
2630
2631         if (list_empty(&dcb->srb_going_list))
2632                 goto mingx0;
2633         list_for_each_entry(i, &dcb->srb_going_list, list) {
2634                 if (i->tag_number == tag) {
2635                         srb = i;
2636                         break;
2637                 }
2638         }
2639         if (!srb)
2640                 goto mingx0;
2641
2642         dprintkdbg(DBG_0, "msgin_qtag: (pid#%li) <%02i-%i>\n",
2643                 srb->cmd->pid, srb->dcb->target_id, srb->dcb->target_lun);
2644         if (dcb->flag & ABORT_DEV_) {
2645                 /*srb->state = SRB_ABORT_SENT; */
2646                 enable_msgout_abort(acb, srb);
2647         }
2648
2649         if (!(srb->state & SRB_DISCONNECT))
2650                 goto mingx0;
2651
2652         memcpy(srb->msgin_buf, dcb->active_srb->msgin_buf, acb->msg_len);
2653         srb->state |= dcb->active_srb->state;
2654         srb->state |= SRB_DATA_XFER;
2655         dcb->active_srb = srb;
2656         /* How can we make the DORS happy? */
2657         return srb;
2658
2659       mingx0:
2660         srb = acb->tmp_srb;
2661         srb->state = SRB_UNEXPECT_RESEL;
2662         dcb->active_srb = srb;
2663         srb->msgout_buf[0] = MSG_ABORT_TAG;
2664         srb->msg_count = 1;
2665         DC395x_ENABLE_MSGOUT;
2666         dprintkl(KERN_DEBUG, "msgin_qtag: Unknown tag %i - abort\n", tag);
2667         return srb;
2668 }
2669
2670
2671 static inline void reprogram_regs(struct AdapterCtlBlk *acb,
2672                 struct DeviceCtlBlk *dcb)
2673 {
2674         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);
2675         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);
2676         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);
2677         set_xfer_rate(acb, dcb);
2678 }
2679
2680
2681 /* set async transfer mode */
2682 static void msgin_set_async(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
2683 {
2684         struct DeviceCtlBlk *dcb = srb->dcb;
2685         dprintkl(KERN_DEBUG, "msgin_set_async: No sync transfers <%02i-%i>\n",
2686                 dcb->target_id, dcb->target_lun);
2687
2688         dcb->sync_mode &= ~(SYNC_NEGO_ENABLE);
2689         dcb->sync_mode |= SYNC_NEGO_DONE;
2690         /*dcb->sync_period &= 0; */
2691         dcb->sync_offset = 0;
2692         dcb->min_nego_period = 200 >> 2;        /* 200ns <=> 5 MHz */
2693         srb->state &= ~SRB_DO_SYNC_NEGO;
2694         reprogram_regs(acb, dcb);
2695         if ((dcb->sync_mode & WIDE_NEGO_ENABLE)
2696             && !(dcb->sync_mode & WIDE_NEGO_DONE)) {
2697                 build_wdtr(acb, dcb, srb);
2698                 DC395x_ENABLE_MSGOUT;
2699                 dprintkdbg(DBG_0, "msgin_set_async(rej): Try WDTR anyway\n");
2700         }
2701 }
2702
2703
2704 /* set sync transfer mode */
2705 static void msgin_set_sync(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
2706 {
2707         struct DeviceCtlBlk *dcb = srb->dcb;
2708         u8 bval;
2709         int fact;
2710         dprintkdbg(DBG_1, "msgin_set_sync: <%02i> Sync: %ins "
2711                 "(%02i.%01i MHz) Offset %i\n",
2712                 dcb->target_id, srb->msgin_buf[3] << 2,
2713                 (250 / srb->msgin_buf[3]),
2714                 ((250 % srb->msgin_buf[3]) * 10) / srb->msgin_buf[3],
2715                 srb->msgin_buf[4]);
2716
2717         if (srb->msgin_buf[4] > 15)
2718                 srb->msgin_buf[4] = 15;
2719         if (!(dcb->dev_mode & NTC_DO_SYNC_NEGO))
2720                 dcb->sync_offset = 0;
2721         else if (dcb->sync_offset == 0)
2722                 dcb->sync_offset = srb->msgin_buf[4];
2723         if (srb->msgin_buf[4] > dcb->sync_offset)
2724                 srb->msgin_buf[4] = dcb->sync_offset;
2725         else
2726                 dcb->sync_offset = srb->msgin_buf[4];
2727         bval = 0;
2728         while (bval < 7 && (srb->msgin_buf[3] > clock_period[bval]
2729                             || dcb->min_nego_period >
2730                             clock_period[bval]))
2731                 bval++;
2732         if (srb->msgin_buf[3] < clock_period[bval])
2733                 dprintkl(KERN_INFO,
2734                         "msgin_set_sync: Increase sync nego period to %ins\n",
2735                         clock_period[bval] << 2);
2736         srb->msgin_buf[3] = clock_period[bval];
2737         dcb->sync_period &= 0xf0;
2738         dcb->sync_period |= ALT_SYNC | bval;
2739         dcb->min_nego_period = srb->msgin_buf[3];
2740
2741         if (dcb->sync_period & WIDE_SYNC)
2742                 fact = 500;
2743         else
2744                 fact = 250;
2745
2746         dprintkl(KERN_INFO,
2747                 "Target %02i: %s Sync: %ins Offset %i (%02i.%01i MB/s)\n",
2748                 dcb->target_id, (fact == 500) ? "Wide16" : "",
2749                 dcb->min_nego_period << 2, dcb->sync_offset,
2750                 (fact / dcb->min_nego_period),
2751                 ((fact % dcb->min_nego_period) * 10 +
2752                 dcb->min_nego_period / 2) / dcb->min_nego_period);
2753
2754         if (!(srb->state & SRB_DO_SYNC_NEGO)) {
2755                 /* Reply with corrected SDTR Message */
2756                 dprintkl(KERN_DEBUG, "msgin_set_sync: answer w/%ins %i\n",
2757                         srb->msgin_buf[3] << 2, srb->msgin_buf[4]);
2758
2759                 memcpy(srb->msgout_buf, srb->msgin_buf, 5);
2760                 srb->msg_count = 5;
2761                 DC395x_ENABLE_MSGOUT;
2762                 dcb->sync_mode |= SYNC_NEGO_DONE;
2763         } else {
2764                 if ((dcb->sync_mode & WIDE_NEGO_ENABLE)
2765                     && !(dcb->sync_mode & WIDE_NEGO_DONE)) {
2766                         build_wdtr(acb, dcb, srb);
2767                         DC395x_ENABLE_MSGOUT;
2768                         dprintkdbg(DBG_0, "msgin_set_sync: Also try WDTR\n");
2769                 }
2770         }
2771         srb->state &= ~SRB_DO_SYNC_NEGO;
2772         dcb->sync_mode |= SYNC_NEGO_DONE | SYNC_NEGO_ENABLE;
2773
2774         reprogram_regs(acb, dcb);
2775 }
2776
2777
2778 static inline void msgin_set_nowide(struct AdapterCtlBlk *acb,
2779                 struct ScsiReqBlk *srb)
2780 {
2781         struct DeviceCtlBlk *dcb = srb->dcb;
2782         dprintkdbg(DBG_1, "msgin_set_nowide: <%02i>\n", dcb->target_id);
2783
2784         dcb->sync_period &= ~WIDE_SYNC;
2785         dcb->sync_mode &= ~(WIDE_NEGO_ENABLE);
2786         dcb->sync_mode |= WIDE_NEGO_DONE;
2787         srb->state &= ~SRB_DO_WIDE_NEGO;
2788         reprogram_regs(acb, dcb);
2789         if ((dcb->sync_mode & SYNC_NEGO_ENABLE)
2790             && !(dcb->sync_mode & SYNC_NEGO_DONE)) {
2791                 build_sdtr(acb, dcb, srb);
2792                 DC395x_ENABLE_MSGOUT;
2793                 dprintkdbg(DBG_0, "msgin_set_nowide: Rejected. Try SDTR anyway\n");
2794         }
2795 }
2796
2797 static void msgin_set_wide(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
2798 {
2799         struct DeviceCtlBlk *dcb = srb->dcb;
2800         u8 wide = (dcb->dev_mode & NTC_DO_WIDE_NEGO
2801                    && acb->config & HCC_WIDE_CARD) ? 1 : 0;
2802         dprintkdbg(DBG_1, "msgin_set_wide: <%02i>\n", dcb->target_id);
2803
2804         if (srb->msgin_buf[3] > wide)
2805                 srb->msgin_buf[3] = wide;
2806         /* Completed */
2807         if (!(srb->state & SRB_DO_WIDE_NEGO)) {
2808                 dprintkl(KERN_DEBUG,
2809                         "msgin_set_wide: Wide nego initiated <%02i>\n",
2810                         dcb->target_id);
2811                 memcpy(srb->msgout_buf, srb->msgin_buf, 4);
2812                 srb->msg_count = 4;
2813                 srb->state |= SRB_DO_WIDE_NEGO;
2814                 DC395x_ENABLE_MSGOUT;
2815         }
2816
2817         dcb->sync_mode |= (WIDE_NEGO_ENABLE | WIDE_NEGO_DONE);
2818         if (srb->msgin_buf[3] > 0)
2819                 dcb->sync_period |= WIDE_SYNC;
2820         else
2821                 dcb->sync_period &= ~WIDE_SYNC;
2822         srb->state &= ~SRB_DO_WIDE_NEGO;
2823         /*dcb->sync_mode &= ~(WIDE_NEGO_ENABLE+WIDE_NEGO_DONE); */
2824         dprintkdbg(DBG_1,
2825                 "msgin_set_wide: Wide (%i bit) negotiated <%02i>\n",
2826                 (8 << srb->msgin_buf[3]), dcb->target_id);
2827         reprogram_regs(acb, dcb);
2828         if ((dcb->sync_mode & SYNC_NEGO_ENABLE)
2829             && !(dcb->sync_mode & SYNC_NEGO_DONE)) {
2830                 build_sdtr(acb, dcb, srb);
2831                 DC395x_ENABLE_MSGOUT;
2832                 dprintkdbg(DBG_0, "msgin_set_wide: Also try SDTR.\n");
2833         }
2834 }
2835
2836
2837 /*
2838  * extended message codes:
2839  *
2840  *      code    description
2841  *
2842  *      02h     Reserved
2843  *      00h     MODIFY DATA  POINTER
2844  *      01h     SYNCHRONOUS DATA TRANSFER REQUEST
2845  *      03h     WIDE DATA TRANSFER REQUEST
2846  *   04h - 7Fh  Reserved
2847  *   80h - FFh  Vendor specific
2848  */
2849 static void msgin_phase0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2850                 u16 *pscsi_status)
2851 {
2852         struct DeviceCtlBlk *dcb = acb->active_dcb;
2853         dprintkdbg(DBG_0, "msgin_phase0: (pid#%li)\n", srb->cmd->pid);
2854
2855         srb->msgin_buf[acb->msg_len++] = DC395x_read8(acb, TRM_S1040_SCSI_FIFO);
2856         if (msgin_completed(srb->msgin_buf, acb->msg_len)) {
2857                 /* Now eval the msg */
2858                 switch (srb->msgin_buf[0]) {
2859                 case DISCONNECT:
2860                         srb->state = SRB_DISCONNECT;
2861                         break;
2862
2863                 case SIMPLE_QUEUE_TAG:
2864                 case HEAD_OF_QUEUE_TAG:
2865                 case ORDERED_QUEUE_TAG:
2866                         srb =
2867                             msgin_qtag(acb, dcb,
2868                                               srb->msgin_buf[1]);
2869                         break;
2870
2871                 case MESSAGE_REJECT:
2872                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL,
2873                                        DO_CLRATN | DO_DATALATCH);
2874                         /* A sync nego message was rejected ! */
2875                         if (srb->state & SRB_DO_SYNC_NEGO) {
2876                                 msgin_set_async(acb, srb);
2877                                 break;
2878                         }
2879                         /* A wide nego message was rejected ! */
2880                         if (srb->state & SRB_DO_WIDE_NEGO) {
2881                                 msgin_set_nowide(acb, srb);
2882                                 break;
2883                         }
2884                         enable_msgout_abort(acb, srb);
2885                         /*srb->state |= SRB_ABORT_SENT */
2886                         break;
2887
2888                 case EXTENDED_MESSAGE:
2889                         /* SDTR */
2890                         if (srb->msgin_buf[1] == 3
2891                             && srb->msgin_buf[2] == EXTENDED_SDTR) {
2892                                 msgin_set_sync(acb, srb);
2893                                 break;
2894                         }
2895                         /* WDTR */
2896                         if (srb->msgin_buf[1] == 2
2897                             && srb->msgin_buf[2] == EXTENDED_WDTR
2898                             && srb->msgin_buf[3] <= 2) { /* sanity check ... */
2899                                 msgin_set_wide(acb, srb);
2900                                 break;
2901                         }
2902                         msgin_reject(acb, srb);
2903                         break;
2904
2905                 case MSG_IGNOREWIDE:
2906                         /* Discard  wide residual */
2907                         dprintkdbg(DBG_0, "msgin_phase0: Ignore Wide Residual!\n");
2908                         break;
2909
2910                 case COMMAND_COMPLETE:
2911                         /* nothing has to be done */
2912                         break;
2913
2914                 case SAVE_POINTERS:
2915                         /*
2916                          * SAVE POINTER may be ignored as we have the struct
2917                          * ScsiReqBlk* associated with the scsi command.
2918                          */
2919                         dprintkdbg(DBG_0, "msgin_phase0: (pid#%li) "
2920                                 "SAVE POINTER rem=%i Ignore\n",
2921                                 srb->cmd->pid, srb->total_xfer_length);
2922                         break;
2923
2924                 case RESTORE_POINTERS:
2925                         dprintkdbg(DBG_0, "msgin_phase0: RESTORE POINTER. Ignore\n");
2926                         break;
2927
2928                 case ABORT:
2929                         dprintkdbg(DBG_0, "msgin_phase0: (pid#%li) "
2930                                 "<%02i-%i> ABORT msg\n",
2931                                 srb->cmd->pid, dcb->target_id,
2932                                 dcb->target_lun);
2933                         dcb->flag |= ABORT_DEV_;
2934                         enable_msgout_abort(acb, srb);
2935                         break;
2936
2937                 default:
2938                         /* reject unknown messages */
2939                         if (srb->msgin_buf[0] & IDENTIFY_BASE) {
2940                                 dprintkdbg(DBG_0, "msgin_phase0: Identify msg\n");
2941                                 srb->msg_count = 1;
2942                                 srb->msgout_buf[0] = dcb->identify_msg;
2943                                 DC395x_ENABLE_MSGOUT;
2944                                 srb->state |= SRB_MSGOUT;
2945                                 /*break; */
2946                         }
2947                         msgin_reject(acb, srb);
2948                 }
2949
2950                 /* Clear counter and MsgIn state */
2951                 srb->state &= ~SRB_MSGIN;
2952                 acb->msg_len = 0;
2953         }
2954         *pscsi_status = PH_BUS_FREE;
2955         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important ... you know! */
2956         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
2957 }
2958
2959
2960 static void msgin_phase1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2961                 u16 *pscsi_status)
2962 {
2963         dprintkdbg(DBG_0, "msgin_phase1: (pid#%li)\n", srb->cmd->pid);
2964         clear_fifo(acb, "msgin_phase1");
2965         DC395x_write32(acb, TRM_S1040_SCSI_COUNTER, 1);
2966         if (!(srb->state & SRB_MSGIN)) {
2967                 srb->state &= ~SRB_DISCONNECT;
2968                 srb->state |= SRB_MSGIN;
2969         }
2970         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
2971         /* SCSI command */
2972         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_FIFO_IN);
2973 }
2974
2975
2976 static void nop0(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2977                 u16 *pscsi_status)
2978 {
2979 }
2980
2981
2982 static void nop1(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb,
2983                 u16 *pscsi_status)
2984 {
2985 }
2986
2987
2988 static void set_xfer_rate(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb)
2989 {
2990         struct DeviceCtlBlk *i;
2991
2992         /* set all lun device's  period, offset */
2993         if (dcb->identify_msg & 0x07)
2994                 return;
2995
2996         if (acb->scan_devices) {
2997                 current_sync_offset = dcb->sync_offset;
2998                 return;
2999         }
3000
3001         list_for_each_entry(i, &acb->dcb_list, list)
3002                 if (i->target_id == dcb->target_id) {
3003                         i->sync_period = dcb->sync_period;
3004                         i->sync_offset = dcb->sync_offset;
3005                         i->sync_mode = dcb->sync_mode;
3006                         i->min_nego_period = dcb->min_nego_period;
3007                 }
3008 }
3009
3010
3011 static void disconnect(struct AdapterCtlBlk *acb)
3012 {
3013         struct DeviceCtlBlk *dcb = acb->active_dcb;
3014         struct ScsiReqBlk *srb;
3015
3016         if (!dcb) {
3017                 dprintkl(KERN_ERR, "disconnect: No such device\n");
3018                 udelay(500);
3019                 /* Suspend queue for a while */
3020                 acb->scsi_host->last_reset =
3021                     jiffies + HZ / 2 +
3022                     HZ * acb->eeprom.delay_time;
3023                 clear_fifo(acb, "disconnectEx");
3024                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT);
3025                 return;
3026         }
3027         srb = dcb->active_srb;
3028         acb->active_dcb = NULL;
3029         dprintkdbg(DBG_0, "disconnect: (pid#%li)\n", srb->cmd->pid);
3030
3031         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
3032         clear_fifo(acb, "disconnect");
3033         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT);
3034         if (srb->state & SRB_UNEXPECT_RESEL) {
3035                 dprintkl(KERN_ERR,
3036                         "disconnect: Unexpected reselection <%02i-%i>\n",
3037                         dcb->target_id, dcb->target_lun);
3038                 srb->state = 0;
3039                 waiting_process_next(acb);
3040         } else if (srb->state & SRB_ABORT_SENT) {
3041                 dcb->flag &= ~ABORT_DEV_;
3042                 acb->scsi_host->last_reset = jiffies + HZ / 2 + 1;
3043                 dprintkl(KERN_ERR, "disconnect: SRB_ABORT_SENT\n");
3044                 doing_srb_done(acb, DID_ABORT, srb->cmd, 1);
3045                 waiting_process_next(acb);
3046         } else {
3047                 if ((srb->state & (SRB_START_ + SRB_MSGOUT))
3048                     || !(srb->
3049                          state & (SRB_DISCONNECT + SRB_COMPLETED))) {
3050                         /*
3051                          * Selection time out 
3052                          * SRB_START_ || SRB_MSGOUT || (!SRB_DISCONNECT && !SRB_COMPLETED)
3053                          */
3054                         /* Unexp. Disc / Sel Timeout */
3055                         if (srb->state != SRB_START_
3056                             && srb->state != SRB_MSGOUT) {
3057                                 srb->state = SRB_READY;
3058                                 dprintkl(KERN_DEBUG,
3059                                         "disconnect: (pid#%li) Unexpected\n",
3060                                         srb->cmd->pid);
3061                                 srb->target_status = SCSI_STAT_SEL_TIMEOUT;
3062                                 goto disc1;
3063                         } else {
3064                                 /* Normal selection timeout */
3065                                 dprintkdbg(DBG_KG, "disconnect: (pid#%li) "
3066                                         "<%02i-%i> SelTO\n", srb->cmd->pid,
3067                                         dcb->target_id, dcb->target_lun);
3068                                 if (srb->retry_count++ > DC395x_MAX_RETRIES
3069                                     || acb->scan_devices) {
3070                                         srb->target_status =
3071                                             SCSI_STAT_SEL_TIMEOUT;
3072                                         goto disc1;
3073                                 }
3074                                 free_tag(dcb, srb);
3075                                 srb_going_to_waiting_move(dcb, srb);
3076                                 dprintkdbg(DBG_KG,
3077                                         "disconnect: (pid#%li) Retry\n",
3078                                         srb->cmd->pid);
3079                                 waiting_set_timer(acb, HZ / 20);
3080                         }
3081                 } else if (srb->state & SRB_DISCONNECT) {
3082                         u8 bval = DC395x_read8(acb, TRM_S1040_SCSI_SIGNAL);
3083                         /*
3084                          * SRB_DISCONNECT (This is what we expect!)
3085                          */
3086                         if (bval & 0x40) {
3087                                 dprintkdbg(DBG_0, "disconnect: SCSI bus stat "
3088                                         " 0x%02x: ACK set! Other controllers?\n",
3089                                         bval);
3090                                 /* It could come from another initiator, therefore don't do much ! */
3091                         } else
3092                                 waiting_process_next(acb);
3093                 } else if (srb->state & SRB_COMPLETED) {
3094                       disc1:
3095                         /*
3096                          ** SRB_COMPLETED
3097                          */
3098                         free_tag(dcb, srb);
3099                         dcb->active_srb = NULL;
3100                         srb->state = SRB_FREE;
3101                         srb_done(acb, dcb, srb);
3102                 }
3103         }
3104 }
3105
3106
3107 static void reselect(struct AdapterCtlBlk *acb)
3108 {
3109         struct DeviceCtlBlk *dcb = acb->active_dcb;
3110         struct ScsiReqBlk *srb = NULL;
3111         u16 rsel_tar_lun_id;
3112         u8 id, lun;
3113         u8 arblostflag = 0;
3114         dprintkdbg(DBG_0, "reselect: acb=%p\n", acb);
3115
3116         clear_fifo(acb, "reselect");
3117         /*DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT | DO_DATALATCH); */
3118         /* Read Reselected Target ID and LUN */
3119         rsel_tar_lun_id = DC395x_read16(acb, TRM_S1040_SCSI_TARGETID);
3120         if (dcb) {              /* Arbitration lost but Reselection win */
3121                 srb = dcb->active_srb;
3122                 if (!srb) {
3123                         dprintkl(KERN_DEBUG, "reselect: Arb lost Resel won, "
3124                                 "but active_srb == NULL\n");
3125                         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3126                         return;
3127                 }
3128                 /* Why the if ? */
3129                 if (!acb->scan_devices) {
3130                         dprintkdbg(DBG_KG, "reselect: (pid#%li) <%02i-%i> "
3131                                 "Arb lost but Resel win rsel=%i stat=0x%04x\n",
3132                                 srb->cmd->pid, dcb->target_id,
3133                                 dcb->target_lun, rsel_tar_lun_id,
3134                                 DC395x_read16(acb, TRM_S1040_SCSI_STATUS));
3135                         arblostflag = 1;
3136                         /*srb->state |= SRB_DISCONNECT; */
3137
3138                         srb->state = SRB_READY;
3139                         free_tag(dcb, srb);
3140                         srb_going_to_waiting_move(dcb, srb);
3141                         waiting_set_timer(acb, HZ / 20);
3142
3143                         /* return; */
3144                 }
3145         }
3146         /* Read Reselected Target Id and LUN */
3147         if (!(rsel_tar_lun_id & (IDENTIFY_BASE << 8)))
3148                 dprintkl(KERN_DEBUG, "reselect: Expects identify msg. "
3149                         "Got %i!\n", rsel_tar_lun_id);
3150         id = rsel_tar_lun_id & 0xff;
3151         lun = (rsel_tar_lun_id >> 8) & 7;
3152         dcb = find_dcb(acb, id, lun);
3153         if (!dcb) {
3154                 dprintkl(KERN_ERR, "reselect: From non existent device "
3155                         "<%02i-%i>\n", id, lun);
3156                 DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);      /* it's important for atn stop */
3157                 return;
3158         }
3159         acb->active_dcb = dcb;
3160
3161         if (!(dcb->dev_mode & NTC_DO_DISCONNECT))
3162                 dprintkl(KERN_DEBUG, "reselect: in spite of forbidden "
3163                         "disconnection? <%02i-%i>\n",
3164                         dcb->target_id, dcb->target_lun);
3165
3166         if (dcb->sync_mode & EN_TAG_QUEUEING /*&& !arblostflag */) {
3167                 srb = acb->tmp_srb;
3168                 dcb->active_srb = srb;
3169         } else {
3170                 /* There can be only one! */
3171                 srb = dcb->active_srb;
3172                 if (!srb || !(srb->state & SRB_DISCONNECT)) {
3173                         /*
3174                          * abort command
3175                          */
3176                         dprintkl(KERN_DEBUG,
3177                                 "reselect: w/o disconnected cmds <%02i-%i>\n",
3178                                 dcb->target_id, dcb->target_lun);
3179                         srb = acb->tmp_srb;
3180                         srb->state = SRB_UNEXPECT_RESEL;
3181                         dcb->active_srb = srb;
3182                         enable_msgout_abort(acb, srb);
3183                 } else {
3184                         if (dcb->flag & ABORT_DEV_) {
3185                                 /*srb->state = SRB_ABORT_SENT; */
3186                                 enable_msgout_abort(acb, srb);
3187                         } else
3188                                 srb->state = SRB_DATA_XFER;
3189
3190                 }
3191         }
3192         srb->scsi_phase = PH_BUS_FREE;  /* initial phase */
3193
3194         /* Program HA ID, target ID, period and offset */
3195         dprintkdbg(DBG_0, "reselect: select <%i>\n", dcb->target_id);
3196         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);     /* host   ID */
3197         DC395x_write8(acb, TRM_S1040_SCSI_TARGETID, dcb->target_id);            /* target ID */
3198         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, dcb->sync_offset);            /* offset    */
3199         DC395x_write8(acb, TRM_S1040_SCSI_SYNC, dcb->sync_period);              /* sync period, wide */
3200         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_DATALATCH);              /* it's important for atn stop */
3201         /* SCSI command */
3202         DC395x_write8(acb, TRM_S1040_SCSI_COMMAND, SCMD_MSGACCEPT);
3203 }
3204
3205
3206 static inline u8 tagq_blacklist(char *name)
3207 {
3208 #ifndef DC395x_NO_TAGQ
3209 #if 0
3210         u8 i;
3211         for (i = 0; i < BADDEVCNT; i++)
3212                 if (memcmp(name, DC395x_baddevname1[i], 28) == 0)
3213                         return 1;
3214 #endif
3215         return 0;
3216 #else
3217         return 1;
3218 #endif
3219 }
3220
3221
3222 static void disc_tagq_set(struct DeviceCtlBlk *dcb, struct ScsiInqData *ptr)
3223 {
3224         /* Check for SCSI format (ANSI and Response data format) */
3225         if ((ptr->Vers & 0x07) >= 2 || (ptr->RDF & 0x0F) == 2) {
3226                 if ((ptr->Flags & SCSI_INQ_CMDQUEUE)
3227                     && (dcb->dev_mode & NTC_DO_TAG_QUEUEING) &&
3228                     /*(dcb->dev_mode & NTC_DO_DISCONNECT) */
3229                     /* ((dcb->dev_type == TYPE_DISK) 
3230                        || (dcb->dev_type == TYPE_MOD)) && */
3231                     !tagq_blacklist(((char *)ptr) + 8)) {
3232                         if (dcb->max_command == 1)
3233                                 dcb->max_command =
3234                                     dcb->acb->tag_max_num;
3235                         dcb->sync_mode |= EN_TAG_QUEUEING;
3236                         /*dcb->tag_mask = 0; */
3237                 } else
3238                         dcb->max_command = 1;
3239         }
3240 }
3241
3242
3243 static void add_dev(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
3244                 struct ScsiInqData *ptr)
3245 {
3246         u8 bval1 = ptr->DevType & SCSI_DEVTYPE;
3247         dcb->dev_type = bval1;
3248         /* if (bval1 == TYPE_DISK || bval1 == TYPE_MOD) */
3249         disc_tagq_set(dcb, ptr);
3250 }
3251
3252
3253 /* unmap mapped pci regions from SRB */
3254 static void pci_unmap_srb(struct AdapterCtlBlk *acb, struct ScsiReqBlk *srb)
3255 {
3256         struct scsi_cmnd *cmd = srb->cmd;
3257         enum dma_data_direction dir = cmd->sc_data_direction;
3258         if (cmd->use_sg && dir != PCI_DMA_NONE) {
3259                 /* unmap DC395x SG list */
3260                 dprintkdbg(DBG_SG, "pci_unmap_srb: list=%08x(%05x)\n",
3261                         srb->sg_bus_addr, SEGMENTX_LEN);
3262                 pci_unmap_single(acb->dev, srb->sg_bus_addr,
3263                                  SEGMENTX_LEN,
3264                                  PCI_DMA_TODEVICE);
3265                 dprintkdbg(DBG_SG, "pci_unmap_srb: segs=%i buffer=%p\n",
3266                         cmd->use_sg, cmd->request_buffer);
3267                 /* unmap the sg segments */
3268                 pci_unmap_sg(acb->dev,
3269                              (struct scatterlist *)cmd->request_buffer,
3270                              cmd->use_sg, dir);
3271         } else if (cmd->request_buffer && dir != PCI_DMA_NONE) {
3272                 dprintkdbg(DBG_SG, "pci_unmap_srb: buffer=%08x(%05x)\n",
3273                         srb->segment_x[0].address, cmd->request_bufflen);
3274                 pci_unmap_single(acb->dev, srb->segment_x[0].address,
3275                                  cmd->request_bufflen, dir);
3276         }
3277 }
3278
3279
3280 /* unmap mapped pci sense buffer from SRB */
3281 static void pci_unmap_srb_sense(struct AdapterCtlBlk *acb,
3282                 struct ScsiReqBlk *srb)
3283 {
3284         if (!(srb->flag & AUTO_REQSENSE))
3285                 return;
3286         /* Unmap sense buffer */
3287         dprintkdbg(DBG_SG, "pci_unmap_srb_sense: buffer=%08x\n",
3288                srb->segment_x[0].address);
3289         pci_unmap_single(acb->dev, srb->segment_x[0].address,
3290                          srb->segment_x[0].length, PCI_DMA_FROMDEVICE);
3291         /* Restore SG stuff */
3292         srb->total_xfer_length = srb->xferred;
3293         srb->segment_x[0].address =
3294             srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].address;
3295         srb->segment_x[0].length =
3296             srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].length;
3297 }
3298
3299
3300 /*
3301  * Complete execution of a SCSI command
3302  * Signal completion to the generic SCSI driver  
3303  */
3304 static void srb_done(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
3305                 struct ScsiReqBlk *srb)
3306 {
3307         u8 tempcnt, status;
3308         struct scsi_cmnd *cmd = srb->cmd;
3309         struct ScsiInqData *ptr;
3310         enum dma_data_direction dir = cmd->sc_data_direction;
3311
3312         if (cmd->use_sg) {
3313                 struct scatterlist* sg = (struct scatterlist *)cmd->request_buffer;
3314                 ptr = (struct ScsiInqData *)(page_address(sg->page) + sg->offset);
3315         } else {
3316                 ptr = (struct ScsiInqData *)(cmd->request_buffer);
3317         }
3318
3319         dprintkdbg(DBG_1, "srb_done: (pid#%li) <%02i-%i>\n", srb->cmd->pid,
3320                 srb->cmd->device->id, srb->cmd->device->lun);
3321         dprintkdbg(DBG_SG, "srb_done: srb=%p sg=%i(%i/%i) buf=%p addr=%p\n",
3322                 srb, cmd->use_sg, srb->sg_index, srb->sg_count,
3323                 cmd->request_buffer, ptr);
3324         status = srb->target_status;
3325         if (srb->flag & AUTO_REQSENSE) {
3326                 dprintkdbg(DBG_0, "srb_done: AUTO_REQSENSE1\n");
3327                 pci_unmap_srb_sense(acb, srb);
3328                 /*
3329                  ** target status..........................
3330                  */
3331                 srb->flag &= ~AUTO_REQSENSE;
3332                 srb->adapter_status = 0;
3333                 srb->target_status = CHECK_CONDITION << 1;
3334                 if (debug_enabled(DBG_1)) {
3335                         switch (cmd->sense_buffer[2] & 0x0f) {
3336                         case NOT_READY:
3337                                 dprintkl(KERN_DEBUG,
3338                                      "ReqSense: NOT_READY cmnd=0x%02x <%02i-%i> stat=%i scan=%i ",
3339                                      cmd->cmnd[0], dcb->target_id,
3340                                      dcb->target_lun, status, acb->scan_devices);
3341                                 break;
3342                         case UNIT_ATTENTION:
3343                                 dprintkl(KERN_DEBUG,
3344                                      "ReqSense: UNIT_ATTENTION cmnd=0x%02x <%02i-%i> stat=%i scan=%i ",
3345                                      cmd->cmnd[0], dcb->target_id,
3346                                      dcb->target_lun, status, acb->scan_devices);
3347                                 break;
3348                         case ILLEGAL_REQUEST:
3349                                 dprintkl(KERN_DEBUG,
3350                                      "ReqSense: ILLEGAL_REQUEST cmnd=0x%02x <%02i-%i> stat=%i scan=%i ",
3351                                      cmd->cmnd[0], dcb->target_id,
3352                                      dcb->target_lun, status, acb->scan_devices);
3353                                 break;
3354                         case MEDIUM_ERROR:
3355                                 dprintkl(KERN_DEBUG,
3356                                      "ReqSense: MEDIUM_ERROR cmnd=0x%02x <%02i-%i> stat=%i scan=%i ",
3357                                      cmd->cmnd[0], dcb->target_id,
3358                                      dcb->target_lun, status, acb->scan_devices);
3359                                 break;
3360                         case HARDWARE_ERROR:
3361                                 dprintkl(KERN_DEBUG,
3362                                      "ReqSense: HARDWARE_ERROR cmnd=0x%02x <%02i-%i> stat=%i scan=%i ",
3363                                      cmd->cmnd[0], dcb->target_id,
3364                                      dcb->target_lun, status, acb->scan_devices);
3365                                 break;
3366                         }
3367                         if (cmd->sense_buffer[7] >= 6)
3368                                 printk("sense=0x%02x ASC=0x%02x ASCQ=0x%02x "
3369                                         "(0x%08x 0x%08x)\n",
3370                                         cmd->sense_buffer[2], cmd->sense_buffer[12],
3371                                         cmd->sense_buffer[13],
3372                                         *((unsigned int *)(cmd->sense_buffer + 3)),
3373                                         *((unsigned int *)(cmd->sense_buffer + 8)));
3374                         else
3375                                 printk("sense=0x%02x No ASC/ASCQ (0x%08x)\n",
3376                                         cmd->sense_buffer[2],
3377                                         *((unsigned int *)(cmd->sense_buffer + 3)));
3378                 }
3379
3380                 if (status == (CHECK_CONDITION << 1)) {
3381                         cmd->result = DID_BAD_TARGET << 16;
3382                         goto ckc_e;
3383                 }
3384                 dprintkdbg(DBG_0, "srb_done: AUTO_REQSENSE2\n");
3385
3386                 if (srb->total_xfer_length
3387                     && srb->total_xfer_length >= cmd->underflow)
3388                         cmd->result =
3389                             MK_RES_LNX(DRIVER_SENSE, DID_OK,
3390                                        srb->end_message, CHECK_CONDITION);
3391                 /*SET_RES_DID(cmd->result,DID_OK) */
3392                 else
3393                         cmd->result =
3394                             MK_RES_LNX(DRIVER_SENSE, DID_OK,
3395                                        srb->end_message, CHECK_CONDITION);
3396
3397                 goto ckc_e;
3398         }
3399
3400 /*************************************************************/
3401         if (status) {
3402                 /*
3403                  * target status..........................
3404                  */
3405                 if (status_byte(status) == CHECK_CONDITION) {
3406                         request_sense(acb, dcb, srb);
3407                         return;
3408                 } else if (status_byte(status) == QUEUE_FULL) {
3409                         tempcnt = (u8)list_size(&dcb->srb_going_list);
3410                         dprintkl(KERN_INFO, "QUEUE_FULL for dev <%02i-%i> with %i cmnds\n",
3411                              dcb->target_id, dcb->target_lun, tempcnt);
3412                         if (tempcnt > 1)
3413                                 tempcnt--;
3414                         dcb->max_command = tempcnt;
3415                         free_tag(dcb, srb);
3416                         srb_going_to_waiting_move(dcb, srb);
3417                         waiting_set_timer(acb, HZ / 20);
3418                         srb->adapter_status = 0;
3419                         srb->target_status = 0;
3420                         return;
3421                 } else if (status == SCSI_STAT_SEL_TIMEOUT) {
3422                         srb->adapter_status = H_SEL_TIMEOUT;
3423                         srb->target_status = 0;
3424                         cmd->result = DID_NO_CONNECT << 16;
3425                 } else {
3426                         srb->adapter_status = 0;
3427                         SET_RES_DID(cmd->result, DID_ERROR);
3428                         SET_RES_MSG(cmd->result, srb->end_message);
3429                         SET_RES_TARGET(cmd->result, status);
3430
3431                 }
3432         } else {
3433                 /*
3434                  ** process initiator status..........................
3435                  */
3436                 status = srb->adapter_status;
3437                 if (status & H_OVER_UNDER_RUN) {
3438                         srb->target_status = 0;
3439                         SET_RES_DID(cmd->result, DID_OK);
3440                         SET_RES_MSG(cmd->result, srb->end_message);
3441                 } else if (srb->status & PARITY_ERROR) {
3442                         SET_RES_DID(cmd->result, DID_PARITY);
3443                         SET_RES_MSG(cmd->result, srb->end_message);
3444                 } else {        /* No error */
3445
3446                         srb->adapter_status = 0;
3447                         srb->target_status = 0;
3448                         SET_RES_DID(cmd->result, DID_OK);
3449                 }
3450         }
3451
3452         if (dir != PCI_DMA_NONE) {
3453                 if (cmd->use_sg)
3454                         pci_dma_sync_sg_for_cpu(acb->dev,
3455                                         (struct scatterlist *)cmd->
3456                                         request_buffer, cmd->use_sg, dir);
3457                 else if (cmd->request_buffer)
3458                         pci_dma_sync_single_for_cpu(acb->dev,
3459                                             srb->segment_x[0].address,
3460                                             cmd->request_bufflen, dir);
3461         }
3462
3463         if ((cmd->result & RES_DID) == 0 && cmd->cmnd[0] == INQUIRY
3464             && cmd->cmnd[2] == 0 && cmd->request_bufflen >= 8
3465             && dir != PCI_DMA_NONE && ptr && (ptr->Vers & 0x07) >= 2)
3466                 dcb->inquiry7 = ptr->Flags;
3467 /* Check Error Conditions */
3468       ckc_e:
3469
3470         /*if( srb->cmd->cmnd[0] == INQUIRY && */
3471         /*  (host_byte(cmd->result) == DID_OK || status_byte(cmd->result) & CHECK_CONDITION) ) */
3472         if (cmd->cmnd[0] == INQUIRY && (cmd->result == (DID_OK << 16)
3473                                          || status_byte(cmd->
3474                                                         result) &
3475                                          CHECK_CONDITION)) {
3476
3477                 if (!dcb->init_tcq_flag) {
3478                         add_dev(acb, dcb, ptr);
3479                         dcb->init_tcq_flag = 1;
3480                 }
3481
3482         }
3483
3484
3485         /* Here is the info for Doug Gilbert's sg3 ... */
3486         cmd->resid = srb->total_xfer_length;
3487         /* This may be interpreted by sb. or not ... */
3488         cmd->SCp.this_residual = srb->total_xfer_length;
3489         cmd->SCp.buffers_residual = 0;
3490         if (debug_enabled(DBG_KG)) {
3491                 if (srb->total_xfer_length)
3492                         dprintkdbg(DBG_KG, "srb_done: (pid#%li) <%02i-%i> "
3493                                 "cmnd=0x%02x Missed %i bytes\n",
3494                                 cmd->pid, cmd->device->id, cmd->device->lun,
3495                                 cmd->cmnd[0], srb->total_xfer_length);
3496         }
3497
3498         srb_going_remove(dcb, srb);
3499         /* Add to free list */
3500         if (srb == acb->tmp_srb)
3501                 dprintkl(KERN_ERR, "srb_done: ERROR! Completed cmd with tmp_srb\n");
3502         else {
3503                 dprintkdbg(DBG_0, "srb_done: (pid#%li) done result=0x%08x\n",
3504                         cmd->pid, cmd->result);
3505                 srb_free_insert(acb, srb);
3506         }
3507         pci_unmap_srb(acb, srb);
3508
3509         cmd->scsi_done(cmd);
3510         waiting_process_next(acb);
3511 }
3512
3513
3514 /* abort all cmds in our queues */
3515 static void doing_srb_done(struct AdapterCtlBlk *acb, u8 did_flag,
3516                 struct scsi_cmnd *cmd, u8 force)
3517 {
3518         struct DeviceCtlBlk *dcb;
3519         dprintkl(KERN_INFO, "doing_srb_done: pids ");
3520
3521         list_for_each_entry(dcb, &acb->dcb_list, list) {
3522                 struct ScsiReqBlk *srb;
3523                 struct ScsiReqBlk *tmp;
3524                 struct scsi_cmnd *p;
3525
3526                 list_for_each_entry_safe(srb, tmp, &dcb->srb_going_list, list) {
3527                         enum dma_data_direction dir;
3528                         int result;
3529
3530                         p = srb->cmd;
3531                         dir = p->sc_data_direction;
3532                         result = MK_RES(0, did_flag, 0, 0);
3533                         printk("G:%li(%02i-%i) ", p->pid,
3534                                p->device->id, p->device->lun);
3535                         srb_going_remove(dcb, srb);
3536                         free_tag(dcb, srb);
3537                         srb_free_insert(acb, srb);
3538                         p->result = result;
3539                         pci_unmap_srb_sense(acb, srb);
3540                         pci_unmap_srb(acb, srb);
3541                         if (force) {
3542                                 /* For new EH, we normally don't need to give commands back,
3543                                  * as they all complete or all time out */
3544                                 p->scsi_done(p);
3545                         }
3546                 }
3547                 if (!list_empty(&dcb->srb_going_list))
3548                         dprintkl(KERN_DEBUG, 
3549                                "How could the ML send cmnds to the Going queue? <%02i-%i>\n",
3550                                dcb->target_id, dcb->target_lun);
3551                 if (dcb->tag_mask)
3552                         dprintkl(KERN_DEBUG,
3553                                "tag_mask for <%02i-%i> should be empty, is %08x!\n",
3554                                dcb->target_id, dcb->target_lun,
3555                                dcb->tag_mask);
3556
3557                 /* Waiting queue */
3558                 list_for_each_entry_safe(srb, tmp, &dcb->srb_waiting_list, list) {
3559                         int result;
3560                         p = srb->cmd;
3561
3562                         result = MK_RES(0, did_flag, 0, 0);
3563                         printk("W:%li<%02i-%i>", p->pid, p->device->id,
3564                                p->device->lun);
3565                         srb_waiting_remove(dcb, srb);
3566                         srb_free_insert(acb, srb);
3567                         p->result = result;
3568                         pci_unmap_srb_sense(acb, srb);
3569                         pci_unmap_srb(acb, srb);
3570                         if (force) {
3571                                 /* For new EH, we normally don't need to give commands back,
3572                                  * as they all complete or all time out */
3573                                 cmd->scsi_done(cmd);
3574                         }
3575                 }
3576                 if (!list_empty(&dcb->srb_waiting_list))
3577                         dprintkl(KERN_DEBUG, "ML queued %i cmnds again to <%02i-%i>\n",
3578                              list_size(&dcb->srb_waiting_list), dcb->target_id,
3579                              dcb->target_lun);
3580                 dcb->flag &= ~ABORT_DEV_;
3581         }
3582         printk("\n");
3583 }
3584
3585
3586 static void reset_scsi_bus(struct AdapterCtlBlk *acb)
3587 {
3588         dprintkdbg(DBG_0, "reset_scsi_bus: acb=%p\n", acb);
3589         acb->acb_flag |= RESET_DEV;     /* RESET_DETECT, RESET_DONE, RESET_DEV */
3590         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_RSTSCSI);
3591
3592         while (!(DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS) & INT_SCSIRESET))
3593                 /* nothing */;
3594 }
3595
3596
3597 static void set_basic_config(struct AdapterCtlBlk *acb)
3598 {
3599         u8 bval;
3600         u16 wval;
3601         DC395x_write8(acb, TRM_S1040_SCSI_TIMEOUT, acb->sel_timeout);
3602         if (acb->config & HCC_PARITY)
3603                 bval = PHASELATCH | INITIATOR | BLOCKRST | PARITYCHECK;
3604         else
3605                 bval = PHASELATCH | INITIATOR | BLOCKRST;
3606
3607         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG0, bval);
3608
3609         /* program configuration 1: Act_Neg (+ Act_Neg_Enh? + Fast_Filter? + DataDis?) */
3610         DC395x_write8(acb, TRM_S1040_SCSI_CONFIG1, 0x03);       /* was 0x13: default */
3611         /* program Host ID                  */
3612         DC395x_write8(acb, TRM_S1040_SCSI_HOSTID, acb->scsi_host->this_id);
3613         /* set ansynchronous transfer       */
3614         DC395x_write8(acb, TRM_S1040_SCSI_OFFSET, 0x00);
3615         /* Turn LED control off */
3616         wval = DC395x_read16(acb, TRM_S1040_GEN_CONTROL) & 0x7F;
3617         DC395x_write16(acb, TRM_S1040_GEN_CONTROL, wval);
3618         /* DMA config          */
3619         wval = DC395x_read16(acb, TRM_S1040_DMA_CONFIG) & ~DMA_FIFO_CTRL;
3620         wval |=
3621             DMA_FIFO_HALF_HALF | DMA_ENHANCE /*| DMA_MEM_MULTI_READ */ ;
3622         DC395x_write16(acb, TRM_S1040_DMA_CONFIG, wval);
3623         /* Clear pending interrupt status */
3624         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
3625         /* Enable SCSI interrupt    */
3626         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x7F);
3627         DC395x_write8(acb, TRM_S1040_DMA_INTEN, EN_SCSIINTR | EN_DMAXFERERROR
3628                       /*| EN_DMAXFERABORT | EN_DMAXFERCOMP | EN_FORCEDMACOMP */
3629                       );
3630 }
3631
3632
3633 static void scsi_reset_detect(struct AdapterCtlBlk *acb)
3634 {
3635         dprintkl(KERN_INFO, "scsi_reset_detect: acb=%p\n", acb);
3636         /* delay half a second */
3637         if (timer_pending(&acb->waiting_timer))
3638                 del_timer(&acb->waiting_timer);
3639
3640         DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
3641         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
3642         /*DC395x_write8(acb, TRM_S1040_DMA_CONTROL,STOPDMAXFER); */
3643         udelay(500);
3644         /* Maybe we locked up the bus? Then lets wait even longer ... */
3645         acb->scsi_host->last_reset =
3646             jiffies + 5 * HZ / 2 +
3647             HZ * acb->eeprom.delay_time;
3648
3649         clear_fifo(acb, "scsi_reset_detect");
3650         set_basic_config(acb);
3651         /*1.25 */
3652         /*DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_HWRESELECT); */
3653
3654         if (acb->acb_flag & RESET_DEV) {        /* RESET_DETECT, RESET_DONE, RESET_DEV */
3655                 acb->acb_flag |= RESET_DONE;
3656         } else {
3657                 acb->acb_flag |= RESET_DETECT;
3658                 reset_dev_param(acb);
3659                 doing_srb_done(acb, DID_RESET, 0, 1);
3660                 /*DC395x_RecoverSRB( acb ); */
3661                 acb->active_dcb = NULL;
3662                 acb->acb_flag = 0;
3663                 waiting_process_next(acb);
3664         }
3665 }
3666
3667
3668 static void request_sense(struct AdapterCtlBlk *acb, struct DeviceCtlBlk *dcb,
3669                 struct ScsiReqBlk *srb)
3670 {
3671         struct scsi_cmnd *cmd = srb->cmd;
3672         dprintkdbg(DBG_1, "request_sense: (pid#%li) <%02i-%i>\n",
3673                 cmd->pid, cmd->device->id, cmd->device->lun);
3674
3675         srb->flag |= AUTO_REQSENSE;
3676         srb->adapter_status = 0;
3677         srb->target_status = 0;
3678
3679         /* KG: Can this prevent crap sense data ? */
3680         memset(cmd->sense_buffer, 0, sizeof(cmd->sense_buffer));
3681
3682         /* Save some data */
3683         srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].address =
3684             srb->segment_x[0].address;
3685         srb->segment_x[DC395x_MAX_SG_LISTENTRY - 1].length =
3686             srb->segment_x[0].length;
3687         srb->xferred = srb->total_xfer_length;
3688         /* srb->segment_x : a one entry of S/G list table */
3689         srb->total_xfer_length = sizeof(cmd->sense_buffer);
3690         srb->segment_x[0].length = sizeof(cmd->sense_buffer);
3691         /* Map sense buffer */
3692         srb->segment_x[0].address =
3693             pci_map_single(acb->dev, cmd->sense_buffer,
3694                            sizeof(cmd->sense_buffer), PCI_DMA_FROMDEVICE);
3695         dprintkdbg(DBG_SG, "request_sense: map buffer %p->%08x(%05x)\n",
3696                cmd->sense_buffer, srb->segment_x[0].address,
3697                sizeof(cmd->sense_buffer));
3698         srb->sg_count = 1;
3699         srb->sg_index = 0;
3700
3701         if (start_scsi(acb, dcb, srb)) {        /* Should only happen, if sb. else grabs the bus */
3702                 dprintkl(KERN_DEBUG,
3703                         "request_sense: (pid#%li) failed <%02i-%i>\n",
3704                         srb->cmd->pid, dcb->target_id, dcb->target_lun);
3705                 srb_going_to_waiting_move(dcb, srb);
3706                 waiting_set_timer(acb, HZ / 100);
3707         }
3708 }
3709
3710
3711 /**
3712  * device_alloc - Allocate a new device instance. This create the
3713  * devices instance and sets up all the data items. The adapter
3714  * instance is required to obtain confiuration information for this
3715  * device. This does *not* add this device to the adapters device
3716  * list.
3717  *
3718  * @acb: The adapter to obtain configuration information from.
3719  * @target: The target for the new device.
3720  * @lun: The lun for the new device.
3721  *
3722  * Return the new device if succesfull or NULL on failure.
3723  **/
3724 static struct DeviceCtlBlk *device_alloc(struct AdapterCtlBlk *acb,
3725                 u8 target, u8 lun)
3726 {
3727         struct NvRamType *eeprom = &acb->eeprom;
3728         u8 period_index = eeprom->target[target].period & 0x07;
3729         struct DeviceCtlBlk *dcb;
3730
3731         dcb = kmalloc(sizeof(struct DeviceCtlBlk), GFP_ATOMIC);
3732         dprintkdbg(DBG_0, "device_alloc: <%02i-%i>\n", target, lun);
3733         if (!dcb)
3734                 return NULL;
3735         dcb->acb = NULL;
3736         INIT_LIST_HEAD(&dcb->srb_going_list);
3737         INIT_LIST_HEAD(&dcb->srb_waiting_list);
3738         dcb->active_srb = NULL;
3739         dcb->tag_mask = 0;
3740         dcb->max_command = 1;
3741         dcb->target_id = target;
3742         dcb->target_lun = lun;
3743 #ifndef DC395x_NO_DISCONNECT
3744         dcb->identify_msg =
3745             IDENTIFY(dcb->dev_mode & NTC_DO_DISCONNECT, lun);
3746 #else
3747         dcb->identify_msg = IDENTIFY(0, lun);
3748 #endif
3749         dcb->dev_mode = eeprom->target[target].cfg0;
3750         dcb->inquiry7 = 0;
3751         dcb->sync_mode = 0;
3752         dcb->min_nego_period = clock_period[period_index];
3753         dcb->sync_period = 0;
3754         dcb->sync_offset = 0;
3755         dcb->flag = 0;
3756
3757 #ifndef DC395x_NO_WIDE
3758         if ((dcb->dev_mode & NTC_DO_WIDE_NEGO)
3759             && (acb->config & HCC_WIDE_CARD))
3760                 dcb->sync_mode |= WIDE_NEGO_ENABLE;
3761 #endif
3762 #ifndef DC395x_NO_SYNC
3763         if (dcb->dev_mode & NTC_DO_SYNC_NEGO)
3764                 if (!(lun) || current_sync_offset)
3765                         dcb->sync_mode |= SYNC_NEGO_ENABLE;
3766 #endif
3767         if (dcb->target_lun != 0) {
3768                 /* Copy settings */
3769                 struct DeviceCtlBlk *p;
3770                 list_for_each_entry(p, &acb->dcb_list, list)
3771                         if (p->target_id == dcb->target_id)
3772                                 break;
3773                 dprintkdbg(DBG_1, 
3774                        "device_alloc: <%02i-%i> copy from <%02i-%i>\n",
3775                        dcb->target_id, dcb->target_lun,
3776                        p->target_id, p->target_lun);
3777                 dcb->sync_mode = p->sync_mode;
3778                 dcb->sync_period = p->sync_period;
3779                 dcb->min_nego_period = p->min_nego_period;
3780                 dcb->sync_offset = p->sync_offset;
3781                 dcb->inquiry7 = p->inquiry7;
3782         }
3783         return dcb;
3784 }
3785
3786
3787 /**
3788  * adapter_add_device - Adds the device instance to the adaptor instance.
3789  *
3790  * @acb: The adapter device to be updated
3791  * @dcb: A newly created and intialised device instance to add.
3792  **/
3793 static void adapter_add_device(struct AdapterCtlBlk *acb,
3794                 struct DeviceCtlBlk *dcb)
3795 {
3796         /* backpointer to adapter */
3797         dcb->acb = acb;
3798         
3799         /* set run_robin to this device if it is currently empty */
3800         if (list_empty(&acb->dcb_list))
3801                 acb->dcb_run_robin = dcb;
3802
3803         /* add device to list */
3804         list_add_tail(&dcb->list, &acb->dcb_list);
3805
3806         /* update device maps */
3807         acb->dcb_map[dcb->target_id] |= (1 << dcb->target_lun);
3808         acb->children[dcb->target_id][dcb->target_lun] = dcb;
3809 }
3810
3811
3812 /**
3813  * adapter_remove_device - Removes the device instance from the adaptor
3814  * instance. The device instance is not check in any way or freed by this. 
3815  * The caller is expected to take care of that. This will simply remove the
3816  * device from the adapters data strcutures.
3817  *
3818  * @acb: The adapter device to be updated
3819  * @dcb: A device that has previously been added to the adapter.
3820  **/
3821 static void adapter_remove_device(struct AdapterCtlBlk *acb,
3822                 struct DeviceCtlBlk *dcb)
3823 {
3824         struct DeviceCtlBlk *i;
3825         struct DeviceCtlBlk *tmp;
3826         dprintkdbg(DBG_0, "adapter_remove_device: <%02i-%i>\n",
3827                 dcb->target_id, dcb->target_lun);
3828
3829         /* fix up any pointers to this device that we have in the adapter */
3830         if (acb->active_dcb == dcb)
3831                 acb->active_dcb = NULL;
3832         if (acb->dcb_run_robin == dcb)
3833                 acb->dcb_run_robin = dcb_get_next(&acb->dcb_list, dcb);
3834
3835         /* unlink from list */
3836         list_for_each_entry_safe(i, tmp, &acb->dcb_list, list)
3837                 if (dcb == i) {
3838                         list_del(&i->list);
3839                         break;
3840                 }
3841
3842         /* clear map and children */    
3843         acb->dcb_map[dcb->target_id] &= ~(1 << dcb->target_lun);
3844         acb->children[dcb->target_id][dcb->target_lun] = NULL;
3845         dcb->acb = NULL;
3846 }
3847
3848
3849 /**
3850  * adapter_remove_and_free_device - Removes a single device from the adapter
3851  * and then frees the device information.
3852  *
3853  * @acb: The adapter device to be updated
3854  * @dcb: A device that has previously been added to the adapter.
3855  */
3856 static void adapter_remove_and_free_device(struct AdapterCtlBlk *acb,
3857                 struct DeviceCtlBlk *dcb)
3858 {
3859         if (list_size(&dcb->srb_going_list) > 1) {
3860                 dprintkdbg(DBG_1, "adapter_remove_and_free_device: <%02i-%i> "
3861                            "Won't remove because of %i active requests.\n",
3862                            dcb->target_id, dcb->target_lun,
3863                            list_size(&dcb->srb_going_list));
3864                 return;
3865         }
3866         adapter_remove_device(acb, dcb);
3867         kfree(dcb);
3868 }
3869
3870
3871 /**
3872  * adapter_remove_and_free_all_devices - Removes and frees all of the
3873  * devices associated with the specified adapter.
3874  *
3875  * @acb: The adapter from which all devices should be removed.
3876  **/
3877 static void adapter_remove_and_free_all_devices(struct AdapterCtlBlk* acb)
3878 {
3879         struct DeviceCtlBlk *dcb;
3880         struct DeviceCtlBlk *tmp;
3881         dprintkdbg(DBG_1, "adapter_remove_and_free_all_devices: num=%i\n",
3882                    list_size(&acb->dcb_list));
3883
3884         list_for_each_entry_safe(dcb, tmp, &acb->dcb_list, list)
3885                 adapter_remove_and_free_device(acb, dcb);
3886 }
3887
3888
3889 /**
3890  * dc395x_slave_alloc - Called by the scsi mid layer to tell us about a new
3891  * scsi device that we need to deal with. We allocate a new device and then
3892  * insert that device into the adapters device list.
3893  *
3894  * @scsi_device: The new scsi device that we need to handle.
3895  **/
3896 static int dc395x_slave_alloc(struct scsi_device *scsi_device)
3897 {
3898         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)scsi_device->host->hostdata;
3899         struct DeviceCtlBlk *dcb;
3900
3901         dcb = device_alloc(acb, scsi_device->id, scsi_device->lun);
3902         if (!dcb)
3903                 return -ENOMEM;
3904         adapter_add_device(acb, dcb);
3905
3906         return 0;
3907 }
3908
3909
3910 /**
3911  * dc395x_slave_destroy - Called by the scsi mid layer to tell us about a
3912  * device that is going away.
3913  *
3914  * @scsi_device: The new scsi device that we need to handle.
3915  **/
3916 static void dc395x_slave_destroy(struct scsi_device *scsi_device)
3917 {
3918         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)scsi_device->host->hostdata;
3919         struct DeviceCtlBlk *dcb = find_dcb(acb, scsi_device->id, scsi_device->lun);
3920         if (dcb)
3921                 adapter_remove_and_free_device(acb, dcb);
3922 }
3923
3924
3925
3926
3927 /**
3928  * trms1040_wait_30us: wait for 30 us
3929  *
3930  * Waits for 30us (using the chip by the looks of it..)
3931  *
3932  * @io_port: base I/O address
3933  **/
3934 static void __init trms1040_wait_30us(u16 io_port)
3935 {
3936         /* ScsiPortStallExecution(30); wait 30 us */
3937         outb(5, io_port + TRM_S1040_GEN_TIMER);
3938         while (!(inb(io_port + TRM_S1040_GEN_STATUS) & GTIMEOUT))
3939                 /* nothing */ ;
3940 }
3941
3942
3943 /**
3944  * trms1040_write_cmd - write the secified command and address to
3945  * chip
3946  *
3947  * @io_port:    base I/O address
3948  * @cmd:        SB + op code (command) to send
3949  * @addr:       address to send
3950  **/
3951 static void __init trms1040_write_cmd(u16 io_port, u8 cmd, u8 addr)
3952 {
3953         int i;
3954         u8 send_data;
3955
3956         /* program SB + OP code */
3957         for (i = 0; i < 3; i++, cmd <<= 1) {
3958                 send_data = NVR_SELECT;
3959                 if (cmd & 0x04) /* Start from bit 2 */
3960                         send_data |= NVR_BITOUT;
3961
3962                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
3963                 trms1040_wait_30us(io_port);
3964                 outb((send_data | NVR_CLOCK),
3965                      io_port + TRM_S1040_GEN_NVRAM);
3966                 trms1040_wait_30us(io_port);
3967         }
3968
3969         /* send address */
3970         for (i = 0; i < 7; i++, addr <<= 1) {
3971                 send_data = NVR_SELECT;
3972                 if (addr & 0x40)        /* Start from bit 6 */
3973                         send_data |= NVR_BITOUT;
3974
3975                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
3976                 trms1040_wait_30us(io_port);
3977                 outb((send_data | NVR_CLOCK),
3978                      io_port + TRM_S1040_GEN_NVRAM);
3979                 trms1040_wait_30us(io_port);
3980         }
3981         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
3982         trms1040_wait_30us(io_port);
3983 }
3984
3985
3986 /**
3987  * trms1040_set_data - store a single byte in the eeprom
3988  *
3989  * Called from write all to write a single byte into the SSEEPROM
3990  * Which is done one bit at a time.
3991  *
3992  * @io_port:    base I/O address
3993  * @addr:       offset into EEPROM
3994  * @byte:       bytes to write
3995  **/
3996 static void __init trms1040_set_data(u16 io_port, u8 addr, u8 byte)
3997 {
3998         int i;
3999         u8 send_data;
4000
4001         /* Send write command & address */
4002         trms1040_write_cmd(io_port, 0x05, addr);
4003
4004         /* Write data */
4005         for (i = 0; i < 8; i++, byte <<= 1) {
4006                 send_data = NVR_SELECT;
4007                 if (byte & 0x80)        /* Start from bit 7 */
4008                         send_data |= NVR_BITOUT;
4009
4010                 outb(send_data, io_port + TRM_S1040_GEN_NVRAM);
4011                 trms1040_wait_30us(io_port);
4012                 outb((send_data | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
4013                 trms1040_wait_30us(io_port);
4014         }
4015         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
4016         trms1040_wait_30us(io_port);
4017
4018         /* Disable chip select */
4019         outb(0, io_port + TRM_S1040_GEN_NVRAM);
4020         trms1040_wait_30us(io_port);
4021
4022         outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
4023         trms1040_wait_30us(io_port);
4024
4025         /* Wait for write ready */
4026         while (1) {
4027                 outb((NVR_SELECT | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
4028                 trms1040_wait_30us(io_port);
4029
4030                 outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
4031                 trms1040_wait_30us(io_port);
4032
4033                 if (inb(io_port + TRM_S1040_GEN_NVRAM) & NVR_BITIN)
4034                         break;
4035         }
4036
4037         /*  Disable chip select */
4038         outb(0, io_port + TRM_S1040_GEN_NVRAM);
4039 }
4040
4041
4042 /**
4043  * trms1040_write_all - write 128 bytes to the eeprom
4044  *
4045  * Write the supplied 128 bytes to the chips SEEPROM
4046  *
4047  * @eeprom:     the data to write
4048  * @io_port:    the base io port
4049  **/
4050 static void __init trms1040_write_all(struct NvRamType *eeprom, u16 io_port)
4051 {
4052         u8 *b_eeprom = (u8 *)eeprom;
4053         u8 addr;
4054
4055         /* Enable SEEPROM */
4056         outb((inb(io_port + TRM_S1040_GEN_CONTROL) | EN_EEPROM),
4057              io_port + TRM_S1040_GEN_CONTROL);
4058
4059         /* write enable */
4060         trms1040_write_cmd(io_port, 0x04, 0xFF);
4061         outb(0, io_port + TRM_S1040_GEN_NVRAM);
4062         trms1040_wait_30us(io_port);
4063
4064         /* write */
4065         for (addr = 0; addr < 128; addr++, b_eeprom++)
4066                 trms1040_set_data(io_port, addr, *b_eeprom);
4067
4068         /* write disable */
4069         trms1040_write_cmd(io_port, 0x04, 0x00);
4070         outb(0, io_port + TRM_S1040_GEN_NVRAM);
4071         trms1040_wait_30us(io_port);
4072
4073         /* Disable SEEPROM */
4074         outb((inb(io_port + TRM_S1040_GEN_CONTROL) & ~EN_EEPROM),
4075              io_port + TRM_S1040_GEN_CONTROL);
4076 }
4077
4078
4079 /**
4080  * trms1040_get_data - get a single byte from the eeprom
4081  *
4082  * Called from read all to read a single byte into the SSEEPROM
4083  * Which is done one bit at a time.
4084  *
4085  * @io_port:    base I/O address
4086  * @addr:       offset into SEEPROM
4087  *
4088  * Returns the the byte read.
4089  **/
4090 static u8 __init trms1040_get_data(u16 io_port, u8 addr)
4091 {
4092         int i;
4093         u8 read_byte;
4094         u8 result = 0;
4095
4096         /* Send read command & address */
4097         trms1040_write_cmd(io_port, 0x06, addr);
4098
4099         /* read data */
4100         for (i = 0; i < 8; i++) {
4101                 outb((NVR_SELECT | NVR_CLOCK), io_port + TRM_S1040_GEN_NVRAM);
4102                 trms1040_wait_30us(io_port);
4103                 outb(NVR_SELECT, io_port + TRM_S1040_GEN_NVRAM);
4104
4105                 /* Get data bit while falling edge */
4106                 read_byte = inb(io_port + TRM_S1040_GEN_NVRAM);
4107                 result <<= 1;
4108                 if (read_byte & NVR_BITIN)
4109                         result |= 1;
4110
4111                 trms1040_wait_30us(io_port);
4112         }
4113
4114         /* Disable chip select */
4115         outb(0, io_port + TRM_S1040_GEN_NVRAM);
4116         return result;
4117 }
4118
4119
4120 /**
4121  * trms1040_read_all - read all bytes from the eeprom
4122  *
4123  * Read the 128 bytes from the SEEPROM.
4124  *
4125  * @eeprom:     where to store the data
4126  * @io_port:    the base io port
4127  **/
4128 static void __init trms1040_read_all(struct NvRamType *eeprom, u16 io_port)
4129 {
4130         u8 *b_eeprom = (u8 *)eeprom;
4131         u8 addr;
4132
4133         /* Enable SEEPROM */
4134         outb((inb(io_port + TRM_S1040_GEN_CONTROL) | EN_EEPROM),
4135              io_port + TRM_S1040_GEN_CONTROL);
4136
4137         /* read details */
4138         for (addr = 0; addr < 128; addr++, b_eeprom++)
4139                 *b_eeprom = trms1040_get_data(io_port, addr);
4140
4141         /* Disable SEEPROM */
4142         outb((inb(io_port + TRM_S1040_GEN_CONTROL) & ~EN_EEPROM),
4143              io_port + TRM_S1040_GEN_CONTROL);
4144 }
4145
4146
4147
4148 /**
4149  * check_eeprom - get and check contents of the eeprom
4150  *
4151  * Read seeprom 128 bytes into the memory provider in eeprom.
4152  * Checks the checksum and if it's not correct it uses a set of default
4153  * values.
4154  *
4155  * @eeprom:     caller allocated strcuture to read the eeprom data into
4156  * @io_port:    io port to read from
4157  **/
4158 static void __init check_eeprom(struct NvRamType *eeprom, u16 io_port)
4159 {
4160         u16 *w_eeprom = (u16 *)eeprom;
4161         u16 w_addr;
4162         u16 cksum;
4163         u32 d_addr;
4164         u32 *d_eeprom;
4165
4166         trms1040_read_all(eeprom, io_port);     /* read eeprom */
4167
4168         cksum = 0;
4169         for (w_addr = 0, w_eeprom = (u16 *)eeprom; w_addr < 64;
4170              w_addr++, w_eeprom++)
4171                 cksum += *w_eeprom;
4172         if (cksum != 0x1234) {
4173                 /*
4174                  * Checksum is wrong.
4175                  * Load a set of defaults into the eeprom buffer
4176                  */
4177                 dprintkl(KERN_WARNING,
4178                         "EEProm checksum error: using default values and options.\n");
4179                 eeprom->sub_vendor_id[0] = (u8)PCI_VENDOR_ID_TEKRAM;
4180                 eeprom->sub_vendor_id[1] = (u8)(PCI_VENDOR_ID_TEKRAM >> 8);
4181                 eeprom->sub_sys_id[0] = (u8)PCI_DEVICE_ID_TEKRAM_TRMS1040;
4182                 eeprom->sub_sys_id[1] =
4183                     (u8)(PCI_DEVICE_ID_TEKRAM_TRMS1040 >> 8);
4184                 eeprom->sub_class = 0x00;
4185                 eeprom->vendor_id[0] = (u8)PCI_VENDOR_ID_TEKRAM;
4186                 eeprom->vendor_id[1] = (u8)(PCI_VENDOR_ID_TEKRAM >> 8);
4187                 eeprom->device_id[0] = (u8)PCI_DEVICE_ID_TEKRAM_TRMS1040;
4188                 eeprom->device_id[1] =
4189                     (u8)(PCI_DEVICE_ID_TEKRAM_TRMS1040 >> 8);
4190                 eeprom->reserved = 0x00;
4191
4192                 for (d_addr = 0, d_eeprom = (u32 *)eeprom->target;
4193                      d_addr < 16; d_addr++, d_eeprom++)
4194                         *d_eeprom = 0x00000077; /* cfg3,cfg2,period,cfg0 */
4195
4196                 *d_eeprom++ = 0x04000F07;       /* max_tag,delay_time,channel_cfg,scsi_id */
4197                 *d_eeprom++ = 0x00000015;       /* reserved1,boot_lun,boot_target,reserved0 */
4198                 for (d_addr = 0; d_addr < 12; d_addr++, d_eeprom++)
4199                         *d_eeprom = 0x00;
4200
4201                 /* Now load defaults (maybe set by boot/module params) */
4202                 set_safe_settings();
4203                 fix_settings();
4204                 eeprom_override(eeprom);
4205
4206                 eeprom->cksum = 0x00;
4207                 for (w_addr = 0, cksum = 0, w_eeprom = (u16 *)eeprom;
4208                      w_addr < 63; w_addr++, w_eeprom++)
4209                         cksum += *w_eeprom;
4210
4211                 *w_eeprom = 0x1234 - cksum;
4212                 trms1040_write_all(eeprom, io_port);
4213                 eeprom->delay_time = cfg_data[CFG_RESET_DELAY].value;
4214         } else {
4215                 set_safe_settings();
4216                 eeprom_index_to_delay(eeprom);
4217                 eeprom_override(eeprom);
4218         }
4219 }
4220
4221
4222 /**
4223  * print_eeprom_settings - output the eeprom settings
4224  * to the kernel log so people can see what they were.
4225  *
4226  * @eeprom: The eeprom data strucutre to show details for.
4227  **/
4228 static void __init print_eeprom_settings(struct NvRamType *eeprom)
4229 {
4230         dprintkl(KERN_INFO, "Used settings: AdapterID=%02i, Speed=%i(%02i.%01iMHz), dev_mode=0x%02x\n",
4231                 eeprom->scsi_id,
4232                 eeprom->target[0].period,
4233                 clock_speed[eeprom->target[0].period] / 10,
4234                 clock_speed[eeprom->target[0].period] % 10,
4235                 eeprom->target[0].cfg0);
4236         dprintkl(KERN_INFO, "               AdaptMode=0x%02x, Tags=%i(%02i), DelayReset=%is\n",
4237                 eeprom->channel_cfg, eeprom->max_tag,
4238                 1 << eeprom->max_tag, eeprom->delay_time);
4239 }
4240
4241
4242 /* Free SG tables */
4243 static void adapter_sg_tables_free(struct AdapterCtlBlk *acb)
4244 {
4245         int i;
4246         const unsigned srbs_per_page = PAGE_SIZE/SEGMENTX_LEN;
4247
4248         for (i = 0; i < DC395x_MAX_SRB_CNT; i += srbs_per_page)
4249                 if (acb->srb_array[i].segment_x)
4250                         kfree(acb->srb_array[i].segment_x);
4251 }
4252
4253
4254 /*
4255  * Allocate SG tables; as we have to pci_map them, an SG list (struct SGentry*)
4256  * should never cross a page boundary */
4257 static int __init adapter_sg_tables_alloc(struct AdapterCtlBlk *acb)
4258 {
4259         const unsigned mem_needed = (DC395x_MAX_SRB_CNT+1)
4260                                     *SEGMENTX_LEN;
4261         int pages = (mem_needed+(PAGE_SIZE-1))/PAGE_SIZE;
4262         const unsigned srbs_per_page = PAGE_SIZE/SEGMENTX_LEN;
4263         int srb_idx = 0;
4264         unsigned i = 0;
4265         struct SGentry *ptr;
4266
4267         for (i = 0; i < DC395x_MAX_SRB_CNT; i++)
4268                 acb->srb_array[i].segment_x = NULL;
4269
4270         dprintkdbg(DBG_1, "Allocate %i pages for SG tables\n", pages);
4271         while (pages--) {
4272                 ptr = (struct SGentry *)kmalloc(PAGE_SIZE, GFP_KERNEL);
4273                 if (!ptr) {
4274                         adapter_sg_tables_free(acb);
4275                         return 1;
4276                 }
4277                 dprintkdbg(DBG_1, "Allocate %li bytes at %p for SG segments %i\n",
4278                         PAGE_SIZE, ptr, srb_idx);
4279                 i = 0;
4280                 while (i < srbs_per_page && srb_idx < DC395x_MAX_SRB_CNT)
4281                         acb->srb_array[srb_idx++].segment_x =
4282                             ptr + (i++ * DC395x_MAX_SG_LISTENTRY);
4283         }
4284         if (i < srbs_per_page)
4285                 acb->srb.segment_x =
4286                     ptr + (i * DC395x_MAX_SG_LISTENTRY);
4287         else
4288                 dprintkl(KERN_DEBUG, "No space for tmsrb SG table reserved?!\n");
4289         return 0;
4290 }
4291
4292
4293
4294 /**
4295  * adapter_print_config - print adapter connection and termination
4296  * config
4297  *
4298  * The io port in the adapter needs to have been set before calling
4299  * this function.
4300  *
4301  * @acb: The adapter to print the information for.
4302  **/
4303 static void __init adapter_print_config(struct AdapterCtlBlk *acb)
4304 {
4305         u8 bval;
4306
4307         bval = DC395x_read8(acb, TRM_S1040_GEN_STATUS);
4308         dprintkl(KERN_INFO, "%sConnectors: ",
4309                 ((bval & WIDESCSI) ? "(Wide) " : ""));
4310         if (!(bval & CON5068))
4311                 printk("ext%s ", !(bval & EXT68HIGH) ? "68" : "50");
4312         if (!(bval & CON68))
4313                 printk("int68%s ", !(bval & INT68HIGH) ? "" : "(50)");
4314         if (!(bval & CON50))
4315                 printk("int50 ");
4316         if ((bval & (CON5068 | CON50 | CON68)) ==
4317             0 /*(CON5068 | CON50 | CON68) */ )
4318                 printk(" Oops! (All 3?) ");
4319         bval = DC395x_read8(acb, TRM_S1040_GEN_CONTROL);
4320         printk(" Termination: ");
4321         if (bval & DIS_TERM)
4322                 printk("Disabled\n");
4323         else {
4324                 if (bval & AUTOTERM)
4325                         printk("Auto ");
4326                 if (bval & LOW8TERM)
4327                         printk("Low ");
4328                 if (bval & UP8TERM)
4329                         printk("High ");
4330                 printk("\n");
4331         }
4332 }
4333
4334
4335 /**
4336  * adapter_init_params - Initialize the various parameters in the
4337  * adapter structure. Note that the pointer to the scsi_host is set
4338  * early (when this instance is created) and the io_port and irq
4339  * values are set later after they have been reserved. This just gets
4340  * everything set to a good starting position.
4341  *
4342  * The eeprom structure in the adapter needs to have been set before
4343  * calling this function.
4344  *
4345  * @acb: The adapter to initialize.
4346  **/
4347 static void __init adapter_init_params(struct AdapterCtlBlk *acb)
4348 {
4349         struct NvRamType *eeprom = &acb->eeprom;
4350         int i;
4351
4352         /* NOTE: acb->scsi_host is set at scsi_host/acb creation time */
4353         /* NOTE: acb->io_port_base is set at port registration time */
4354         /* NOTE: acb->io_port_len is set at port registration time */
4355
4356         INIT_LIST_HEAD(&acb->dcb_list);
4357         acb->dcb_run_robin = NULL;
4358         acb->active_dcb = NULL;
4359
4360         INIT_LIST_HEAD(&acb->srb_free_list);
4361         /*  temp SRB for Q tag used or abort command used  */
4362         acb->tmp_srb = &acb->srb;
4363         init_timer(&acb->waiting_timer);
4364         init_timer(&acb->selto_timer);
4365
4366         acb->srb_count = DC395x_MAX_SRB_CNT;
4367
4368         acb->sel_timeout = DC395x_SEL_TIMEOUT;  /* timeout=250ms */
4369         /* NOTE: acb->irq_level is set at IRQ registration time */
4370
4371         acb->tag_max_num = 1 << eeprom->max_tag;
4372         if (acb->tag_max_num > 30)
4373                 acb->tag_max_num = 30;
4374
4375         acb->acb_flag = 0;      /* RESET_DETECT, RESET_DONE, RESET_DEV */
4376         acb->gmode2 = eeprom->channel_cfg;
4377         acb->config = 0;        /* NOTE: actually set in adapter_init_chip */
4378
4379         if (eeprom->channel_cfg & NAC_SCANLUN)
4380                 acb->lun_chk = 1;
4381         acb->scan_devices = 1;
4382
4383         acb->scsi_host->this_id = eeprom->scsi_id;
4384         acb->hostid_bit = (1 << acb->scsi_host->this_id);
4385
4386         for (i = 0; i < DC395x_MAX_SCSI_ID; i++)
4387                 acb->dcb_map[i] = 0;
4388
4389         acb->msg_len = 0;
4390         
4391         /* link static array of srbs into the srb free list */
4392         for (i = 0; i < acb->srb_count - 1; i++)
4393                 srb_free_insert(acb, &acb->srb_array[i]);
4394 }
4395
4396
4397 /**
4398  * adapter_init_host - Initialize the scsi host instance based on
4399  * values that we have already stored in the adapter instance. There's
4400  * some mention that a lot of these are deprecated, so we won't use
4401  * them (we'll use the ones in the adapter instance) but we'll fill
4402  * them in in case something else needs them.
4403  *
4404  * The eeprom structure, irq and io ports in the adapter need to have
4405  * been set before calling this function.
4406  *
4407  * @host: The scsi host instance to fill in the values for.
4408  **/
4409 static void __init adapter_init_scsi_host(struct Scsi_Host *host)
4410 {
4411         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)host->hostdata;
4412         struct NvRamType *eeprom = &acb->eeprom;
4413         
4414         host->max_cmd_len = 24;
4415         host->can_queue = DC395x_MAX_CMD_QUEUE;
4416         host->cmd_per_lun = DC395x_MAX_CMD_PER_LUN;
4417         host->this_id = (int)eeprom->scsi_id;
4418         host->io_port = acb->io_port_base;
4419         host->n_io_port = acb->io_port_len;
4420         host->dma_channel = -1;
4421         host->unique_id = acb->io_port_base;
4422         host->irq = acb->irq_level;
4423         host->last_reset = jiffies;
4424
4425         host->max_id = 16;
4426         if (host->max_id - 1 == eeprom->scsi_id)
4427                 host->max_id--;
4428
4429 #ifdef CONFIG_SCSI_MULTI_LUN
4430         if (eeprom->channel_cfg & NAC_SCANLUN)
4431                 host->max_lun = 8;
4432         else
4433                 host->max_lun = 1;
4434 #else
4435         host->max_lun = 1;
4436 #endif
4437
4438 }
4439
4440
4441 /**
4442  * adapter_init_chip - Get the chip into a know state and figure out
4443  * some of the settings that apply to this adapter.
4444  *
4445  * The io port in the adapter needs to have been set before calling
4446  * this function. The config will be configured correctly on return.
4447  *
4448  * @acb: The adapter which we are to init.
4449  **/
4450 void __init adapter_init_chip(struct AdapterCtlBlk *acb)
4451 {
4452         struct NvRamType *eeprom = &acb->eeprom;
4453         
4454         /* Mask all the interrupt */
4455         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0x00);
4456         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0x00);
4457
4458         /* Reset SCSI module */
4459         DC395x_write16(acb, TRM_S1040_SCSI_CONTROL, DO_RSTMODULE);
4460
4461         /* Reset PCI/DMA module */
4462         DC395x_write8(acb, TRM_S1040_DMA_CONTROL, DMARESETMODULE);
4463         udelay(20);
4464
4465         /* program configuration 0 */
4466         acb->config = HCC_AUTOTERM | HCC_PARITY;
4467         if (DC395x_read8(acb, TRM_S1040_GEN_STATUS) & WIDESCSI)
4468                 acb->config |= HCC_WIDE_CARD;
4469
4470         if (eeprom->channel_cfg & NAC_POWERON_SCSI_RESET)
4471                 acb->config |= HCC_SCSI_RESET;
4472
4473         if (acb->config & HCC_SCSI_RESET) {
4474                 dprintkl(KERN_INFO, "Performing initial SCSI bus reset\n");
4475                 DC395x_write8(acb, TRM_S1040_SCSI_CONTROL, DO_RSTSCSI);
4476
4477                 /*while (!( DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS) & INT_SCSIRESET )); */
4478                 /*spin_unlock_irq (&io_request_lock); */
4479                 udelay(500);
4480
4481                 acb->scsi_host->last_reset =
4482                     jiffies + HZ / 2 +
4483                     HZ * acb->eeprom.delay_time;
4484
4485                 /*spin_lock_irq (&io_request_lock); */
4486         }
4487 }
4488
4489
4490 /**
4491  * init_adapter - Grab the resource for the card, setup the adapter
4492  * information, set the card into a known state, create the various
4493  * tables etc etc. This basically gets all adapter information all up
4494  * to date, intialised and gets the chip in sync with it.
4495  *
4496  * @host:       This hosts adapter structure
4497  * @io_port:    The base I/O port
4498  * @irq:        IRQ
4499  *
4500  * Returns 0 if the initialization succeeds, any other value on
4501  * failure.
4502  **/
4503 static int __init adapter_init(struct AdapterCtlBlk *acb, u32 io_port,
4504                 u32 io_port_len, u8 irq)
4505 {
4506         if (!request_region(io_port, io_port_len, DC395X_NAME)) {
4507                 dprintkl(KERN_ERR, "Failed to reserve IO region 0x%x\n", io_port);
4508                 goto failed;
4509         }
4510         /* store port base to indicate we have registered it */
4511         acb->io_port_base = io_port;
4512         acb->io_port_len = io_port_len;
4513         
4514         if (request_irq(irq, dc395x_interrupt, SA_SHIRQ, DC395X_NAME, acb)) {
4515                 /* release the region we just claimed */
4516                 dprintkl(KERN_INFO, "Failed to register IRQ\n");
4517                 goto failed;
4518         }
4519         /* store irq to indicate we have registered it */
4520         acb->irq_level = irq;
4521
4522         /* get eeprom configuration information and command line settings etc */
4523         check_eeprom(&acb->eeprom, (u16)io_port);
4524         print_eeprom_settings(&acb->eeprom);
4525
4526         /* setup adapter control block */       
4527         adapter_init_params(acb);
4528         
4529         /* display card connectors/termination settings */
4530         adapter_print_config(acb);
4531
4532         if (adapter_sg_tables_alloc(acb)) {
4533                 dprintkl(KERN_DEBUG, "Memory allocation for SG tables failed\n");
4534                 goto failed;
4535         }
4536         adapter_init_scsi_host(acb->scsi_host);
4537         adapter_init_chip(acb);
4538         set_basic_config(acb);
4539
4540         dprintkdbg(DBG_0,
4541                 "adapter_init: acb=%p, pdcb_map=%p psrb_array=%p "
4542                 "size{acb=0x%04x dcb=0x%04x srb=0x%04x}\n",
4543                 acb, acb->dcb_map, acb->srb_array, sizeof(struct AdapterCtlBlk),
4544                 sizeof(struct DeviceCtlBlk), sizeof(struct ScsiReqBlk));
4545         return 0;
4546
4547 failed:
4548         if (acb->irq_level)
4549                 free_irq(acb->irq_level, acb);
4550         if (acb->io_port_base)
4551                 release_region(acb->io_port_base, acb->io_port_len);
4552         adapter_sg_tables_free(acb);
4553
4554         return 1;
4555 }
4556
4557
4558 /**
4559  * adapter_uninit_chip - cleanly shut down the scsi controller chip,
4560  * stopping all operations and disabling interrupt generation on the
4561  * card.
4562  *
4563  * @acb: The adapter which we are to shutdown.
4564  **/
4565 static void adapter_uninit_chip(struct AdapterCtlBlk *acb)
4566 {
4567         /* disable interrupts */
4568         DC395x_write8(acb, TRM_S1040_DMA_INTEN, 0);
4569         DC395x_write8(acb, TRM_S1040_SCSI_INTEN, 0);
4570
4571         /* reset the scsi bus */
4572         if (acb->config & HCC_SCSI_RESET)
4573                 reset_scsi_bus(acb);
4574
4575         /* clear any pending interupt state */
4576         DC395x_read8(acb, TRM_S1040_SCSI_INTSTATUS);
4577 }
4578
4579
4580
4581 /**
4582  * adapter_uninit - Shut down the chip and release any resources that
4583  * we had allocated. Once this returns the adapter should not be used
4584  * anymore.
4585  *
4586  * @acb: The adapter which we are to un-initialize.
4587  **/
4588 static void adapter_uninit(struct AdapterCtlBlk *acb)
4589 {
4590         unsigned long flags;
4591         DC395x_LOCK_IO(acb->scsi_host, flags);
4592
4593         /* remove timers */
4594         if (timer_pending(&acb->waiting_timer))
4595                 del_timer(&acb->waiting_timer);
4596         if (timer_pending(&acb->selto_timer))
4597                 del_timer(&acb->selto_timer);
4598
4599         adapter_uninit_chip(acb);
4600         adapter_remove_and_free_all_devices(acb);
4601         DC395x_UNLOCK_IO(acb->scsi_host, flags);
4602
4603         if (acb->irq_level)
4604                 free_irq(acb->irq_level, acb);
4605         if (acb->io_port_base)
4606                 release_region(acb->io_port_base, acb->io_port_len);
4607
4608         adapter_sg_tables_free(acb);
4609 }
4610
4611
4612 #undef SPRINTF
4613 #define SPRINTF(args...) pos += sprintf(pos, args)
4614
4615 #undef YESNO
4616 #define YESNO(YN) \
4617  if (YN) SPRINTF(" Yes ");\
4618  else SPRINTF(" No  ")
4619
4620 static int dc395x_proc_info(struct Scsi_Host *host, char *buffer,
4621                 char **start, off_t offset, int length, int inout)
4622 {
4623         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)host->hostdata;
4624         int spd, spd1;
4625         char *pos = buffer;
4626         struct DeviceCtlBlk *dcb;
4627         unsigned long flags;
4628         int dev;
4629
4630         if (inout)              /* Has data been written to the file ? */
4631                 return -EPERM;
4632
4633         SPRINTF(DC395X_BANNER " PCI SCSI Host Adapter\n");
4634         SPRINTF(" Driver Version " DC395X_VERSION "\n");
4635
4636         DC395x_LOCK_IO(acb->scsi_host, flags);
4637
4638         SPRINTF("SCSI Host Nr %i, ", host->host_no);
4639         SPRINTF("DC395U/UW/F DC315/U %s\n",
4640                 (acb->config & HCC_WIDE_CARD) ? "Wide" : "");
4641         SPRINTF("io_port_base 0x%04x, ", acb->io_port_base);
4642         SPRINTF("irq_level 0x%02x, ", acb->irq_level);
4643         SPRINTF(" SelTimeout %ims\n", (1638 * acb->sel_timeout) / 1000);
4644
4645         SPRINTF("MaxID %i, MaxLUN %i, ", host->max_id, host->max_lun);
4646         SPRINTF("AdapterID %i\n", host->this_id);
4647
4648         SPRINTF("tag_max_num %i", acb->tag_max_num);
4649         /*SPRINTF(", DMA_Status %i\n", DC395x_read8(acb, TRM_S1040_DMA_STATUS)); */
4650         SPRINTF(", FilterCfg 0x%02x",
4651                 DC395x_read8(acb, TRM_S1040_SCSI_CONFIG1));
4652         SPRINTF(", DelayReset %is\n", acb->eeprom.delay_time);
4653         /*SPRINTF("\n"); */
4654
4655         SPRINTF("Nr of DCBs: %i\n", list_size(&acb->dcb_list));
4656         SPRINTF
4657             ("Map of attached LUNs: %02x %02x %02x %02x %02x %02x %02x %02x\n",
4658              acb->dcb_map[0], acb->dcb_map[1], acb->dcb_map[2],
4659              acb->dcb_map[3], acb->dcb_map[4], acb->dcb_map[5],
4660              acb->dcb_map[6], acb->dcb_map[7]);
4661         SPRINTF
4662             ("                      %02x %02x %02x %02x %02x %02x %02x %02x\n",
4663              acb->dcb_map[8], acb->dcb_map[9], acb->dcb_map[10],
4664              acb->dcb_map[11], acb->dcb_map[12], acb->dcb_map[13],
4665              acb->dcb_map[14], acb->dcb_map[15]);
4666
4667         SPRINTF
4668             ("Un ID LUN Prty Sync Wide DsCn SndS TagQ nego_period SyncFreq SyncOffs MaxCmd\n");
4669
4670         dev = 0;
4671         list_for_each_entry(dcb, &acb->dcb_list, list) {
4672                 int nego_period;
4673                 SPRINTF("%02i %02i  %02i ", dev, dcb->target_id,
4674                         dcb->target_lun);
4675                 YESNO(dcb->dev_mode & NTC_DO_PARITY_CHK);
4676                 YESNO(dcb->sync_offset);
4677                 YESNO(dcb->sync_period & WIDE_SYNC);
4678                 YESNO(dcb->dev_mode & NTC_DO_DISCONNECT);
4679                 YESNO(dcb->dev_mode & NTC_DO_SEND_START);
4680                 YESNO(dcb->sync_mode & EN_TAG_QUEUEING);
4681                 nego_period = clock_period[dcb->sync_period & 0x07] << 2;
4682                 if (dcb->sync_offset)
4683                         SPRINTF("  %03i ns ", nego_period);
4684                 else
4685                         SPRINTF(" (%03i ns)", (dcb->min_nego_period << 2));
4686
4687                 if (dcb->sync_offset & 0x0f) {
4688                         spd = 1000 / (nego_period);
4689                         spd1 = 1000 % (nego_period);
4690                         spd1 = (spd1 * 10 + nego_period / 2) / (nego_period);
4691                         SPRINTF("   %2i.%1i M     %02i ", spd, spd1,
4692                                 (dcb->sync_offset & 0x0f));
4693                 } else
4694                         SPRINTF("                 ");
4695
4696                 /* Add more info ... */
4697                 SPRINTF("     %02i\n", dcb->max_command);
4698                 dev++;
4699         }
4700
4701         if (timer_pending(&acb->waiting_timer))
4702                 SPRINTF("Waiting queue timer running\n");
4703         else
4704                 SPRINTF("\n");
4705
4706         list_for_each_entry(dcb, &acb->dcb_list, list) {
4707                 struct ScsiReqBlk *srb;
4708                 if (!list_empty(&dcb->srb_waiting_list))
4709                         SPRINTF("DCB (%02i-%i): Waiting: %i:",
4710                                 dcb->target_id, dcb->target_lun,
4711                                 list_size(&dcb->srb_waiting_list));
4712                 list_for_each_entry(srb, &dcb->srb_waiting_list, list)
4713                         SPRINTF(" %li", srb->cmd->pid);
4714                 if (!list_empty(&dcb->srb_going_list))
4715                         SPRINTF("\nDCB (%02i-%i): Going  : %i:",
4716                                 dcb->target_id, dcb->target_lun,
4717                                 list_size(&dcb->srb_going_list));
4718                 list_for_each_entry(srb, &dcb->srb_going_list, list)
4719                         SPRINTF(" %li", srb->cmd->pid);
4720                 if (!list_empty(&dcb->srb_waiting_list) || !list_empty(&dcb->srb_going_list))
4721                         SPRINTF("\n");
4722         }
4723
4724         if (debug_enabled(DBG_1)) {
4725                 SPRINTF("DCB list for ACB %p:\n", acb);
4726                 list_for_each_entry(dcb, &acb->dcb_list, list) {
4727                         SPRINTF("%p -> ", dcb);
4728                 }
4729                 SPRINTF("END\n");
4730         }
4731
4732         *start = buffer + offset;
4733         DC395x_UNLOCK_IO(acb->scsi_host, flags);
4734
4735         if (pos - buffer < offset)
4736                 return 0;
4737         else if (pos - buffer - offset < length)
4738                 return pos - buffer - offset;
4739         else
4740                 return length;
4741 }
4742
4743
4744 static struct scsi_host_template dc395x_driver_template = {
4745         .module                 = THIS_MODULE,
4746         .proc_name              = DC395X_NAME,
4747         .proc_info              = dc395x_proc_info,
4748         .name                   = DC395X_BANNER " " DC395X_VERSION,
4749         .queuecommand           = dc395x_queue_command,
4750         .bios_param             = dc395x_bios_param,
4751         .slave_alloc            = dc395x_slave_alloc,
4752         .slave_destroy          = dc395x_slave_destroy,
4753         .can_queue              = DC395x_MAX_CAN_QUEUE,
4754         .this_id                = 7,
4755         .sg_tablesize           = DC395x_MAX_SG_TABLESIZE,
4756         .cmd_per_lun            = DC395x_MAX_CMD_PER_LUN,
4757         .eh_abort_handler       = dc395x_eh_abort,
4758         .eh_bus_reset_handler   = dc395x_eh_bus_reset,
4759         .unchecked_isa_dma      = 0,
4760         .use_clustering         = DISABLE_CLUSTERING,
4761 };
4762
4763
4764 /**
4765  * banner_display - Display banner on first instance of driver
4766  * initialized.
4767  **/
4768 static void banner_display(void)
4769 {
4770         static int banner_done = 0;
4771         if (!banner_done)
4772         {
4773                 dprintkl(KERN_INFO, "%s %s\n", DC395X_BANNER, DC395X_VERSION);
4774                 banner_done = 1;
4775         }
4776 }
4777
4778
4779 /**
4780  * dc395x_init_one - Initialise a single instance of the adapter.
4781  *
4782  * The PCI layer will call this once for each instance of the adapter
4783  * that it finds in the system. The pci_dev strcuture indicates which
4784  * instance we are being called from.
4785  * 
4786  * @dev: The PCI device to intialize.
4787  * @id: Looks like a pointer to the entry in our pci device table
4788  * that was actually matched by the PCI subsystem.
4789  *
4790  * Returns 0 on success, or an error code (-ve) on failure.
4791  **/
4792 static int __devinit dc395x_init_one(struct pci_dev *dev,
4793                 const struct pci_device_id *id)
4794 {
4795         struct Scsi_Host *scsi_host;
4796         struct AdapterCtlBlk *acb;
4797         unsigned int io_port_base;
4798         unsigned int io_port_len;
4799         u8 irq;
4800         
4801         dprintkdbg(DBG_0, "Init one instance (%s)\n", pci_name(dev));
4802         banner_display();
4803
4804         if (pci_enable_device(dev))
4805         {
4806                 dprintkl(KERN_INFO, "PCI Enable device failed.\n");
4807                 return -ENODEV;
4808         }
4809         io_port_base = pci_resource_start(dev, 0) & PCI_BASE_ADDRESS_IO_MASK;
4810         io_port_len = pci_resource_len(dev, 0);
4811         irq = dev->irq;
4812         dprintkdbg(DBG_0, "IO_PORT=%04x, IRQ=%x\n", io_port_base, dev->irq);
4813
4814         /* allocate scsi host information (includes out adapter) */
4815         scsi_host = scsi_host_alloc(&dc395x_driver_template,
4816                                     sizeof(struct AdapterCtlBlk));
4817         if (!scsi_host) {
4818                 dprintkl(KERN_INFO, "scsi_host_alloc failed\n");
4819                 return -ENOMEM;
4820         }
4821         acb = (struct AdapterCtlBlk*)scsi_host->hostdata;
4822         acb->scsi_host = scsi_host;
4823
4824         /* initialise the adapter and everything we need */
4825         if (adapter_init(acb, io_port_base, io_port_len, irq)) {
4826                 dprintkl(KERN_INFO, "adapter init failed\n");
4827                 scsi_host_put(scsi_host);
4828                 return -ENODEV;
4829         }
4830
4831         pci_set_master(dev);
4832
4833         /* get the scsi mid level to scan for new devices on the bus */
4834         if (scsi_add_host(scsi_host, &dev->dev)) {
4835                 dprintkl(KERN_ERR, "scsi_add_host failed\n");
4836                 adapter_uninit(acb);
4837                 scsi_host_put(scsi_host);
4838                 return -ENODEV;
4839         }
4840         pci_set_drvdata(dev, scsi_host);
4841         scsi_scan_host(scsi_host);
4842                 
4843         return 0;
4844 }
4845
4846
4847 /**
4848  * dc395x_remove_one - Called to remove a single instance of the
4849  * adapter.
4850  *
4851  * @dev: The PCI device to intialize.
4852  **/
4853 static void __devexit dc395x_remove_one(struct pci_dev *dev)
4854 {
4855         struct Scsi_Host *scsi_host = pci_get_drvdata(dev);
4856         struct AdapterCtlBlk *acb = (struct AdapterCtlBlk *)(scsi_host->hostdata);
4857
4858         dprintkdbg(DBG_0, "dc395x_remove_one: acb=%p\n", acb);
4859
4860         scsi_remove_host(scsi_host);
4861         adapter_uninit(acb);
4862         scsi_host_put(scsi_host);
4863         pci_set_drvdata(dev, NULL);
4864 }
4865
4866
4867 static struct pci_device_id dc395x_pci_table[] = {
4868         {
4869                 .vendor         = PCI_VENDOR_ID_TEKRAM,
4870                 .device         = PCI_DEVICE_ID_TEKRAM_TRMS1040,
4871                 .subvendor      = PCI_ANY_ID,
4872                 .subdevice      = PCI_ANY_ID,
4873          },
4874         {}                      /* Terminating entry */
4875 };
4876 MODULE_DEVICE_TABLE(pci, dc395x_pci_table);
4877
4878
4879 static struct pci_driver dc395x_driver = {
4880         .name           = DC395X_NAME,
4881         .id_table       = dc395x_pci_table,
4882         .probe          = dc395x_init_one,
4883         .remove         = __devexit_p(dc395x_remove_one),
4884 };
4885
4886
4887 /**
4888  * dc395x_module_init - Module initialization function
4889  *
4890  * Used by both module and built-in driver to initialise this driver.
4891  **/
4892 static int __init dc395x_module_init(void)
4893 {
4894         return pci_module_init(&dc395x_driver);
4895 }
4896
4897
4898 /**
4899  * dc395x_module_exit - Module cleanup function.
4900  **/
4901 static void __exit dc395x_module_exit(void)
4902 {
4903         pci_unregister_driver(&dc395x_driver);
4904 }
4905
4906
4907 module_init(dc395x_module_init);
4908 module_exit(dc395x_module_exit);
4909
4910 MODULE_AUTHOR("C.L. Huang / Erich Chen / Kurt Garloff");
4911 MODULE_DESCRIPTION("SCSI host adapter driver for Tekram TRM-S1040 based adapters: Tekram DC395 and DC315 series");
4912 MODULE_LICENSE("GPL");