xref: /openbmc/linux/drivers/scsi/nsp32.c (revision e8ffca61)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NinjaSCSI-32Bi Cardbus, NinjaSCSI-32UDE PCI/CardBus SCSI driver
4  * Copyright (C) 2001, 2002, 2003
5  *      YOKOTA Hiroshi <yokota@netlab.is.tsukuba.ac.jp>
6  *      GOTO Masanori <gotom@debian.or.jp>, <gotom@debian.org>
7  *
8  * Revision History:
9  *   1.0: Initial Release.
10  *   1.1: Add /proc SDTR status.
11  *        Remove obsolete error handler nsp32_reset.
12  *        Some clean up.
13  *   1.2: PowerPC (big endian) support.
14  */
15 
16 #include <linux/module.h>
17 #include <linux/init.h>
18 #include <linux/kernel.h>
19 #include <linux/string.h>
20 #include <linux/timer.h>
21 #include <linux/ioport.h>
22 #include <linux/major.h>
23 #include <linux/blkdev.h>
24 #include <linux/interrupt.h>
25 #include <linux/pci.h>
26 #include <linux/delay.h>
27 #include <linux/ctype.h>
28 #include <linux/dma-mapping.h>
29 
30 #include <asm/dma.h>
31 #include <asm/io.h>
32 
33 #include <scsi/scsi.h>
34 #include <scsi/scsi_cmnd.h>
35 #include <scsi/scsi_device.h>
36 #include <scsi/scsi_host.h>
37 #include <scsi/scsi_ioctl.h>
38 
39 #include "nsp32.h"
40 
41 
42 /***********************************************************************
43  * Module parameters
44  */
45 static int       trans_mode = 0;	/* default: BIOS */
46 module_param     (trans_mode, int, 0);
47 MODULE_PARM_DESC(trans_mode, "transfer mode (0: BIOS(default) 1: Async 2: Ultra20M");
48 #define ASYNC_MODE    1
49 #define ULTRA20M_MODE 2
50 
51 static bool      auto_param = 0;	/* default: ON */
52 module_param     (auto_param, bool, 0);
53 MODULE_PARM_DESC(auto_param, "AutoParameter mode (0: ON(default) 1: OFF)");
54 
55 static bool      disc_priv  = 1;	/* default: OFF */
56 module_param     (disc_priv, bool, 0);
57 MODULE_PARM_DESC(disc_priv,  "disconnection privilege mode (0: ON 1: OFF(default))");
58 
59 MODULE_AUTHOR("YOKOTA Hiroshi <yokota@netlab.is.tsukuba.ac.jp>, GOTO Masanori <gotom@debian.or.jp>");
60 MODULE_DESCRIPTION("Workbit NinjaSCSI-32Bi/UDE CardBus/PCI SCSI host bus adapter module");
61 MODULE_LICENSE("GPL");
62 
63 static const char *nsp32_release_version = "1.2";
64 
65 
66 /****************************************************************************
67  * Supported hardware
68  */
69 static struct pci_device_id nsp32_pci_table[] = {
70 	{
71 		.vendor      = PCI_VENDOR_ID_IODATA,
72 		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_CBSC_II,
73 		.subvendor   = PCI_ANY_ID,
74 		.subdevice   = PCI_ANY_ID,
75 		.driver_data = MODEL_IODATA,
76 	},
77 	{
78 		.vendor      = PCI_VENDOR_ID_WORKBIT,
79 		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_KME,
80 		.subvendor   = PCI_ANY_ID,
81 		.subdevice   = PCI_ANY_ID,
82 		.driver_data = MODEL_KME,
83 	},
84 	{
85 		.vendor      = PCI_VENDOR_ID_WORKBIT,
86 		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_WBT,
87 		.subvendor   = PCI_ANY_ID,
88 		.subdevice   = PCI_ANY_ID,
89 		.driver_data = MODEL_WORKBIT,
90 	},
91 	{
92 		.vendor      = PCI_VENDOR_ID_WORKBIT,
93 		.device      = PCI_DEVICE_ID_WORKBIT_STANDARD,
94 		.subvendor   = PCI_ANY_ID,
95 		.subdevice   = PCI_ANY_ID,
96 		.driver_data = MODEL_PCI_WORKBIT,
97 	},
98 	{
99 		.vendor      = PCI_VENDOR_ID_WORKBIT,
100 		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_LOGITEC,
101 		.subvendor   = PCI_ANY_ID,
102 		.subdevice   = PCI_ANY_ID,
103 		.driver_data = MODEL_LOGITEC,
104 	},
105 	{
106 		.vendor      = PCI_VENDOR_ID_WORKBIT,
107 		.device      = PCI_DEVICE_ID_NINJASCSI_32BIB_LOGITEC,
108 		.subvendor   = PCI_ANY_ID,
109 		.subdevice   = PCI_ANY_ID,
110 		.driver_data = MODEL_PCI_LOGITEC,
111 	},
112 	{
113 		.vendor      = PCI_VENDOR_ID_WORKBIT,
114 		.device      = PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO,
115 		.subvendor   = PCI_ANY_ID,
116 		.subdevice   = PCI_ANY_ID,
117 		.driver_data = MODEL_PCI_MELCO,
118 	},
119 	{
120 		.vendor      = PCI_VENDOR_ID_WORKBIT,
121 		.device      = PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO_II,
122 		.subvendor   = PCI_ANY_ID,
123 		.subdevice   = PCI_ANY_ID,
124 		.driver_data = MODEL_PCI_MELCO,
125 	},
126 	{0,0,},
127 };
128 MODULE_DEVICE_TABLE(pci, nsp32_pci_table);
129 
130 static nsp32_hw_data nsp32_data_base;  /* probe <-> detect glue */
131 
132 
133 /*
134  * Period/AckWidth speed conversion table
135  *
136  * Note: This period/ackwidth speed table must be in descending order.
137  */
138 static nsp32_sync_table nsp32_sync_table_40M[] = {
139      /* {PNo, AW,   SP,   EP, SREQ smpl}  Speed(MB/s) Period AckWidth */
140 	{0x1,  0, 0x0c, 0x0c, SMPL_40M},  /*  20.0 :  50ns,  25ns */
141 	{0x2,  0, 0x0d, 0x18, SMPL_40M},  /*  13.3 :  75ns,  25ns */
142 	{0x3,  1, 0x19, 0x19, SMPL_40M},  /*  10.0 : 100ns,  50ns */
143 	{0x4,  1, 0x1a, 0x1f, SMPL_20M},  /*   8.0 : 125ns,  50ns */
144 	{0x5,  2, 0x20, 0x25, SMPL_20M},  /*   6.7 : 150ns,  75ns */
145 	{0x6,  2, 0x26, 0x31, SMPL_20M},  /*   5.7 : 175ns,  75ns */
146 	{0x7,  3, 0x32, 0x32, SMPL_20M},  /*   5.0 : 200ns, 100ns */
147 	{0x8,  3, 0x33, 0x38, SMPL_10M},  /*   4.4 : 225ns, 100ns */
148 	{0x9,  3, 0x39, 0x3e, SMPL_10M},  /*   4.0 : 250ns, 100ns */
149 };
150 
151 static nsp32_sync_table nsp32_sync_table_20M[] = {
152 	{0x1,  0, 0x19, 0x19, SMPL_40M},  /* 10.0 : 100ns,  50ns */
153 	{0x2,  0, 0x1a, 0x25, SMPL_20M},  /*  6.7 : 150ns,  50ns */
154 	{0x3,  1, 0x26, 0x32, SMPL_20M},  /*  5.0 : 200ns, 100ns */
155 	{0x4,  1, 0x33, 0x3e, SMPL_10M},  /*  4.0 : 250ns, 100ns */
156 	{0x5,  2, 0x3f, 0x4b, SMPL_10M},  /*  3.3 : 300ns, 150ns */
157 	{0x6,  2, 0x4c, 0x57, SMPL_10M},  /*  2.8 : 350ns, 150ns */
158 	{0x7,  3, 0x58, 0x64, SMPL_10M},  /*  2.5 : 400ns, 200ns */
159 	{0x8,  3, 0x65, 0x70, SMPL_10M},  /*  2.2 : 450ns, 200ns */
160 	{0x9,  3, 0x71, 0x7d, SMPL_10M},  /*  2.0 : 500ns, 200ns */
161 };
162 
163 static nsp32_sync_table nsp32_sync_table_pci[] = {
164 	{0x1,  0, 0x0c, 0x0f, SMPL_40M},  /* 16.6 :  60ns,  30ns */
165 	{0x2,  0, 0x10, 0x16, SMPL_40M},  /* 11.1 :  90ns,  30ns */
166 	{0x3,  1, 0x17, 0x1e, SMPL_20M},  /*  8.3 : 120ns,  60ns */
167 	{0x4,  1, 0x1f, 0x25, SMPL_20M},  /*  6.7 : 150ns,  60ns */
168 	{0x5,  2, 0x26, 0x2d, SMPL_20M},  /*  5.6 : 180ns,  90ns */
169 	{0x6,  2, 0x2e, 0x34, SMPL_10M},  /*  4.8 : 210ns,  90ns */
170 	{0x7,  3, 0x35, 0x3c, SMPL_10M},  /*  4.2 : 240ns, 120ns */
171 	{0x8,  3, 0x3d, 0x43, SMPL_10M},  /*  3.7 : 270ns, 120ns */
172 	{0x9,  3, 0x44, 0x4b, SMPL_10M},  /*  3.3 : 300ns, 120ns */
173 };
174 
175 /*
176  * function declaration
177  */
178 /* module entry point */
179 static int nsp32_probe (struct pci_dev *, const struct pci_device_id *);
180 static void nsp32_remove(struct pci_dev *);
181 static int  __init init_nsp32  (void);
182 static void __exit exit_nsp32  (void);
183 
184 /* struct struct scsi_host_template */
185 static int	   nsp32_show_info   (struct seq_file *, struct Scsi_Host *);
186 
187 static int	   nsp32_detect      (struct pci_dev *pdev);
188 static int	   nsp32_queuecommand(struct Scsi_Host *, struct scsi_cmnd *);
189 static const char *nsp32_info	     (struct Scsi_Host *);
190 static int	   nsp32_release     (struct Scsi_Host *);
191 
192 /* SCSI error handler */
193 static int	   nsp32_eh_abort     (struct scsi_cmnd *);
194 static int	   nsp32_eh_host_reset(struct scsi_cmnd *);
195 
196 /* generate SCSI message */
197 static void nsp32_build_identify(struct scsi_cmnd *);
198 static void nsp32_build_nop     (struct scsi_cmnd *);
199 static void nsp32_build_reject  (struct scsi_cmnd *);
200 static void nsp32_build_sdtr    (struct scsi_cmnd *, unsigned char,
201 				 unsigned char);
202 
203 /* SCSI message handler */
204 static int  nsp32_busfree_occur(struct scsi_cmnd *, unsigned short);
205 static void nsp32_msgout_occur (struct scsi_cmnd *);
206 static void nsp32_msgin_occur  (struct scsi_cmnd *, unsigned long,
207 				unsigned short);
208 
209 static int  nsp32_setup_sg_table    (struct scsi_cmnd *);
210 static int  nsp32_selection_autopara(struct scsi_cmnd *);
211 static int  nsp32_selection_autoscsi(struct scsi_cmnd *);
212 static void nsp32_scsi_done	    (struct scsi_cmnd *);
213 static int  nsp32_arbitration       (struct scsi_cmnd *, unsigned int);
214 static int  nsp32_reselection       (struct scsi_cmnd *, unsigned char);
215 static void nsp32_adjust_busfree    (struct scsi_cmnd *, unsigned int);
216 static void nsp32_restart_autoscsi  (struct scsi_cmnd *, unsigned short);
217 
218 /* SCSI SDTR */
219 static void nsp32_analyze_sdtr       (struct scsi_cmnd *);
220 static int  nsp32_search_period_entry(nsp32_hw_data *, nsp32_target *,
221 				      unsigned char);
222 static void nsp32_set_async	     (nsp32_hw_data *, nsp32_target *);
223 static void nsp32_set_max_sync       (nsp32_hw_data *, nsp32_target *,
224 				      unsigned char *, unsigned char *);
225 static void nsp32_set_sync_entry     (nsp32_hw_data *, nsp32_target *,
226 				      int, unsigned char);
227 
228 /* SCSI bus status handler */
229 static void nsp32_wait_req    (nsp32_hw_data *, int);
230 static void nsp32_wait_sack   (nsp32_hw_data *, int);
231 static void nsp32_sack_assert (nsp32_hw_data *);
232 static void nsp32_sack_negate (nsp32_hw_data *);
233 static void nsp32_do_bus_reset(nsp32_hw_data *);
234 
235 /* hardware interrupt handler */
236 static irqreturn_t do_nsp32_isr(int, void *);
237 
238 /* initialize hardware */
239 static int  nsp32hw_init(nsp32_hw_data *);
240 
241 /* EEPROM handler */
242 static int  nsp32_getprom_param (nsp32_hw_data *);
243 static int  nsp32_getprom_at24  (nsp32_hw_data *);
244 static int  nsp32_getprom_c16   (nsp32_hw_data *);
245 static void nsp32_prom_start    (nsp32_hw_data *);
246 static void nsp32_prom_stop     (nsp32_hw_data *);
247 static int  nsp32_prom_read     (nsp32_hw_data *, int);
248 static int  nsp32_prom_read_bit (nsp32_hw_data *);
249 static void nsp32_prom_write_bit(nsp32_hw_data *, int);
250 static void nsp32_prom_set      (nsp32_hw_data *, int, int);
251 static int  nsp32_prom_get      (nsp32_hw_data *, int);
252 
253 /* debug/warning/info message */
254 static void nsp32_message (const char *, int, char *, char *, ...);
255 #ifdef NSP32_DEBUG
256 static void nsp32_dmessage(const char *, int, int,    char *, ...);
257 #endif
258 
259 /*
260  * max_sectors is currently limited up to 128.
261  */
262 static struct scsi_host_template nsp32_template = {
263 	.proc_name			= "nsp32",
264 	.name				= "Workbit NinjaSCSI-32Bi/UDE",
265 	.show_info			= nsp32_show_info,
266 	.info				= nsp32_info,
267 	.queuecommand			= nsp32_queuecommand,
268 	.can_queue			= 1,
269 	.sg_tablesize			= NSP32_SG_SIZE,
270 	.max_sectors			= 128,
271 	.this_id			= NSP32_HOST_SCSIID,
272 	.dma_boundary			= PAGE_SIZE - 1,
273 	.eh_abort_handler		= nsp32_eh_abort,
274 	.eh_host_reset_handler		= nsp32_eh_host_reset,
275 /*	.highmem_io			= 1, */
276 };
277 
278 #include "nsp32_io.h"
279 
280 /***********************************************************************
281  * debug, error print
282  */
283 #ifndef NSP32_DEBUG
284 # define NSP32_DEBUG_MASK	      0x000000
285 # define nsp32_msg(type, args...)     nsp32_message ("", 0, (type), args)
286 # define nsp32_dbg(mask, args...)     /* */
287 #else
288 # define NSP32_DEBUG_MASK	      0xffffff
289 # define nsp32_msg(type, args...) \
290 	nsp32_message (__func__, __LINE__, (type), args)
291 # define nsp32_dbg(mask, args...) \
292 	nsp32_dmessage(__func__, __LINE__, (mask), args)
293 #endif
294 
295 #define NSP32_DEBUG_QUEUECOMMAND	BIT(0)
296 #define NSP32_DEBUG_REGISTER		BIT(1)
297 #define NSP32_DEBUG_AUTOSCSI		BIT(2)
298 #define NSP32_DEBUG_INTR		BIT(3)
299 #define NSP32_DEBUG_SGLIST		BIT(4)
300 #define NSP32_DEBUG_BUSFREE		BIT(5)
301 #define NSP32_DEBUG_CDB_CONTENTS	BIT(6)
302 #define NSP32_DEBUG_RESELECTION		BIT(7)
303 #define NSP32_DEBUG_MSGINOCCUR		BIT(8)
304 #define NSP32_DEBUG_EEPROM		BIT(9)
305 #define NSP32_DEBUG_MSGOUTOCCUR		BIT(10)
306 #define NSP32_DEBUG_BUSRESET		BIT(11)
307 #define NSP32_DEBUG_RESTART		BIT(12)
308 #define NSP32_DEBUG_SYNC		BIT(13)
309 #define NSP32_DEBUG_WAIT		BIT(14)
310 #define NSP32_DEBUG_TARGETFLAG		BIT(15)
311 #define NSP32_DEBUG_PROC		BIT(16)
312 #define NSP32_DEBUG_INIT		BIT(17)
313 #define NSP32_SPECIAL_PRINT_REGISTER	BIT(20)
314 
315 #define NSP32_DEBUG_BUF_LEN		100
316 
317 __printf(4, 5)
318 static void nsp32_message(const char *func, int line, char *type, char *fmt, ...)
319 {
320 	va_list args;
321 	char buf[NSP32_DEBUG_BUF_LEN];
322 
323 	va_start(args, fmt);
324 	vsnprintf(buf, sizeof(buf), fmt, args);
325 	va_end(args);
326 
327 #ifndef NSP32_DEBUG
328 	printk("%snsp32: %s\n", type, buf);
329 #else
330 	printk("%snsp32: %s (%d): %s\n", type, func, line, buf);
331 #endif
332 }
333 
334 #ifdef NSP32_DEBUG
335 static void nsp32_dmessage(const char *func, int line, int mask, char *fmt, ...)
336 {
337 	va_list args;
338 	char buf[NSP32_DEBUG_BUF_LEN];
339 
340 	va_start(args, fmt);
341 	vsnprintf(buf, sizeof(buf), fmt, args);
342 	va_end(args);
343 
344 	if (mask & NSP32_DEBUG_MASK) {
345 		printk("nsp32-debug: 0x%x %s (%d): %s\n", mask, func, line, buf);
346 	}
347 }
348 #endif
349 
350 #ifdef NSP32_DEBUG
351 # include "nsp32_debug.c"
352 #else
353 # define show_command(arg)   /* */
354 # define show_busphase(arg)  /* */
355 # define show_autophase(arg) /* */
356 #endif
357 
358 /*
359  * IDENTIFY Message
360  */
361 static void nsp32_build_identify(struct scsi_cmnd *SCpnt)
362 {
363 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
364 	int pos		    = data->msgout_len;
365 	int mode	    = FALSE;
366 
367 	/* XXX: Auto DiscPriv detection is progressing... */
368 	if (disc_priv == 0) {
369 		/* mode = TRUE; */
370 	}
371 
372 	data->msgoutbuf[pos] = IDENTIFY(mode, SCpnt->device->lun); pos++;
373 
374 	data->msgout_len = pos;
375 }
376 
377 /*
378  * SDTR Message Routine
379  */
380 static void nsp32_build_sdtr(struct scsi_cmnd    *SCpnt,
381 			     unsigned char period,
382 			     unsigned char offset)
383 {
384 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
385 	int pos = data->msgout_len;
386 
387 	data->msgoutbuf[pos] = EXTENDED_MESSAGE;  pos++;
388 	data->msgoutbuf[pos] = EXTENDED_SDTR_LEN; pos++;
389 	data->msgoutbuf[pos] = EXTENDED_SDTR;     pos++;
390 	data->msgoutbuf[pos] = period;		  pos++;
391 	data->msgoutbuf[pos] = offset;		  pos++;
392 
393 	data->msgout_len = pos;
394 }
395 
396 /*
397  * No Operation Message
398  */
399 static void nsp32_build_nop(struct scsi_cmnd *SCpnt)
400 {
401 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
402 	int pos  = data->msgout_len;
403 
404 	if (pos != 0) {
405 		nsp32_msg(KERN_WARNING,
406 			  "Some messages are already contained!");
407 		return;
408 	}
409 
410 	data->msgoutbuf[pos] = NOP; pos++;
411 	data->msgout_len = pos;
412 }
413 
414 /*
415  * Reject Message
416  */
417 static void nsp32_build_reject(struct scsi_cmnd *SCpnt)
418 {
419 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
420 	int pos  = data->msgout_len;
421 
422 	data->msgoutbuf[pos] = MESSAGE_REJECT; pos++;
423 	data->msgout_len = pos;
424 }
425 
426 /*
427  * timer
428  */
429 #if 0
430 static void nsp32_start_timer(struct scsi_cmnd *SCpnt, int time)
431 {
432 	unsigned int base = SCpnt->host->io_port;
433 
434 	nsp32_dbg(NSP32_DEBUG_INTR, "timer=%d", time);
435 
436 	if (time & (~TIMER_CNT_MASK)) {
437 		nsp32_dbg(NSP32_DEBUG_INTR, "timer set overflow");
438 	}
439 
440 	nsp32_write2(base, TIMER_SET, time & TIMER_CNT_MASK);
441 }
442 #endif
443 
444 
445 /*
446  * set SCSI command and other parameter to asic, and start selection phase
447  */
448 static int nsp32_selection_autopara(struct scsi_cmnd *SCpnt)
449 {
450 	nsp32_hw_data  *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
451 	unsigned int	base    = SCpnt->device->host->io_port;
452 	unsigned int	host_id = SCpnt->device->host->this_id;
453 	unsigned char	target  = scmd_id(SCpnt);
454 	nsp32_autoparam *param  = data->autoparam;
455 	unsigned char	phase;
456 	int		i, ret;
457 	unsigned int	msgout;
458 	u16_le		s;
459 
460 	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "in");
461 
462 	/*
463 	 * check bus free
464 	 */
465 	phase = nsp32_read1(base, SCSI_BUS_MONITOR);
466 	if (phase != BUSMON_BUS_FREE) {
467 		nsp32_msg(KERN_WARNING, "bus busy");
468 		show_busphase(phase & BUSMON_PHASE_MASK);
469 		SCpnt->result = DID_BUS_BUSY << 16;
470 		return FALSE;
471 	}
472 
473 	/*
474 	 * message out
475 	 *
476 	 * Note: If the range of msgout_len is 1 - 3, fill scsi_msgout.
477 	 *       over 3 messages needs another routine.
478 	 */
479 	if (data->msgout_len == 0) {
480 		nsp32_msg(KERN_ERR, "SCSI MsgOut without any message!");
481 		SCpnt->result = DID_ERROR << 16;
482 		return FALSE;
483 	} else if (data->msgout_len > 0 && data->msgout_len <= 3) {
484 		msgout = 0;
485 		for (i = 0; i < data->msgout_len; i++) {
486 			/*
487 			 * the sending order of the message is:
488 			 *  MCNT 3: MSG#0 -> MSG#1 -> MSG#2
489 			 *  MCNT 2:          MSG#1 -> MSG#2
490 			 *  MCNT 1:                   MSG#2
491 			 */
492 			msgout >>= 8;
493 			msgout |= ((unsigned int)(data->msgoutbuf[i]) << 24);
494 		}
495 		msgout |= MV_VALID;	/* MV valid */
496 		msgout |= (unsigned int)data->msgout_len; /* len */
497 	} else {
498 		/* data->msgout_len > 3 */
499 		msgout = 0;
500 	}
501 
502 	// nsp_dbg(NSP32_DEBUG_AUTOSCSI, "sel time out=0x%x\n",
503 	// nsp32_read2(base, SEL_TIME_OUT));
504 	// nsp32_write2(base, SEL_TIME_OUT,   SEL_TIMEOUT_TIME);
505 
506 	/*
507 	 * setup asic parameter
508 	 */
509 	memset(param, 0, sizeof(nsp32_autoparam));
510 
511 	/* cdb */
512 	for (i = 0; i < SCpnt->cmd_len; i++) {
513 		param->cdb[4 * i] = SCpnt->cmnd[i];
514 	}
515 
516 	/* outgoing messages */
517 	param->msgout = cpu_to_le32(msgout);
518 
519 	/* syncreg, ackwidth, target id, SREQ sampling rate */
520 	param->syncreg    = data->cur_target->syncreg;
521 	param->ackwidth   = data->cur_target->ackwidth;
522 	param->target_id  = BIT(host_id) | BIT(target);
523 	param->sample_reg = data->cur_target->sample_reg;
524 
525 	// nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "sample rate=0x%x\n", data->cur_target->sample_reg);
526 
527 	/* command control */
528 	param->command_control = cpu_to_le16(CLEAR_CDB_FIFO_POINTER |
529 					     AUTOSCSI_START |
530 					     AUTO_MSGIN_00_OR_04 |
531 					     AUTO_MSGIN_02 |
532 					     AUTO_ATN );
533 
534 
535 	/* transfer control */
536 	s = 0;
537 	switch (data->trans_method) {
538 	case NSP32_TRANSFER_BUSMASTER:
539 		s |= BM_START;
540 		break;
541 	case NSP32_TRANSFER_MMIO:
542 		s |= CB_MMIO_MODE;
543 		break;
544 	case NSP32_TRANSFER_PIO:
545 		s |= CB_IO_MODE;
546 		break;
547 	default:
548 		nsp32_msg(KERN_ERR, "unknown trans_method");
549 		break;
550 	}
551 	/*
552 	 * OR-ed BLIEND_MODE, FIFO intr is decreased, instead of PCI bus waits.
553 	 * For bus master transfer, it's taken off.
554 	 */
555 	s |= (TRANSFER_GO | ALL_COUNTER_CLR);
556 	param->transfer_control = cpu_to_le16(s);
557 
558 	/* sg table addr */
559 	param->sgt_pointer = cpu_to_le32(data->cur_lunt->sglun_paddr);
560 
561 	/*
562 	 * transfer parameter to ASIC
563 	 */
564 	nsp32_write4(base, SGT_ADR, data->auto_paddr);
565 	nsp32_write2(base, COMMAND_CONTROL,
566 		     CLEAR_CDB_FIFO_POINTER | AUTO_PARAMETER );
567 
568 	/*
569 	 * Check arbitration
570 	 */
571 	ret = nsp32_arbitration(SCpnt, base);
572 
573 	return ret;
574 }
575 
576 
577 /*
578  * Selection with AUTO SCSI (without AUTO PARAMETER)
579  */
580 static int nsp32_selection_autoscsi(struct scsi_cmnd *SCpnt)
581 {
582 	nsp32_hw_data  *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
583 	unsigned int	base    = SCpnt->device->host->io_port;
584 	unsigned int	host_id = SCpnt->device->host->this_id;
585 	unsigned char	target  = scmd_id(SCpnt);
586 	unsigned char	phase;
587 	int		status;
588 	unsigned short	command	= 0;
589 	unsigned int	msgout  = 0;
590 	int		i;
591 
592 	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "in");
593 
594 	/*
595 	 * IRQ disable
596 	 */
597 	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
598 
599 	/*
600 	 * check bus line
601 	 */
602 	phase = nsp32_read1(base, SCSI_BUS_MONITOR);
603 	if ((phase & BUSMON_BSY) || (phase & BUSMON_SEL)) {
604 		nsp32_msg(KERN_WARNING, "bus busy");
605 		SCpnt->result = DID_BUS_BUSY << 16;
606 		status = 1;
607 		goto out;
608 	}
609 
610 	/*
611 	 * clear execph
612 	 */
613 	nsp32_read2(base, SCSI_EXECUTE_PHASE);
614 
615 	/*
616 	 * clear FIFO counter to set CDBs
617 	 */
618 	nsp32_write2(base, COMMAND_CONTROL, CLEAR_CDB_FIFO_POINTER);
619 
620 	/*
621 	 * set CDB0 - CDB15
622 	 */
623 	for (i = 0; i < SCpnt->cmd_len; i++) {
624 		nsp32_write1(base, COMMAND_DATA, SCpnt->cmnd[i]);
625 	}
626 	nsp32_dbg(NSP32_DEBUG_CDB_CONTENTS, "CDB[0]=[0x%x]", SCpnt->cmnd[0]);
627 
628 	/*
629 	 * set SCSIOUT LATCH(initiator)/TARGET(target) (OR-ed) ID
630 	 */
631 	nsp32_write1(base, SCSI_OUT_LATCH_TARGET_ID,
632 		     BIT(host_id) | BIT(target));
633 
634 	/*
635 	 * set SCSI MSGOUT REG
636 	 *
637 	 * Note: If the range of msgout_len is 1 - 3, fill scsi_msgout.
638 	 *       over 3 messages needs another routine.
639 	 */
640 	if (data->msgout_len == 0) {
641 		nsp32_msg(KERN_ERR, "SCSI MsgOut without any message!");
642 		SCpnt->result = DID_ERROR << 16;
643 		status = 1;
644 		goto out;
645 	} else if (data->msgout_len > 0 && data->msgout_len <= 3) {
646 		msgout = 0;
647 		for (i = 0; i < data->msgout_len; i++) {
648 			/*
649 			 * the sending order of the message is:
650 			 *  MCNT 3: MSG#0 -> MSG#1 -> MSG#2
651 			 *  MCNT 2:          MSG#1 -> MSG#2
652 			 *  MCNT 1:                   MSG#2
653 			 */
654 			msgout >>= 8;
655 			msgout |= ((unsigned int)(data->msgoutbuf[i]) << 24);
656 		}
657 		msgout |= MV_VALID;	/* MV valid */
658 		msgout |= (unsigned int)data->msgout_len; /* len */
659 		nsp32_write4(base, SCSI_MSG_OUT, msgout);
660 	} else {
661 		/* data->msgout_len > 3 */
662 		nsp32_write4(base, SCSI_MSG_OUT, 0);
663 	}
664 
665 	/*
666 	 * set selection timeout(= 250ms)
667 	 */
668 	nsp32_write2(base, SEL_TIME_OUT,   SEL_TIMEOUT_TIME);
669 
670 	/*
671 	 * set SREQ hazard killer sampling rate
672 	 *
673 	 * TODO: sample_rate (BASE+0F) is 0 when internal clock = 40MHz.
674 	 *      check other internal clock!
675 	 */
676 	nsp32_write1(base, SREQ_SMPL_RATE, data->cur_target->sample_reg);
677 
678 	/*
679 	 * clear Arbit
680 	 */
681 	nsp32_write1(base, SET_ARBIT,      ARBIT_CLEAR);
682 
683 	/*
684 	 * set SYNCREG
685 	 * Don't set BM_START_ADR before setting this register.
686 	 */
687 	nsp32_write1(base, SYNC_REG,  data->cur_target->syncreg);
688 
689 	/*
690 	 * set ACKWIDTH
691 	 */
692 	nsp32_write1(base, ACK_WIDTH, data->cur_target->ackwidth);
693 
694 	nsp32_dbg(NSP32_DEBUG_AUTOSCSI,
695 		  "syncreg=0x%x, ackwidth=0x%x, sgtpaddr=0x%x, id=0x%x",
696 		  nsp32_read1(base, SYNC_REG), nsp32_read1(base, ACK_WIDTH),
697 		  nsp32_read4(base, SGT_ADR),
698 		  nsp32_read1(base, SCSI_OUT_LATCH_TARGET_ID));
699 	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "msgout_len=%d, msgout=0x%x",
700 		  data->msgout_len, msgout);
701 
702 	/*
703 	 * set SGT ADDR (physical address)
704 	 */
705 	nsp32_write4(base, SGT_ADR, data->cur_lunt->sglun_paddr);
706 
707 	/*
708 	 * set TRANSFER CONTROL REG
709 	 */
710 	command = 0;
711 	command |= (TRANSFER_GO | ALL_COUNTER_CLR);
712 	if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
713 		if (scsi_bufflen(SCpnt) > 0) {
714 			command |= BM_START;
715 		}
716 	} else if (data->trans_method & NSP32_TRANSFER_MMIO) {
717 		command |= CB_MMIO_MODE;
718 	} else if (data->trans_method & NSP32_TRANSFER_PIO) {
719 		command |= CB_IO_MODE;
720 	}
721 	nsp32_write2(base, TRANSFER_CONTROL, command);
722 
723 	/*
724 	 * start AUTO SCSI, kick off arbitration
725 	 */
726 	command = (CLEAR_CDB_FIFO_POINTER |
727 		   AUTOSCSI_START	  |
728 		   AUTO_MSGIN_00_OR_04    |
729 		   AUTO_MSGIN_02	  |
730 		   AUTO_ATN);
731 	nsp32_write2(base, COMMAND_CONTROL, command);
732 
733 	/*
734 	 * Check arbitration
735 	 */
736 	status = nsp32_arbitration(SCpnt, base);
737 
738  out:
739 	/*
740 	 * IRQ enable
741 	 */
742 	nsp32_write2(base, IRQ_CONTROL, 0);
743 
744 	return status;
745 }
746 
747 
748 /*
749  * Arbitration Status Check
750  *
751  * Note: Arbitration counter is waited during ARBIT_GO is not lifting.
752  *	 Using udelay(1) consumes CPU time and system time, but
753  *	 arbitration delay time is defined minimal 2.4us in SCSI
754  *	 specification, thus udelay works as coarse grained wait timer.
755  */
756 static int nsp32_arbitration(struct scsi_cmnd *SCpnt, unsigned int base)
757 {
758 	unsigned char arbit;
759 	int	      status = TRUE;
760 	int	      time   = 0;
761 
762 	do {
763 		arbit = nsp32_read1(base, ARBIT_STATUS);
764 		time++;
765 	} while ((arbit & (ARBIT_WIN | ARBIT_FAIL)) == 0 &&
766 		 (time <= ARBIT_TIMEOUT_TIME));
767 
768 	nsp32_dbg(NSP32_DEBUG_AUTOSCSI,
769 		  "arbit: 0x%x, delay time: %d", arbit, time);
770 
771 	if (arbit & ARBIT_WIN) {
772 		/* Arbitration succeeded */
773 		SCpnt->result = DID_OK << 16;
774 		nsp32_index_write1(base, EXT_PORT, LED_ON); /* PCI LED on */
775 	} else if (arbit & ARBIT_FAIL) {
776 		/* Arbitration failed */
777 		SCpnt->result = DID_BUS_BUSY << 16;
778 		status = FALSE;
779 	} else {
780 		/*
781 		 * unknown error or ARBIT_GO timeout,
782 		 * something lock up! guess no connection.
783 		 */
784 		nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "arbit timeout");
785 		SCpnt->result = DID_NO_CONNECT << 16;
786 		status = FALSE;
787 	}
788 
789 	/*
790 	 * clear Arbit
791 	 */
792 	nsp32_write1(base, SET_ARBIT, ARBIT_CLEAR);
793 
794 	return status;
795 }
796 
797 
798 /*
799  * reselection
800  *
801  * Note: This reselection routine is called from msgin_occur,
802  *	 reselection target id&lun must be already set.
803  *	 SCSI-2 says IDENTIFY implies RESTORE_POINTER operation.
804  */
805 static int nsp32_reselection(struct scsi_cmnd *SCpnt, unsigned char newlun)
806 {
807 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
808 	unsigned int   host_id = SCpnt->device->host->this_id;
809 	unsigned int   base    = SCpnt->device->host->io_port;
810 	unsigned char  tmpid, newid;
811 
812 	nsp32_dbg(NSP32_DEBUG_RESELECTION, "enter");
813 
814 	/*
815 	 * calculate reselected SCSI ID
816 	 */
817 	tmpid = nsp32_read1(base, RESELECT_ID);
818 	tmpid &= (~BIT(host_id));
819 	newid = 0;
820 	while (tmpid) {
821 		if (tmpid & 1) {
822 			break;
823 		}
824 		tmpid >>= 1;
825 		newid++;
826 	}
827 
828 	/*
829 	 * If reselected New ID:LUN is not existed
830 	 * or current nexus is not existed, unexpected
831 	 * reselection is occurred. Send reject message.
832 	 */
833 	if (newid >= ARRAY_SIZE(data->lunt) ||
834 	    newlun >= ARRAY_SIZE(data->lunt[0])) {
835 		nsp32_msg(KERN_WARNING, "unknown id/lun");
836 		return FALSE;
837 	} else if(data->lunt[newid][newlun].SCpnt == NULL) {
838 		nsp32_msg(KERN_WARNING, "no SCSI command is processing");
839 		return FALSE;
840 	}
841 
842 	data->cur_id    = newid;
843 	data->cur_lun   = newlun;
844 	data->cur_target = &(data->target[newid]);
845 	data->cur_lunt   = &(data->lunt[newid][newlun]);
846 
847 	/* reset SACK/SavedACK counter (or ALL clear?) */
848 	nsp32_write4(base, CLR_COUNTER, CLRCOUNTER_ALLMASK);
849 
850 	return TRUE;
851 }
852 
853 
854 /*
855  * nsp32_setup_sg_table - build scatter gather list for transfer data
856  *			    with bus master.
857  *
858  * Note: NinjaSCSI-32Bi/UDE bus master can not transfer over 64KB at a time.
859  */
860 static int nsp32_setup_sg_table(struct scsi_cmnd *SCpnt)
861 {
862 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
863 	struct scatterlist *sg;
864 	nsp32_sgtable *sgt = data->cur_lunt->sglun->sgt;
865 	int num, i;
866 	u32_le l;
867 
868 	if (sgt == NULL) {
869 		nsp32_dbg(NSP32_DEBUG_SGLIST, "SGT == null");
870 		return FALSE;
871 	}
872 
873 	num = scsi_dma_map(SCpnt);
874 	if (!num)
875 		return TRUE;
876 	else if (num < 0)
877 		return FALSE;
878 	else {
879 		scsi_for_each_sg(SCpnt, sg, num, i) {
880 			/*
881 			 * Build nsp32_sglist, substitute sg dma addresses.
882 			 */
883 			sgt[i].addr = cpu_to_le32(sg_dma_address(sg));
884 			sgt[i].len  = cpu_to_le32(sg_dma_len(sg));
885 
886 			if (le32_to_cpu(sgt[i].len) > 0x10000) {
887 				nsp32_msg(KERN_ERR,
888 					"can't transfer over 64KB at a time, "
889 					"size=0x%x", le32_to_cpu(sgt[i].len));
890 				return FALSE;
891 			}
892 			nsp32_dbg(NSP32_DEBUG_SGLIST,
893 				  "num 0x%x : addr 0x%lx len 0x%lx",
894 				  i,
895 				  le32_to_cpu(sgt[i].addr),
896 				  le32_to_cpu(sgt[i].len ));
897 		}
898 
899 		/* set end mark */
900 		l = le32_to_cpu(sgt[num-1].len);
901 		sgt[num-1].len = cpu_to_le32(l | SGTEND);
902 	}
903 
904 	return TRUE;
905 }
906 
907 static int nsp32_queuecommand_lck(struct scsi_cmnd *SCpnt)
908 {
909 	void (*done)(struct scsi_cmnd *) = scsi_done;
910 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
911 	nsp32_target *target;
912 	nsp32_lunt   *cur_lunt;
913 	int ret;
914 
915 	nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
916 		  "enter. target: 0x%x LUN: 0x%llx cmnd: 0x%x cmndlen: 0x%x "
917 		  "use_sg: 0x%x reqbuf: 0x%lx reqlen: 0x%x",
918 		  SCpnt->device->id, SCpnt->device->lun, SCpnt->cmnd[0],
919 		  SCpnt->cmd_len, scsi_sg_count(SCpnt), scsi_sglist(SCpnt),
920 		  scsi_bufflen(SCpnt));
921 
922 	if (data->CurrentSC != NULL) {
923 		nsp32_msg(KERN_ERR, "Currentsc != NULL. Cancel this command request");
924 		data->CurrentSC = NULL;
925 		SCpnt->result   = DID_NO_CONNECT << 16;
926 		done(SCpnt);
927 		return 0;
928 	}
929 
930 	/* check target ID is not same as this initiator ID */
931 	if (scmd_id(SCpnt) == SCpnt->device->host->this_id) {
932 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "target==host???");
933 		SCpnt->result = DID_BAD_TARGET << 16;
934 		done(SCpnt);
935 		return 0;
936 	}
937 
938 	/* check target LUN is allowable value */
939 	if (SCpnt->device->lun >= MAX_LUN) {
940 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "no more lun");
941 		SCpnt->result = DID_BAD_TARGET << 16;
942 		done(SCpnt);
943 		return 0;
944 	}
945 
946 	show_command(SCpnt);
947 
948 	data->CurrentSC      = SCpnt;
949 	SCpnt->SCp.Status    = SAM_STAT_CHECK_CONDITION;
950 	scsi_set_resid(SCpnt, scsi_bufflen(SCpnt));
951 
952 	SCpnt->SCp.ptr		    = (char *)scsi_sglist(SCpnt);
953 	SCpnt->SCp.this_residual    = scsi_bufflen(SCpnt);
954 	SCpnt->SCp.buffer	    = NULL;
955 	SCpnt->SCp.buffers_residual = 0;
956 
957 	/* initialize data */
958 	data->msgout_len	= 0;
959 	data->msgin_len		= 0;
960 	cur_lunt		= &(data->lunt[SCpnt->device->id][SCpnt->device->lun]);
961 	cur_lunt->SCpnt		= SCpnt;
962 	cur_lunt->save_datp	= 0;
963 	cur_lunt->msgin03	= FALSE;
964 	data->cur_lunt		= cur_lunt;
965 	data->cur_id		= SCpnt->device->id;
966 	data->cur_lun		= SCpnt->device->lun;
967 
968 	ret = nsp32_setup_sg_table(SCpnt);
969 	if (ret == FALSE) {
970 		nsp32_msg(KERN_ERR, "SGT fail");
971 		SCpnt->result = DID_ERROR << 16;
972 		nsp32_scsi_done(SCpnt);
973 		return 0;
974 	}
975 
976 	/* Build IDENTIFY */
977 	nsp32_build_identify(SCpnt);
978 
979 	/*
980 	 * If target is the first time to transfer after the reset
981 	 * (target don't have SDTR_DONE and SDTR_INITIATOR), sync
982 	 * message SDTR is needed to do synchronous transfer.
983 	 */
984 	target = &data->target[scmd_id(SCpnt)];
985 	data->cur_target = target;
986 
987 	if (!(target->sync_flag & (SDTR_DONE | SDTR_INITIATOR | SDTR_TARGET))) {
988 		unsigned char period, offset;
989 
990 		if (trans_mode != ASYNC_MODE) {
991 			nsp32_set_max_sync(data, target, &period, &offset);
992 			nsp32_build_sdtr(SCpnt, period, offset);
993 			target->sync_flag |= SDTR_INITIATOR;
994 		} else {
995 			nsp32_set_async(data, target);
996 			target->sync_flag |= SDTR_DONE;
997 		}
998 
999 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
1000 			  "SDTR: entry: %d start_period: 0x%x offset: 0x%x\n",
1001 			  target->limit_entry, period, offset);
1002 	} else if (target->sync_flag & SDTR_INITIATOR) {
1003 		/*
1004 		 * It was negotiating SDTR with target, sending from the
1005 		 * initiator, but there are no chance to remove this flag.
1006 		 * Set async because we don't get proper negotiation.
1007 		 */
1008 		nsp32_set_async(data, target);
1009 		target->sync_flag &= ~SDTR_INITIATOR;
1010 		target->sync_flag |= SDTR_DONE;
1011 
1012 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
1013 			  "SDTR_INITIATOR: fall back to async");
1014 	} else if (target->sync_flag & SDTR_TARGET) {
1015 		/*
1016 		 * It was negotiating SDTR with target, sending from target,
1017 		 * but there are no chance to remove this flag.  Set async
1018 		 * because we don't get proper negotiation.
1019 		 */
1020 		nsp32_set_async(data, target);
1021 		target->sync_flag &= ~SDTR_TARGET;
1022 		target->sync_flag |= SDTR_DONE;
1023 
1024 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
1025 			  "Unknown SDTR from target is reached, fall back to async.");
1026 	}
1027 
1028 	nsp32_dbg(NSP32_DEBUG_TARGETFLAG,
1029 		  "target: %d sync_flag: 0x%x syncreg: 0x%x ackwidth: 0x%x",
1030 		  SCpnt->device->id, target->sync_flag, target->syncreg,
1031 		  target->ackwidth);
1032 
1033 	/* Selection */
1034 	if (auto_param == 0) {
1035 		ret = nsp32_selection_autopara(SCpnt);
1036 	} else {
1037 		ret = nsp32_selection_autoscsi(SCpnt);
1038 	}
1039 
1040 	if (ret != TRUE) {
1041 		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "selection fail");
1042 		nsp32_scsi_done(SCpnt);
1043 	}
1044 
1045 	return 0;
1046 }
1047 
1048 static DEF_SCSI_QCMD(nsp32_queuecommand)
1049 
1050 /* initialize asic */
1051 static int nsp32hw_init(nsp32_hw_data *data)
1052 {
1053 	unsigned int   base = data->BaseAddress;
1054 	unsigned short irq_stat;
1055 	unsigned long  lc_reg;
1056 	unsigned char  power;
1057 
1058 	lc_reg = nsp32_index_read4(base, CFG_LATE_CACHE);
1059 	if ((lc_reg & 0xff00) == 0) {
1060 		lc_reg |= (0x20 << 8);
1061 		nsp32_index_write2(base, CFG_LATE_CACHE, lc_reg & 0xffff);
1062 	}
1063 
1064 	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
1065 	nsp32_write2(base, TRANSFER_CONTROL, 0);
1066 	nsp32_write4(base, BM_CNT, 0);
1067 	nsp32_write2(base, SCSI_EXECUTE_PHASE, 0);
1068 
1069 	do {
1070 		irq_stat = nsp32_read2(base, IRQ_STATUS);
1071 		nsp32_dbg(NSP32_DEBUG_INIT, "irq_stat 0x%x", irq_stat);
1072 	} while (irq_stat & IRQSTATUS_ANY_IRQ);
1073 
1074 	/*
1075 	 * Fill FIFO_FULL_SHLD, FIFO_EMPTY_SHLD. Below parameter is
1076 	 *  designated by specification.
1077 	 */
1078 	if ((data->trans_method & NSP32_TRANSFER_PIO) ||
1079 	    (data->trans_method & NSP32_TRANSFER_MMIO)) {
1080 		nsp32_index_write1(base, FIFO_FULL_SHLD_COUNT,  0x40);
1081 		nsp32_index_write1(base, FIFO_EMPTY_SHLD_COUNT, 0x40);
1082 	} else if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
1083 		nsp32_index_write1(base, FIFO_FULL_SHLD_COUNT,  0x10);
1084 		nsp32_index_write1(base, FIFO_EMPTY_SHLD_COUNT, 0x60);
1085 	} else {
1086 		nsp32_dbg(NSP32_DEBUG_INIT, "unknown transfer mode");
1087 	}
1088 
1089 	nsp32_dbg(NSP32_DEBUG_INIT, "full 0x%x emp 0x%x",
1090 		  nsp32_index_read1(base, FIFO_FULL_SHLD_COUNT),
1091 		  nsp32_index_read1(base, FIFO_EMPTY_SHLD_COUNT));
1092 
1093 	nsp32_index_write1(base, CLOCK_DIV, data->clock);
1094 	nsp32_index_write1(base, BM_CYCLE,
1095 			   MEMRD_CMD1 | SGT_AUTO_PARA_MEMED_CMD);
1096 	nsp32_write1(base, PARITY_CONTROL, 0);	/* parity check is disable */
1097 
1098 	/*
1099 	 * initialize MISC_WRRD register
1100 	 *
1101 	 * Note: Designated parameters is obeyed as following:
1102 	 *	MISC_SCSI_DIRECTION_DETECTOR_SELECT: It must be set.
1103 	 *	MISC_MASTER_TERMINATION_SELECT:      It must be set.
1104 	 *	MISC_BMREQ_NEGATE_TIMING_SEL:	     It should be set.
1105 	 *	MISC_AUTOSEL_TIMING_SEL:	     It should be set.
1106 	 *	MISC_BMSTOP_CHANGE2_NONDATA_PHASE:   It should be set.
1107 	 *	MISC_DELAYED_BMSTART:		     It's selected for safety.
1108 	 *
1109 	 * Note: If MISC_BMSTOP_CHANGE2_NONDATA_PHASE is set, then
1110 	 *	we have to set TRANSFERCONTROL_BM_START as 0 and set
1111 	 *	appropriate value before restarting bus master transfer.
1112 	 */
1113 	nsp32_index_write2(base, MISC_WR,
1114 			   (SCSI_DIRECTION_DETECTOR_SELECT |
1115 			    DELAYED_BMSTART |
1116 			    MASTER_TERMINATION_SELECT |
1117 			    BMREQ_NEGATE_TIMING_SEL |
1118 			    AUTOSEL_TIMING_SEL |
1119 			    BMSTOP_CHANGE2_NONDATA_PHASE));
1120 
1121 	nsp32_index_write1(base, TERM_PWR_CONTROL, 0);
1122 	power = nsp32_index_read1(base, TERM_PWR_CONTROL);
1123 	if (!(power & SENSE)) {
1124 		nsp32_msg(KERN_INFO, "term power on");
1125 		nsp32_index_write1(base, TERM_PWR_CONTROL, BPWR);
1126 	}
1127 
1128 	nsp32_write2(base, TIMER_SET, TIMER_STOP);
1129 	nsp32_write2(base, TIMER_SET, TIMER_STOP); /* Required 2 times */
1130 
1131 	nsp32_write1(base, SYNC_REG,     0);
1132 	nsp32_write1(base, ACK_WIDTH,    0);
1133 	nsp32_write2(base, SEL_TIME_OUT, SEL_TIMEOUT_TIME);
1134 
1135 	/*
1136 	 * enable to select designated IRQ (except for
1137 	 * IRQSELECT_SERR, IRQSELECT_PERR, IRQSELECT_BMCNTERR)
1138 	 */
1139 	nsp32_index_write2(base, IRQ_SELECT,
1140 			   IRQSELECT_TIMER_IRQ |
1141 			   IRQSELECT_SCSIRESET_IRQ |
1142 			   IRQSELECT_FIFO_SHLD_IRQ |
1143 			   IRQSELECT_RESELECT_IRQ |
1144 			   IRQSELECT_PHASE_CHANGE_IRQ |
1145 			   IRQSELECT_AUTO_SCSI_SEQ_IRQ |
1146 			   //   IRQSELECT_BMCNTERR_IRQ      |
1147 			   IRQSELECT_TARGET_ABORT_IRQ |
1148 			   IRQSELECT_MASTER_ABORT_IRQ );
1149 	nsp32_write2(base, IRQ_CONTROL, 0);
1150 
1151 	/* PCI LED off */
1152 	nsp32_index_write1(base, EXT_PORT_DDR, LED_OFF);
1153 	nsp32_index_write1(base, EXT_PORT,     LED_OFF);
1154 
1155 	return TRUE;
1156 }
1157 
1158 
1159 /* interrupt routine */
1160 static irqreturn_t do_nsp32_isr(int irq, void *dev_id)
1161 {
1162 	nsp32_hw_data *data = dev_id;
1163 	unsigned int base = data->BaseAddress;
1164 	struct scsi_cmnd *SCpnt = data->CurrentSC;
1165 	unsigned short auto_stat, irq_stat, trans_stat;
1166 	unsigned char busmon, busphase;
1167 	unsigned long flags;
1168 	int ret;
1169 	int handled = 0;
1170 	struct Scsi_Host *host = data->Host;
1171 
1172 	spin_lock_irqsave(host->host_lock, flags);
1173 
1174 	/*
1175 	 * IRQ check, then enable IRQ mask
1176 	 */
1177 	irq_stat = nsp32_read2(base, IRQ_STATUS);
1178 	nsp32_dbg(NSP32_DEBUG_INTR,
1179 		  "enter IRQ: %d, IRQstatus: 0x%x", irq, irq_stat);
1180 	/* is this interrupt comes from Ninja asic? */
1181 	if ((irq_stat & IRQSTATUS_ANY_IRQ) == 0) {
1182 		nsp32_dbg(NSP32_DEBUG_INTR,
1183 			  "shared interrupt: irq other 0x%x", irq_stat);
1184 		goto out2;
1185 	}
1186 	handled = 1;
1187 	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
1188 
1189 	busmon = nsp32_read1(base, SCSI_BUS_MONITOR);
1190 	busphase = busmon & BUSMON_PHASE_MASK;
1191 
1192 	trans_stat = nsp32_read2(base, TRANSFER_STATUS);
1193 	if ((irq_stat == 0xffff) && (trans_stat == 0xffff)) {
1194 		nsp32_msg(KERN_INFO, "card disconnect");
1195 		if (data->CurrentSC != NULL) {
1196 			nsp32_msg(KERN_INFO, "clean up current SCSI command");
1197 			SCpnt->result = DID_BAD_TARGET << 16;
1198 			nsp32_scsi_done(SCpnt);
1199 		}
1200 		goto out;
1201 	}
1202 
1203 	/* Timer IRQ */
1204 	if (irq_stat & IRQSTATUS_TIMER_IRQ) {
1205 		nsp32_dbg(NSP32_DEBUG_INTR, "timer stop");
1206 		nsp32_write2(base, TIMER_SET, TIMER_STOP);
1207 		goto out;
1208 	}
1209 
1210 	/* SCSI reset */
1211 	if (irq_stat & IRQSTATUS_SCSIRESET_IRQ) {
1212 		nsp32_msg(KERN_INFO, "detected someone do bus reset");
1213 		nsp32_do_bus_reset(data);
1214 		if (SCpnt != NULL) {
1215 			SCpnt->result = DID_RESET << 16;
1216 			nsp32_scsi_done(SCpnt);
1217 		}
1218 		goto out;
1219 	}
1220 
1221 	if (SCpnt == NULL) {
1222 		nsp32_msg(KERN_WARNING, "SCpnt==NULL this can't be happened");
1223 		nsp32_msg(KERN_WARNING, "irq_stat=0x%x trans_stat=0x%x",
1224 			  irq_stat, trans_stat);
1225 		goto out;
1226 	}
1227 
1228 	/*
1229 	 * AutoSCSI Interrupt.
1230 	 * Note: This interrupt is occurred when AutoSCSI is finished.  Then
1231 	 * check SCSIEXECUTEPHASE, and do appropriate action.  Each phases are
1232 	 * recorded when AutoSCSI sequencer has been processed.
1233 	 */
1234 	if(irq_stat & IRQSTATUS_AUTOSCSI_IRQ) {
1235 		/* getting SCSI executed phase */
1236 		auto_stat = nsp32_read2(base, SCSI_EXECUTE_PHASE);
1237 		nsp32_write2(base, SCSI_EXECUTE_PHASE, 0);
1238 
1239 		/* Selection Timeout, go busfree phase. */
1240 		if (auto_stat & SELECTION_TIMEOUT) {
1241 			nsp32_dbg(NSP32_DEBUG_INTR,
1242 				  "selection timeout occurred");
1243 
1244 			SCpnt->result = DID_TIME_OUT << 16;
1245 			nsp32_scsi_done(SCpnt);
1246 			goto out;
1247 		}
1248 
1249 		if (auto_stat & MSGOUT_PHASE) {
1250 			/*
1251 			 * MsgOut phase was processed.
1252 			 * If MSG_IN_OCCUER is not set, then MsgOut phase is
1253 			 * completed. Thus, msgout_len must reset.  Otherwise,
1254 			 * nothing to do here. If MSG_OUT_OCCUER is occurred,
1255 			 * then we will encounter the condition and check.
1256 			 */
1257 			if (!(auto_stat & MSG_IN_OCCUER) &&
1258 			     (data->msgout_len <= 3)) {
1259 				/*
1260 				 * !MSG_IN_OCCUER && msgout_len <=3
1261 				 *   ---> AutoSCSI with MSGOUTreg is processed.
1262 				 */
1263 				data->msgout_len = 0;
1264 			}
1265 
1266 			nsp32_dbg(NSP32_DEBUG_INTR, "MsgOut phase processed");
1267 		}
1268 
1269 		if ((auto_stat & DATA_IN_PHASE) &&
1270 		    (scsi_get_resid(SCpnt) > 0) &&
1271 		    ((nsp32_read2(base, FIFO_REST_CNT) & FIFO_REST_MASK) != 0)) {
1272 			printk( "auto+fifo\n");
1273 			//nsp32_pio_read(SCpnt);
1274 		}
1275 
1276 		if (auto_stat & (DATA_IN_PHASE | DATA_OUT_PHASE)) {
1277 			/* DATA_IN_PHASE/DATA_OUT_PHASE was processed. */
1278 			nsp32_dbg(NSP32_DEBUG_INTR,
1279 				  "Data in/out phase processed");
1280 
1281 			/* read BMCNT, SGT pointer addr */
1282 			nsp32_dbg(NSP32_DEBUG_INTR, "BMCNT=0x%lx",
1283 				    nsp32_read4(base, BM_CNT));
1284 			nsp32_dbg(NSP32_DEBUG_INTR, "addr=0x%lx",
1285 				    nsp32_read4(base, SGT_ADR));
1286 			nsp32_dbg(NSP32_DEBUG_INTR, "SACK=0x%lx",
1287 				    nsp32_read4(base, SACK_CNT));
1288 			nsp32_dbg(NSP32_DEBUG_INTR, "SSACK=0x%lx",
1289 				    nsp32_read4(base, SAVED_SACK_CNT));
1290 
1291 			scsi_set_resid(SCpnt, 0); /* all data transferred! */
1292 		}
1293 
1294 		/*
1295 		 * MsgIn Occur
1296 		 */
1297 		if (auto_stat & MSG_IN_OCCUER) {
1298 			nsp32_msgin_occur(SCpnt, irq_stat, auto_stat);
1299 		}
1300 
1301 		/*
1302 		 * MsgOut Occur
1303 		 */
1304 		if (auto_stat & MSG_OUT_OCCUER) {
1305 			nsp32_msgout_occur(SCpnt);
1306 		}
1307 
1308 		/*
1309 		 * Bus Free Occur
1310 		 */
1311 		if (auto_stat & BUS_FREE_OCCUER) {
1312 			ret = nsp32_busfree_occur(SCpnt, auto_stat);
1313 			if (ret == TRUE) {
1314 				goto out;
1315 			}
1316 		}
1317 
1318 		if (auto_stat & STATUS_PHASE) {
1319 			/*
1320 			 * Read CSB and substitute CSB for SCpnt->result
1321 			 * to save status phase stutas byte.
1322 			 * scsi error handler checks host_byte (DID_*:
1323 			 * low level driver to indicate status), then checks
1324 			 * status_byte (SCSI status byte).
1325 			 */
1326 			SCpnt->result =	(int)nsp32_read1(base, SCSI_CSB_IN);
1327 		}
1328 
1329 		if (auto_stat & ILLEGAL_PHASE) {
1330 			/* Illegal phase is detected. SACK is not back. */
1331 			nsp32_msg(KERN_WARNING,
1332 				  "AUTO SCSI ILLEGAL PHASE OCCUR!!!!");
1333 
1334 			/* TODO: currently we don't have any action... bus reset? */
1335 
1336 			/*
1337 			 * To send back SACK, assert, wait, and negate.
1338 			 */
1339 			nsp32_sack_assert(data);
1340 			nsp32_wait_req(data, NEGATE);
1341 			nsp32_sack_negate(data);
1342 
1343 		}
1344 
1345 		if (auto_stat & COMMAND_PHASE) {
1346 			/* nothing to do */
1347 			nsp32_dbg(NSP32_DEBUG_INTR, "Command phase processed");
1348 		}
1349 
1350 		if (auto_stat & AUTOSCSI_BUSY) {
1351 			/* AutoSCSI is running */
1352 		}
1353 
1354 		show_autophase(auto_stat);
1355 	}
1356 
1357 	/* FIFO_SHLD_IRQ */
1358 	if (irq_stat & IRQSTATUS_FIFO_SHLD_IRQ) {
1359 		nsp32_dbg(NSP32_DEBUG_INTR, "FIFO IRQ");
1360 
1361 		switch(busphase) {
1362 		case BUSPHASE_DATA_OUT:
1363 			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/write");
1364 
1365 			//nsp32_pio_write(SCpnt);
1366 
1367 			break;
1368 
1369 		case BUSPHASE_DATA_IN:
1370 			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/read");
1371 
1372 			//nsp32_pio_read(SCpnt);
1373 
1374 			break;
1375 
1376 		case BUSPHASE_STATUS:
1377 			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/status");
1378 
1379 			SCpnt->SCp.Status = nsp32_read1(base, SCSI_CSB_IN);
1380 
1381 			break;
1382 		default:
1383 			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/other phase");
1384 			nsp32_dbg(NSP32_DEBUG_INTR, "irq_stat=0x%x trans_stat=0x%x",
1385 				  irq_stat, trans_stat);
1386 			show_busphase(busphase);
1387 			break;
1388 		}
1389 
1390 		goto out;
1391 	}
1392 
1393 	/* Phase Change IRQ */
1394 	if (irq_stat & IRQSTATUS_PHASE_CHANGE_IRQ) {
1395 		nsp32_dbg(NSP32_DEBUG_INTR, "phase change IRQ");
1396 
1397 		switch(busphase) {
1398 		case BUSPHASE_MESSAGE_IN:
1399 			nsp32_dbg(NSP32_DEBUG_INTR, "phase chg/msg in");
1400 			nsp32_msgin_occur(SCpnt, irq_stat, 0);
1401 			break;
1402 		default:
1403 			nsp32_msg(KERN_WARNING, "phase chg/other phase?");
1404 			nsp32_msg(KERN_WARNING, "irq_stat=0x%x trans_stat=0x%x\n",
1405 				  irq_stat, trans_stat);
1406 			show_busphase(busphase);
1407 			break;
1408 		}
1409 		goto out;
1410 	}
1411 
1412 	/* PCI_IRQ */
1413 	if (irq_stat & IRQSTATUS_PCI_IRQ) {
1414 		nsp32_dbg(NSP32_DEBUG_INTR, "PCI IRQ occurred");
1415 		/* Do nothing */
1416 	}
1417 
1418 	/* BMCNTERR_IRQ */
1419 	if (irq_stat & IRQSTATUS_BMCNTERR_IRQ) {
1420 		nsp32_msg(KERN_ERR, "Received unexpected BMCNTERR IRQ! ");
1421 		/*
1422 		 * TODO: To be implemented improving bus master
1423 		 * transfer reliability when BMCNTERR is occurred in
1424 		 * AutoSCSI phase described in specification.
1425 		 */
1426 	}
1427 
1428 #if 0
1429 	nsp32_dbg(NSP32_DEBUG_INTR,
1430 		  "irq_stat=0x%x trans_stat=0x%x", irq_stat, trans_stat);
1431 	show_busphase(busphase);
1432 #endif
1433 
1434  out:
1435 	/* disable IRQ mask */
1436 	nsp32_write2(base, IRQ_CONTROL, 0);
1437 
1438  out2:
1439 	spin_unlock_irqrestore(host->host_lock, flags);
1440 
1441 	nsp32_dbg(NSP32_DEBUG_INTR, "exit");
1442 
1443 	return IRQ_RETVAL(handled);
1444 }
1445 
1446 
1447 static int nsp32_show_info(struct seq_file *m, struct Scsi_Host *host)
1448 {
1449 	unsigned long     flags;
1450 	nsp32_hw_data    *data;
1451 	int		  hostno;
1452 	unsigned int      base;
1453 	unsigned char     mode_reg;
1454 	int		  id, speed;
1455 	long		  model;
1456 
1457 	hostno = host->host_no;
1458 	data = (nsp32_hw_data *)host->hostdata;
1459 	base = host->io_port;
1460 
1461 	seq_puts(m, "NinjaSCSI-32 status\n\n");
1462 	seq_printf(m, "Driver version:        %s, $Revision: 1.33 $\n",
1463 		   nsp32_release_version);
1464 	seq_printf(m, "SCSI host No.:         %d\n", hostno);
1465 	seq_printf(m, "IRQ:                   %d\n", host->irq);
1466 	seq_printf(m, "IO:                    0x%lx-0x%lx\n",
1467 		   host->io_port, host->io_port + host->n_io_port - 1);
1468 	seq_printf(m, "MMIO(virtual address): 0x%lx-0x%lx\n",
1469 		   host->base, host->base + data->MmioLength - 1);
1470 	seq_printf(m, "sg_tablesize:          %d\n",
1471 		   host->sg_tablesize);
1472 	seq_printf(m, "Chip revision:         0x%x\n",
1473 		   (nsp32_read2(base, INDEX_REG) >> 8) & 0xff);
1474 
1475 	mode_reg = nsp32_index_read1(base, CHIP_MODE);
1476 	model    = data->pci_devid->driver_data;
1477 
1478 #ifdef CONFIG_PM
1479 	seq_printf(m, "Power Management:      %s\n",
1480 		   (mode_reg & OPTF) ? "yes" : "no");
1481 #endif
1482 	seq_printf(m, "OEM:                   %ld, %s\n",
1483 		   (mode_reg & (OEM0|OEM1)), nsp32_model[model]);
1484 
1485 	spin_lock_irqsave(&(data->Lock), flags);
1486 	seq_printf(m, "CurrentSC:             0x%p\n\n",      data->CurrentSC);
1487 	spin_unlock_irqrestore(&(data->Lock), flags);
1488 
1489 
1490 	seq_puts(m, "SDTR status\n");
1491 	for (id = 0; id < ARRAY_SIZE(data->target); id++) {
1492 
1493 		seq_printf(m, "id %d: ", id);
1494 
1495 		if (id == host->this_id) {
1496 			seq_puts(m, "----- NinjaSCSI-32 host adapter\n");
1497 			continue;
1498 		}
1499 
1500 		if (data->target[id].sync_flag == SDTR_DONE) {
1501 			if (data->target[id].period == 0 &&
1502 			    data->target[id].offset == ASYNC_OFFSET ) {
1503 				seq_puts(m, "async");
1504 			} else {
1505 				seq_puts(m, " sync");
1506 			}
1507 		} else {
1508 			seq_puts(m, " none");
1509 		}
1510 
1511 		if (data->target[id].period != 0) {
1512 
1513 			speed = 1000000 / (data->target[id].period * 4);
1514 
1515 			seq_printf(m, " transfer %d.%dMB/s, offset %d",
1516 				speed / 1000,
1517 				speed % 1000,
1518 				data->target[id].offset
1519 				);
1520 		}
1521 		seq_putc(m, '\n');
1522 	}
1523 	return 0;
1524 }
1525 
1526 
1527 
1528 /*
1529  * Reset parameters and call scsi_done for data->cur_lunt.
1530  * Be careful setting SCpnt->result = DID_* before calling this function.
1531  */
1532 static void nsp32_scsi_done(struct scsi_cmnd *SCpnt)
1533 {
1534 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1535 	unsigned int   base = SCpnt->device->host->io_port;
1536 
1537 	scsi_dma_unmap(SCpnt);
1538 
1539 	/*
1540 	 * clear TRANSFERCONTROL_BM_START
1541 	 */
1542 	nsp32_write2(base, TRANSFER_CONTROL, 0);
1543 	nsp32_write4(base, BM_CNT, 0);
1544 
1545 	/*
1546 	 * call scsi_done
1547 	 */
1548 	scsi_done(SCpnt);
1549 
1550 	/*
1551 	 * reset parameters
1552 	 */
1553 	data->cur_lunt->SCpnt	= NULL;
1554 	data->cur_lunt		= NULL;
1555 	data->cur_target	= NULL;
1556 	data->CurrentSC		= NULL;
1557 }
1558 
1559 
1560 /*
1561  * Bus Free Occur
1562  *
1563  * Current Phase is BUSFREE. AutoSCSI is automatically execute BUSFREE phase
1564  * with ACK reply when below condition is matched:
1565  *	MsgIn 00: Command Complete.
1566  *	MsgIn 02: Save Data Pointer.
1567  *	MsgIn 04: Disconnect.
1568  * In other case, unexpected BUSFREE is detected.
1569  */
1570 static int nsp32_busfree_occur(struct scsi_cmnd *SCpnt, unsigned short execph)
1571 {
1572 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1573 	unsigned int base   = SCpnt->device->host->io_port;
1574 
1575 	nsp32_dbg(NSP32_DEBUG_BUSFREE, "enter execph=0x%x", execph);
1576 	show_autophase(execph);
1577 
1578 	nsp32_write4(base, BM_CNT, 0);
1579 	nsp32_write2(base, TRANSFER_CONTROL, 0);
1580 
1581 	/*
1582 	 * MsgIn 02: Save Data Pointer
1583 	 *
1584 	 * VALID:
1585 	 *   Save Data Pointer is received. Adjust pointer.
1586 	 *
1587 	 * NO-VALID:
1588 	 *   SCSI-3 says if Save Data Pointer is not received, then we restart
1589 	 *   processing and we can't adjust any SCSI data pointer in next data
1590 	 *   phase.
1591 	 */
1592 	if (execph & MSGIN_02_VALID) {
1593 		nsp32_dbg(NSP32_DEBUG_BUSFREE, "MsgIn02_Valid");
1594 
1595 		/*
1596 		 * Check sack_cnt/saved_sack_cnt, then adjust sg table if
1597 		 * needed.
1598 		 */
1599 		if (!(execph & MSGIN_00_VALID) &&
1600 		    ((execph & DATA_IN_PHASE) || (execph & DATA_OUT_PHASE))) {
1601 			unsigned int sacklen, s_sacklen;
1602 
1603 			/*
1604 			 * Read SACK count and SAVEDSACK count, then compare.
1605 			 */
1606 			sacklen   = nsp32_read4(base, SACK_CNT      );
1607 			s_sacklen = nsp32_read4(base, SAVED_SACK_CNT);
1608 
1609 			/*
1610 			 * If SAVEDSACKCNT == 0, it means SavedDataPointer is
1611 			 * come after data transferring.
1612 			 */
1613 			if (s_sacklen > 0) {
1614 				/*
1615 				 * Comparing between sack and savedsack to
1616 				 * check the condition of AutoMsgIn03.
1617 				 *
1618 				 * If they are same, set msgin03 == TRUE,
1619 				 * COMMANDCONTROL_AUTO_MSGIN_03 is enabled at
1620 				 * reselection.  On the other hand, if they
1621 				 * aren't same, set msgin03 == FALSE, and
1622 				 * COMMANDCONTROL_AUTO_MSGIN_03 is disabled at
1623 				 * reselection.
1624 				 */
1625 				if (sacklen != s_sacklen) {
1626 					data->cur_lunt->msgin03 = FALSE;
1627 				} else {
1628 					data->cur_lunt->msgin03 = TRUE;
1629 				}
1630 
1631 				nsp32_adjust_busfree(SCpnt, s_sacklen);
1632 			}
1633 		}
1634 
1635 		/* This value has not substitude with valid value yet... */
1636 		//data->cur_lunt->save_datp = data->cur_datp;
1637 	} else {
1638 		/*
1639 		 * no processing.
1640 		 */
1641 	}
1642 
1643 	if (execph & MSGIN_03_VALID) {
1644 		/* MsgIn03 was valid to be processed. No need processing. */
1645 	}
1646 
1647 	/*
1648 	 * target SDTR check
1649 	 */
1650 	if (data->cur_target->sync_flag & SDTR_INITIATOR) {
1651 		/*
1652 		 * SDTR negotiation pulled by the initiator has not
1653 		 * finished yet. Fall back to ASYNC mode.
1654 		 */
1655 		nsp32_set_async(data, data->cur_target);
1656 		data->cur_target->sync_flag &= ~SDTR_INITIATOR;
1657 		data->cur_target->sync_flag |= SDTR_DONE;
1658 	} else if (data->cur_target->sync_flag & SDTR_TARGET) {
1659 		/*
1660 		 * SDTR negotiation pulled by the target has been
1661 		 * negotiating.
1662 		 */
1663 		if (execph & (MSGIN_00_VALID | MSGIN_04_VALID)) {
1664 			/*
1665 			 * If valid message is received, then
1666 			 * negotiation is succeeded.
1667 			 */
1668 		} else {
1669 			/*
1670 			 * On the contrary, if unexpected bus free is
1671 			 * occurred, then negotiation is failed. Fall
1672 			 * back to ASYNC mode.
1673 			 */
1674 			nsp32_set_async(data, data->cur_target);
1675 		}
1676 		data->cur_target->sync_flag &= ~SDTR_TARGET;
1677 		data->cur_target->sync_flag |= SDTR_DONE;
1678 	}
1679 
1680 	/*
1681 	 * It is always ensured by SCSI standard that initiator
1682 	 * switches into Bus Free Phase after
1683 	 * receiving message 00 (Command Complete), 04 (Disconnect).
1684 	 * It's the reason that processing here is valid.
1685 	 */
1686 	if (execph & MSGIN_00_VALID) {
1687 		/* MsgIn 00: Command Complete */
1688 		nsp32_dbg(NSP32_DEBUG_BUSFREE, "command complete");
1689 
1690 		SCpnt->SCp.Status  = nsp32_read1(base, SCSI_CSB_IN);
1691 		nsp32_dbg(NSP32_DEBUG_BUSFREE,
1692 			  "normal end stat=0x%x resid=0x%x\n",
1693 			  SCpnt->SCp.Status, scsi_get_resid(SCpnt));
1694 		SCpnt->result = (DID_OK << 16) |
1695 			(SCpnt->SCp.Status << 0);
1696 		nsp32_scsi_done(SCpnt);
1697 		/* All operation is done */
1698 		return TRUE;
1699 	} else if (execph & MSGIN_04_VALID) {
1700 		/* MsgIn 04: Disconnect */
1701 		SCpnt->SCp.Status  = nsp32_read1(base, SCSI_CSB_IN);
1702 
1703 		nsp32_dbg(NSP32_DEBUG_BUSFREE, "disconnect");
1704 		return TRUE;
1705 	} else {
1706 		/* Unexpected bus free */
1707 		nsp32_msg(KERN_WARNING, "unexpected bus free occurred");
1708 
1709 		/* DID_ERROR? */
1710 		//SCpnt->result   = (DID_OK << 16) | (SCpnt->SCp.Status << 0);
1711 		SCpnt->result = DID_ERROR << 16;
1712 		nsp32_scsi_done(SCpnt);
1713 		return TRUE;
1714 	}
1715 	return FALSE;
1716 }
1717 
1718 
1719 /*
1720  * nsp32_adjust_busfree - adjusting SG table
1721  *
1722  * Note: This driver adjust the SG table using SCSI ACK
1723  *       counter instead of BMCNT counter!
1724  */
1725 static void nsp32_adjust_busfree(struct scsi_cmnd *SCpnt, unsigned int s_sacklen)
1726 {
1727 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1728 	int old_entry = data->cur_entry;
1729 	int new_entry;
1730 	int sg_num = data->cur_lunt->sg_num;
1731 	nsp32_sgtable *sgt = data->cur_lunt->sglun->sgt;
1732 	unsigned int restlen, sentlen;
1733 	u32_le len, addr;
1734 
1735 	nsp32_dbg(NSP32_DEBUG_SGLIST, "old resid=0x%x", scsi_get_resid(SCpnt));
1736 
1737 	/* adjust saved SACK count with 4 byte start address boundary */
1738 	s_sacklen -= le32_to_cpu(sgt[old_entry].addr) & 3;
1739 
1740 	/*
1741 	 * calculate new_entry from sack count and each sgt[].len
1742 	 * calculate the byte which is intent to send
1743 	 */
1744 	sentlen = 0;
1745 	for (new_entry = old_entry; new_entry < sg_num; new_entry++) {
1746 		sentlen += (le32_to_cpu(sgt[new_entry].len) & ~SGTEND);
1747 		if (sentlen > s_sacklen) {
1748 			break;
1749 		}
1750 	}
1751 
1752 	/* all sgt is processed */
1753 	if (new_entry == sg_num) {
1754 		goto last;
1755 	}
1756 
1757 	if (sentlen == s_sacklen) {
1758 		/* XXX: confirm it's ok or not */
1759 		/* In this case, it's ok because we are at
1760 		 * the head element of the sg. restlen is correctly
1761 		 * calculated.
1762 		 */
1763 	}
1764 
1765 	/* calculate the rest length for transferring */
1766 	restlen = sentlen - s_sacklen;
1767 
1768 	/* update adjusting current SG table entry */
1769 	len  = le32_to_cpu(sgt[new_entry].len);
1770 	addr = le32_to_cpu(sgt[new_entry].addr);
1771 	addr += (len - restlen);
1772 	sgt[new_entry].addr = cpu_to_le32(addr);
1773 	sgt[new_entry].len  = cpu_to_le32(restlen);
1774 
1775 	/* set cur_entry with new_entry */
1776 	data->cur_entry = new_entry;
1777 
1778 	return;
1779 
1780  last:
1781 	if (scsi_get_resid(SCpnt) < sentlen) {
1782 		nsp32_msg(KERN_ERR, "resid underflow");
1783 	}
1784 
1785 	scsi_set_resid(SCpnt, scsi_get_resid(SCpnt) - sentlen);
1786 	nsp32_dbg(NSP32_DEBUG_SGLIST, "new resid=0x%x", scsi_get_resid(SCpnt));
1787 
1788 	/* update hostdata and lun */
1789 
1790 	return;
1791 }
1792 
1793 
1794 /*
1795  * It's called MsgOut phase occur.
1796  * NinjaSCSI-32Bi/UDE automatically processes up to 3 messages in
1797  * message out phase. It, however, has more than 3 messages,
1798  * HBA creates the interrupt and we have to process by hand.
1799  */
1800 static void nsp32_msgout_occur(struct scsi_cmnd *SCpnt)
1801 {
1802 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1803 	unsigned int base   = SCpnt->device->host->io_port;
1804 	int i;
1805 
1806 	nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR,
1807 		  "enter: msgout_len: 0x%x", data->msgout_len);
1808 
1809 	/*
1810 	 * If MsgOut phase is occurred without having any
1811 	 * message, then No_Operation is sent (SCSI-2).
1812 	 */
1813 	if (data->msgout_len == 0) {
1814 		nsp32_build_nop(SCpnt);
1815 	}
1816 
1817 	/*
1818 	 * send messages
1819 	 */
1820 	for (i = 0; i < data->msgout_len; i++) {
1821 		nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR,
1822 			  "%d : 0x%x", i, data->msgoutbuf[i]);
1823 
1824 		/*
1825 		 * Check REQ is asserted.
1826 		 */
1827 		nsp32_wait_req(data, ASSERT);
1828 
1829 		if (i == (data->msgout_len - 1)) {
1830 			/*
1831 			 * If the last message, set the AutoSCSI restart
1832 			 * before send back the ack message. AutoSCSI
1833 			 * restart automatically negate ATN signal.
1834 			 */
1835 			//command = (AUTO_MSGIN_00_OR_04 | AUTO_MSGIN_02);
1836 			//nsp32_restart_autoscsi(SCpnt, command);
1837 			nsp32_write2(base, COMMAND_CONTROL,
1838 					 (CLEAR_CDB_FIFO_POINTER |
1839 					  AUTO_COMMAND_PHASE |
1840 					  AUTOSCSI_RESTART |
1841 					  AUTO_MSGIN_00_OR_04 |
1842 					  AUTO_MSGIN_02 ));
1843 		}
1844 		/*
1845 		 * Write data with SACK, then wait sack is
1846 		 * automatically negated.
1847 		 */
1848 		nsp32_write1(base, SCSI_DATA_WITH_ACK, data->msgoutbuf[i]);
1849 		nsp32_wait_sack(data, NEGATE);
1850 
1851 		nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR, "bus: 0x%x\n",
1852 			  nsp32_read1(base, SCSI_BUS_MONITOR));
1853 	}
1854 
1855 	data->msgout_len = 0;
1856 
1857 	nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR, "exit");
1858 }
1859 
1860 /*
1861  * Restart AutoSCSI
1862  *
1863  * Note: Restarting AutoSCSI needs set:
1864  *		SYNC_REG, ACK_WIDTH, SGT_ADR, TRANSFER_CONTROL
1865  */
1866 static void nsp32_restart_autoscsi(struct scsi_cmnd *SCpnt, unsigned short command)
1867 {
1868 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1869 	unsigned int   base = data->BaseAddress;
1870 	unsigned short transfer = 0;
1871 
1872 	nsp32_dbg(NSP32_DEBUG_RESTART, "enter");
1873 
1874 	if (data->cur_target == NULL || data->cur_lunt == NULL) {
1875 		nsp32_msg(KERN_ERR, "Target or Lun is invalid");
1876 	}
1877 
1878 	/*
1879 	 * set SYNC_REG
1880 	 * Don't set BM_START_ADR before setting this register.
1881 	 */
1882 	nsp32_write1(base, SYNC_REG, data->cur_target->syncreg);
1883 
1884 	/*
1885 	 * set ACKWIDTH
1886 	 */
1887 	nsp32_write1(base, ACK_WIDTH, data->cur_target->ackwidth);
1888 
1889 	/*
1890 	 * set SREQ hazard killer sampling rate
1891 	 */
1892 	nsp32_write1(base, SREQ_SMPL_RATE, data->cur_target->sample_reg);
1893 
1894 	/*
1895 	 * set SGT ADDR (physical address)
1896 	 */
1897 	nsp32_write4(base, SGT_ADR, data->cur_lunt->sglun_paddr);
1898 
1899 	/*
1900 	 * set TRANSFER CONTROL REG
1901 	 */
1902 	transfer = 0;
1903 	transfer |= (TRANSFER_GO | ALL_COUNTER_CLR);
1904 	if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
1905 		if (scsi_bufflen(SCpnt) > 0) {
1906 			transfer |= BM_START;
1907 		}
1908 	} else if (data->trans_method & NSP32_TRANSFER_MMIO) {
1909 		transfer |= CB_MMIO_MODE;
1910 	} else if (data->trans_method & NSP32_TRANSFER_PIO) {
1911 		transfer |= CB_IO_MODE;
1912 	}
1913 	nsp32_write2(base, TRANSFER_CONTROL, transfer);
1914 
1915 	/*
1916 	 * restart AutoSCSI
1917 	 *
1918 	 * TODO: COMMANDCONTROL_AUTO_COMMAND_PHASE is needed ?
1919 	 */
1920 	command |= (CLEAR_CDB_FIFO_POINTER |
1921 		    AUTO_COMMAND_PHASE     |
1922 		    AUTOSCSI_RESTART       );
1923 	nsp32_write2(base, COMMAND_CONTROL, command);
1924 
1925 	nsp32_dbg(NSP32_DEBUG_RESTART, "exit");
1926 }
1927 
1928 
1929 /*
1930  * cannot run automatically message in occur
1931  */
1932 static void nsp32_msgin_occur(struct scsi_cmnd     *SCpnt,
1933 			      unsigned long  irq_status,
1934 			      unsigned short execph)
1935 {
1936 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
1937 	unsigned int   base = SCpnt->device->host->io_port;
1938 	unsigned char  msg;
1939 	unsigned char  msgtype;
1940 	unsigned char  newlun;
1941 	unsigned short command  = 0;
1942 	int	       msgclear = TRUE;
1943 	long	       new_sgtp;
1944 	int	       ret;
1945 
1946 	/*
1947 	 * read first message
1948 	 *    Use SCSIDATA_W_ACK instead of SCSIDATAIN, because the procedure
1949 	 *    of Message-In have to be processed before sending back SCSI ACK.
1950 	 */
1951 	msg = nsp32_read1(base, SCSI_DATA_IN);
1952 	data->msginbuf[(unsigned char)data->msgin_len] = msg;
1953 	msgtype = data->msginbuf[0];
1954 	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR,
1955 		  "enter: msglen: 0x%x msgin: 0x%x msgtype: 0x%x",
1956 		  data->msgin_len, msg, msgtype);
1957 
1958 	/*
1959 	 * TODO: We need checking whether bus phase is message in?
1960 	 */
1961 
1962 	/*
1963 	 * assert SCSI ACK
1964 	 */
1965 	nsp32_sack_assert(data);
1966 
1967 	/*
1968 	 * processing IDENTIFY
1969 	 */
1970 	if (msgtype & 0x80) {
1971 		if (!(irq_status & IRQSTATUS_RESELECT_OCCUER)) {
1972 			/* Invalid (non reselect) phase */
1973 			goto reject;
1974 		}
1975 
1976 		newlun = msgtype & 0x1f; /* TODO: SPI-3 compliant? */
1977 		ret = nsp32_reselection(SCpnt, newlun);
1978 		if (ret == TRUE) {
1979 			goto restart;
1980 		} else {
1981 			goto reject;
1982 		}
1983 	}
1984 
1985 	/*
1986 	 * processing messages except for IDENTIFY
1987 	 *
1988 	 * TODO: Messages are all SCSI-2 terminology. SCSI-3 compliance is TODO.
1989 	 */
1990 	switch (msgtype) {
1991 	/*
1992 	 * 1-byte message
1993 	 */
1994 	case COMMAND_COMPLETE:
1995 	case DISCONNECT:
1996 		/*
1997 		 * These messages should not be occurred.
1998 		 * They should be processed on AutoSCSI sequencer.
1999 		 */
2000 		nsp32_msg(KERN_WARNING,
2001 			   "unexpected message of AutoSCSI MsgIn: 0x%x", msg);
2002 		break;
2003 
2004 	case RESTORE_POINTERS:
2005 		/*
2006 		 * AutoMsgIn03 is disabled, and HBA gets this message.
2007 		 */
2008 
2009 		if ((execph & DATA_IN_PHASE) || (execph & DATA_OUT_PHASE)) {
2010 			unsigned int s_sacklen;
2011 
2012 			s_sacklen = nsp32_read4(base, SAVED_SACK_CNT);
2013 			if ((execph & MSGIN_02_VALID) && (s_sacklen > 0)) {
2014 				nsp32_adjust_busfree(SCpnt, s_sacklen);
2015 			} else {
2016 				/* No need to rewrite SGT */
2017 			}
2018 		}
2019 		data->cur_lunt->msgin03 = FALSE;
2020 
2021 		/* Update with the new value */
2022 
2023 		/* reset SACK/SavedACK counter (or ALL clear?) */
2024 		nsp32_write4(base, CLR_COUNTER, CLRCOUNTER_ALLMASK);
2025 
2026 		/*
2027 		 * set new sg pointer
2028 		 */
2029 		new_sgtp = data->cur_lunt->sglun_paddr +
2030 			(data->cur_lunt->cur_entry * sizeof(nsp32_sgtable));
2031 		nsp32_write4(base, SGT_ADR, new_sgtp);
2032 
2033 		break;
2034 
2035 	case SAVE_POINTERS:
2036 		/*
2037 		 * These messages should not be occurred.
2038 		 * They should be processed on AutoSCSI sequencer.
2039 		 */
2040 		nsp32_msg (KERN_WARNING,
2041 			   "unexpected message of AutoSCSI MsgIn: SAVE_POINTERS");
2042 
2043 		break;
2044 
2045 	case MESSAGE_REJECT:
2046 		/* If previous message_out is sending SDTR, and get
2047 		   message_reject from target, SDTR negotiation is failed */
2048 		if (data->cur_target->sync_flag &
2049 				(SDTR_INITIATOR | SDTR_TARGET)) {
2050 			/*
2051 			 * Current target is negotiating SDTR, but it's
2052 			 * failed.  Fall back to async transfer mode, and set
2053 			 * SDTR_DONE.
2054 			 */
2055 			nsp32_set_async(data, data->cur_target);
2056 			data->cur_target->sync_flag &= ~SDTR_INITIATOR;
2057 			data->cur_target->sync_flag |= SDTR_DONE;
2058 
2059 		}
2060 		break;
2061 
2062 	case LINKED_CMD_COMPLETE:
2063 	case LINKED_FLG_CMD_COMPLETE:
2064 		/* queue tag is not supported currently */
2065 		nsp32_msg (KERN_WARNING,
2066 			   "unsupported message: 0x%x", msgtype);
2067 		break;
2068 
2069 	case INITIATE_RECOVERY:
2070 		/* staring ECA (Extended Contingent Allegiance) state. */
2071 		/* This message is declined in SPI2 or later. */
2072 
2073 		goto reject;
2074 
2075 	/*
2076 	 * 2-byte message
2077 	 */
2078 	case SIMPLE_QUEUE_TAG:
2079 	case 0x23:
2080 		/*
2081 		 * 0x23: Ignore_Wide_Residue is not declared in scsi.h.
2082 		 * No support is needed.
2083 		 */
2084 		if (data->msgin_len >= 1) {
2085 			goto reject;
2086 		}
2087 
2088 		/* current position is 1-byte of 2 byte */
2089 		msgclear = FALSE;
2090 
2091 		break;
2092 
2093 	/*
2094 	 * extended message
2095 	 */
2096 	case EXTENDED_MESSAGE:
2097 		if (data->msgin_len < 1) {
2098 			/*
2099 			 * Current position does not reach 2-byte
2100 			 * (2-byte is extended message length).
2101 			 */
2102 			msgclear = FALSE;
2103 			break;
2104 		}
2105 
2106 		if ((data->msginbuf[1] + 1) > data->msgin_len) {
2107 			/*
2108 			 * Current extended message has msginbuf[1] + 2
2109 			 * (msgin_len starts counting from 0, so buf[1] + 1).
2110 			 * If current message position is not finished,
2111 			 * continue receiving message.
2112 			 */
2113 			msgclear = FALSE;
2114 			break;
2115 		}
2116 
2117 		/*
2118 		 * Reach here means regular length of each type of
2119 		 * extended messages.
2120 		 */
2121 		switch (data->msginbuf[2]) {
2122 		case EXTENDED_MODIFY_DATA_POINTER:
2123 			/* TODO */
2124 			goto reject; /* not implemented yet */
2125 			break;
2126 
2127 		case EXTENDED_SDTR:
2128 			/*
2129 			 * Exchange this message between initiator and target.
2130 			 */
2131 			if (data->msgin_len != EXTENDED_SDTR_LEN + 1) {
2132 				/*
2133 				 * received inappropriate message.
2134 				 */
2135 				goto reject;
2136 				break;
2137 			}
2138 
2139 			nsp32_analyze_sdtr(SCpnt);
2140 
2141 			break;
2142 
2143 		case EXTENDED_EXTENDED_IDENTIFY:
2144 			/* SCSI-I only, not supported. */
2145 			goto reject; /* not implemented yet */
2146 
2147 			break;
2148 
2149 		case EXTENDED_WDTR:
2150 			goto reject; /* not implemented yet */
2151 
2152 			break;
2153 
2154 		default:
2155 			goto reject;
2156 		}
2157 		break;
2158 
2159 	default:
2160 		goto reject;
2161 	}
2162 
2163  restart:
2164 	if (msgclear == TRUE) {
2165 		data->msgin_len = 0;
2166 
2167 		/*
2168 		 * If restarting AutoSCSI, but there are some message to out
2169 		 * (msgout_len > 0), set AutoATN, and set SCSIMSGOUT as 0
2170 		 * (MV_VALID = 0). When commandcontrol is written with
2171 		 * AutoSCSI restart, at the same time MsgOutOccur should be
2172 		 * happened (however, such situation is really possible...?).
2173 		 */
2174 		if (data->msgout_len > 0) {
2175 			nsp32_write4(base, SCSI_MSG_OUT, 0);
2176 			command |= AUTO_ATN;
2177 		}
2178 
2179 		/*
2180 		 * restart AutoSCSI
2181 		 * If it's failed, COMMANDCONTROL_AUTO_COMMAND_PHASE is needed.
2182 		 */
2183 		command |= (AUTO_MSGIN_00_OR_04 | AUTO_MSGIN_02);
2184 
2185 		/*
2186 		 * If current msgin03 is TRUE, then flag on.
2187 		 */
2188 		if (data->cur_lunt->msgin03 == TRUE) {
2189 			command |= AUTO_MSGIN_03;
2190 		}
2191 		data->cur_lunt->msgin03 = FALSE;
2192 	} else {
2193 		data->msgin_len++;
2194 	}
2195 
2196 	/*
2197 	 * restart AutoSCSI
2198 	 */
2199 	nsp32_restart_autoscsi(SCpnt, command);
2200 
2201 	/*
2202 	 * wait SCSI REQ negate for REQ-ACK handshake
2203 	 */
2204 	nsp32_wait_req(data, NEGATE);
2205 
2206 	/*
2207 	 * negate SCSI ACK
2208 	 */
2209 	nsp32_sack_negate(data);
2210 
2211 	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit");
2212 
2213 	return;
2214 
2215  reject:
2216 	nsp32_msg(KERN_WARNING,
2217 		  "invalid or unsupported MessageIn, rejected. "
2218 		  "current msg: 0x%x (len: 0x%x), processing msg: 0x%x",
2219 		  msg, data->msgin_len, msgtype);
2220 	nsp32_build_reject(SCpnt);
2221 	data->msgin_len = 0;
2222 
2223 	goto restart;
2224 }
2225 
2226 /*
2227  *
2228  */
2229 static void nsp32_analyze_sdtr(struct scsi_cmnd *SCpnt)
2230 {
2231 	nsp32_hw_data   *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
2232 	nsp32_target    *target     = data->cur_target;
2233 	unsigned char    get_period = data->msginbuf[3];
2234 	unsigned char    get_offset = data->msginbuf[4];
2235 	int		 entry;
2236 
2237 	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "enter");
2238 
2239 	/*
2240 	 * If this inititor sent the SDTR message, then target responds SDTR,
2241 	 * initiator SYNCREG, ACKWIDTH from SDTR parameter.
2242 	 * Messages are not appropriate, then send back reject message.
2243 	 * If initiator did not send the SDTR, but target sends SDTR,
2244 	 * initiator calculator the appropriate parameter and send back SDTR.
2245 	 */
2246 	if (target->sync_flag & SDTR_INITIATOR) {
2247 		/*
2248 		 * Initiator sent SDTR, the target responds and
2249 		 * send back negotiation SDTR.
2250 		 */
2251 		nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "target responds SDTR");
2252 
2253 		target->sync_flag &= ~SDTR_INITIATOR;
2254 		target->sync_flag |= SDTR_DONE;
2255 
2256 		/*
2257 		 * offset:
2258 		 */
2259 		if (get_offset > SYNC_OFFSET) {
2260 			/*
2261 			 * Negotiation is failed, the target send back
2262 			 * unexpected offset value.
2263 			 */
2264 			goto reject;
2265 		}
2266 
2267 		if (get_offset == ASYNC_OFFSET) {
2268 			/*
2269 			 * Negotiation is succeeded, the target want
2270 			 * to fall back into asynchronous transfer mode.
2271 			 */
2272 			goto async;
2273 		}
2274 
2275 		/*
2276 		 * period:
2277 		 *    Check whether sync period is too short. If too short,
2278 		 *    fall back to async mode. If it's ok, then investigate
2279 		 *    the received sync period. If sync period is acceptable
2280 		 *    between sync table start_period and end_period, then
2281 		 *    set this I_T nexus as sent offset and period.
2282 		 *    If it's not acceptable, send back reject and fall back
2283 		 *    to async mode.
2284 		 */
2285 		if (get_period < data->synct[0].period_num) {
2286 			/*
2287 			 * Negotiation is failed, the target send back
2288 			 * unexpected period value.
2289 			 */
2290 			goto reject;
2291 		}
2292 
2293 		entry = nsp32_search_period_entry(data, target, get_period);
2294 
2295 		if (entry < 0) {
2296 			/*
2297 			 * Target want to use long period which is not
2298 			 * acceptable NinjaSCSI-32Bi/UDE.
2299 			 */
2300 			goto reject;
2301 		}
2302 
2303 		/*
2304 		 * Set new sync table and offset in this I_T nexus.
2305 		 */
2306 		nsp32_set_sync_entry(data, target, entry, get_offset);
2307 	} else {
2308 		/* Target send SDTR to initiator. */
2309 		nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "target send SDTR");
2310 
2311 		target->sync_flag |= SDTR_INITIATOR;
2312 
2313 		/* offset: */
2314 		if (get_offset > SYNC_OFFSET) {
2315 			/* send back as SYNC_OFFSET */
2316 			get_offset = SYNC_OFFSET;
2317 		}
2318 
2319 		/* period: */
2320 		if (get_period < data->synct[0].period_num) {
2321 			get_period = data->synct[0].period_num;
2322 		}
2323 
2324 		entry = nsp32_search_period_entry(data, target, get_period);
2325 
2326 		if (get_offset == ASYNC_OFFSET || entry < 0) {
2327 			nsp32_set_async(data, target);
2328 			nsp32_build_sdtr(SCpnt, 0, ASYNC_OFFSET);
2329 		} else {
2330 			nsp32_set_sync_entry(data, target, entry, get_offset);
2331 			nsp32_build_sdtr(SCpnt, get_period, get_offset);
2332 		}
2333 	}
2334 
2335 	target->period = get_period;
2336 	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit");
2337 	return;
2338 
2339  reject:
2340 	/*
2341 	 * If the current message is unacceptable, send back to the target
2342 	 * with reject message.
2343 	 */
2344 	nsp32_build_reject(SCpnt);
2345 
2346  async:
2347 	nsp32_set_async(data, target);	/* set as ASYNC transfer mode */
2348 
2349 	target->period = 0;
2350 	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit: set async");
2351 	return;
2352 }
2353 
2354 
2355 /*
2356  * Search config entry number matched in sync_table from given
2357  * target and speed period value. If failed to search, return negative value.
2358  */
2359 static int nsp32_search_period_entry(nsp32_hw_data *data,
2360 				     nsp32_target  *target,
2361 				     unsigned char  period)
2362 {
2363 	int i;
2364 
2365 	if (target->limit_entry >= data->syncnum) {
2366 		nsp32_msg(KERN_ERR, "limit_entry exceeds syncnum!");
2367 		target->limit_entry = 0;
2368 	}
2369 
2370 	for (i = target->limit_entry; i < data->syncnum; i++) {
2371 		if (period >= data->synct[i].start_period &&
2372 		    period <= data->synct[i].end_period) {
2373 				break;
2374 		}
2375 	}
2376 
2377 	/*
2378 	 * Check given period value is over the sync_table value.
2379 	 * If so, return max value.
2380 	 */
2381 	if (i == data->syncnum) {
2382 		i = -1;
2383 	}
2384 
2385 	return i;
2386 }
2387 
2388 
2389 /*
2390  * target <-> initiator use ASYNC transfer
2391  */
2392 static void nsp32_set_async(nsp32_hw_data *data, nsp32_target *target)
2393 {
2394 	unsigned char period = data->synct[target->limit_entry].period_num;
2395 
2396 	target->offset     = ASYNC_OFFSET;
2397 	target->period     = 0;
2398 	target->syncreg    = TO_SYNCREG(period, ASYNC_OFFSET);
2399 	target->ackwidth   = 0;
2400 	target->sample_reg = 0;
2401 
2402 	nsp32_dbg(NSP32_DEBUG_SYNC, "set async");
2403 }
2404 
2405 
2406 /*
2407  * target <-> initiator use maximum SYNC transfer
2408  */
2409 static void nsp32_set_max_sync(nsp32_hw_data *data,
2410 			       nsp32_target  *target,
2411 			       unsigned char *period,
2412 			       unsigned char *offset)
2413 {
2414 	unsigned char period_num, ackwidth;
2415 
2416 	period_num = data->synct[target->limit_entry].period_num;
2417 	*period    = data->synct[target->limit_entry].start_period;
2418 	ackwidth   = data->synct[target->limit_entry].ackwidth;
2419 	*offset    = SYNC_OFFSET;
2420 
2421 	target->syncreg    = TO_SYNCREG(period_num, *offset);
2422 	target->ackwidth   = ackwidth;
2423 	target->offset     = *offset;
2424 	target->sample_reg = 0;       /* disable SREQ sampling */
2425 }
2426 
2427 
2428 /*
2429  * target <-> initiator use entry number speed
2430  */
2431 static void nsp32_set_sync_entry(nsp32_hw_data *data,
2432 				 nsp32_target  *target,
2433 				 int		entry,
2434 				 unsigned char  offset)
2435 {
2436 	unsigned char period, ackwidth, sample_rate;
2437 
2438 	period      = data->synct[entry].period_num;
2439 	ackwidth    = data->synct[entry].ackwidth;
2440 	sample_rate = data->synct[entry].sample_rate;
2441 
2442 	target->syncreg    = TO_SYNCREG(period, offset);
2443 	target->ackwidth   = ackwidth;
2444 	target->offset     = offset;
2445 	target->sample_reg = sample_rate | SAMPLING_ENABLE;
2446 
2447 	nsp32_dbg(NSP32_DEBUG_SYNC, "set sync");
2448 }
2449 
2450 
2451 /*
2452  * It waits until SCSI REQ becomes assertion or negation state.
2453  *
2454  * Note: If nsp32_msgin_occur is called, we asserts SCSI ACK. Then
2455  *     connected target responds SCSI REQ negation.  We have to wait
2456  *     SCSI REQ becomes negation in order to negate SCSI ACK signal for
2457  *     REQ-ACK handshake.
2458  */
2459 static void nsp32_wait_req(nsp32_hw_data *data, int state)
2460 {
2461 	unsigned int  base      = data->BaseAddress;
2462 	int	      wait_time = 0;
2463 	unsigned char bus, req_bit;
2464 
2465 	if (!((state == ASSERT) || (state == NEGATE))) {
2466 		nsp32_msg(KERN_ERR, "unknown state designation");
2467 	}
2468 	/* REQ is BIT(5) */
2469 	req_bit = (state == ASSERT ? BUSMON_REQ : 0);
2470 
2471 	do {
2472 		bus = nsp32_read1(base, SCSI_BUS_MONITOR);
2473 		if ((bus & BUSMON_REQ) == req_bit) {
2474 			nsp32_dbg(NSP32_DEBUG_WAIT,
2475 				  "wait_time: %d", wait_time);
2476 			return;
2477 		}
2478 		udelay(1);
2479 		wait_time++;
2480 	} while (wait_time < REQSACK_TIMEOUT_TIME);
2481 
2482 	nsp32_msg(KERN_WARNING, "wait REQ timeout, req_bit: 0x%x", req_bit);
2483 }
2484 
2485 /*
2486  * It waits until SCSI SACK becomes assertion or negation state.
2487  */
2488 static void nsp32_wait_sack(nsp32_hw_data *data, int state)
2489 {
2490 	unsigned int  base      = data->BaseAddress;
2491 	int	      wait_time = 0;
2492 	unsigned char bus, ack_bit;
2493 
2494 	if (!((state == ASSERT) || (state == NEGATE))) {
2495 		nsp32_msg(KERN_ERR, "unknown state designation");
2496 	}
2497 	/* ACK is BIT(4) */
2498 	ack_bit = (state == ASSERT ? BUSMON_ACK : 0);
2499 
2500 	do {
2501 		bus = nsp32_read1(base, SCSI_BUS_MONITOR);
2502 		if ((bus & BUSMON_ACK) == ack_bit) {
2503 			nsp32_dbg(NSP32_DEBUG_WAIT,
2504 				  "wait_time: %d", wait_time);
2505 			return;
2506 		}
2507 		udelay(1);
2508 		wait_time++;
2509 	} while (wait_time < REQSACK_TIMEOUT_TIME);
2510 
2511 	nsp32_msg(KERN_WARNING, "wait SACK timeout, ack_bit: 0x%x", ack_bit);
2512 }
2513 
2514 /*
2515  * assert SCSI ACK
2516  *
2517  * Note: SCSI ACK assertion needs with ACKENB=1, AUTODIRECTION=1.
2518  */
2519 static void nsp32_sack_assert(nsp32_hw_data *data)
2520 {
2521 	unsigned int  base = data->BaseAddress;
2522 	unsigned char busctrl;
2523 
2524 	busctrl  = nsp32_read1(base, SCSI_BUS_CONTROL);
2525 	busctrl	|= (BUSCTL_ACK | AUTODIRECTION | ACKENB);
2526 	nsp32_write1(base, SCSI_BUS_CONTROL, busctrl);
2527 }
2528 
2529 /*
2530  * negate SCSI ACK
2531  */
2532 static void nsp32_sack_negate(nsp32_hw_data *data)
2533 {
2534 	unsigned int  base = data->BaseAddress;
2535 	unsigned char busctrl;
2536 
2537 	busctrl  = nsp32_read1(base, SCSI_BUS_CONTROL);
2538 	busctrl	&= ~BUSCTL_ACK;
2539 	nsp32_write1(base, SCSI_BUS_CONTROL, busctrl);
2540 }
2541 
2542 
2543 
2544 /*
2545  * Note: n_io_port is defined as 0x7f because I/O register port is
2546  *	 assigned as:
2547  *	0x800-0x8ff: memory mapped I/O port
2548  *	0x900-0xbff: (map same 0x800-0x8ff I/O port image repeatedly)
2549  *	0xc00-0xfff: CardBus status registers
2550  */
2551 static int nsp32_detect(struct pci_dev *pdev)
2552 {
2553 	struct Scsi_Host *host;	/* registered host structure */
2554 	struct resource  *res;
2555 	nsp32_hw_data    *data;
2556 	int		  ret;
2557 	int		  i, j;
2558 
2559 	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");
2560 
2561 	/*
2562 	 * register this HBA as SCSI device
2563 	 */
2564 	host = scsi_host_alloc(&nsp32_template, sizeof(nsp32_hw_data));
2565 	if (host == NULL) {
2566 		nsp32_msg (KERN_ERR, "failed to scsi register");
2567 		goto err;
2568 	}
2569 
2570 	/*
2571 	 * set nsp32_hw_data
2572 	 */
2573 	data = (nsp32_hw_data *)host->hostdata;
2574 
2575 	memcpy(data, &nsp32_data_base, sizeof(nsp32_hw_data));
2576 
2577 	host->irq       = data->IrqNumber;
2578 	host->io_port   = data->BaseAddress;
2579 	host->unique_id = data->BaseAddress;
2580 	host->n_io_port	= data->NumAddress;
2581 	host->base      = (unsigned long)data->MmioAddress;
2582 
2583 	data->Host      = host;
2584 	spin_lock_init(&(data->Lock));
2585 
2586 	data->cur_lunt   = NULL;
2587 	data->cur_target = NULL;
2588 
2589 	/*
2590 	 * Bus master transfer mode is supported currently.
2591 	 */
2592 	data->trans_method = NSP32_TRANSFER_BUSMASTER;
2593 
2594 	/*
2595 	 * Set clock div, CLOCK_4 (HBA has own external clock, and
2596 	 * dividing * 100ns/4).
2597 	 * Currently CLOCK_4 has only tested, not for CLOCK_2/PCICLK yet.
2598 	 */
2599 	data->clock = CLOCK_4;
2600 
2601 	/*
2602 	 * Select appropriate nsp32_sync_table and set I_CLOCKDIV.
2603 	 */
2604 	switch (data->clock) {
2605 	case CLOCK_4:
2606 		/* If data->clock is CLOCK_4, then select 40M sync table. */
2607 		data->synct   = nsp32_sync_table_40M;
2608 		data->syncnum = ARRAY_SIZE(nsp32_sync_table_40M);
2609 		break;
2610 	case CLOCK_2:
2611 		/* If data->clock is CLOCK_2, then select 20M sync table. */
2612 		data->synct   = nsp32_sync_table_20M;
2613 		data->syncnum = ARRAY_SIZE(nsp32_sync_table_20M);
2614 		break;
2615 	case PCICLK:
2616 		/* If data->clock is PCICLK, then select pci sync table. */
2617 		data->synct   = nsp32_sync_table_pci;
2618 		data->syncnum = ARRAY_SIZE(nsp32_sync_table_pci);
2619 		break;
2620 	default:
2621 		nsp32_msg(KERN_WARNING,
2622 			  "Invalid clock div is selected, set CLOCK_4.");
2623 		/* Use default value CLOCK_4 */
2624 		data->clock   = CLOCK_4;
2625 		data->synct   = nsp32_sync_table_40M;
2626 		data->syncnum = ARRAY_SIZE(nsp32_sync_table_40M);
2627 	}
2628 
2629 	/*
2630 	 * setup nsp32_lunt
2631 	 */
2632 
2633 	/*
2634 	 * setup DMA
2635 	 */
2636 	if (dma_set_mask(&pdev->dev, DMA_BIT_MASK(32)) != 0) {
2637 		nsp32_msg (KERN_ERR, "failed to set PCI DMA mask");
2638 		goto scsi_unregister;
2639 	}
2640 
2641 	/*
2642 	 * allocate autoparam DMA resource.
2643 	 */
2644 	data->autoparam = dma_alloc_coherent(&pdev->dev,
2645 			sizeof(nsp32_autoparam), &(data->auto_paddr),
2646 			GFP_KERNEL);
2647 	if (data->autoparam == NULL) {
2648 		nsp32_msg(KERN_ERR, "failed to allocate DMA memory");
2649 		goto scsi_unregister;
2650 	}
2651 
2652 	/*
2653 	 * allocate scatter-gather DMA resource.
2654 	 */
2655 	data->sg_list = dma_alloc_coherent(&pdev->dev, NSP32_SG_TABLE_SIZE,
2656 			&data->sg_paddr, GFP_KERNEL);
2657 	if (data->sg_list == NULL) {
2658 		nsp32_msg(KERN_ERR, "failed to allocate DMA memory");
2659 		goto free_autoparam;
2660 	}
2661 
2662 	for (i = 0; i < ARRAY_SIZE(data->lunt); i++) {
2663 		for (j = 0; j < ARRAY_SIZE(data->lunt[0]); j++) {
2664 			int offset = i * ARRAY_SIZE(data->lunt[0]) + j;
2665 			nsp32_lunt tmp = {
2666 				.SCpnt       = NULL,
2667 				.save_datp   = 0,
2668 				.msgin03     = FALSE,
2669 				.sg_num      = 0,
2670 				.cur_entry   = 0,
2671 				.sglun       = &(data->sg_list[offset]),
2672 				.sglun_paddr = data->sg_paddr + (offset * sizeof(nsp32_sglun)),
2673 			};
2674 
2675 			data->lunt[i][j] = tmp;
2676 		}
2677 	}
2678 
2679 	/*
2680 	 * setup target
2681 	 */
2682 	for (i = 0; i < ARRAY_SIZE(data->target); i++) {
2683 		nsp32_target *target = &(data->target[i]);
2684 
2685 		target->limit_entry  = 0;
2686 		target->sync_flag    = 0;
2687 		nsp32_set_async(data, target);
2688 	}
2689 
2690 	/*
2691 	 * EEPROM check
2692 	 */
2693 	ret = nsp32_getprom_param(data);
2694 	if (ret == FALSE) {
2695 		data->resettime = 3;	/* default 3 */
2696 	}
2697 
2698 	/*
2699 	 * setup HBA
2700 	 */
2701 	nsp32hw_init(data);
2702 
2703 	snprintf(data->info_str, sizeof(data->info_str),
2704 		 "NinjaSCSI-32Bi/UDE: irq %d, io 0x%lx+0x%x",
2705 		 host->irq, host->io_port, host->n_io_port);
2706 
2707 	/*
2708 	 * SCSI bus reset
2709 	 *
2710 	 * Note: It's important to reset SCSI bus in initialization phase.
2711 	 *     NinjaSCSI-32Bi/UDE HBA EEPROM seems to exchange SDTR when
2712 	 *     system is coming up, so SCSI devices connected to HBA is set as
2713 	 *     un-asynchronous mode.  It brings the merit that this HBA is
2714 	 *     ready to start synchronous transfer without any preparation,
2715 	 *     but we are difficult to control transfer speed.  In addition,
2716 	 *     it prevents device transfer speed from effecting EEPROM start-up
2717 	 *     SDTR.  NinjaSCSI-32Bi/UDE has the feature if EEPROM is set as
2718 	 *     Auto Mode, then FAST-10M is selected when SCSI devices are
2719 	 *     connected same or more than 4 devices.  It should be avoided
2720 	 *     depending on this specification. Thus, resetting the SCSI bus
2721 	 *     restores all connected SCSI devices to asynchronous mode, then
2722 	 *     this driver set SDTR safely later, and we can control all SCSI
2723 	 *     device transfer mode.
2724 	 */
2725 	nsp32_do_bus_reset(data);
2726 
2727 	ret = request_irq(host->irq, do_nsp32_isr, IRQF_SHARED, "nsp32", data);
2728 	if (ret < 0) {
2729 		nsp32_msg(KERN_ERR, "Unable to allocate IRQ for NinjaSCSI32 "
2730 			  "SCSI PCI controller. Interrupt: %d", host->irq);
2731 		goto free_sg_list;
2732 	}
2733 
2734 	/*
2735          * PCI IO register
2736          */
2737 	res = request_region(host->io_port, host->n_io_port, "nsp32");
2738 	if (res == NULL) {
2739 		nsp32_msg(KERN_ERR,
2740 			  "I/O region 0x%x+0x%x is already used",
2741 			  data->BaseAddress, data->NumAddress);
2742 		goto free_irq;
2743 	}
2744 
2745 	ret = scsi_add_host(host, &pdev->dev);
2746 	if (ret) {
2747 		nsp32_msg(KERN_ERR, "failed to add scsi host");
2748 		goto free_region;
2749 	}
2750 	scsi_scan_host(host);
2751 	pci_set_drvdata(pdev, host);
2752 	return 0;
2753 
2754  free_region:
2755 	release_region(host->io_port, host->n_io_port);
2756 
2757  free_irq:
2758 	free_irq(host->irq, data);
2759 
2760  free_sg_list:
2761 	dma_free_coherent(&pdev->dev, NSP32_SG_TABLE_SIZE,
2762 			    data->sg_list, data->sg_paddr);
2763 
2764  free_autoparam:
2765 	dma_free_coherent(&pdev->dev, sizeof(nsp32_autoparam),
2766 			    data->autoparam, data->auto_paddr);
2767 
2768  scsi_unregister:
2769 	scsi_host_put(host);
2770 
2771  err:
2772 	return 1;
2773 }
2774 
2775 static int nsp32_release(struct Scsi_Host *host)
2776 {
2777 	nsp32_hw_data *data = (nsp32_hw_data *)host->hostdata;
2778 
2779 	if (data->autoparam) {
2780 		dma_free_coherent(&data->Pci->dev, sizeof(nsp32_autoparam),
2781 				    data->autoparam, data->auto_paddr);
2782 	}
2783 
2784 	if (data->sg_list) {
2785 		dma_free_coherent(&data->Pci->dev, NSP32_SG_TABLE_SIZE,
2786 				    data->sg_list, data->sg_paddr);
2787 	}
2788 
2789 	if (host->irq) {
2790 		free_irq(host->irq, data);
2791 	}
2792 
2793 	if (host->io_port && host->n_io_port) {
2794 		release_region(host->io_port, host->n_io_port);
2795 	}
2796 
2797 	if (data->MmioAddress) {
2798 		iounmap(data->MmioAddress);
2799 	}
2800 
2801 	return 0;
2802 }
2803 
2804 static const char *nsp32_info(struct Scsi_Host *shpnt)
2805 {
2806 	nsp32_hw_data *data = (nsp32_hw_data *)shpnt->hostdata;
2807 
2808 	return data->info_str;
2809 }
2810 
2811 
2812 /****************************************************************************
2813  * error handler
2814  */
2815 static int nsp32_eh_abort(struct scsi_cmnd *SCpnt)
2816 {
2817 	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
2818 	unsigned int   base = SCpnt->device->host->io_port;
2819 
2820 	nsp32_msg(KERN_WARNING, "abort");
2821 
2822 	if (data->cur_lunt->SCpnt == NULL) {
2823 		nsp32_dbg(NSP32_DEBUG_BUSRESET, "abort failed");
2824 		return FAILED;
2825 	}
2826 
2827 	if (data->cur_target->sync_flag & (SDTR_INITIATOR | SDTR_TARGET)) {
2828 		/* reset SDTR negotiation */
2829 		data->cur_target->sync_flag = 0;
2830 		nsp32_set_async(data, data->cur_target);
2831 	}
2832 
2833 	nsp32_write2(base, TRANSFER_CONTROL, 0);
2834 	nsp32_write2(base, BM_CNT, 0);
2835 
2836 	SCpnt->result = DID_ABORT << 16;
2837 	nsp32_scsi_done(SCpnt);
2838 
2839 	nsp32_dbg(NSP32_DEBUG_BUSRESET, "abort success");
2840 	return SUCCESS;
2841 }
2842 
2843 static void nsp32_do_bus_reset(nsp32_hw_data *data)
2844 {
2845 	unsigned int   base = data->BaseAddress;
2846 	int i;
2847 	unsigned short __maybe_unused intrdat;
2848 
2849 	nsp32_dbg(NSP32_DEBUG_BUSRESET, "in");
2850 
2851 	/*
2852 	 * stop all transfer
2853 	 * clear TRANSFERCONTROL_BM_START
2854 	 * clear counter
2855 	 */
2856 	nsp32_write2(base, TRANSFER_CONTROL, 0);
2857 	nsp32_write4(base, BM_CNT, 0);
2858 	nsp32_write4(base, CLR_COUNTER, CLRCOUNTER_ALLMASK);
2859 
2860 	/*
2861 	 * fall back to asynchronous transfer mode
2862 	 * initialize SDTR negotiation flag
2863 	 */
2864 	for (i = 0; i < ARRAY_SIZE(data->target); i++) {
2865 		nsp32_target *target = &data->target[i];
2866 
2867 		target->sync_flag = 0;
2868 		nsp32_set_async(data, target);
2869 	}
2870 
2871 	/*
2872 	 * reset SCSI bus
2873 	 */
2874 	nsp32_write1(base, SCSI_BUS_CONTROL, BUSCTL_RST);
2875 	mdelay(RESET_HOLD_TIME / 1000);
2876 	nsp32_write1(base, SCSI_BUS_CONTROL, 0);
2877 	for(i = 0; i < 5; i++) {
2878 		intrdat = nsp32_read2(base, IRQ_STATUS); /* dummy read */
2879 		nsp32_dbg(NSP32_DEBUG_BUSRESET, "irq:1: 0x%x", intrdat);
2880 	}
2881 
2882 	data->CurrentSC = NULL;
2883 }
2884 
2885 static int nsp32_eh_host_reset(struct scsi_cmnd *SCpnt)
2886 {
2887 	struct Scsi_Host *host = SCpnt->device->host;
2888 	unsigned int      base = SCpnt->device->host->io_port;
2889 	nsp32_hw_data    *data = (nsp32_hw_data *)host->hostdata;
2890 
2891 	nsp32_msg(KERN_INFO, "Host Reset");
2892 	nsp32_dbg(NSP32_DEBUG_BUSRESET, "SCpnt=0x%x", SCpnt);
2893 
2894 	spin_lock_irq(SCpnt->device->host->host_lock);
2895 
2896 	nsp32hw_init(data);
2897 	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
2898 	nsp32_do_bus_reset(data);
2899 	nsp32_write2(base, IRQ_CONTROL, 0);
2900 
2901 	spin_unlock_irq(SCpnt->device->host->host_lock);
2902 	return SUCCESS;	/* Host reset is succeeded at any time. */
2903 }
2904 
2905 
2906 /**************************************************************************
2907  * EEPROM handler
2908  */
2909 
2910 /*
2911  * getting EEPROM parameter
2912  */
2913 static int nsp32_getprom_param(nsp32_hw_data *data)
2914 {
2915 	int vendor = data->pci_devid->vendor;
2916 	int device = data->pci_devid->device;
2917 	int ret, i;
2918 	int __maybe_unused val;
2919 
2920 	/*
2921 	 * EEPROM checking.
2922 	 */
2923 	ret = nsp32_prom_read(data, 0x7e);
2924 	if (ret != 0x55) {
2925 		nsp32_msg(KERN_INFO, "No EEPROM detected: 0x%x", ret);
2926 		return FALSE;
2927 	}
2928 	ret = nsp32_prom_read(data, 0x7f);
2929 	if (ret != 0xaa) {
2930 		nsp32_msg(KERN_INFO, "Invalid number: 0x%x", ret);
2931 		return FALSE;
2932 	}
2933 
2934 	/*
2935 	 * check EEPROM type
2936 	 */
2937 	if (vendor == PCI_VENDOR_ID_WORKBIT &&
2938 	    device == PCI_DEVICE_ID_WORKBIT_STANDARD) {
2939 		ret = nsp32_getprom_c16(data);
2940 	} else if (vendor == PCI_VENDOR_ID_WORKBIT &&
2941 		   device == PCI_DEVICE_ID_NINJASCSI_32BIB_LOGITEC) {
2942 		ret = nsp32_getprom_at24(data);
2943 	} else if (vendor == PCI_VENDOR_ID_WORKBIT &&
2944 		   device == PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO ) {
2945 		ret = nsp32_getprom_at24(data);
2946 	} else {
2947 		nsp32_msg(KERN_WARNING, "Unknown EEPROM");
2948 		ret = FALSE;
2949 	}
2950 
2951 	/* for debug : SPROM data full checking */
2952 	for (i = 0; i <= 0x1f; i++) {
2953 		val = nsp32_prom_read(data, i);
2954 		nsp32_dbg(NSP32_DEBUG_EEPROM,
2955 			  "rom address 0x%x : 0x%x", i, val);
2956 	}
2957 
2958 	return ret;
2959 }
2960 
2961 
2962 /*
2963  * AT24C01A (Logitec: LHA-600S), AT24C02 (Melco Buffalo: IFC-USLP) data map:
2964  *
2965  *   ROMADDR
2966  *   0x00 - 0x06 :  Device Synchronous Transfer Period (SCSI ID 0 - 6)
2967  *			Value 0x0: ASYNC, 0x0c: Ultra-20M, 0x19: Fast-10M
2968  *   0x07        :  HBA Synchronous Transfer Period
2969  *			Value 0: AutoSync, 1: Manual Setting
2970  *   0x08 - 0x0f :  Not Used? (0x0)
2971  *   0x10        :  Bus Termination
2972  *			Value 0: Auto[ON], 1: ON, 2: OFF
2973  *   0x11        :  Not Used? (0)
2974  *   0x12        :  Bus Reset Delay Time (0x03)
2975  *   0x13        :  Bootable CD Support
2976  *			Value 0: Disable, 1: Enable
2977  *   0x14        :  Device Scan
2978  *			Bit   7  6  5  4  3  2  1  0
2979  *			      |  <----------------->
2980  *			      |    SCSI ID: Value 0: Skip, 1: YES
2981  *			      |->  Value 0: ALL scan,  Value 1: Manual
2982  *   0x15 - 0x1b :  Not Used? (0)
2983  *   0x1c        :  Constant? (0x01) (clock div?)
2984  *   0x1d - 0x7c :  Not Used (0xff)
2985  *   0x7d	 :  Not Used? (0xff)
2986  *   0x7e        :  Constant (0x55), Validity signature
2987  *   0x7f        :  Constant (0xaa), Validity signature
2988  */
2989 static int nsp32_getprom_at24(nsp32_hw_data *data)
2990 {
2991 	int	      ret, i;
2992 	int	      auto_sync;
2993 	nsp32_target *target;
2994 	int	      entry;
2995 
2996 	/*
2997 	 * Reset time which is designated by EEPROM.
2998 	 *
2999 	 * TODO: Not used yet.
3000 	 */
3001 	data->resettime = nsp32_prom_read(data, 0x12);
3002 
3003 	/*
3004 	 * HBA Synchronous Transfer Period
3005 	 *
3006 	 * Note: auto_sync = 0: auto, 1: manual.  Ninja SCSI HBA spec says
3007 	 *	that if auto_sync is 0 (auto), and connected SCSI devices are
3008 	 *	same or lower than 3, then transfer speed is set as ULTRA-20M.
3009 	 *	On the contrary if connected SCSI devices are same or higher
3010 	 *	than 4, then transfer speed is set as FAST-10M.
3011 	 *
3012 	 *	I break this rule. The number of connected SCSI devices are
3013 	 *	only ignored. If auto_sync is 0 (auto), then transfer speed is
3014 	 *	forced as ULTRA-20M.
3015 	 */
3016 	ret = nsp32_prom_read(data, 0x07);
3017 	switch (ret) {
3018 	case 0:
3019 		auto_sync = TRUE;
3020 		break;
3021 	case 1:
3022 		auto_sync = FALSE;
3023 		break;
3024 	default:
3025 		nsp32_msg(KERN_WARNING,
3026 			  "Unsupported Auto Sync mode. Fall back to manual mode.");
3027 		auto_sync = TRUE;
3028 	}
3029 
3030 	if (trans_mode == ULTRA20M_MODE) {
3031 		auto_sync = TRUE;
3032 	}
3033 
3034 	/*
3035 	 * each device Synchronous Transfer Period
3036 	 */
3037 	for (i = 0; i < NSP32_HOST_SCSIID; i++) {
3038 		target = &data->target[i];
3039 		if (auto_sync == TRUE) {
3040 			target->limit_entry = 0;   /* set as ULTRA20M */
3041 		} else {
3042 			ret   = nsp32_prom_read(data, i);
3043 			entry = nsp32_search_period_entry(data, target, ret);
3044 			if (entry < 0) {
3045 				/* search failed... set maximum speed */
3046 				entry = 0;
3047 			}
3048 			target->limit_entry = entry;
3049 		}
3050 	}
3051 
3052 	return TRUE;
3053 }
3054 
3055 
3056 /*
3057  * C16 110 (I-O Data: SC-NBD) data map:
3058  *
3059  *   ROMADDR
3060  *   0x00 - 0x06 :  Device Synchronous Transfer Period (SCSI ID 0 - 6)
3061  *			Value 0x0: 20MB/S, 0x1: 10MB/S, 0x2: 5MB/S, 0x3: ASYNC
3062  *   0x07        :  0 (HBA Synchronous Transfer Period: Auto Sync)
3063  *   0x08 - 0x0f :  Not Used? (0x0)
3064  *   0x10        :  Transfer Mode
3065  *			Value 0: PIO, 1: Busmater
3066  *   0x11        :  Bus Reset Delay Time (0x00-0x20)
3067  *   0x12        :  Bus Termination
3068  *			Value 0: Disable, 1: Enable
3069  *   0x13 - 0x19 :  Disconnection
3070  *			Value 0: Disable, 1: Enable
3071  *   0x1a - 0x7c :  Not Used? (0)
3072  *   0x7d	 :  Not Used? (0xf8)
3073  *   0x7e        :  Constant (0x55), Validity signature
3074  *   0x7f        :  Constant (0xaa), Validity signature
3075  */
3076 static int nsp32_getprom_c16(nsp32_hw_data *data)
3077 {
3078 	int	      ret, i;
3079 	nsp32_target *target;
3080 	int	      entry, val;
3081 
3082 	/*
3083 	 * Reset time which is designated by EEPROM.
3084 	 *
3085 	 * TODO: Not used yet.
3086 	 */
3087 	data->resettime = nsp32_prom_read(data, 0x11);
3088 
3089 	/*
3090 	 * each device Synchronous Transfer Period
3091 	 */
3092 	for (i = 0; i < NSP32_HOST_SCSIID; i++) {
3093 		target = &data->target[i];
3094 		ret = nsp32_prom_read(data, i);
3095 		switch (ret) {
3096 		case 0:		/* 20MB/s */
3097 			val = 0x0c;
3098 			break;
3099 		case 1:		/* 10MB/s */
3100 			val = 0x19;
3101 			break;
3102 		case 2:		/* 5MB/s */
3103 			val = 0x32;
3104 			break;
3105 		case 3:		/* ASYNC */
3106 			val = 0x00;
3107 			break;
3108 		default:	/* default 20MB/s */
3109 			val = 0x0c;
3110 			break;
3111 		}
3112 		entry = nsp32_search_period_entry(data, target, val);
3113 		if (entry < 0 || trans_mode == ULTRA20M_MODE) {
3114 			/* search failed... set maximum speed */
3115 			entry = 0;
3116 		}
3117 		target->limit_entry = entry;
3118 	}
3119 
3120 	return TRUE;
3121 }
3122 
3123 
3124 /*
3125  * Atmel AT24C01A (drived in 5V) serial EEPROM routines
3126  */
3127 static int nsp32_prom_read(nsp32_hw_data *data, int romaddr)
3128 {
3129 	int i, val;
3130 
3131 	/* start condition */
3132 	nsp32_prom_start(data);
3133 
3134 	/* device address */
3135 	nsp32_prom_write_bit(data, 1);	/* 1 */
3136 	nsp32_prom_write_bit(data, 0);	/* 0 */
3137 	nsp32_prom_write_bit(data, 1);	/* 1 */
3138 	nsp32_prom_write_bit(data, 0);	/* 0 */
3139 	nsp32_prom_write_bit(data, 0);	/* A2: 0 (GND) */
3140 	nsp32_prom_write_bit(data, 0);	/* A1: 0 (GND) */
3141 	nsp32_prom_write_bit(data, 0);	/* A0: 0 (GND) */
3142 
3143 	/* R/W: W for dummy write */
3144 	nsp32_prom_write_bit(data, 0);
3145 
3146 	/* ack */
3147 	nsp32_prom_write_bit(data, 0);
3148 
3149 	/* word address */
3150 	for (i = 7; i >= 0; i--) {
3151 		nsp32_prom_write_bit(data, ((romaddr >> i) & 1));
3152 	}
3153 
3154 	/* ack */
3155 	nsp32_prom_write_bit(data, 0);
3156 
3157 	/* start condition */
3158 	nsp32_prom_start(data);
3159 
3160 	/* device address */
3161 	nsp32_prom_write_bit(data, 1);	/* 1 */
3162 	nsp32_prom_write_bit(data, 0);	/* 0 */
3163 	nsp32_prom_write_bit(data, 1);	/* 1 */
3164 	nsp32_prom_write_bit(data, 0);	/* 0 */
3165 	nsp32_prom_write_bit(data, 0);	/* A2: 0 (GND) */
3166 	nsp32_prom_write_bit(data, 0);	/* A1: 0 (GND) */
3167 	nsp32_prom_write_bit(data, 0);	/* A0: 0 (GND) */
3168 
3169 	/* R/W: R */
3170 	nsp32_prom_write_bit(data, 1);
3171 
3172 	/* ack */
3173 	nsp32_prom_write_bit(data, 0);
3174 
3175 	/* data... */
3176 	val = 0;
3177 	for (i = 7; i >= 0; i--) {
3178 		val += (nsp32_prom_read_bit(data) << i);
3179 	}
3180 
3181 	/* no ack */
3182 	nsp32_prom_write_bit(data, 1);
3183 
3184 	/* stop condition */
3185 	nsp32_prom_stop(data);
3186 
3187 	return val;
3188 }
3189 
3190 static void nsp32_prom_set(nsp32_hw_data *data, int bit, int val)
3191 {
3192 	int base = data->BaseAddress;
3193 	int tmp;
3194 
3195 	tmp = nsp32_index_read1(base, SERIAL_ROM_CTL);
3196 
3197 	if (val == 0) {
3198 		tmp &= ~bit;
3199 	} else {
3200 		tmp |=  bit;
3201 	}
3202 
3203 	nsp32_index_write1(base, SERIAL_ROM_CTL, tmp);
3204 
3205 	udelay(10);
3206 }
3207 
3208 static int nsp32_prom_get(nsp32_hw_data *data, int bit)
3209 {
3210 	int base = data->BaseAddress;
3211 	int tmp, ret;
3212 
3213 	if (bit != SDA) {
3214 		nsp32_msg(KERN_ERR, "return value is not appropriate");
3215 		return 0;
3216 	}
3217 
3218 
3219 	tmp = nsp32_index_read1(base, SERIAL_ROM_CTL) & bit;
3220 
3221 	if (tmp == 0) {
3222 		ret = 0;
3223 	} else {
3224 		ret = 1;
3225 	}
3226 
3227 	udelay(10);
3228 
3229 	return ret;
3230 }
3231 
3232 static void nsp32_prom_start (nsp32_hw_data *data)
3233 {
3234 	/* start condition */
3235 	nsp32_prom_set(data, SCL, 1);
3236 	nsp32_prom_set(data, SDA, 1);
3237 	nsp32_prom_set(data, ENA, 1);	/* output mode */
3238 	nsp32_prom_set(data, SDA, 0);	/* keeping SCL=1 and transiting
3239 					 * SDA 1->0 is start condition */
3240 	nsp32_prom_set(data, SCL, 0);
3241 }
3242 
3243 static void nsp32_prom_stop (nsp32_hw_data *data)
3244 {
3245 	/* stop condition */
3246 	nsp32_prom_set(data, SCL, 1);
3247 	nsp32_prom_set(data, SDA, 0);
3248 	nsp32_prom_set(data, ENA, 1);	/* output mode */
3249 	nsp32_prom_set(data, SDA, 1);
3250 	nsp32_prom_set(data, SCL, 0);
3251 }
3252 
3253 static void nsp32_prom_write_bit(nsp32_hw_data *data, int val)
3254 {
3255 	/* write */
3256 	nsp32_prom_set(data, SDA, val);
3257 	nsp32_prom_set(data, SCL, 1  );
3258 	nsp32_prom_set(data, SCL, 0  );
3259 }
3260 
3261 static int nsp32_prom_read_bit(nsp32_hw_data *data)
3262 {
3263 	int val;
3264 
3265 	/* read */
3266 	nsp32_prom_set(data, ENA, 0);	/* input mode */
3267 	nsp32_prom_set(data, SCL, 1);
3268 
3269 	val = nsp32_prom_get(data, SDA);
3270 
3271 	nsp32_prom_set(data, SCL, 0);
3272 	nsp32_prom_set(data, ENA, 1);	/* output mode */
3273 
3274 	return val;
3275 }
3276 
3277 
3278 /**************************************************************************
3279  * Power Management
3280  */
3281 #ifdef CONFIG_PM
3282 
3283 /* Device suspended */
3284 static int nsp32_suspend(struct pci_dev *pdev, pm_message_t state)
3285 {
3286 	struct Scsi_Host *host = pci_get_drvdata(pdev);
3287 
3288 	nsp32_msg(KERN_INFO, "pci-suspend: pdev=0x%p, state.event=%x, slot=%s, host=0x%p",
3289 		  pdev, state.event, pci_name(pdev), host);
3290 
3291 	pci_save_state     (pdev);
3292 	pci_disable_device (pdev);
3293 	pci_set_power_state(pdev, pci_choose_state(pdev, state));
3294 
3295 	return 0;
3296 }
3297 
3298 /* Device woken up */
3299 static int nsp32_resume(struct pci_dev *pdev)
3300 {
3301 	struct Scsi_Host *host = pci_get_drvdata(pdev);
3302 	nsp32_hw_data    *data = (nsp32_hw_data *)host->hostdata;
3303 	unsigned short    reg;
3304 
3305 	nsp32_msg(KERN_INFO, "pci-resume: pdev=0x%p, slot=%s, host=0x%p",
3306 		  pdev, pci_name(pdev), host);
3307 
3308 	pci_set_power_state(pdev, PCI_D0);
3309 	pci_enable_wake    (pdev, PCI_D0, 0);
3310 	pci_restore_state  (pdev);
3311 
3312 	reg = nsp32_read2(data->BaseAddress, INDEX_REG);
3313 
3314 	nsp32_msg(KERN_INFO, "io=0x%x reg=0x%x", data->BaseAddress, reg);
3315 
3316 	if (reg == 0xffff) {
3317 		nsp32_msg(KERN_INFO, "missing device. abort resume.");
3318 		return 0;
3319 	}
3320 
3321 	nsp32hw_init      (data);
3322 	nsp32_do_bus_reset(data);
3323 
3324 	nsp32_msg(KERN_INFO, "resume success");
3325 
3326 	return 0;
3327 }
3328 
3329 #endif
3330 
3331 /************************************************************************
3332  * PCI/Cardbus probe/remove routine
3333  */
3334 static int nsp32_probe(struct pci_dev *pdev, const struct pci_device_id *id)
3335 {
3336 	int ret;
3337 	nsp32_hw_data *data = &nsp32_data_base;
3338 
3339 	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");
3340 
3341 	ret = pci_enable_device(pdev);
3342 	if (ret) {
3343 		nsp32_msg(KERN_ERR, "failed to enable pci device");
3344 		return ret;
3345 	}
3346 
3347 	data->Pci	  = pdev;
3348 	data->pci_devid   = id;
3349 	data->IrqNumber   = pdev->irq;
3350 	data->BaseAddress = pci_resource_start(pdev, 0);
3351 	data->NumAddress  = pci_resource_len  (pdev, 0);
3352 	data->MmioAddress = pci_ioremap_bar(pdev, 1);
3353 	data->MmioLength  = pci_resource_len  (pdev, 1);
3354 
3355 	pci_set_master(pdev);
3356 
3357 	ret = nsp32_detect(pdev);
3358 
3359 	nsp32_msg(KERN_INFO, "irq: %i mmio: %p+0x%lx slot: %s model: %s",
3360 		  pdev->irq,
3361 		  data->MmioAddress, data->MmioLength,
3362 		  pci_name(pdev),
3363 		  nsp32_model[id->driver_data]);
3364 
3365 	nsp32_dbg(NSP32_DEBUG_REGISTER, "exit %d", ret);
3366 
3367 	return ret;
3368 }
3369 
3370 static void nsp32_remove(struct pci_dev *pdev)
3371 {
3372 	struct Scsi_Host *host = pci_get_drvdata(pdev);
3373 
3374 	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");
3375 
3376 	scsi_remove_host(host);
3377 
3378 	nsp32_release(host);
3379 
3380 	scsi_host_put(host);
3381 }
3382 
3383 static struct pci_driver nsp32_driver = {
3384 	.name		= "nsp32",
3385 	.id_table	= nsp32_pci_table,
3386 	.probe		= nsp32_probe,
3387 	.remove		= nsp32_remove,
3388 #ifdef CONFIG_PM
3389 	.suspend	= nsp32_suspend,
3390 	.resume		= nsp32_resume,
3391 #endif
3392 };
3393 
3394 /*********************************************************************
3395  * Moule entry point
3396  */
3397 static int __init init_nsp32(void) {
3398 	nsp32_msg(KERN_INFO, "loading...");
3399 	return pci_register_driver(&nsp32_driver);
3400 }
3401 
3402 static void __exit exit_nsp32(void) {
3403 	nsp32_msg(KERN_INFO, "unloading...");
3404 	pci_unregister_driver(&nsp32_driver);
3405 }
3406 
3407 module_init(init_nsp32);
3408 module_exit(exit_nsp32);
3409 
3410 /* end */
3411