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