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