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