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