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