nsp32.c 92.2 KB
Newer Older
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 8 9 10 11 12 13 14 15
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
16 17 18 19 20 21 22 23
 *
 *
 * Revision History:
 *   1.0: Initial Release.
 *   1.1: Add /proc SDTR status.
 *        Remove obsolete error handler nsp32_reset.
 *        Some clean up.
 *   1.2: PowerPC (big endian) support.
24 25 26 27 28 29 30 31 32 33 34 35
 */

#include <linux/version.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/timer.h>
#include <linux/ioport.h>
#include <linux/major.h>
36
#include <linux/blkdev.h>
Andrew Morton's avatar
Andrew Morton committed
37
#include <linux/interrupt.h>
38 39 40 41 42 43 44 45 46 47 48 49 50
#include <linux/pci.h>
#include <linux/delay.h>
#include <linux/ctype.h>

#include <asm/dma.h>
#include <asm/system.h>
#include <asm/io.h>

#include "scsi.h"
#include "hosts.h"
#include <scsi/scsi_ioctl.h>
#include <scsi/scsi.h>

51 52 53 54
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,0))
# include <linux/blk.h>
#endif

55 56 57
#include "nsp32.h"


58 59 60 61 62 63
/***********************************************************************
 * Module parameters
 */
static int       trans_mode = 0;	/* default: BIOS */
MODULE_PARM     (trans_mode, "i");
MODULE_PARM_DESC(trans_mode, "transfer mode (0: BIOS(default) 1: Async 2: Ultra20M");
64 65 66
#define ASYNC_MODE    1
#define ULTRA20M_MODE 2

67 68 69
static int       auto_param = 0;	/* default: ON */
MODULE_PARM     (auto_param, "i");
MODULE_PARM_DESC(auto_param, "AutoParameter mode (0: ON(default) 1: OFF)");
70

71 72 73
static int       disc_priv  = 1;	/* default: OFF */
MODULE_PARM     (disc_priv,  "i");
MODULE_PARM_DESC(disc_priv,  "disconnection privilege mode (0: ON 1: OFF(default))");
74

75 76 77
MODULE_AUTHOR("YOKOTA Hiroshi <yokota@netlab.is.tsukuba.ac.jp>, GOTO Masanori <gotom@debian.or.jp>");
MODULE_DESCRIPTION("Workbit NinjaSCSI-32Bi/UDE CardBus/PCI SCSI host bus adapter module");
MODULE_LICENSE("GPL");
78

79
static const char *nsp32_release_version = "1.2";
80 81


82 83
/****************************************************************************
 * Supported hardware
84
 */
85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142
static struct pci_device_id nsp32_pci_table[] __devinitdata = {
	{
		.vendor      = PCI_VENDOR_ID_IODATA,
		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_CBSC_II,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_IODATA,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_KME,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_KME,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_WBT,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_WORKBIT,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_WORKBIT_STANDARD,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_PCI_WORKBIT,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32BI_LOGITEC,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_LOGITEC,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32BIB_LOGITEC,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_PCI_LOGITEC,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_PCI_MELCO,
	},
	{
		.vendor      = PCI_VENDOR_ID_WORKBIT,
		.device      = PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO_II,
		.subvendor   = PCI_ANY_ID,
		.subdevice   = PCI_ANY_ID,
		.driver_data = MODEL_PCI_MELCO,
	},
	{0,0,},
143
};
144
MODULE_DEVICE_TABLE(pci, nsp32_pci_table);
145 146 147 148 149 150 151 152 153

static nsp32_hw_data nsp32_data_base;  /* probe <-> detect glue */


/*
 * Period/AckWidth speed conversion table
 *
 * Note: This period/ackwidth speed table must be in descending order.
 */
154 155 156 157 158 159 160 161 162 163 164
static nsp32_sync_table nsp32_sync_table_40M[] = {
     /* {PNo, AW,   SP,   EP, SREQ smpl}  Speed(MB/s) Period AckWidth */
	{0x1,  0, 0x0c, 0x0c, SMPL_40M},  /*  20.0 :  50ns,  25ns */
	{0x2,  0, 0x0d, 0x18, SMPL_40M},  /*  13.3 :  75ns,  25ns */
	{0x3,  1, 0x19, 0x19, SMPL_40M},  /*  10.0 : 100ns,  50ns */
	{0x4,  1, 0x1a, 0x1f, SMPL_20M},  /*   8.0 : 125ns,  50ns */
	{0x5,  2, 0x20, 0x25, SMPL_20M},  /*   6.7 : 150ns,  75ns */
	{0x6,  2, 0x26, 0x31, SMPL_20M},  /*   5.7 : 175ns,  75ns */
	{0x7,  3, 0x32, 0x32, SMPL_20M},  /*   5.0 : 200ns, 100ns */
	{0x8,  3, 0x33, 0x38, SMPL_10M},  /*   4.4 : 225ns, 100ns */
	{0x9,  3, 0x39, 0x3e, SMPL_10M},  /*   4.0 : 250ns, 100ns */
165
};
166 167 168 169 170 171 172 173 174 175 176

static nsp32_sync_table nsp32_sync_table_20M[] = {
	{0x1,  0, 0x19, 0x19, SMPL_40M},  /* 10.0 : 100ns,  50ns */
	{0x2,  0, 0x1a, 0x25, SMPL_20M},  /*  6.7 : 150ns,  50ns */
	{0x3,  1, 0x26, 0x32, SMPL_20M},  /*  5.0 : 200ns, 100ns */
	{0x4,  1, 0x33, 0x3e, SMPL_10M},  /*  4.0 : 250ns, 100ns */
	{0x5,  2, 0x3f, 0x4b, SMPL_10M},  /*  3.3 : 300ns, 150ns */
	{0x6,  2, 0x4c, 0x57, SMPL_10M},  /*  2.8 : 350ns, 150ns */
	{0x7,  3, 0x58, 0x64, SMPL_10M},  /*  2.5 : 400ns, 200ns */
	{0x8,  3, 0x65, 0x70, SMPL_10M},  /*  2.2 : 450ns, 200ns */
	{0x9,  3, 0x71, 0x7d, SMPL_10M},  /*  2.0 : 500ns, 200ns */
177
};
178 179 180 181 182 183 184 185 186 187 188

static nsp32_sync_table nsp32_sync_table_pci[] = {
	{0x1,  0, 0x0c, 0x0f, SMPL_40M},  /* 16.6 :  60ns,  30ns */
	{0x2,  0, 0x10, 0x16, SMPL_40M},  /* 11.1 :  90ns,  30ns */
	{0x3,  1, 0x17, 0x1e, SMPL_20M},  /*  8.3 : 120ns,  60ns */
	{0x4,  1, 0x1f, 0x25, SMPL_20M},  /*  6.7 : 150ns,  60ns */
	{0x5,  2, 0x26, 0x2d, SMPL_20M},  /*  5.6 : 180ns,  90ns */
	{0x6,  2, 0x2e, 0x34, SMPL_10M},  /*  4.8 : 210ns,  90ns */
	{0x7,  3, 0x35, 0x3c, SMPL_10M},  /*  4.2 : 240ns, 120ns */
	{0x8,  3, 0x3d, 0x43, SMPL_10M},  /*  3.7 : 270ns, 120ns */
	{0x9,  3, 0x44, 0x4b, SMPL_10M},  /*  3.3 : 300ns, 120ns */
189 190 191 192 193
};

/*
 * function declaration
 */
194 195
/* module entry point */
static int  __devinit nsp32_probe (struct pci_dev *, const struct pci_device_id *);
196
static void __devexit nsp32_remove(struct pci_dev *);
197 198 199 200 201 202 203 204 205
static int  __init    init_nsp32  (void);
static void __exit    exit_nsp32  (void);

/* struct Scsi_Host_Template */
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
static int         nsp32_proc_info   (struct Scsi_Host *, char *, char **, off_t, int, int);
#else
static int         nsp32_proc_info   (char *, char **, off_t, int, int, int);
#endif
206

207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
static int         nsp32_detect      (struct pci_dev *pdev);
#else
static int         nsp32_detect      (Scsi_Host_Template *);
#endif
static int         nsp32_queuecommand(Scsi_Cmnd *, void (*done)(Scsi_Cmnd *));
static const char *nsp32_info        (struct Scsi_Host *);
static int         nsp32_release     (struct Scsi_Host *);

/* SCSI error handler */
static int         nsp32_eh_abort     (Scsi_Cmnd *);
static int         nsp32_eh_bus_reset (Scsi_Cmnd *);
static int         nsp32_eh_host_reset(Scsi_Cmnd *);

/* generate SCSI message */
static void nsp32_build_identify(Scsi_Cmnd *);
static void nsp32_build_nop     (Scsi_Cmnd *);
static void nsp32_build_reject  (Scsi_Cmnd *);
static void nsp32_build_sdtr    (Scsi_Cmnd *, unsigned char, unsigned char);

/* SCSI message handler */
static int  nsp32_busfree_occur(Scsi_Cmnd *, unsigned short);
static void nsp32_msgout_occur (Scsi_Cmnd *);
static void nsp32_msgin_occur  (Scsi_Cmnd *, unsigned long, unsigned short);

static int  nsp32_setup_sg_table    (Scsi_Cmnd *);
static int  nsp32_selection_autopara(Scsi_Cmnd *);
static int  nsp32_selection_autoscsi(Scsi_Cmnd *);
static void nsp32_scsi_done         (Scsi_Cmnd *);
static int  nsp32_arbitration       (Scsi_Cmnd *, unsigned int);
static int  nsp32_reselection       (Scsi_Cmnd *, unsigned char);
static void nsp32_adjust_busfree    (Scsi_Cmnd *, unsigned int);
static void nsp32_restart_autoscsi  (Scsi_Cmnd *, unsigned short);

/* SCSI SDTR */
static void nsp32_analyze_sdtr       (Scsi_Cmnd *);
static int  nsp32_search_period_entry(nsp32_hw_data *, nsp32_target *, unsigned char);
static void nsp32_set_async          (nsp32_hw_data *, nsp32_target *);
static void nsp32_set_max_sync       (nsp32_hw_data *, nsp32_target *, unsigned char *, unsigned char *);
static void nsp32_set_sync_entry     (nsp32_hw_data *, nsp32_target *, int, unsigned char);

/* SCSI bus status handler */
static void nsp32_wait_req    (nsp32_hw_data *, int);
static void nsp32_wait_sack   (nsp32_hw_data *, int);
static void nsp32_sack_assert (nsp32_hw_data *);
static void nsp32_sack_negate (nsp32_hw_data *);
static void nsp32_do_bus_reset(nsp32_hw_data *);
254

255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
/* hardware interrupt handler */
static irqreturn_t do_nsp32_isr(int, void *, struct pt_regs *);

/* initialize hardware */
static int  nsp32hw_init(nsp32_hw_data *);

/* EEPROM handler */
static        int  nsp32_getprom_param (nsp32_hw_data *);
static        int  nsp32_getprom_at24  (nsp32_hw_data *);
static        int  nsp32_getprom_c16   (nsp32_hw_data *);
static        void nsp32_prom_start    (nsp32_hw_data *);
static        void nsp32_prom_stop     (nsp32_hw_data *);
static        int  nsp32_prom_read     (nsp32_hw_data *, int);
static        int  nsp32_prom_read_bit (nsp32_hw_data *);
static        void nsp32_prom_write_bit(nsp32_hw_data *, int);
static inline void nsp32_prom_set      (nsp32_hw_data *, int, int);
static inline int  nsp32_prom_get      (nsp32_hw_data *, int);

/* debug/warning/info message */
static void nsp32_message (const char *, int, char *, char *, ...);
#ifdef NSP32_DEBUG
static void nsp32_dmessage(const char *, int, int,    char *, ...);
#endif
278 279 280 281

/*
 * max_sectors is currently limited up to 128.
 */
282
static Scsi_Host_Template nsp32_template = {
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306
	.proc_name			= "nsp32",
	.name				= "Workbit NinjaSCSI-32Bi/UDE",
	.proc_info			= nsp32_proc_info,
	.info				= nsp32_info,
	.queuecommand			= nsp32_queuecommand,
	.can_queue			= 1,
	.sg_tablesize			= NSP32_SG_SIZE,
	.max_sectors			= 128,
	.cmd_per_lun			= 1,
	.this_id			= NSP32_HOST_SCSIID,
	.use_clustering			= DISABLE_CLUSTERING,
	.eh_abort_handler       	= nsp32_eh_abort,
/*	.eh_device_reset_handler	= NULL, */
	.eh_bus_reset_handler		= nsp32_eh_bus_reset,
	.eh_host_reset_handler		= nsp32_eh_host_reset,
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,74))
	.detect				= nsp32_detect,
	.release			= nsp32_release,
#endif
#if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,2))
	.use_new_eh_code        	= 1,
#else
/*	.highmem_io			= 1, */
#endif
307 308 309 310
};

#include "nsp32_io.h"

311
/***********************************************************************
312 313 314
 * debug, error print
 */
#ifndef NSP32_DEBUG
315 316 317
# define NSP32_DEBUG_MASK	      0x000000
# define nsp32_msg(type, args...)     nsp32_message ("", 0, (type), args)
# define nsp32_dbg(mask, args...)     /* */
318
#else
319 320 321 322 323
# define NSP32_DEBUG_MASK	      0xffffff
# define nsp32_msg(type, args...) \
	nsp32_message (__FUNCTION__, __LINE__, (type), args)
# define nsp32_dbg(mask, args...) \
	nsp32_dmessage(__FUNCTION__, __LINE__, (mask), args)
324 325
#endif

326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344
#define NSP32_DEBUG_QUEUECOMMAND	BIT(0)
#define NSP32_DEBUG_REGISTER		BIT(1)
#define NSP32_DEBUG_AUTOSCSI		BIT(2)
#define NSP32_DEBUG_INTR		BIT(3)
#define NSP32_DEBUG_SGLIST		BIT(4)
#define NSP32_DEBUG_BUSFREE		BIT(5)
#define NSP32_DEBUG_CDB_CONTENTS	BIT(6)
#define NSP32_DEBUG_RESELECTION		BIT(7)
#define NSP32_DEBUG_MSGINOCCUR		BIT(8)
#define NSP32_DEBUG_EEPROM		BIT(9)
#define NSP32_DEBUG_MSGOUTOCCUR		BIT(10)
#define NSP32_DEBUG_BUSRESET		BIT(11)
#define NSP32_DEBUG_RESTART		BIT(12)
#define NSP32_DEBUG_SYNC		BIT(13)
#define NSP32_DEBUG_WAIT		BIT(14)
#define NSP32_DEBUG_TARGETFLAG		BIT(15)
#define NSP32_DEBUG_PROC		BIT(16)
#define NSP32_DEBUG_INIT		BIT(17)
#define NSP32_SPECIAL_PRINT_REGISTER	BIT(20)
345 346 347

#define NSP32_DEBUG_BUF_LEN		100

Andrew Morton's avatar
Andrew Morton committed
348
static void nsp32_message(const char *func, int line, char *type, char *fmt, ...)
349 350 351 352 353
{
	va_list args;
	char buf[NSP32_DEBUG_BUF_LEN];

	va_start(args, fmt);
354
	vsnprintf(buf, sizeof(buf), fmt, args);
355 356 357 358 359 360 361 362 363
	va_end(args);

#ifndef NSP32_DEBUG
	printk("%snsp32: %s\n", type, buf);
#else
	printk("%snsp32: %s (%d): %s\n", type, func, line, buf);
#endif
}

364
#ifdef NSP32_DEBUG
Andrew Morton's avatar
Andrew Morton committed
365
static void nsp32_dmessage(const char *func, int line, int mask, char *fmt, ...)
366 367 368 369 370
{
	va_list args;
	char buf[NSP32_DEBUG_BUF_LEN];

	va_start(args, fmt);
371
	vsnprintf(buf, sizeof(buf), fmt, args);
372 373 374
	va_end(args);

	if (mask & NSP32_DEBUG_MASK) {
375
		printk("nsp32-debug: 0x%x %s (%d): %s\n", mask, func, line, buf);
376 377
	}
}
378
#endif
379 380 381 382 383 384 385 386 387 388 389 390

#ifdef NSP32_DEBUG
# include "nsp32_debug.c"
#else
# define show_command(arg)   /* */
# define show_busphase(arg)  /* */
# define show_autophase(arg) /* */
#endif

/*
 * IDENTIFY Message
 */
391
static void nsp32_build_identify(Scsi_Cmnd *SCpnt)
392
{
393 394 395
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	int pos             = data->msgout_len;
	int mode            = FALSE;
396

397 398 399 400
	/* XXX: Auto DiscPriv detection is progressing... */
	if (disc_priv == 0) {
		/* mode = TRUE; */
	}
401

402 403 404
	data->msgoutbuf[pos] = IDENTIFY(mode, SCpnt->device->lun); pos++;

	data->msgout_len = pos;
405 406 407 408 409
}

/*
 * SDTR Message Routine
 */
410 411 412
static void nsp32_build_sdtr(Scsi_Cmnd    *SCpnt,
			     unsigned char period,
			     unsigned char offset)
413
{
414 415
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	int pos             = data->msgout_len;
416

417 418 419 420 421
	data->msgoutbuf[pos] = EXTENDED_MESSAGE;  pos++;
	data->msgoutbuf[pos] = EXTENDED_SDTR_LEN; pos++;
	data->msgoutbuf[pos] = EXTENDED_SDTR;     pos++;
	data->msgoutbuf[pos] = period;            pos++;
	data->msgoutbuf[pos] = offset;            pos++;
422

423
	data->msgout_len = pos;
424 425 426 427 428
}

/*
 * No Operation Message
 */
429
static void nsp32_build_nop(Scsi_Cmnd *SCpnt)
430
{
431 432
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	int            pos  = data->msgout_len;
433 434 435 436 437 438 439

	if (pos != 0) {
		nsp32_msg(KERN_WARNING,
			  "Some messages are already contained!");
		return;
	}

440 441
	data->msgoutbuf[pos] = NOP; pos++;
	data->msgout_len = pos;
442 443 444 445 446
}

/*
 * Reject Message
 */
447
static void nsp32_build_reject(Scsi_Cmnd *SCpnt)
448
{
449 450
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	int            pos  = data->msgout_len;
451

452 453
	data->msgoutbuf[pos] = MESSAGE_REJECT; pos++;
	data->msgout_len = pos;
454 455 456 457 458 459 460 461 462 463
}
	
/*
 * timer
 */
#if 0
static void nsp32_start_timer(Scsi_Cmnd *SCpnt, int time)
{
	unsigned int base = SCpnt->host->io_port;

464
	nsp32_dbg(NSP32_DEBUG_INTR, "timer=%d", time);
465 466

	if (time & (~TIMER_CNT_MASK)) {
467
		nsp32_dbg(NSP32_DEBUG_INTR, "timer set overflow");
468 469 470 471 472 473 474 475 476 477
	}

	nsp32_write2(base, TIMER_SET, time & TIMER_CNT_MASK);
}
#endif


/*
 * set SCSI command and other parameter to asic, and start selection phase
 */
478
static int nsp32_selection_autopara(Scsi_Cmnd *SCpnt)
479
{
480 481 482 483 484 485 486 487 488 489 490
	nsp32_hw_data  *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int	base    = SCpnt->device->host->io_port;
	unsigned int	host_id = SCpnt->device->host->this_id;
	unsigned char	target  = SCpnt->device->id;
	nsp32_autoparam *param  = data->autoparam;
	unsigned char	phase;
	int		i, ret;
	unsigned int	msgout;
	u16_le	        s;

	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "in");
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505

	/*
	 * check bus free
	 */
	phase = nsp32_read1(base, SCSI_BUS_MONITOR);
	if (phase != BUSMON_BUS_FREE) {
		nsp32_msg(KERN_WARNING, "bus busy");
		show_busphase(phase & BUSMON_PHASE_MASK);
		SCpnt->result = DID_BUS_BUSY << 16;
		return FALSE;
	}

	/*
	 * message out
	 *
506
	 * Note: If the range of msgout_len is 1 - 3, fill scsi_msgout.
507 508
	 *       over 3 messages needs another routine.
	 */
509
	if (data->msgout_len == 0) {
510 511 512
		nsp32_msg(KERN_ERR, "SCSI MsgOut without any message!");
		SCpnt->result = DID_ERROR << 16;
		return FALSE;
513
	} else if (data->msgout_len > 0 && data->msgout_len <= 3) {
514
		msgout = 0;
515
		for (i = 0; i < data->msgout_len; i++) {
516 517 518 519 520 521 522
			/*
			 * the sending order of the message is:
			 *  MCNT 3: MSG#0 -> MSG#1 -> MSG#2
			 *  MCNT 2:          MSG#1 -> MSG#2
			 *  MCNT 1:                   MSG#2    
			 */
			msgout >>= 8;
523
			msgout |= ((unsigned int)(data->msgoutbuf[i]) << 24);
524 525
		}
		msgout |= MV_VALID;	/* MV valid */
526
		msgout |= (unsigned int)data->msgout_len; /* len */
527
	} else {
528
		/* data->msgout_len > 3 */
529 530 531
		msgout = 0;
	}

532 533 534
	// nsp_dbg(NSP32_DEBUG_AUTOSCSI, "sel time out=0x%x\n", nsp32_read2(base, SEL_TIME_OUT));
	// nsp32_write2(base, SEL_TIME_OUT,   SEL_TIMEOUT_TIME);

535 536 537
	/*
	 * setup asic parameter
	 */
538
	memset(param, 0, sizeof(nsp32_autoparam));
539 540

	/* cdb */
541 542
	for (i = 0; i < SCpnt->cmd_len; i++) {
		param->cdb[4 * i] = SCpnt->cmnd[i];
543 544
	}

545 546 547 548 549 550 551 552
	/* outgoing messages */
	param->msgout = cpu_to_le32(msgout);

	/* syncreg, ackwidth, target id, SREQ sampling rate */
	param->syncreg    = data->cur_target->syncreg;
	param->ackwidth   = data->cur_target->ackwidth;
	param->target_id  = BIT(host_id) | BIT(target);
	param->sample_reg = data->cur_target->sample_reg;
553

554
	// nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "sample rate=0x%x\n", data->cur_target->sample_reg);
555 556

	/* command control */
557 558 559 560 561 562
	param->command_control = cpu_to_le16(CLEAR_CDB_FIFO_POINTER |
					     AUTOSCSI_START         |
					     AUTO_MSGIN_00_OR_04    |
					     AUTO_MSGIN_02          |
					     AUTO_ATN               );

563 564 565 566 567 568 569 570 571 572 573 574 575 576 577

	/* transfer control */
	s = 0;
	switch (data->trans_method) {
	case NSP32_TRANSFER_BUSMASTER:
		s |= BM_START;
		break;
	case NSP32_TRANSFER_MMIO:
		s |= CB_MMIO_MODE;
		break;
	case NSP32_TRANSFER_PIO:
		s |= CB_IO_MODE;
		break;
	default:
		nsp32_msg(KERN_ERR, "unknown trans_method");
578
		break;
579 580
	}
	/*
581
	 * OR-ed BLIEND_MODE, FIFO intr is decreased, instead of PCI bus waits.
582 583 584
	 * For bus master transfer, it's taken off.
	 */
	s |= (TRANSFER_GO | ALL_COUNTER_CLR);
585
	param->transfer_control = cpu_to_le16(s);
586 587

	/* sg table addr */
588
	param->sgt_pointer = cpu_to_le32(data->cur_lunt->sglun_paddr);
589 590

	/*
591
	 * transfer parameter to ASIC
592
	 */
593
	nsp32_write4(base, SGT_ADR,         data->auto_paddr);
594 595 596 597
	nsp32_write2(base, COMMAND_CONTROL, CLEAR_CDB_FIFO_POINTER |
		                            AUTO_PARAMETER         );

	/*
598
	 * Check arbitration
599
	 */
600
	ret = nsp32_arbitration(SCpnt, base);
601

602
	return ret;
603 604 605 606 607 608
}


/*
 * Selection with AUTO SCSI (without AUTO PARAMETER)
 */
609
static int nsp32_selection_autoscsi(Scsi_Cmnd *SCpnt)
610
{
611 612 613 614
	nsp32_hw_data  *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int	base    = SCpnt->device->host->io_port;
	unsigned int	host_id = SCpnt->device->host->this_id;
	unsigned char	target  = SCpnt->device->id;
615 616 617
	unsigned char	phase;
	int		status;
	unsigned short	command	= 0;
618
	unsigned int	msgout  = 0;
619
	unsigned short	execph;
620 621 622
	int		i;

	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "in");
623 624 625 626 627 628 629 630 631 632

	/*
	 * IRQ disable
	 */
	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);

	/*
	 * check bus line
	 */
	phase = nsp32_read1(base, SCSI_BUS_MONITOR);
633
	if(((phase & BUSMON_BSY) == 1) || (phase & BUSMON_SEL) == 1) {
634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652
		nsp32_msg(KERN_WARNING, "bus busy");
		SCpnt->result = DID_BUS_BUSY << 16;
		status = 1;
		goto out;
        }

	/*
	 * clear execph
	 */
	execph = nsp32_read2(base, SCSI_EXECUTE_PHASE);

	/*
	 * clear FIFO counter to set CDBs
	 */
	nsp32_write2(base, COMMAND_CONTROL, CLEAR_CDB_FIFO_POINTER);

	/*
	 * set CDB0 - CDB15
	 */
653
	for (i = 0; i < SCpnt->cmd_len; i++) {
654 655
		nsp32_write1(base, COMMAND_DATA, SCpnt->cmnd[i]);
        }
656
	nsp32_dbg(NSP32_DEBUG_CDB_CONTENTS, "CDB[0]=[0x%x]", SCpnt->cmnd[0]);
657 658

	/*
659
	 * set SCSIOUT LATCH(initiator)/TARGET(target) (OR-ed) ID
660
	 */
661
	nsp32_write1(base, SCSI_OUT_LATCH_TARGET_ID, BIT(host_id) | BIT(target));
662 663 664 665

	/*
	 * set SCSI MSGOUT REG
	 *
666
	 * Note: If the range of msgout_len is 1 - 3, fill scsi_msgout.
667 668
	 *       over 3 messages needs another routine.
	 */
669 670
	if (data->msgout_len == 0) {
		nsp32_msg(KERN_ERR, "SCSI MsgOut without any message!");
671 672 673
		SCpnt->result = DID_ERROR << 16;
		status = 1;
		goto out;
674
	} else if (data->msgout_len > 0 && data->msgout_len <= 3) {
675
		msgout = 0;
676
		for (i = 0; i < data->msgout_len; i++) {
677 678 679 680 681 682 683
			/*
			 * the sending order of the message is:
			 *  MCNT 3: MSG#0 -> MSG#1 -> MSG#2
			 *  MCNT 2:          MSG#1 -> MSG#2
			 *  MCNT 1:                   MSG#2    
			 */
			msgout >>= 8;
684
			msgout |= ((unsigned int)(data->msgoutbuf[i]) << 24);
685 686
		}
		msgout |= MV_VALID;	/* MV valid */
687
		msgout |= (unsigned int)data->msgout_len; /* len */
688 689
		nsp32_write4(base, SCSI_MSG_OUT, msgout);
	} else {
690
		/* data->msgout_len > 3 */
691 692 693 694 695 696
		nsp32_write4(base, SCSI_MSG_OUT, 0);
	}

	/*
	 * set selection timeout(= 250ms)
	 */
697
	nsp32_write2(base, SEL_TIME_OUT,   SEL_TIMEOUT_TIME);
698 699

	/*
700
	 * set SREQ hazard killer sampling rate
701
	 * 
702
	 * TODO: sample_rate (BASE+0F) is 0 when internal clock = 40MHz.
703 704
	 *      check other internal clock!
	 */
705
	nsp32_write1(base, SREQ_SMPL_RATE, data->cur_target->sample_reg);
706 707 708 709

	/*
	 * clear Arbit
	 */
710
	nsp32_write1(base, SET_ARBIT,      ARBIT_CLEAR);
711 712 713 714 715

	/*
	 * set SYNCREG
	 * Don't set BM_START_ADR before setting this register.
	 */
716
	nsp32_write1(base, SYNC_REG,  data->cur_target->syncreg);
717 718 719 720

	/*
	 * set ACKWIDTH
	 */
721
	nsp32_write1(base, ACK_WIDTH, data->cur_target->ackwidth);
722 723 724 725 726

	nsp32_dbg(NSP32_DEBUG_AUTOSCSI,
		  "syncreg=0x%x, ackwidth=0x%x, sgtpaddr=0x%x, id=0x%x",
		  nsp32_read1(base, SYNC_REG), nsp32_read1(base, ACK_WIDTH),
		  nsp32_read4(base, SGT_ADR), nsp32_read1(base, SCSI_OUT_LATCH_TARGET_ID));
727 728
	nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "msgout_len=%d, msgout=0x%x",
		  data->msgout_len, msgout);
729 730 731 732

	/*
	 * set SGT ADDR (physical address)
	 */
733
	nsp32_write4(base, SGT_ADR, data->cur_lunt->sglun_paddr);
734 735 736 737 738

	/*
	 * set TRANSFER CONTROL REG
	 */
	command = 0;
739
	command |= (TRANSFER_GO | ALL_COUNTER_CLR);
740 741 742 743 744 745 746 747 748 749 750 751 752 753
	if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
		if (SCpnt->request_bufflen > 0) {
			command |= BM_START;
		}
	} else if (data->trans_method & NSP32_TRANSFER_MMIO) {
		command |= CB_MMIO_MODE;
	} else if (data->trans_method & NSP32_TRANSFER_PIO) {
		command |= CB_IO_MODE;
	}
	nsp32_write2(base, TRANSFER_CONTROL, command);

	/*
	 * start AUTO SCSI, kick off arbitration
	 */
754 755 756 757 758
	command = (CLEAR_CDB_FIFO_POINTER |
		   AUTOSCSI_START         |
		   AUTO_MSGIN_00_OR_04    |
		   AUTO_MSGIN_02          |
		   AUTO_ATN                );
759 760 761
	nsp32_write2(base, COMMAND_CONTROL, command);

	/*
762
	 * Check arbitration
763
	 */
764
	status = nsp32_arbitration(SCpnt, base);
765

766
 out:
767
	/*
768
	 * IRQ enable
769
	 */
770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799
	nsp32_write2(base, IRQ_CONTROL, 0);

	return status;
}


/*
 * Arbitration Status Check
 *	
 * Note: Arbitration counter is waited during ARBIT_GO is not lifting.
 *	 Using udelay(1) consumes CPU time and system time, but 
 *	 arbitration delay time is defined minimal 2.4us in SCSI
 *	 specification, thus udelay works as coarse grained wait timer.
 */
static int nsp32_arbitration(Scsi_Cmnd *SCpnt, unsigned int base)
{
	unsigned char arbit;
	int	      status = TRUE;
	int	      time   = 0;

	do {
		arbit = nsp32_read1(base, ARBIT_STATUS);
		time++;
	} while ((arbit & (ARBIT_WIN | ARBIT_FAIL)) == 0 &&
		 (time <= ARBIT_TIMEOUT_TIME));

	nsp32_dbg(NSP32_DEBUG_AUTOSCSI,
		  "arbit: 0x%x, delay time: %d", arbit, time);

	if (arbit & ARBIT_WIN) {
800 801
		/* Arbitration succeeded */
		SCpnt->result = DID_OK << 16;
802 803
		nsp32_index_write1(base, EXT_PORT, LED_ON); /* PCI LED on */
	} else if (arbit & ARBIT_FAIL) {
804 805 806
		/* Arbitration failed */
		SCpnt->result = DID_BUS_BUSY << 16;
		status = FALSE;
807 808 809 810 811 812
	} else {
		/*
		 * unknown error or ARBIT_GO timeout,
		 * something lock up! guess no connection.
		 */
		nsp32_dbg(NSP32_DEBUG_AUTOSCSI, "arbit timeout");
813
		SCpnt->result = DID_NO_CONNECT << 16;
814 815
		status = FALSE;
        }
816 817 818 819 820 821

	/*
	 * clear Arbit
	 */
	nsp32_write1(base, SET_ARBIT, ARBIT_CLEAR);

822
	return status;
823 824 825 826 827 828 829 830 831 832
}


/*
 * reselection
 *
 * Note: This reselection routine is called from msgin_occur,
 *	 reselection target id&lun must be already set.
 *	 SCSI-2 says IDENTIFY implies RESTORE_POINTER operation.
 */
833
static int nsp32_reselection(Scsi_Cmnd *SCpnt, unsigned char newlun)
834
{
835 836 837 838
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   host_id = SCpnt->device->host->this_id;
	unsigned int   base    = SCpnt->device->host->io_port;
	unsigned char  tmpid, newid;
839 840 841 842 843 844 845

	nsp32_dbg(NSP32_DEBUG_RESELECTION, "enter");

	/*
	 * calculate reselected SCSI ID
	 */
	tmpid = nsp32_read1(base, RESELECT_ID);
846
	tmpid &= (~BIT(host_id));
847 848 849 850 851 852 853 854 855 856 857 858
	newid = 0;
	while (tmpid) {
		if (tmpid & 1) {
			break;
		}
		tmpid >>= 1;
		newid++;
	}

	/*
	 * If reselected New ID:LUN is not existed
	 * or current nexus is not existed, unexpected
859
	 * reselection is occurred. Send reject message.
860
	 */
861
	if (newid >= ARRAY_SIZE(data->lunt) || newlun >= ARRAY_SIZE(data->lunt[0])) {
862 863
		nsp32_msg(KERN_WARNING, "unknown id/lun");
		return FALSE;
864
	} else if(data->lunt[newid][newlun].SCpnt == NULL) {
865 866 867 868
		nsp32_msg(KERN_WARNING, "no SCSI command is processing");
		return FALSE;
	}

869 870 871 872
	data->cur_id    = newid;
	data->cur_lun   = newlun;
	data->cur_target = &(data->target[newid]);
	data->cur_lunt   = &(data->lunt[newid][newlun]);
873 874 875 876 877 878 879 880 881

	/* reset SACK/SavedACK counter (or ALL clear?) */
	nsp32_write4(base, CLR_COUNTER, CLRCOUNTER_ALLMASK);

	return TRUE;
}


/*
882
 * nsp32_setup_sg_table - build scatter gather list for transfer data
883 884 885 886
 *			    with bus master.
 *
 * Note: NinjaSCSI-32Bi/UDE bus master can not transfer over 64KB at a time.
 */
887
static int nsp32_setup_sg_table(Scsi_Cmnd *SCpnt)
888
{
889 890 891
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	struct scatterlist   *sgl;
	nsp32_sgtable *sgt = data->cur_lunt->sglun->sgt;
892
	int num, i;
893
	u32_le l;
894 895 896 897 898 899 900 901 902 903 904 905 906 907

	if (SCpnt->request_bufflen == 0) {
		return TRUE;
	}

	if (sgt == NULL) {
		nsp32_dbg(NSP32_DEBUG_SGLIST, "SGT == null");
		return FALSE;
	}

	if (SCpnt->use_sg) {
		sgl = (struct scatterlist *)SCpnt->request_buffer;
		num = pci_map_sg(data->Pci, sgl, SCpnt->use_sg,
				 scsi_to_pci_dma_dir(SCpnt->sc_data_direction));
908
		for (i = 0; i < num; i++) {
909 910 911 912 913 914 915
			/*
			 * Build nsp32_sglist, substitute sg dma addresses.
			 */
			sgt[i].addr = cpu_to_le32(sg_dma_address(sgl));
			sgt[i].len  = cpu_to_le32(sg_dma_len(sgl));
			sgl++;

916
			if (le32_to_cpu(sgt[i].len) > 0x10000) {
917
				nsp32_msg(KERN_ERR,
918
					"can't transfer over 64KB at a time, size=0x%lx", le32_to_cpu(sgt[i].len));
919 920 921
				return FALSE;
			}
			nsp32_dbg(NSP32_DEBUG_SGLIST,
922 923 924 925
				  "num 0x%x : addr 0x%lx len 0x%lx",
				  i,
				  le32_to_cpu(sgt[i].addr),
				  le32_to_cpu(sgt[i].len ));
926
		}
927 928 929 930 931

		/* set end mark */
		l = le32_to_cpu(sgt[num-1].len);
		sgt[num-1].len = cpu_to_le32(l | SGTEND);

932 933 934 935
	} else {
		SCpnt->SCp.have_data_in	= pci_map_single(data->Pci,
			SCpnt->request_buffer, SCpnt->request_bufflen,
			scsi_to_pci_dma_dir(SCpnt->sc_data_direction));
936

937
		sgt[0].addr = cpu_to_le32(SCpnt->SCp.have_data_in);
938
		sgt[0].len  = cpu_to_le32(SCpnt->request_bufflen | SGTEND); /* set end mark */
939

940 941 942 943 944 945 946 947
		if (SCpnt->request_bufflen > 0x10000) {
			nsp32_msg(KERN_ERR,
				  "can't transfer over 64KB at a time, size=0x%lx", SCpnt->request_bufflen);
			return FALSE;
		}
		nsp32_dbg(NSP32_DEBUG_SGLIST, "single : addr 0x%lx len=0x%lx",
			  le32_to_cpu(sgt[0].addr),
			  le32_to_cpu(sgt[0].len ));
948 949 950 951 952 953 954
	}

	return TRUE;
}

static int nsp32_queuecommand(Scsi_Cmnd *SCpnt, void (*done)(Scsi_Cmnd *))
{
955
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
956 957
	nsp32_target *target;
	nsp32_lunt   *cur_lunt;
958 959 960 961 962
	int ret;

	nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
		  "enter. target: 0x%x LUN: 0x%x cmnd: 0x%x cmndlen: 0x%x "
		  "use_sg: 0x%x reqbuf: 0x%lx reqlen: 0x%x",
963
		  SCpnt->device->id, SCpnt->device->lun, SCpnt->cmnd[0], SCpnt->cmd_len,
964 965
		  SCpnt->use_sg, SCpnt->request_buffer, SCpnt->request_bufflen);

966
	if (data->CurrentSC != NULL) {
967 968 969 970 971
		nsp32_msg(KERN_ERR, "Currentsc != NULL. Cancel this command request");
		data->CurrentSC = NULL;
		SCpnt->result   = DID_NO_CONNECT << 16;
		done(SCpnt);

972
		return SCSI_MLQUEUE_HOST_BUSY;
973 974 975
	}

	/* check target ID is not same as this initiator ID */
976 977
	if (SCpnt->device->id == SCpnt->device->host->this_id) {
		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "terget==host???");
978 979
		SCpnt->result = DID_BAD_TARGET << 16;
		done(SCpnt);
980
		return SCSI_MLQUEUE_DEVICE_BUSY;
981 982 983
	}

	/* check target LUN is allowable value */
984
	if (SCpnt->device->lun >= MAX_LUN) {
985
		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "no more lun");
986 987
		SCpnt->result = DID_BAD_TARGET << 16;
		done(SCpnt);
988
		return SCSI_MLQUEUE_DEVICE_BUSY;
989 990 991 992 993 994 995 996
	}

	show_command(SCpnt);

	SCpnt->scsi_done     = done;
	data->CurrentSC      = SCpnt;
	SCpnt->SCp.Status    = CHECK_CONDITION;
	SCpnt->SCp.Message   = 0;
997
	SCpnt->resid         = SCpnt->request_bufflen;
998 999 1000 1001 1002 1003 1004

	SCpnt->SCp.ptr		    = (char *) SCpnt->request_buffer;
	SCpnt->SCp.this_residual    = SCpnt->request_bufflen;
	SCpnt->SCp.buffer	    = NULL;
	SCpnt->SCp.buffers_residual = 0;

	/* initialize data */
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
	data->msgout_len	= 0;
	data->msgin_len		= 0;
	cur_lunt		= &(data->lunt[SCpnt->device->id][SCpnt->device->lun]);
	cur_lunt->SCpnt		= SCpnt;
	cur_lunt->save_datp	= 0;
	cur_lunt->msgin03	= FALSE;
	data->cur_lunt		= cur_lunt;
	data->cur_id		= SCpnt->device->id;
	data->cur_lun		= SCpnt->device->lun;

	ret = nsp32_setup_sg_table(SCpnt);
1016
	if (ret == FALSE) {
1017
		nsp32_msg(KERN_ERR, "SGT fail");
1018
		SCpnt->result = DID_ERROR << 16;
1019 1020
		nsp32_scsi_done(SCpnt);
		return SCSI_MLQUEUE_HOST_BUSY;
1021 1022 1023
	}

	/* Build IDENTIFY */
1024
	nsp32_build_identify(SCpnt);
1025 1026 1027 1028 1029 1030

	/* 
	 * If target is the first time to transfer after the reset
	 * (target don't have SDTR_DONE and SDTR_INITIATOR), sync
	 * message SDTR is needed to do synchronous transfer.
	 */
1031
	target = &data->target[SCpnt->device->id];
1032
	data->cur_target = target;
1033 1034 1035 1036 1037 1038

	if (!(target->sync_flag & (SDTR_DONE | SDTR_INITIATOR | SDTR_TARGET))) {
		unsigned char period, offset;

		if (trans_mode != ASYNC_MODE) {
			nsp32_set_max_sync(data, target, &period, &offset);
1039
			nsp32_build_sdtr(SCpnt, period, offset);
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076
			target->sync_flag |= SDTR_INITIATOR;
		} else {
			nsp32_set_async(data, target);
			target->sync_flag |= SDTR_DONE;
		}

		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
			  "SDTR: entry: %d start_period: 0x%x offset: 0x%x\n",
			  target->limit_entry, period, offset);
	} else if (target->sync_flag & SDTR_INITIATOR) {
		/*
		 * It was negotiating SDTR with target, sending from the
		 * initiator, but there are no chance to remove this flag.
		 * Set async because we don't get proper negotiation.
		 */
		nsp32_set_async(data, target);
		target->sync_flag &= ~SDTR_INITIATOR;
		target->sync_flag |= SDTR_DONE;

		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
			  "SDTR_INITIATOR: fall back to async");
	} else if (target->sync_flag & SDTR_TARGET) {
		/*
		 * It was negotiating SDTR with target, sending from target,
		 * but there are no chance to remove this flag.  Set async
		 * because we don't get proper negotiation.
		 */
		nsp32_set_async(data, target);
		target->sync_flag &= ~SDTR_TARGET;
		target->sync_flag |= SDTR_DONE;

		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND,
			  "Unknown SDTR from target is reached, fall back to async.");
	}

	nsp32_dbg(NSP32_DEBUG_TARGETFLAG,
		  "target: %d sync_flag: 0x%x syncreg: 0x%x ackwidth: 0x%x",
1077
		  SCpnt->device->id, target->sync_flag, target->syncreg,
1078 1079 1080 1081
		  target->ackwidth);

	/* Selection */
	if (auto_param == 0) {
1082
		ret = nsp32_selection_autopara(SCpnt);
1083
	} else {
1084
		ret = nsp32_selection_autoscsi(SCpnt);
1085 1086 1087
	}

	if (ret != TRUE) {
1088 1089 1090
		nsp32_dbg(NSP32_DEBUG_QUEUECOMMAND, "selection fail");
		nsp32_scsi_done(SCpnt);
		return SCSI_MLQUEUE_DEVICE_BUSY;
1091 1092 1093 1094 1095 1096
	}

	return 0;
}

/* initialize asic */
1097
static int nsp32hw_init(nsp32_hw_data *data)
1098
{
1099
	unsigned int   base = data->BaseAddress;
1100
	unsigned short irq_stat;
1101 1102
	unsigned long  lc_reg;
	unsigned char  power;
1103 1104 1105 1106 1107 1108 1109

	lc_reg = nsp32_index_read4(base, CFG_LATE_CACHE);
	if ((lc_reg & 0xff00) == 0) {
		lc_reg |= (0x20 << 8);
		nsp32_index_write2(base, CFG_LATE_CACHE, lc_reg & 0xffff);
	}

1110 1111 1112
	nsp32_write2(base, IRQ_CONTROL,        IRQ_CONTROL_ALL_IRQ_MASK);
	nsp32_write2(base, TRANSFER_CONTROL,   0);
	nsp32_write4(base, BM_CNT,             0);
1113 1114 1115 1116
	nsp32_write2(base, SCSI_EXECUTE_PHASE, 0);

	do {
		irq_stat = nsp32_read2(base, IRQ_STATUS);
1117
		nsp32_dbg(NSP32_DEBUG_INIT, "irq_stat 0x%x", irq_stat);
1118 1119 1120 1121 1122 1123 1124 1125
	} while (irq_stat & IRQSTATUS_ANY_IRQ);

	/*
	 * Fill FIFO_FULL_SHLD, FIFO_EMPTY_SHLD. Below parameter is
	 *  designated by specification.
	 */
	if ((data->trans_method & NSP32_TRANSFER_PIO) ||
	    (data->trans_method & NSP32_TRANSFER_MMIO)) {
1126 1127
		nsp32_index_write1(base, FIFO_FULL_SHLD_COUNT,  0x40);
		nsp32_index_write1(base, FIFO_EMPTY_SHLD_COUNT, 0x40);
1128
	} else if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
1129 1130 1131 1132
		nsp32_index_write1(base, FIFO_FULL_SHLD_COUNT,  0x10);
		nsp32_index_write1(base, FIFO_EMPTY_SHLD_COUNT, 0x60);
	} else {
		nsp32_dbg(NSP32_DEBUG_INIT, "unknown transfer mode");
1133 1134 1135 1136 1137 1138 1139
	}

	nsp32_dbg(NSP32_DEBUG_INIT, "full 0x%x emp 0x%x",
		  nsp32_index_read1(base, FIFO_FULL_SHLD_COUNT),
		  nsp32_index_read1(base, FIFO_EMPTY_SHLD_COUNT));

	nsp32_index_write1(base, CLOCK_DIV, data->clock);
1140
	nsp32_index_write1(base, BM_CYCLE,  MEMRD_CMD1 | SGT_AUTO_PARA_MEMED_CMD);
1141 1142 1143
	nsp32_write1(base, PARITY_CONTROL, 0);	/* parity check is disable */

	/*
1144
	 * initialize MISC_WRRD register
1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159
	 * 
	 * Note: Designated parameters is obeyed as following:
	 *	MISC_SCSI_DIRECTION_DETECTOR_SELECT: It must be set.
	 *	MISC_MASTER_TERMINATION_SELECT:      It must be set.
	 *	MISC_BMREQ_NEGATE_TIMING_SEL:	     It should be set.
	 *	MISC_AUTOSEL_TIMING_SEL:	     It should be set.
	 *	MISC_BMSTOP_CHANGE2_NONDATA_PHASE:   It should be set.
	 *	MISC_DELAYED_BMSTART:		     It's selected for safety.
	 *
	 * Note: If MISC_BMSTOP_CHANGE2_NONDATA_PHASE is set, then
	 *	we have to set TRANSFERCONTROL_BM_START as 0 and set
	 *	appropriate value before restarting bus master transfer.
	 */
	nsp32_index_write2(base, MISC_WR,
			   (SCSI_DIRECTION_DETECTOR_SELECT |
1160 1161 1162 1163
			    DELAYED_BMSTART                |
			    MASTER_TERMINATION_SELECT      |
			    BMREQ_NEGATE_TIMING_SEL        |
			    AUTOSEL_TIMING_SEL             |
1164 1165 1166 1167 1168 1169 1170 1171 1172 1173
			    BMSTOP_CHANGE2_NONDATA_PHASE));

	nsp32_index_write1(base, TERM_PWR_CONTROL, 0);
	power = nsp32_index_read1(base, TERM_PWR_CONTROL);
	if (!(power & SENSE)) {
		nsp32_msg(KERN_INFO, "term power on");
		nsp32_index_write1(base, TERM_PWR_CONTROL, BPWR);
	}

	nsp32_write2(base, TIMER_SET, TIMER_STOP);
1174
	nsp32_write2(base, TIMER_SET, TIMER_STOP); /* Required 2 times */
1175

1176 1177 1178
	nsp32_write1(base, SYNC_REG,     0);
	nsp32_write1(base, ACK_WIDTH,    0);
	nsp32_write2(base, SEL_TIME_OUT, SEL_TIMEOUT_TIME);
1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189

	/*
	 * enable to select designated IRQ (except for
	 * IRQSELECT_SERR, IRQSELECT_PERR, IRQSELECT_BMCNTERR)
	 */
	nsp32_index_write2(base, IRQ_SELECT, IRQSELECT_TIMER_IRQ         |
			                     IRQSELECT_SCSIRESET_IRQ     |
			                     IRQSELECT_FIFO_SHLD_IRQ     |
			                     IRQSELECT_RESELECT_IRQ      |
			                     IRQSELECT_PHASE_CHANGE_IRQ  |
			                     IRQSELECT_AUTO_SCSI_SEQ_IRQ |
1190
			                  //   IRQSELECT_BMCNTERR_IRQ      |
1191 1192 1193 1194 1195 1196
			                     IRQSELECT_TARGET_ABORT_IRQ  |
			                     IRQSELECT_MASTER_ABORT_IRQ );
	nsp32_write2(base, IRQ_CONTROL, 0);

	/* PCI LED off */
	nsp32_index_write1(base, EXT_PORT_DDR, LED_OFF);
1197
	nsp32_index_write1(base, EXT_PORT,     LED_OFF);
1198 1199 1200 1201 1202 1203

	return TRUE;
}


/* interrupt routine */
Andrew Morton's avatar
Andrew Morton committed
1204
static irqreturn_t do_nsp32_isr(int irq, void *dev_id, struct pt_regs *regs)
1205 1206 1207 1208 1209 1210 1211 1212
{
	nsp32_hw_data *data = dev_id;
	unsigned int base = data->BaseAddress;
	Scsi_Cmnd *SCpnt = data->CurrentSC;
	unsigned short auto_stat, irq_stat, trans_stat;
	unsigned char busmon, busphase;
	unsigned long flags;
	int ret;
Andrew Morton's avatar
Andrew Morton committed
1213
	int handled = 0;
1214

1215
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229
	struct Scsi_Host *host = data->Host;
	spin_lock_irqsave(host->host_lock, flags);
#else
	spin_lock_irqsave(&io_request_lock, flags);
#endif

	/*
	 * IRQ check, then enable IRQ mask
	 */
	irq_stat = nsp32_read2(base, IRQ_STATUS);
	nsp32_dbg(NSP32_DEBUG_INTR, 
		  "enter IRQ: %d, IRQstatus: 0x%x", irq, irq_stat);
	/* is this interrupt comes from Ninja asic? */
	if ((irq_stat & IRQSTATUS_ANY_IRQ) == 0) {
1230
		nsp32_dbg(NSP32_DEBUG_INTR, "shared interrupt: irq other 0x%x", irq_stat);
1231 1232
		goto out2;
	}
Andrew Morton's avatar
Andrew Morton committed
1233
	handled = 1;
1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244
	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);

	busmon = nsp32_read1(base, SCSI_BUS_MONITOR);
	busphase = busmon & BUSMON_PHASE_MASK;

	trans_stat = nsp32_read2(base, TRANSFER_STATUS);
	if ((irq_stat == 0xffff) && (trans_stat == 0xffff)) {
		nsp32_msg(KERN_INFO, "card disconnect");
		if (data->CurrentSC != NULL) {
			nsp32_msg(KERN_INFO, "clean up current SCSI command");
			SCpnt->result = DID_BAD_TARGET << 16;
1245
			nsp32_scsi_done(SCpnt);
1246 1247 1248 1249 1250 1251
		}
		goto out;
	}

	/* Timer IRQ */
	if (irq_stat & IRQSTATUS_TIMER_IRQ) {
1252
		nsp32_dbg(NSP32_DEBUG_INTR, "timer stop");
1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
		nsp32_write2(base, TIMER_SET, TIMER_STOP);
		goto out;
	}

	/* SCSI reset */
	if (irq_stat & IRQSTATUS_SCSIRESET_IRQ) {
		nsp32_msg(KERN_INFO, "detected someone do bus reset");
		nsp32_do_bus_reset(data);
		if (SCpnt != NULL) {
			SCpnt->result = DID_RESET << 16;
1263
			nsp32_scsi_done(SCpnt);
1264 1265 1266
		}
		goto out;
	}
1267

1268
	if (SCpnt == NULL) {
1269 1270
		nsp32_msg(KERN_WARNING, "SCpnt==NULL this can't be happened");
		nsp32_msg(KERN_WARNING, "irq_stat=0x%x trans_stat=0x%x", irq_stat, trans_stat);
1271 1272 1273 1274 1275
		goto out;
	}

	/*
	 * AutoSCSI Interrupt.
1276
	 * Note: This interrupt is occurred when AutoSCSI is finished.  Then
1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
	 * check SCSIEXECUTEPHASE, and do appropriate action.  Each phases are
	 * recorded when AutoSCSI sequencer has been processed.
	 */
	if(irq_stat & IRQSTATUS_AUTOSCSI_IRQ) {
		/* getting SCSI executed phase */
		auto_stat = nsp32_read2(base, SCSI_EXECUTE_PHASE);
		nsp32_write2(base, SCSI_EXECUTE_PHASE, 0);

		/* Selection Timeout, go busfree phase. */
		if (auto_stat & SELECTION_TIMEOUT) {
			nsp32_dbg(NSP32_DEBUG_INTR,
1288
				  "selection timeout occurred");
1289 1290

			SCpnt->result = DID_TIME_OUT << 16;
1291
			nsp32_scsi_done(SCpnt);
1292 1293 1294 1295 1296 1297 1298
			goto out;
		}

		if (auto_stat & MSGOUT_PHASE) {
			/*
			 * MsgOut phase was processed.
			 * If MSG_IN_OCCUER is not set, then MsgOut phase is
1299
			 * completed. Thus, msgout_len must reset.  Otherwise,
1300
			 * nothing to do here. If MSG_OUT_OCCUER is occurred,
1301 1302 1303
			 * then we will encounter the condition and check.
			 */
			if (!(auto_stat & MSG_IN_OCCUER) &&
1304
			     (data->msgout_len <= 3)) {
1305
				/*
1306
				 * !MSG_IN_OCCUER && msgout_len <=3
1307 1308
				 *   ---> AutoSCSI with MSGOUTreg is processed.
				 */
1309
				data->msgout_len = 0;
1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
			};

			nsp32_dbg(NSP32_DEBUG_INTR, "MsgOut phase processed");
		}

		if ((auto_stat & DATA_IN_PHASE) &&
		    (SCpnt->resid > 0) &&
		    ((nsp32_read2(base, FIFO_REST_CNT) & FIFO_REST_MASK) != 0)) {
			printk( "auto+fifo\n");
			//nsp32_pio_read(SCpnt);
		}

		if (auto_stat & (DATA_IN_PHASE | DATA_OUT_PHASE)) {
			/* DATA_IN_PHASE/DATA_OUT_PHASE was processed. */
			nsp32_dbg(NSP32_DEBUG_INTR,
				  "Data in/out phase processed");

			/* read BMCNT, SGT pointer addr */
			nsp32_dbg(NSP32_DEBUG_INTR, "BMCNT=0x%lx", 
				    nsp32_read4(base, BM_CNT));
			nsp32_dbg(NSP32_DEBUG_INTR, "addr=0x%lx", 
				    nsp32_read4(base, SGT_ADR));
			nsp32_dbg(NSP32_DEBUG_INTR, "SACK=0x%lx", 
				    nsp32_read4(base, SACK_CNT));
			nsp32_dbg(NSP32_DEBUG_INTR, "SSACK=0x%lx", 
				    nsp32_read4(base, SAVED_SACK_CNT));
1336 1337

			SCpnt->resid = 0; /* all data transfered! */
1338 1339 1340 1341 1342 1343
		}

		/*
		 * MsgIn Occur
		 */
		if (auto_stat & MSG_IN_OCCUER) {
1344
			nsp32_msgin_occur(SCpnt, irq_stat, auto_stat);
1345 1346 1347 1348 1349 1350
		}

		/*
		 * MsgOut Occur
		 */
		if (auto_stat & MSG_OUT_OCCUER) {
1351
			nsp32_msgout_occur(SCpnt);
1352 1353 1354 1355 1356 1357
		}

		/*
		 * Bus Free Occur
		 */
		if (auto_stat & BUS_FREE_OCCUER) {
1358
			ret = nsp32_busfree_occur(SCpnt, auto_stat);
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408
			if (ret == TRUE) {
				goto out;
			}
		}

		if (auto_stat & STATUS_PHASE) {
			/*
			 * Read CSB and substitute CSB for SCpnt->result
			 * to save status phase stutas byte.
			 * scsi error handler checks host_byte (DID_*:
			 * low level driver to indicate status), then checks 
			 * status_byte (SCSI status byte).
			 */
			SCpnt->result =	(int)nsp32_read1(base, SCSI_CSB_IN);
		}

		if (auto_stat & ILLEGAL_PHASE) {
			/* Illegal phase is detected. SACK is not back. */
			nsp32_msg(KERN_WARNING, 
				  "AUTO SCSI ILLEGAL PHASE OCCUR!!!!");

			/* TODO: currently we don't have any action... bus reset? */

			/*
			 * To send back SACK, assert, wait, and negate.
			 */
			nsp32_sack_assert(data);
			nsp32_wait_req(data, NEGATE);
			nsp32_sack_negate(data);

		}

		if (auto_stat & COMMAND_PHASE) {
			/* nothing to do */
			nsp32_dbg(NSP32_DEBUG_INTR, "Command phase processed");
		}

		if (auto_stat & AUTOSCSI_BUSY) {
			/* AutoSCSI is running */
		}

		show_autophase(auto_stat);
	}

	/* FIFO_SHLD_IRQ */
	if (irq_stat & IRQSTATUS_FIFO_SHLD_IRQ) {
		nsp32_dbg(NSP32_DEBUG_INTR, "FIFO IRQ");

		switch(busphase) {
		case BUSPHASE_DATA_OUT:
1409
			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/write");
1410 1411 1412 1413 1414 1415

			//nsp32_pio_write(SCpnt);

			break;

		case BUSPHASE_DATA_IN:
1416
			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/read");
1417 1418 1419 1420 1421 1422

			//nsp32_pio_read(SCpnt);

			break;

		case BUSPHASE_STATUS:
1423
			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/status");
1424 1425 1426 1427 1428

			SCpnt->SCp.Status = nsp32_read1(base, SCSI_CSB_IN);

			break;
		default:
1429 1430
			nsp32_dbg(NSP32_DEBUG_INTR, "fifo/other phase");
			nsp32_dbg(NSP32_DEBUG_INTR, "irq_stat=0x%x trans_stat=0x%x", irq_stat, trans_stat);
1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444
			show_busphase(busphase);
			break;
		}

		goto out;
	}

	/* Phase Change IRQ */
	if (irq_stat & IRQSTATUS_PHASE_CHANGE_IRQ) {
		nsp32_dbg(NSP32_DEBUG_INTR, "phase change IRQ");

		switch(busphase) {
		case BUSPHASE_MESSAGE_IN:
			nsp32_dbg(NSP32_DEBUG_INTR, "phase chg/msg in");
1445
			nsp32_msgin_occur(SCpnt, irq_stat, 0);
1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458
			break;
		default:
			nsp32_msg(KERN_WARNING, "phase chg/other phase?");
			nsp32_msg(KERN_WARNING, "irq_stat=0x%x trans_stat=0x%x\n",
				  irq_stat, trans_stat);
			show_busphase(busphase);
			break;
		}
		goto out;
	}

	/* PCI_IRQ */
	if (irq_stat & IRQSTATUS_PCI_IRQ) {
1459
		nsp32_dbg(NSP32_DEBUG_INTR, "PCI IRQ occurred");
1460 1461 1462 1463 1464 1465 1466 1467
		/* Do nothing */
	}

	/* BMCNTERR_IRQ */
	if (irq_stat & IRQSTATUS_BMCNTERR_IRQ) {
		nsp32_msg(KERN_ERR, "Received unexpected BMCNTERR IRQ! ");
		/*
		 * TODO: To be implemented improving bus master
1468
		 * transfer reliablity when BMCNTERR is occurred in
1469 1470 1471 1472 1473
		 * AutoSCSI phase described in specification.
		 */
	}

#if 0
1474 1475
	nsp32_dbg(NSP32_DEBUG_INTR,
		  "irq_stat=0x%x trans_stat=0x%x", irq_stat, trans_stat);
1476 1477 1478 1479 1480 1481 1482 1483
	show_busphase(busphase);
#endif

 out:
	/* disable IRQ mask */
	nsp32_write2(base, IRQ_CONTROL, 0);

 out2:
1484
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,0))
1485
	spin_unlock_irqrestore(host->host_lock, flags);
1486 1487
#else
	spin_unlock_irqrestore(&io_request_lock, flags);
1488 1489 1490 1491
#endif

	nsp32_dbg(NSP32_DEBUG_INTR, "exit");

Andrew Morton's avatar
Andrew Morton committed
1492
	return IRQ_RETVAL(handled);
1493 1494 1495 1496
}

#undef SPRINTF
#define SPRINTF(args...) \
1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514
	do { \
		if(length > (pos - buffer)) { \
			pos += snprintf(pos, length - (pos - buffer) + 1, ## args); \
			nsp32_dbg(NSP32_DEBUG_PROC, "buffer=0x%p pos=0x%p length=%d %d\n", buffer, pos, length,  length - (pos - buffer));\
		} \
	} while(0)
static int nsp32_proc_info(
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73)) 
	struct Scsi_Host *host,
#endif
	char             *buffer,
	char            **start,
	off_t             offset,
	int               length,
#if !(LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73)) 
	int               hostno,
#endif
	int               inout)
1515
{
1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528
	char             *pos = buffer;
	int               thislength;
	unsigned long     flags;
	nsp32_hw_data    *data;
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73)) 
	int               hostno;
#else
	struct Scsi_Host *host;
#endif
	unsigned int      base;
	unsigned char     mode_reg;
	int               id, speed;
	long              model;
1529 1530 1531 1532 1533 1534

	/* Write is not supported, just return. */
	if (inout == TRUE) {
		return -EINVAL;
	}

1535 1536 1537 1538 1539 1540 1541 1542 1543
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73)) 
	hostno = host->host_no;
#else
	/* search this HBA host */
	host = scsi_host_hn_get(hostno);
	if (host == NULL) {
		return -ESRCH;
	}
#endif
1544 1545 1546 1547
	data = (nsp32_hw_data *)host->hostdata;
	base = host->io_port;

	SPRINTF("NinjaSCSI-32 status\n\n");
1548 1549
	SPRINTF("Driver version:        %s, $Revision: 1.33 $\n", nsp32_release_version);
	SPRINTF("SCSI host No.:         %d\n",		hostno);
1550 1551
	SPRINTF("IRQ:                   %d\n",		host->irq);
	SPRINTF("IO:                    0x%lx-0x%lx\n", host->io_port, host->io_port + host->n_io_port - 1);
1552
	SPRINTF("MMIO(virtual address): 0x%lx-0x%lx\n",	host->base, host->base + data->MmioLength - 1);
1553
	SPRINTF("sg_tablesize:          %d\n",		host->sg_tablesize);
1554
	SPRINTF("Chip revision:         0x%x\n",       	(nsp32_read2(base, INDEX_REG) >> 8) & 0xff);
1555 1556

	mode_reg = nsp32_index_read1(base, CHIP_MODE);
1557
	model    = data->pci_devid->driver_data;
1558 1559

#ifdef CONFIG_PM
1560
	SPRINTF("Power Management:      %s\n",          (mode_reg & OPTF) ? "yes" : "no");
1561
#endif
1562
	SPRINTF("OEM:                   %ld, %s\n",     (mode_reg & (OEM0|OEM1)), nsp32_model[model]);
1563 1564 1565 1566 1567

	spin_lock_irqsave(&(data->Lock), flags);
	SPRINTF("CurrentSC:             0x%p\n\n",      data->CurrentSC);
	spin_unlock_irqrestore(&(data->Lock), flags);

1568 1569

	SPRINTF("SDTR status\n");
1570
	for (id = 0; id < ARRAY_SIZE(data->target); id++) {
1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603

                SPRINTF("id %d: ", id);

		if (id == host->this_id) {
			SPRINTF("----- NinjaSCSI-32 host adapter\n");
			continue;
		}

		if (data->target[id].sync_flag == SDTR_DONE) {
			if (data->target[id].period == 0            &&
			    data->target[id].offset == ASYNC_OFFSET ) {
				SPRINTF("async");
			} else {
				SPRINTF(" sync");
			}
		} else {
			SPRINTF(" none");
		}

		if (data->target[id].period != 0) {

			speed = 1000000 / (data->target[id].period * 4);

			SPRINTF(" transfer %d.%dMB/s, offset %d",
				speed / 1000,
				speed % 1000,
				data->target[id].offset
				);
		}
		SPRINTF("\n");
	}


1604 1605 1606 1607 1608 1609 1610 1611
	thislength = pos - (buffer + offset);

	if(thislength < 0) {
		*start = 0;
                return 0;
        }


1612
	thislength = min(thislength, length);
1613 1614 1615 1616 1617 1618
	*start = buffer + offset;

	return thislength;
}
#undef SPRINTF

1619 1620


1621
/*
1622 1623
 * Reset parameters and call scsi_done for data->cur_lunt.
 * Be careful setting SCpnt->result = DID_* before calling this function.
1624
 */
1625
static void nsp32_scsi_done(Scsi_Cmnd *SCpnt)
1626
{
1627 1628
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   base = SCpnt->device->host->io_port;
1629 1630

	/*
1631
	 * unmap pci
1632
	 */
1633 1634
	if (SCpnt->request_bufflen == 0) {
		goto skip;
1635 1636
	}

1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647
	if (SCpnt->use_sg) {
		pci_unmap_sg(data->Pci,
			     (struct scatterlist *)SCpnt->buffer,
			     SCpnt->use_sg,
			     scsi_to_pci_dma_dir(SCpnt->sc_data_direction));
	} else {
		pci_unmap_single(data->Pci,
				 (u32)SCpnt->SCp.have_data_in,
				 SCpnt->request_bufflen,
				 scsi_to_pci_dma_dir(SCpnt->sc_data_direction));
	}
1648

1649
 skip:
1650
	/*
1651
	 * clear TRANSFERCONTROL_BM_START
1652
	 */
1653 1654
	nsp32_write2(base, TRANSFER_CONTROL, 0);
	nsp32_write4(base, BM_CNT,           0);
1655 1656

	/*
1657
	 * call scsi_done
1658
	 */
1659
	(*SCpnt->scsi_done)(SCpnt);
1660 1661

	/*
1662
	 * reset parameters
1663
	 */
1664 1665 1666 1667 1668
	data->cur_lunt->SCpnt = NULL;
	data->cur_lunt        = NULL;
	data->cur_target      = NULL;
	data->CurrentSC      = NULL;
}
1669 1670


1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684
/*
 * Bus Free Occur
 *
 * Current Phase is BUSFREE. AutoSCSI is automatically execute BUSFREE phase
 * with ACK reply when below condition is matched:
 *	MsgIn 00: Command Complete.
 *	MsgIn 02: Save Data Pointer.
 *	MsgIn 04: Diconnect.
 * In other case, unexpected BUSFREE is detected.
 */
static int nsp32_busfree_occur(Scsi_Cmnd *SCpnt, unsigned short execph)
{
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int base   = SCpnt->device->host->io_port;
1685

1686 1687 1688 1689 1690
	nsp32_dbg(NSP32_DEBUG_BUSFREE, "enter execph=0x%x", execph);
	show_autophase(execph);

	nsp32_write4(base, BM_CNT,           0);
	nsp32_write2(base, TRANSFER_CONTROL, 0);
1691 1692

	/*
1693 1694 1695 1696 1697 1698 1699 1700 1701
	 * MsgIn 02: Save Data Pointer
	 *
	 * VALID:
	 *   Save Data Pointer is received. Adjust pointer.
	 *   
	 * NO-VALID:
	 *   SCSI-3 says if Save Data Pointer is not received, then we restart
	 *   processing and we can't adjust any SCSI data pointer in next data
	 *   phase.
1702
	 */
1703 1704
	if (execph & MSGIN_02_VALID) {
		nsp32_dbg(NSP32_DEBUG_BUSFREE, "MsgIn02_Valid");
1705

1706 1707 1708 1709 1710 1711 1712
		/*
		 * Check sack_cnt/saved_sack_cnt, then adjust sg table if
		 * needed.
		 */
		if (!(execph & MSGIN_00_VALID) && 
		    ((execph & DATA_IN_PHASE) || (execph & DATA_OUT_PHASE))) {
			unsigned int sacklen, s_sacklen;
1713

1714 1715 1716 1717 1718
			/*
			 * Read SACK count and SAVEDSACK count, then compare.
			 */
			sacklen   = nsp32_read4(base, SACK_CNT      );
			s_sacklen = nsp32_read4(base, SAVED_SACK_CNT);
1719

1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740
			/*
			 * If SAVEDSACKCNT == 0, it means SavedDataPointer is
			 * come after data transfering.
			 */
			if (s_sacklen > 0) {
				/*
				 * Comparing between sack and savedsack to
				 * check the condition of AutoMsgIn03.
				 *
				 * If they are same, set msgin03 == TRUE,
				 * COMMANDCONTROL_AUTO_MSGIN_03 is enabled at
				 * reselection.  On the other hand, if they
				 * aren't same, set msgin03 == FALSE, and
				 * COMMANDCONTROL_AUTO_MSGIN_03 is disabled at
				 * reselection.
				 */
				if (sacklen != s_sacklen) {
					data->cur_lunt->msgin03 = FALSE;
				} else {
					data->cur_lunt->msgin03 = TRUE;
				}
1741

1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755
				nsp32_adjust_busfree(SCpnt, s_sacklen);
			}
		}

		/* This value has not substitude with valid value yet... */
		//data->cur_lunt->save_datp = data->cur_datp;
	} else {
		/*
		 * no processing.
		 */
	}
	
	if (execph & MSGIN_03_VALID) {
		/* MsgIn03 was valid to be processed. No need processing. */
1756 1757 1758
	}

	/*
1759
	 * target SDTR check
1760
	 */
1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788
	if (data->cur_target->sync_flag & SDTR_INITIATOR) {
		/*
		 * SDTR negotiation pulled by the initiator has not
		 * finished yet. Fall back to ASYNC mode.
		 */
		nsp32_set_async(data, data->cur_target);
		data->cur_target->sync_flag &= ~SDTR_INITIATOR;
		data->cur_target->sync_flag |= SDTR_DONE;
	} else if (data->cur_target->sync_flag & SDTR_TARGET) {
		/*
		 * SDTR negotiation pulled by the target has been
		 * negotiating.
		 */
		if (execph & (MSGIN_00_VALID | MSGIN_04_VALID)) {
			/* 
			 * If valid message is received, then
			 * negotiation is succeeded.
			 */
		} else {
			/*
			 * On the contrary, if unexpected bus free is
			 * occurred, then negotiation is failed. Fall
			 * back to ASYNC mode.
			 */
			nsp32_set_async(data, data->cur_target);
		}
		data->cur_target->sync_flag &= ~SDTR_TARGET;
		data->cur_target->sync_flag |= SDTR_DONE;
1789 1790 1791
	}

	/*
1792 1793 1794 1795
	 * It is always ensured by SCSI standard that initiator
	 * switches into Bus Free Phase after
	 * receiving message 00 (Command Complete), 04 (Disconnect).
	 * It's the reason that processing here is valid.
1796
	 */
1797 1798 1799
	if (execph & MSGIN_00_VALID) {
		/* MsgIn 00: Command Complete */
		nsp32_dbg(NSP32_DEBUG_BUSFREE, "command complete");
1800

1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
		SCpnt->SCp.Status  = nsp32_read1(base, SCSI_CSB_IN);
		SCpnt->SCp.Message = 0;
		nsp32_dbg(NSP32_DEBUG_BUSFREE, 
			  "normal end stat=0x%x resid=0x%x\n",
			  SCpnt->SCp.Status, SCpnt->resid);
		SCpnt->result = (DID_OK             << 16) |
			        (SCpnt->SCp.Message <<  8) |
			        (SCpnt->SCp.Status  <<  0);
		nsp32_scsi_done(SCpnt);
		/* All operation is done */
		return TRUE;
	} else if (execph & MSGIN_04_VALID) {
		/* MsgIn 04: Disconnect */
		SCpnt->SCp.Status  = nsp32_read1(base, SCSI_CSB_IN);
		SCpnt->SCp.Message = 4;
		
		nsp32_dbg(NSP32_DEBUG_BUSFREE, "disconnect");
		return TRUE;
	} else {
		/* Unexpected bus free */
		nsp32_msg(KERN_WARNING, "unexpected bus free occurred");
1822

1823 1824 1825 1826 1827
		/* DID_ERROR? */
		//SCpnt->result   = (DID_OK << 16) | (SCpnt->SCp.Message << 8) | (SCpnt->SCp.Status << 0);
		SCpnt->result = DID_ERROR << 16;
		nsp32_scsi_done(SCpnt);
		return TRUE;
1828
	}
1829 1830
	return FALSE;
}
1831 1832


1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847
/*
 * nsp32_adjust_busfree - adjusting SG table
 *
 * Note: This driver adjust the SG table using SCSI ACK
 *       counter instead of BMCNT counter!
 */
static void nsp32_adjust_busfree(Scsi_Cmnd *SCpnt, unsigned int s_sacklen)
{
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	int                   old_entry = data->cur_entry;
	int                   new_entry;
	int                   sg_num = data->cur_lunt->sg_num;
	nsp32_sgtable *sgt    = data->cur_lunt->sglun->sgt;
	unsigned int          restlen, sentlen;
	u32_le                len, addr;
1848

1849
	nsp32_dbg(NSP32_DEBUG_SGLIST, "old resid=0x%x", SCpnt->resid);
1850

1851 1852
	/* adjust saved SACK count with 4 byte start address boundary */
	s_sacklen -= le32_to_cpu(sgt[old_entry].addr) & 3;
1853

1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864
	/*
	 * calculate new_entry from sack count and each sgt[].len 
	 * calculate the byte which is intent to send
	 */
	sentlen = 0;
	for (new_entry = old_entry; new_entry < sg_num; new_entry++) {
		sentlen += (le32_to_cpu(sgt[new_entry].len) & ~SGTEND);
		if (sentlen > s_sacklen) {
			break;
		}
	}
1865

1866 1867 1868 1869
	/* all sgt is processed */
	if (new_entry == sg_num) {
		goto last;
	}
1870

1871 1872 1873 1874 1875
	if (sentlen == s_sacklen) {
		/* XXX: confirm it's ok or not */
		/* In this case, it's ok because we are at 
		   the head element of the sg. restlen is correctly calculated. */
	}
1876

1877 1878
	/* calculate the rest length for transfering */
	restlen = sentlen - s_sacklen;
1879

1880 1881 1882 1883 1884 1885
	/* update adjusting current SG table entry */
	len  = le32_to_cpu(sgt[new_entry].len);
	addr = le32_to_cpu(sgt[new_entry].addr);
	addr += (len - restlen);
	sgt[new_entry].addr = cpu_to_le32(addr);
	sgt[new_entry].len  = cpu_to_le32(restlen);
1886

1887 1888 1889 1890
	/* set cur_entry with new_entry */
	data->cur_entry = new_entry;
 
	return;
1891

1892 1893 1894
 last:
	if (SCpnt->resid < sentlen) {
		nsp32_msg(KERN_ERR, "resid underflow");
1895 1896
	}

1897 1898
	SCpnt->resid -= sentlen;
	nsp32_dbg(NSP32_DEBUG_SGLIST, "new resid=0x%x", SCpnt->resid);
1899

1900
	/* update hostdata and lun */
1901

1902
	return;
1903 1904 1905
}


1906 1907 1908 1909 1910 1911 1912
/*
 * It's called MsgOut phase occur.
 * NinjaSCSI-32Bi/UDE automatically processes up to 3 messages in
 * message out phase. It, however, has more than 3 messages,
 * HBA creates the interrupt and we have to process by hand.
 */
static void nsp32_msgout_occur(Scsi_Cmnd *SCpnt)
1913
{
1914 1915 1916 1917
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int base   = SCpnt->device->host->io_port;
	//unsigned short command;
	long new_sgtp;
1918
	int i;
1919 1920 1921
	
	nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR,
		  "enter: msgout_len: 0x%x", data->msgout_len);
1922 1923

	/*
1924 1925
	 * If MsgOut phase is occurred without having any
	 * message, then No_Operation is sent (SCSI-2).
1926
	 */
1927 1928 1929
	if (data->msgout_len == 0) {
		nsp32_build_nop(SCpnt);
	}
1930 1931

	/*
1932 1933 1934
	 * Set SGTP ADDR current entry for restarting AUTOSCSI, 
	 * because SGTP is incremented next point.
	 * There is few statement in the specification...
1935
	 */
1936 1937
 	new_sgtp = data->cur_lunt->sglun_paddr + 
		   (data->cur_lunt->cur_entry * sizeof(nsp32_sgtable));
1938 1939

	/*
1940
	 * send messages
1941
	 */
1942 1943 1944
	for (i = 0; i < data->msgout_len; i++) {
		nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR,
			  "%d : 0x%x", i, data->msgoutbuf[i]);
1945

1946 1947 1948 1949
		/*
		 * Check REQ is asserted.
		 */
		nsp32_wait_req(data, ASSERT);
1950

1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971
		if (i == (data->msgout_len - 1)) {
			/*
			 * If the last message, set the AutoSCSI restart
			 * before send back the ack message. AutoSCSI
			 * restart automatically negate ATN signal.
			 */
			//command = (AUTO_MSGIN_00_OR_04 | AUTO_MSGIN_02);
			//nsp32_restart_autoscsi(SCpnt, command);
			nsp32_write2(base, COMMAND_CONTROL,
					 (CLEAR_CDB_FIFO_POINTER |
					  AUTO_COMMAND_PHASE     |
					  AUTOSCSI_RESTART       |
					  AUTO_MSGIN_00_OR_04    |
					  AUTO_MSGIN_02          ));
		}
		/*
		 * Write data with SACK, then wait sack is
		 * automatically negated.
		 */
		nsp32_write1(base, SCSI_DATA_WITH_ACK, data->msgoutbuf[i]);
		nsp32_wait_sack(data, NEGATE);
1972

1973 1974 1975
		nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR, "bus: 0x%x\n",
			  nsp32_read1(base, SCSI_BUS_MONITOR));
	};
1976

1977
	data->msgout_len = 0;
1978

1979
	nsp32_dbg(NSP32_DEBUG_MSGOUTOCCUR, "exit");
1980 1981 1982
}

/*
1983 1984 1985 1986
 * Restart AutoSCSI
 *
 * Note: Restarting AutoSCSI needs set:
 *		SYNC_REG, ACK_WIDTH, SGT_ADR, TRANSFER_CONTROL
1987
 */
1988
static void nsp32_restart_autoscsi(Scsi_Cmnd *SCpnt, unsigned short command)
1989
{
1990 1991 1992
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   base = data->BaseAddress;
	unsigned short transfer = 0;
1993

1994
	nsp32_dbg(NSP32_DEBUG_RESTART, "enter");
1995

1996 1997
	if (data->cur_target == NULL || data->cur_lunt == NULL) {
		nsp32_msg(KERN_ERR, "Target or Lun is invalid");
1998 1999
	}

2000 2001 2002 2003 2004
	/*
	 * set SYNC_REG
	 * Don't set BM_START_ADR before setting this register.
	 */
	nsp32_write1(base, SYNC_REG, data->cur_target->syncreg);
2005

2006 2007 2008 2009
	/*
	 * set ACKWIDTH
	 */
	nsp32_write1(base, ACK_WIDTH, data->cur_target->ackwidth);
2010

2011 2012 2013 2014
	/*
	 * set SREQ hazard killer sampling rate
	 */
	nsp32_write1(base, SREQ_SMPL_RATE, data->cur_target->sample_reg);
2015

2016 2017 2018 2019
	/*
	 * set SGT ADDR (physical address)
	 */
	nsp32_write4(base, SGT_ADR, data->cur_lunt->sglun_paddr);
2020

2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035
	/*
	 * set TRANSFER CONTROL REG
	 */
	transfer = 0;
	transfer |= (TRANSFER_GO | ALL_COUNTER_CLR);
	if (data->trans_method & NSP32_TRANSFER_BUSMASTER) {
		if (SCpnt->request_bufflen > 0) {
			transfer |= BM_START;
		}
	} else if (data->trans_method & NSP32_TRANSFER_MMIO) {
		transfer |= CB_MMIO_MODE;
	} else if (data->trans_method & NSP32_TRANSFER_PIO) {
		transfer |= CB_IO_MODE;
	}
	nsp32_write2(base, TRANSFER_CONTROL, transfer);
2036

2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047
	/*
	 * restart AutoSCSI
	 *
	 * TODO: COMMANDCONTROL_AUTO_COMMAND_PHASE is needed ?
	 */
	command |= (CLEAR_CDB_FIFO_POINTER |
		    AUTO_COMMAND_PHASE     |
		    AUTOSCSI_RESTART       );
	nsp32_write2(base, COMMAND_CONTROL, command);

	nsp32_dbg(NSP32_DEBUG_RESTART, "exit");
2048 2049
}

2050 2051 2052 2053 2054 2055 2056

/*
 * cannot run automatically message in occur
 */
static void nsp32_msgin_occur(Scsi_Cmnd     *SCpnt,
			      unsigned long  irq_status,
			      unsigned short execph)
2057
{
2058 2059 2060 2061 2062 2063 2064 2065 2066
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   base = SCpnt->device->host->io_port;
	unsigned char  msg;
	unsigned char  msgtype;
	unsigned char  newlun;
	unsigned short command  = 0;
	int            msgclear = TRUE;
	long           new_sgtp;
	int            ret;
2067

2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078
	/*
	 * read first message
	 *    Use SCSIDATA_W_ACK instead of SCSIDATAIN, because the procedure
	 *    of Message-In have to be processed before sending back SCSI ACK.
	 */
	msg = nsp32_read1(base, SCSI_DATA_IN);
	data->msginbuf[(unsigned char)data->msgin_len] = msg;
	msgtype = data->msginbuf[0];
	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR,
		  "enter: msglen: 0x%x msgin: 0x%x msgtype: 0x%x",
		  data->msgin_len, msg, msgtype);
2079 2080

	/*
2081
	 * TODO: We need checking whether bus phase is message in?
2082 2083 2084
	 */

	/*
2085
	 * assert SCSI ACK
2086
	 */
2087
	nsp32_sack_assert(data);
2088 2089

	/*
2090
	 * processing IDENTIFY
2091
	 */
2092 2093 2094 2095 2096
	if (msgtype & 0x80) {
		if (!(irq_status & IRQSTATUS_RESELECT_OCCUER)) {
			/* Invalid (non reselect) phase */
			goto reject;
		}
2097

2098 2099 2100 2101 2102 2103 2104 2105 2106
		newlun = msgtype & 0x1f; /* TODO: SPI-3 compliant? */
		ret = nsp32_reselection(SCpnt, newlun);
		if (ret == TRUE) {
			goto restart;
		} else {
			goto reject;
		}
	}
	
2107
	/*
2108 2109 2110
	 * processing messages except for IDENTIFY
	 *
	 * TODO: Messages are all SCSI-2 terminology. SCSI-3 compliance is TODO.
2111
	 */
2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129
	switch (msgtype) {
	/*
	 * 1-byte message
	 */
	case COMMAND_COMPLETE:
	case DISCONNECT:
		/*
		 * These messages should not be occurred.
		 * They should be processed on AutoSCSI sequencer.
		 */
		nsp32_msg(KERN_WARNING, 
			   "unexpected message of AutoSCSI MsgIn: 0x%x", msg);
		break;
		
	case RESTORE_POINTERS:
		/*
		 * AutoMsgIn03 is disabled, and HBA gets this message.
		 */
2130

2131 2132
		if ((execph & DATA_IN_PHASE) || (execph & DATA_OUT_PHASE)) {
			unsigned int s_sacklen;
2133

2134 2135 2136 2137 2138 2139 2140 2141
			s_sacklen = nsp32_read4(base, SAVED_SACK_CNT);
			if ((execph & MSGIN_02_VALID) && (s_sacklen > 0)) {
				nsp32_adjust_busfree(SCpnt, s_sacklen);
			} else {
				/* No need to rewrite SGT */
			}
		}
		data->cur_lunt->msgin03 = FALSE;
2142

2143
		/* Update with the new value */
2144

2145 2146
		/* reset SACK/SavedACK counter (or ALL clear?) */
		nsp32_write4(base, CLR_COUNTER, CLRCOUNTER_ALLMASK);
2147 2148

		/*
2149
		 * set new sg pointer
2150
		 */
2151 2152 2153
		new_sgtp = data->cur_lunt->sglun_paddr + 
			(data->cur_lunt->cur_entry * sizeof(nsp32_sgtable));
		nsp32_write4(base, SGT_ADR, new_sgtp);
2154

2155
		break;
2156

2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171
	case SAVE_POINTERS:
		/*
		 * These messages should not be occurred.
		 * They should be processed on AutoSCSI sequencer.
		 */
		nsp32_msg (KERN_WARNING, 
			   "unexpected message of AutoSCSI MsgIn: SAVE_POINTERS");
		
		break;
		
	case MESSAGE_REJECT:
		/* If previous message_out is sending SDTR, and get 
		   message_reject from target, SDTR negotiation is failed */
		if (data->cur_target->sync_flag &
				(SDTR_INITIATOR | SDTR_TARGET)) {
2172
			/*
2173 2174 2175
			 * Current target is negotiating SDTR, but it's
			 * failed.  Fall back to async transfer mode, and set
			 * SDTR_DONE.
2176
			 */
2177 2178 2179
			nsp32_set_async(data, data->cur_target);
			data->cur_target->sync_flag &= ~SDTR_INITIATOR;
			data->cur_target->sync_flag |= SDTR_DONE;
2180 2181

		}
2182
		break;
2183

2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195
	case LINKED_CMD_COMPLETE:
	case LINKED_FLG_CMD_COMPLETE:
		/* queue tag is not supported currently */
		nsp32_msg (KERN_WARNING, 
			   "unsupported message: 0x%x", msgtype);
		break;

	case INITIATE_RECOVERY:
		/* staring ECA (Extended Contingent Allegiance) state. */
		/* This message is declined in SPI2 or later. */

		goto reject;
2196 2197

	/*
2198
	 * 2-byte message
2199
	 */
2200 2201
	case SIMPLE_QUEUE_TAG:
	case 0x23:
2202
		/*
2203 2204
		 * 0x23: Ignore_Wide_Residue is not declared in scsi.h.
		 * No support is needed.
2205
		 */
2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222
		if (data->msgin_len >= 1) {
			goto reject;
		}

		/* current position is 1-byte of 2 byte */
		msgclear = FALSE;

		break;

	/*
	 * extended message
	 */
	case EXTENDED_MESSAGE:
		if (data->msgin_len < 1) {
			/*
			 * Current position does not reach 2-byte
			 * (2-byte is extended message length).
2223
			 */
2224 2225 2226 2227 2228
			msgclear = FALSE;
			break;
		}

		if ((data->msginbuf[1] + 1) > data->msgin_len) {
2229
			/*
2230 2231 2232 2233
			 * Current extended message has msginbuf[1] + 2
			 * (msgin_len starts counting from 0, so buf[1] + 1).
			 * If current message position is not finished,
			 * continue receiving message.
2234
			 */
2235 2236
			msgclear = FALSE;
			break;
2237 2238
		}

2239 2240 2241 2242 2243 2244 2245 2246
		/*
		 * Reach here means regular length of each type of 
		 * extended messages.
		 */
		switch (data->msginbuf[2]) {
		case EXTENDED_MODIFY_DATA_POINTER:
			/* TODO */
			goto reject; /* not implemented yet */
2247 2248
			break;

2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259
		case EXTENDED_SDTR:
			/*
			 * Exchange this message between initiator and target.
			 */
			if (data->msgin_len != EXTENDED_SDTR_LEN + 1) {
				/*
				 * received inappropriate message.
				 */
				goto reject;
				break;
			}
2260

2261
			nsp32_analyze_sdtr(SCpnt);
2262

2263
			break;
2264

2265 2266 2267
		case EXTENDED_EXTENDED_IDENTIFY:
			/* SCSI-I only, not supported. */
			goto reject; /* not implemented yet */
2268

2269
			break;
2270

2271 2272
		case EXTENDED_WDTR:
			goto reject; /* not implemented yet */
2273

2274 2275 2276 2277 2278 2279 2280 2281 2282
			break;
			
		default:
			goto reject;
		}
		break;
		
	default:
		goto reject;
2283 2284
	}

2285 2286 2287
 restart:
	if (msgclear == TRUE) {
		data->msgin_len = 0;
2288 2289

		/*
2290 2291 2292 2293 2294
		 * If restarting AutoSCSI, but there are some message to out
		 * (msgout_len > 0), set AutoATN, and set SCSIMSGOUT as 0
		 * (MV_VALID = 0). When commandcontrol is written with
		 * AutoSCSI restart, at the same time MsgOutOccur should be
		 * happened (however, such situation is really possible...?).
2295
		 */
2296 2297 2298
		if (data->msgout_len > 0) {	
			nsp32_write4(base, SCSI_MSG_OUT, 0);
			command |= AUTO_ATN;
2299
		}
2300

2301
		/*
2302 2303
		 * restart AutoSCSI
		 * If it's failed, COMMANDCONTROL_AUTO_COMMAND_PHASE is needed.
2304
		 */
2305
		command |= (AUTO_MSGIN_00_OR_04 | AUTO_MSGIN_02);
2306

2307 2308 2309 2310 2311 2312 2313 2314 2315
		/*
		 * If current msgin03 is TRUE, then flag on.
		 */
		if (data->cur_lunt->msgin03 == TRUE) {
			command |= AUTO_MSGIN_03;
		}
		data->cur_lunt->msgin03 = FALSE;
	} else {
		data->msgin_len++;
2316 2317 2318
	}

	/*
2319
	 * restart AutoSCSI
2320
	 */
2321
	nsp32_restart_autoscsi(SCpnt, command);
2322 2323

	/*
2324
	 * wait SCSI REQ negate for REQ-ACK handshake
2325
	 */
2326
	nsp32_wait_req(data, NEGATE);
2327 2328

	/*
2329
	 * negate SCSI ACK
2330
	 */
2331
	nsp32_sack_negate(data);
2332

2333
	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit");
2334

2335
	return;
2336

2337 2338 2339 2340 2341 2342 2343
 reject:
	nsp32_msg(KERN_WARNING, 
		  "invalid or unsupported MessageIn, rejected. "
		  "current msg: 0x%x (len: 0x%x), processing msg: 0x%x",
		  msg, data->msgin_len, msgtype);
	nsp32_build_reject(SCpnt);
	data->msgin_len = 0;
2344

2345 2346
	goto restart;
}
2347 2348

/*
2349
 * 
2350
 */
2351
static void nsp32_analyze_sdtr(Scsi_Cmnd *SCpnt)
2352
{
2353 2354 2355 2356 2357 2358 2359
	nsp32_hw_data   *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	nsp32_target     *target     = data->cur_target;
	nsp32_sync_table *synct;
	unsigned char     get_period = data->msginbuf[3];
	unsigned char     get_offset = data->msginbuf[4];
	int               entry;
	int               syncnum;
2360

2361
	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "enter");
2362

2363 2364
	synct   = data->synct;
	syncnum = data->syncnum;
2365 2366

	/*
2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381
	 * If this inititor sent the SDTR message, then target responds SDTR,
	 * initiator SYNCREG, ACKWIDTH from SDTR parameter.
	 * Messages are not appropriate, then send back reject message.
	 * If initiator did not send the SDTR, but target sends SDTR, 
	 * initiator calculator the appropriate parameter and send back SDTR.
	 */	
	if (target->sync_flag & SDTR_INITIATOR) {
		/*
		 * Initiator sent SDTR, the target responds and
		 * send back negotiation SDTR.
		 */
		nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "target responds SDTR");
	
		target->sync_flag &= ~SDTR_INITIATOR;
		target->sync_flag |= SDTR_DONE;
2382 2383

		/*
2384
		 * offset:
2385
		 */
2386 2387 2388 2389 2390 2391 2392
		if (get_offset > SYNC_OFFSET) {
			/*
			 * Negotiation is failed, the target send back
			 * unexpected offset value.
			 */
			goto reject;
		}
2393
		
2394 2395 2396 2397 2398 2399 2400 2401
		if (get_offset == ASYNC_OFFSET) {
			/*
			 * Negotiation is succeeded, the target want
			 * to fall back into asynchronous transfer mode.
			 */
			goto async;
		}

2402
		/*
2403 2404 2405 2406 2407 2408 2409 2410
		 * period:
		 *    Check whether sync period is too short. If too short,
		 *    fall back to async mode. If it's ok, then investigate
		 *    the received sync period. If sync period is acceptable
		 *    between sync table start_period and end_period, then
		 *    set this I_T nexus as sent offset and period.
		 *    If it's not acceptable, send back reject and fall back
		 *    to async mode.
2411
		 */
2412 2413 2414 2415 2416 2417
		if (get_period < data->synct[0].period_num) {
			/*
			 * Negotiation is failed, the target send back
			 * unexpected period value.
			 */
			goto reject;
2418 2419
		}

2420
		entry = nsp32_search_period_entry(data, target, get_period);
2421

2422 2423 2424 2425 2426 2427 2428
		if (entry < 0) {
			/*
			 * Target want to use long period which is not 
			 * acceptable NinjaSCSI-32Bi/UDE.
			 */
			goto reject;
		}
2429 2430

		/*
2431
		 * Set new sync table and offset in this I_T nexus.
2432
		 */
2433 2434 2435 2436 2437 2438
		nsp32_set_sync_entry(data, target, entry, get_offset);
	} else {
		/* Target send SDTR to initiator. */
		nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "target send SDTR");
	
		target->sync_flag |= SDTR_INITIATOR;
2439

2440 2441 2442 2443 2444
		/* offset: */
		if (get_offset > SYNC_OFFSET) {
			/* send back as SYNC_OFFSET */
			get_offset = SYNC_OFFSET;
		}
2445

2446 2447 2448
		/* period: */
		if (get_period < data->synct[0].period_num) {
			get_period = data->synct[0].period_num;
2449 2450
		}

2451
		entry = nsp32_search_period_entry(data, target, get_period);
2452

2453 2454 2455 2456 2457 2458 2459 2460
		if (get_offset == ASYNC_OFFSET || entry < 0) {
			nsp32_set_async(data, target);
			nsp32_build_sdtr(SCpnt, 0, ASYNC_OFFSET);
		} else {
			nsp32_set_sync_entry(data, target, entry, get_offset);
			nsp32_build_sdtr(SCpnt, get_period, get_offset);
		}
	}
2461

2462 2463 2464
	target->period = get_period;
	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit");
	return;
2465

2466
 reject:
2467
	/*
2468 2469
	 * If the current message is unacceptable, send back to the target
	 * with reject message.
2470
	 */
2471
	nsp32_build_reject(SCpnt);
2472

2473 2474
 async:
	nsp32_set_async(data, target);	/* set as ASYNC transfer mode */
2475

2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502
	target->period = 0;
	nsp32_dbg(NSP32_DEBUG_MSGINOCCUR, "exit: set async");
	return;
}


/*
 * Search config entry number matched in sync_table from given
 * target and speed period value. If failed to search, return negative value.
 */
static int nsp32_search_period_entry(nsp32_hw_data *data,
				     nsp32_target  *target,
				     unsigned char  period)
{
	int i;

	if (target->limit_entry >= data->syncnum) {
		nsp32_msg(KERN_ERR, "limit_entry exceeds syncnum!");
		target->limit_entry = 0;
	}

	for (i = target->limit_entry; i < data->syncnum; i++) {
		if (period >= data->synct[i].start_period &&
		    period <= data->synct[i].end_period) {
				break;
		}
	}
2503 2504

	/*
2505 2506
	 * Check given period value is over the sync_table value.
	 * If so, return max value.
2507
	 */
2508 2509 2510
	if (i == data->syncnum) {
		i = -1;
	}
2511

2512 2513
	return i;
}
2514 2515


2516 2517 2518 2519 2520 2521
/*
 * target <-> initiator use ASYNC transfer
 */
static void nsp32_set_async(nsp32_hw_data *data, nsp32_target *target)
{
	unsigned char period = data->synct[target->limit_entry].period_num;
2522

2523 2524 2525 2526 2527
	target->offset     = ASYNC_OFFSET;
	target->period     = 0;
	target->syncreg    = TO_SYNCREG(period, ASYNC_OFFSET);
	target->ackwidth   = 0;
	target->sample_reg = 0;
2528

2529 2530
	nsp32_dbg(NSP32_DEBUG_SYNC, "set async");
}
2531 2532


2533 2534 2535 2536 2537 2538 2539 2540 2541
/*
 * target <-> initiator use maximum SYNC transfer
 */
static void nsp32_set_max_sync(nsp32_hw_data *data,
			       nsp32_target  *target,
			       unsigned char *period,
			       unsigned char *offset)
{
	unsigned char period_num, ackwidth;
2542

2543 2544 2545 2546
	period_num = data->synct[target->limit_entry].period_num;
	*period    = data->synct[target->limit_entry].start_period;
	ackwidth   = data->synct[target->limit_entry].ackwidth;
	*offset    = SYNC_OFFSET;
2547

2548 2549 2550 2551 2552
	target->syncreg    = TO_SYNCREG(period_num, *offset);
	target->ackwidth   = ackwidth;
	target->offset     = *offset;
	target->sample_reg = 0;       /* disable SREQ sampling */
}
2553 2554


2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604
/*
 * target <-> initiator use entry number speed
 */
static void nsp32_set_sync_entry(nsp32_hw_data *data,
				 nsp32_target  *target,
				 int            entry,
				 unsigned char  offset)
{
	unsigned char period, ackwidth, sample_rate;

	period      = data->synct[entry].period_num;
	ackwidth    = data->synct[entry].ackwidth;
	offset      = offset;
	sample_rate = data->synct[entry].sample_rate;

	target->syncreg    = TO_SYNCREG(period, offset);
	target->ackwidth   = ackwidth;
	target->offset     = offset;
	target->sample_reg = sample_rate | SAMPLING_ENABLE;

	nsp32_dbg(NSP32_DEBUG_SYNC, "set sync");
}


/*
 * It waits until SCSI REQ becomes assertion or negation state.
 *
 * Note: If nsp32_msgin_occur is called, we asserts SCSI ACK. Then
 *     connected target responds SCSI REQ negation.  We have to wait
 *     SCSI REQ becomes negation in order to negate SCSI ACK signal for
 *     REQ-ACK handshake.
 */
static void nsp32_wait_req(nsp32_hw_data *data, int state)
{
	unsigned int  base      = data->BaseAddress;
	int           wait_time = 0;
	unsigned char bus, req_bit;

	if (!((state == ASSERT) || (state == NEGATE))) {
		nsp32_msg(KERN_ERR, "unknown state designation");
	}
	/* REQ is BIT(5) */
	req_bit = (state == ASSERT ? BUSMON_REQ : 0);

	do {
		bus = nsp32_read1(base, SCSI_BUS_MONITOR);
		if ((bus & BUSMON_REQ) == req_bit) {
			nsp32_dbg(NSP32_DEBUG_WAIT, 
				  "wait_time: %d", wait_time);
			return;
2605
		}
2606 2607 2608
		udelay(1);
		wait_time++;
	} while (wait_time < REQSACK_TIMEOUT_TIME);
2609

2610 2611
	nsp32_msg(KERN_WARNING, "wait REQ timeout, req_bit: 0x%x", req_bit);
}
2612

2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633
/*
 * It waits until SCSI SACK becomes assertion or negation state.
 */
static void nsp32_wait_sack(nsp32_hw_data *data, int state)
{
	unsigned int  base      = data->BaseAddress;
	int           wait_time = 0;
	unsigned char bus, ack_bit;

	if (!((state == ASSERT) || (state == NEGATE))) {
		nsp32_msg(KERN_ERR, "unknown state designation");
	}
	/* ACK is BIT(4) */
	ack_bit = (state == ASSERT ? BUSMON_ACK : 0);

	do {
		bus = nsp32_read1(base, SCSI_BUS_MONITOR);
		if ((bus & BUSMON_ACK) == ack_bit) {
			nsp32_dbg(NSP32_DEBUG_WAIT,
				  "wait_time: %d", wait_time);
			return;
2634
		}
2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709
		udelay(1);
		wait_time++;
	} while (wait_time < REQSACK_TIMEOUT_TIME);

	nsp32_msg(KERN_WARNING, "wait SACK timeout, ack_bit: 0x%x", ack_bit);
}

/*
 * assert SCSI ACK
 *
 * Note: SCSI ACK assertion needs with ACKENB=1, AUTODIRECTION=1.
 */
static void nsp32_sack_assert(nsp32_hw_data *data)
{
	unsigned int  base = data->BaseAddress;
	unsigned char busctrl;

	busctrl  = nsp32_read1(base, SCSI_BUS_CONTROL);
	busctrl	|= (BUSCTL_ACK | AUTODIRECTION | ACKENB);
	nsp32_write1(base, SCSI_BUS_CONTROL, busctrl);
}

/*
 * negate SCSI ACK
 */
static void nsp32_sack_negate(nsp32_hw_data *data)
{
	unsigned int  base = data->BaseAddress;
	unsigned char busctrl;

	busctrl  = nsp32_read1(base, SCSI_BUS_CONTROL);
	busctrl	&= ~BUSCTL_ACK;
	nsp32_write1(base, SCSI_BUS_CONTROL, busctrl);
}



/*
 * Note: n_io_port is defined as 0x7f because I/O register port is
 *	 assigned as:
 *	0x800-0x8ff: memory mapped I/O port
 *	0x900-0xbff: (map same 0x800-0x8ff I/O port image repeatedly)
 *	0xc00-0xfff: CardBus status registers
 */
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
#define DETECT_OK 0
#define DETECT_NG 1
#define PCIDEV    pdev
static int nsp32_detect(struct pci_dev *pdev)
#else
#define DETECT_OK 1
#define DETECT_NG 0
#define PCIDEV    (data->Pci)
static int nsp32_detect(Scsi_Host_Template *sht)
#endif
{
	struct Scsi_Host *host;	/* registered host structure */
	struct resource  *res;
	nsp32_hw_data    *data;
	int               ret;
	int               i, j;

	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");

	/*
	 * register this HBA as SCSI device
	 */
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
	host = scsi_host_alloc(&nsp32_template, sizeof(nsp32_hw_data));
#else
	host = scsi_register(sht, sizeof(nsp32_hw_data));
#endif
	if (host == NULL) {
		nsp32_msg (KERN_ERR, "failed to scsi register");
		goto err;
2710 2711 2712
	}

	/*
2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744
	 * set nsp32_hw_data
	 */
	data = (nsp32_hw_data *)host->hostdata;

	memcpy(data, &nsp32_data_base, sizeof(nsp32_hw_data));

	host->irq       = data->IrqNumber;
	host->io_port   = data->BaseAddress;
	host->unique_id = data->BaseAddress;
	host->n_io_port	= data->NumAddress;
	host->base      = data->MmioAddress;
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,63))
	scsi_set_device(host, &PCIDEV->dev);
#else
	scsi_set_pci_device(host, PCIDEV);
#endif

	data->Host      = host;
	spin_lock_init(&(data->Lock));

	data->cur_lunt   = NULL;
	data->cur_target = NULL;

	/*
	 * Bus master transfer mode is supported currently.
	 */
	data->trans_method = NSP32_TRANSFER_BUSMASTER;

	/*
	 * Set clock div, CLOCK_4 (HBA has own external clock, and
	 * dividing * 100ns/4).
	 * Currently CLOCK_4 has only tested, not for CLOCK_2/PCICLK yet.
2745
	 */
2746
	data->clock = CLOCK_4;
2747 2748

	/*
2749
	 * Select appropriate nsp32_sync_table and set I_CLOCKDIV.
2750
	 */
2751 2752 2753 2754
	switch (data->clock) {
	case CLOCK_4:
		/* If data->clock is CLOCK_4, then select 40M sync table. */
		data->synct   = nsp32_sync_table_40M;
2755
		data->syncnum = ARRAY_SIZE(nsp32_sync_table_40M);
2756 2757 2758 2759
		break;
	case CLOCK_2:
		/* If data->clock is CLOCK_2, then select 20M sync table. */
		data->synct   = nsp32_sync_table_20M;
2760
		data->syncnum = ARRAY_SIZE(nsp32_sync_table_20M);
2761 2762 2763 2764
		break;
	case PCICLK:
		/* If data->clock is PCICLK, then select pci sync table. */
		data->synct   = nsp32_sync_table_pci;
2765
		data->syncnum = ARRAY_SIZE(nsp32_sync_table_pci);
2766 2767 2768 2769 2770 2771 2772
		break;
	default:
		nsp32_msg(KERN_WARNING,
			  "Invalid clock div is selected, set CLOCK_4.");
		/* Use default value CLOCK_4 */
		data->clock   = CLOCK_4;
		data->synct   = nsp32_sync_table_40M;
2773
		data->syncnum = ARRAY_SIZE(nsp32_sync_table_40M);
2774
	}
2775 2776

	/*
2777
	 * setup nsp32_lunt
2778 2779
	 */

2780 2781 2782 2783 2784 2785 2786
	/*
	 * setup DMA 
	 */
	if (pci_set_dma_mask(PCIDEV, 0xffffffffUL) != 0) {
		nsp32_msg (KERN_ERR, "failed to set PCI DMA mask");
		goto scsi_unregister;
	}
2787

2788 2789 2790 2791 2792 2793 2794 2795
	/*
	 * allocate autoparam DMA resource.
	 */
	data->autoparam = pci_alloc_consistent(PCIDEV, sizeof(nsp32_autoparam), &(data->auto_paddr));
	if (data->autoparam == NULL) {
		nsp32_msg(KERN_ERR, "failed to allocate DMA memory");
		goto scsi_unregister;
	}
2796

2797 2798 2799 2800 2801 2802 2803 2804 2805
	/*
	 * allocate scatter-gather DMA resource.
	 */
	data->sg_list = pci_alloc_consistent(PCIDEV, NSP32_SG_TABLE_SIZE,
					     &(data->sg_paddr));
	if (data->sg_list == NULL) {
		nsp32_msg(KERN_ERR, "failed to allocate DMA memory");
		goto free_autoparam;
	}
2806

2807 2808 2809
	for (i = 0; i < ARRAY_SIZE(data->lunt); i++) {
		for (j = 0; j < ARRAY_SIZE(data->lunt[0]); j++) {
			int offset = i * ARRAY_SIZE(data->lunt[0]) + j;
2810
			nsp32_lunt tmp = {
2811 2812 2813 2814 2815 2816 2817
				.SCpnt       = NULL,
				.save_datp   = 0,
				.msgin03     = FALSE,
				.sg_num      = 0,
				.cur_entry   = 0,
				.sglun       = &(data->sg_list[offset]),
				.sglun_paddr = data->sg_paddr + (offset * sizeof(nsp32_sglun)),
2818
			};
2819

2820 2821 2822
			data->lunt[i][j] = tmp;
		}
	}
2823

2824 2825 2826
	/*
	 * setup target
	 */
2827
	for (i = 0; i < ARRAY_SIZE(data->target); i++) {
2828
		nsp32_target *target = &(data->target[i]);
2829

2830 2831 2832 2833
		target->limit_entry  = 0;
		target->sync_flag    = 0;
		nsp32_set_async(data, target);
	}
2834 2835

	/*
2836 2837 2838 2839 2840 2841
	 * EEPROM check
	 */
	ret = nsp32_getprom_param(data);
	if (ret == FALSE) {
		data->resettime = 3;	/* default 3 */
	}
2842

2843 2844 2845 2846
	/*
	 * setup HBA
	 */
	nsp32hw_init(data);
2847

2848 2849 2850
	snprintf(data->info_str, sizeof(data->info_str),
		 "NinjaSCSI-32Bi/UDE: irq %d, io 0x%lx+0x%x",
		 host->irq, host->io_port, host->n_io_port);
2851

2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870
	/*
	 * SCSI bus reset
	 *
	 * Note: It's important to reset SCSI bus in initialization phase.
	 *     NinjaSCSI-32Bi/UDE HBA EEPROM seems to exchange SDTR when
	 *     system is coming up, so SCSI devices connected to HBA is set as
	 *     un-asynchronous mode.  It brings the merit that this HBA is
	 *     ready to start synchronous transfer without any preparation,
	 *     but we are difficult to control transfer speed.  In addition,
	 *     it prevents device transfer speed from effecting EEPROM start-up
	 *     SDTR.  NinjaSCSI-32Bi/UDE has the feature if EEPROM is set as
	 *     Auto Mode, then FAST-10M is selected when SCSI devices are
	 *     connected same or more than 4 devices.  It should be avoided
	 *     depending on this specification. Thus, resetting the SCSI bus
	 *     restores all connected SCSI devices to asynchronous mode, then
	 *     this driver set SDTR safely later, and we can control all SCSI
	 *     device transfer mode.
	 */
	nsp32_do_bus_reset(data);
2871

2872 2873 2874 2875 2876 2877 2878
	ret = request_irq(host->irq, do_nsp32_isr,
			  SA_SHIRQ | SA_SAMPLE_RANDOM, "nsp32", data);
	if (ret < 0) {
		nsp32_msg(KERN_ERR, "Unable to allocate IRQ for NinjaSCSI32 "
			  "SCSI PCI controller. Interrupt: %d", host->irq);
		goto free_sg_list;
	}
2879

2880 2881 2882 2883 2884 2885 2886 2887 2888 2889
        /*
         * PCI IO register
         */
	res = request_region(host->io_port, host->n_io_port, "nsp32");
	if (res == NULL) {
		nsp32_msg(KERN_ERR, 
			  "I/O region 0x%lx+0x%lx is already used",
			  data->BaseAddress, data->NumAddress);
		goto free_irq;
        }
2890

2891 2892 2893 2894 2895 2896
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
	scsi_add_host (host, &PCIDEV->dev);
	scsi_scan_host(host);
#endif
	pci_set_drvdata(PCIDEV, host);
	return DETECT_OK;
2897

2898 2899
 free_irq:
	free_irq(host->irq, data);
2900

2901 2902 2903
 free_sg_list:
	pci_free_consistent(PCIDEV, NSP32_SG_TABLE_SIZE,
			    data->sg_list, data->sg_paddr);
2904

2905 2906 2907
 free_autoparam:
	pci_free_consistent(PCIDEV, sizeof(nsp32_autoparam),
			    data->autoparam, data->auto_paddr);
2908
	
2909 2910
 scsi_unregister:
	scsi_host_put(host);
2911

2912 2913
 err:
	return DETECT_NG;
2914
}
2915 2916 2917
#undef DETECT_OK
#undef DETECT_NG
#undef PCIDEV
2918

2919
static int nsp32_release(struct Scsi_Host *host)
2920
{
2921
	nsp32_hw_data *data = (nsp32_hw_data *)host->hostdata;
2922

2923 2924 2925
	if (data->autoparam) {
		pci_free_consistent(data->Pci, sizeof(nsp32_autoparam),
				    data->autoparam, data->auto_paddr);
2926 2927
	}

2928 2929 2930
	if (data->sg_list) {
		pci_free_consistent(data->Pci, NSP32_SG_TABLE_SIZE,
				    data->sg_list, data->sg_paddr);
2931 2932
	}

2933 2934
	if (host->irq) {
		free_irq(host->irq, data);
2935 2936
	}

2937 2938 2939
	if (host->io_port && host->n_io_port) {
		release_region(host->io_port, host->n_io_port);
	}
2940

2941 2942 2943
	if (data->MmioAddress != 0) {
		iounmap((void *)(data->MmioAddress));
	}
2944

2945
	return 0;
2946 2947
}

2948 2949 2950
static const char *nsp32_info(struct Scsi_Host *shpnt)
{
	nsp32_hw_data *data = (nsp32_hw_data *)shpnt->hostdata;
2951

2952
	return data->info_str;
2953 2954 2955
}


2956 2957
/****************************************************************************
 * error handler
2958
 */
2959
static int nsp32_eh_abort(Scsi_Cmnd *SCpnt)
2960
{
2961 2962
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   base = SCpnt->device->host->io_port;
2963

2964
	nsp32_msg(KERN_WARNING, "abort");
2965

2966 2967 2968 2969
	if (data->cur_lunt->SCpnt == NULL) {
		nsp32_dbg(NSP32_DEBUG_BUSRESET, "abort failed");
		return FAILED;
	}
2970

2971 2972 2973 2974 2975
	if (data->cur_target->sync_flag & (SDTR_INITIATOR | SDTR_TARGET)) {
		/* reset SDTR negotiation */
		data->cur_target->sync_flag = 0;
		nsp32_set_async(data, data->cur_target);
	}
2976

2977 2978
	nsp32_write2(base, TRANSFER_CONTROL, 0);
	nsp32_write2(base, BM_CNT,           0);
2979

2980 2981 2982 2983 2984 2985 2986 2987
	SCpnt->result = DID_ABORT << 16;
	nsp32_scsi_done(SCpnt);

	nsp32_dbg(NSP32_DEBUG_BUSRESET, "abort success");
	return SUCCESS;
}

static int nsp32_eh_bus_reset(Scsi_Cmnd *SCpnt)
2988
{
2989 2990
	nsp32_hw_data *data = (nsp32_hw_data *)SCpnt->device->host->hostdata;
	unsigned int   base = SCpnt->device->host->io_port;
2991

2992 2993
	nsp32_msg(KERN_INFO, "Bus Reset");	
	nsp32_dbg(NSP32_DEBUG_BUSRESET, "SCpnt=0x%x", SCpnt);
2994

2995 2996 2997
	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
	nsp32_do_bus_reset(data);
	nsp32_write2(base, IRQ_CONTROL, 0);
2998

2999
	return SUCCESS;	/* SCSI bus reset is succeeded at any time. */
3000 3001
}

3002
static void nsp32_do_bus_reset(nsp32_hw_data *data)
3003
{
3004 3005 3006
	unsigned int   base = data->BaseAddress;
	unsigned short intrdat;
	int i;
3007

3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
	nsp32_dbg(NSP32_DEBUG_BUSRESET, "in");

	/*
	 * stop all transfer
	 * clear TRANSFERCONTROL_BM_START
	 * clear counter
	 */
	nsp32_write2(base, TRANSFER_CONTROL, 0);
	nsp32_write4(base, BM_CNT,           0);
	nsp32_write4(base, CLR_COUNTER,      CLRCOUNTER_ALLMASK);

	/*
	 * fall back to asynchronous transfer mode
	 * initialize SDTR negotiation flag
	 */
3023
	for (i = 0; i < ARRAY_SIZE(data->target); i++) {
3024 3025 3026 3027
		nsp32_target *target = &data->target[i];

		target->sync_flag = 0;
		nsp32_set_async(data, target);
3028 3029
	}

3030 3031 3032 3033 3034 3035 3036 3037 3038 3039
	/*
	 * reset SCSI bus
	 */
	nsp32_write1(base, SCSI_BUS_CONTROL, BUSCTL_RST);
	udelay(RESET_HOLD_TIME);
	nsp32_write1(base, SCSI_BUS_CONTROL, 0);
	for(i = 0; i < 5; i++) {
		intrdat = nsp32_read2(base, IRQ_STATUS); /* dummy read */
		nsp32_dbg(NSP32_DEBUG_BUSRESET, "irq:1: 0x%x", intrdat);
        }
3040

3041
	data->CurrentSC = NULL;
3042 3043
}

3044
static int nsp32_eh_host_reset(Scsi_Cmnd *SCpnt)
3045
{
3046 3047 3048
	struct Scsi_Host *host = SCpnt->device->host;
	unsigned int      base = SCpnt->device->host->io_port;
	nsp32_hw_data    *data = (nsp32_hw_data *)host->hostdata;
3049

3050 3051
	nsp32_msg(KERN_INFO, "Host Reset");	
	nsp32_dbg(NSP32_DEBUG_BUSRESET, "SCpnt=0x%x", SCpnt);
3052

3053 3054 3055 3056
	nsp32hw_init(data);
	nsp32_write2(base, IRQ_CONTROL, IRQ_CONTROL_ALL_IRQ_MASK);
	nsp32_do_bus_reset(data);
	nsp32_write2(base, IRQ_CONTROL, 0);
3057

3058
	return SUCCESS;	/* Host reset is succeeded at any time. */
3059 3060 3061
}


3062 3063 3064
/**************************************************************************
 * EEPROM handler
 */
3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080

/*
 * getting EEPROM parameter
 */
static int nsp32_getprom_param(nsp32_hw_data *data)
{
	int vendor = data->pci_devid->vendor;
	int device = data->pci_devid->device;
	int ret, val, i;

	/*
	 * EEPROM checking.
	 */
	ret = nsp32_prom_read(data, 0x7e);
	if (ret != 0x55) {
		nsp32_msg(KERN_INFO, "No EEPROM detected: 0x%x", ret);
3081
		return FALSE;
3082 3083 3084 3085
	}
	ret = nsp32_prom_read(data, 0x7f);
	if (ret != 0xaa) {
		nsp32_msg(KERN_INFO, "Invalid number: 0x%x", ret);
3086
		return FALSE;
3087 3088 3089 3090 3091 3092 3093
	}

	/*
	 * check EEPROM type
	 */
	if (vendor == PCI_VENDOR_ID_WORKBIT &&
	    device == PCI_DEVICE_ID_WORKBIT_STANDARD) {
3094
		ret = nsp32_getprom_c16(data);
3095 3096
	} else if (vendor == PCI_VENDOR_ID_WORKBIT &&
		   device == PCI_DEVICE_ID_NINJASCSI_32BIB_LOGITEC) {
3097
		ret = nsp32_getprom_at24(data);
3098 3099
	} else if (vendor == PCI_VENDOR_ID_WORKBIT &&
		   device == PCI_DEVICE_ID_NINJASCSI_32UDE_MELCO ) {
3100
		ret = nsp32_getprom_at24(data);
3101 3102 3103 3104 3105 3106
	} else {
		nsp32_msg(KERN_WARNING, "Unknown EEPROM");
		ret = FALSE;
	}

	/* for debug : SPROM data full checking */
3107
	for (i = 0; i <= 0x1f; i++) {
3108 3109 3110 3111 3112
		val = nsp32_prom_read(data, i);
		nsp32_dbg(NSP32_DEBUG_EEPROM,
			  "rom address 0x%x : 0x%x", i, val);
	}

3113
	return ret;
3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
}


/*
 * AT24C01A (Logitec: LHA-600S), AT24C02 (Melco Buffalo: IFC-USLP) data map:
 *
 *   ROMADDR
 *   0x00 - 0x06 :  Device Synchronous Transfer Period (SCSI ID 0 - 6) 
 *			Value 0x0: ASYNC, 0x0c: Ultra-20M, 0x19: Fast-10M
 *   0x07        :  HBA Synchronous Transfer Period
 *			Value 0: AutoSync, 1: Manual Setting
 *   0x08 - 0x0f :  Not Used? (0x0)
 *   0x10        :  Bus Termination
 * 			Value 0: Auto[ON], 1: ON, 2: OFF
 *   0x11        :  Not Used? (0)
 *   0x12        :  Bus Reset Delay Time (0x03)
 *   0x13        :  Bootable CD Support
 *			Value 0: Disable, 1: Enable
 *   0x14        :  Device Scan
 *			Bit   7  6  5  4  3  2  1  0
 *			      |  <----------------->
 * 			      |    SCSI ID: Value 0: Skip, 1: YES
 *			      |->  Value 0: ALL scan,  Value 1: Manual
 *   0x15 - 0x1b :  Not Used? (0)
 *   0x1c        :  Constant? (0x01) (clock div?)
 *   0x1d - 0x7c :  Not Used (0xff)
 *   0x7d	 :  Not Used? (0xff)
3141 3142
 *   0x7e        :  Constant (0x55), Validity signature
 *   0x7f        :  Constant (0xaa), Validity signature
3143
 */
3144
static int nsp32_getprom_at24(nsp32_hw_data *data)
3145
{
3146 3147 3148 3149
	int           ret, i;
	int           auto_sync;
	nsp32_target *target;
	int           entry;
3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180

	/*
	 * Reset time which is designated by EEPROM.
	 *
	 * TODO: Not used yet.
	 */
	data->resettime = nsp32_prom_read(data, 0x12);

	/*
	 * HBA Synchronous Transfer Period
	 *
	 * Note: auto_sync = 0: auto, 1: manual.  Ninja SCSI HBA spec says
	 *	that if auto_sync is 0 (auto), and connected SCSI devices are
	 *	same or lower than 3, then transfer speed is set as ULTRA-20M.
	 *	On the contrary if connected SCSI devices are same or higher
	 *	than 4, then transfer speed is set as FAST-10M.
	 *
	 *	I break this rule. The number of connected SCSI devices are
	 *	only ignored. If auto_sync is 0 (auto), then transfer speed is
	 *	forced as ULTRA-20M.
	 */
	ret = nsp32_prom_read(data, 0x07);
	switch (ret) {
	case 0:
		auto_sync = TRUE;
		break;
	case 1:
		auto_sync = FALSE;
		break;
	default:
		nsp32_msg(KERN_WARNING,
3181
			  "Unsupported Auto Sync mode. Fall back to manual mode.");
3182 3183 3184 3185 3186 3187 3188 3189 3190 3191
		auto_sync = TRUE;
	}

	if (trans_mode == ULTRA20M_MODE) {
		auto_sync = TRUE;
	}

	/*
	 * each device Synchronous Transfer Period
	 */
3192
	for (i = 0; i < NSP32_HOST_SCSIID; i++) {
3193 3194 3195 3196
		target = &data->target[i];
		if (auto_sync == TRUE) {
			target->limit_entry = 0;   /* set as ULTRA20M */
		} else {
3197
			ret   = nsp32_prom_read(data, i);
3198 3199 3200 3201 3202 3203 3204 3205 3206
			entry = nsp32_search_period_entry(data, target, ret);
			if (entry < 0) {
				/* search failed... set maximum speed */
				entry = 0;
			}
			target->limit_entry = entry;
		}
	}

3207
	return TRUE;
3208 3209 3210 3211
}


/*
3212
 * C16 110 (I-O Data: SC-NBD) data map:
3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227
 *
 *   ROMADDR
 *   0x00 - 0x06 :  Device Synchronous Transfer Period (SCSI ID 0 - 6) 
 *			Value 0x0: 20MB/S, 0x1: 10MB/S, 0x2: 5MB/S, 0x3: ASYNC
 *   0x07        :  0 (HBA Synchronous Transfer Period: Auto Sync)
 *   0x08 - 0x0f :  Not Used? (0x0)
 *   0x10        :  Transfer Mode
 *			Value 0: PIO, 1: Busmater
 *   0x11        :  Bus Reset Delay Time (0x00-0x20)
 *   0x12        :  Bus Termination
 * 			Value 0: Disable, 1: Enable
 *   0x13 - 0x19 :  Disconnection
 *			Value 0: Disable, 1: Enable
 *   0x1a - 0x7c :  Not Used? (0)
 *   0x7d	 :  Not Used? (0xf8)
3228 3229
 *   0x7e        :  Constant (0x55), Validity signature
 *   0x7f        :  Constant (0xaa), Validity signature
3230
 */
3231
static int nsp32_getprom_c16(nsp32_hw_data *data)
3232
{
3233 3234 3235
	int           ret, i;
	nsp32_target *target;
	int           entry, val;
3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246

	/*
	 * Reset time which is designated by EEPROM.
	 *
	 * TODO: Not used yet.
	 */
	data->resettime = nsp32_prom_read(data, 0x11);

	/*
	 * each device Synchronous Transfer Period
	 */
3247
	for (i = 0; i < NSP32_HOST_SCSIID; i++) {
3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260
		target = &data->target[i];
		ret = nsp32_prom_read(data, i);
		switch (ret) {
		case 0:		/* 20MB/s */
			val = 0x0c;
			break;
		case 1:		/* 10MB/s */
			val = 0x19;
			break;
		case 2:		/* 5MB/s */
			val = 0x32;
			break;
		case 3:		/* ASYNC */
3261
			val = 0x00;
3262 3263 3264
			break;
		default:	/* default 20MB/s */
			val = 0x0c;
3265
			break;
3266 3267 3268 3269 3270 3271 3272 3273 3274
		}
		entry = nsp32_search_period_entry(data, target, val);
		if (entry < 0 || trans_mode == ULTRA20M_MODE) {
			/* search failed... set maximum speed */
			entry = 0;
		}
		target->limit_entry = entry;
	}

3275
	return TRUE;
3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289
}


/*
 * Atmel AT24C01A (drived in 5V) serial EEPROM routines
 */
static int nsp32_prom_read(nsp32_hw_data *data, int romaddr)
{
	int i, val;

	/* start condition */
	nsp32_prom_start(data);

	/* device address */
3290 3291 3292 3293 3294 3295 3296
	nsp32_prom_write_bit(data, 1);	/* 1 */
	nsp32_prom_write_bit(data, 0);	/* 0 */
	nsp32_prom_write_bit(data, 1);	/* 1 */
	nsp32_prom_write_bit(data, 0);	/* 0 */
	nsp32_prom_write_bit(data, 0);	/* A2: 0 (GND) */
	nsp32_prom_write_bit(data, 0);	/* A1: 0 (GND) */
	nsp32_prom_write_bit(data, 0);	/* A0: 0 (GND) */
3297 3298

	/* R/W: W for dummy write */
3299
	nsp32_prom_write_bit(data, 0);
3300 3301

	/* ack */
3302
	nsp32_prom_write_bit(data, 0);
3303 3304

	/* word address */
3305 3306
	for (i = 7; i >= 0; i--) {
		nsp32_prom_write_bit(data, ((romaddr >> i) & 1));
3307 3308 3309
	}

	/* ack */
3310
	nsp32_prom_write_bit(data, 0);
3311 3312 3313 3314 3315

	/* start condition */
	nsp32_prom_start(data);

	/* device address */
3316 3317 3318 3319 3320 3321 3322
	nsp32_prom_write_bit(data, 1);	/* 1 */
	nsp32_prom_write_bit(data, 0);	/* 0 */
	nsp32_prom_write_bit(data, 1);	/* 1 */
	nsp32_prom_write_bit(data, 0);	/* 0 */
	nsp32_prom_write_bit(data, 0);	/* A2: 0 (GND) */
	nsp32_prom_write_bit(data, 0);	/* A1: 0 (GND) */
	nsp32_prom_write_bit(data, 0);	/* A0: 0 (GND) */
3323 3324

	/* R/W: R */
3325
	nsp32_prom_write_bit(data, 1);
3326 3327

	/* ack */
3328
	nsp32_prom_write_bit(data, 0);
3329 3330 3331

	/* data... */
	val = 0;
3332 3333
	for (i = 7; i >= 0; i--) {
		val += (nsp32_prom_read_bit(data) << i);
3334 3335 3336
	}
	
	/* no ack */
3337
	nsp32_prom_write_bit(data, 1);
3338 3339 3340 3341

	/* stop condition */
	nsp32_prom_stop(data);

3342
	return val;
3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365
}

static void nsp32_prom_start (nsp32_hw_data *data)
{
	/* start condition */
	nsp32_prom_set(data, SCL, 1);
	nsp32_prom_set(data, SDA, 1);
	nsp32_prom_set(data, ENA, 1);	/* output mode */
	nsp32_prom_set(data, SDA, 0);	/* keeping SCL=1 and transiting
					 * SDA 1->0 is start condition */
	nsp32_prom_set(data, SCL, 0);
}

static void nsp32_prom_stop (nsp32_hw_data *data)
{
	/* stop condition */
	nsp32_prom_set(data, SCL, 1);
	nsp32_prom_set(data, SDA, 0);
	nsp32_prom_set(data, ENA, 1);	/* output mode */
	nsp32_prom_set(data, SDA, 1);
	nsp32_prom_set(data, SCL, 0);
}

3366
static void nsp32_prom_write_bit(nsp32_hw_data *data, int val)
3367 3368 3369
{
	/* write */
	nsp32_prom_set(data, SDA, val);
3370 3371
	nsp32_prom_set(data, SCL, 1  );
	nsp32_prom_set(data, SCL, 0  );
3372 3373
}

3374
static int nsp32_prom_read_bit(nsp32_hw_data *data)
3375 3376 3377 3378 3379 3380
{
	int val;

	/* read */
	nsp32_prom_set(data, ENA, 0);	/* input mode */
	nsp32_prom_set(data, SCL, 1);
3381

3382
	val = nsp32_prom_get(data, SDA);
3383

3384 3385
	nsp32_prom_set(data, SCL, 0);
	nsp32_prom_set(data, ENA, 1);	/* output mode */
3386 3387

	return val;
3388 3389 3390 3391 3392
}

static inline void nsp32_prom_set(nsp32_hw_data *data, int bit, int val)
{
	int base = data->BaseAddress;
3393
	int tmp;
3394

3395 3396 3397 3398 3399 3400
	tmp = nsp32_index_read1(base, SERIAL_ROM_CTL);

	if (val == 0) {
		tmp &= ~bit;
	} else {
		tmp |=  bit;
3401 3402
	}

3403 3404
	nsp32_index_write1(base, SERIAL_ROM_CTL, tmp);

3405 3406 3407 3408 3409 3410
	udelay(10);
}

static inline int nsp32_prom_get(nsp32_hw_data *data, int bit)
{
	int base = data->BaseAddress;
3411
	int tmp, ret;
3412

3413 3414 3415 3416 3417 3418 3419 3420 3421
	if (bit != SDA) {
		nsp32_msg(KERN_ERR, "return value is not appropriate");
		return 0;
	}


	tmp = nsp32_index_read1(base, SERIAL_ROM_CTL) & bit;

	if (tmp == 0) {
3422
		ret = 0;
3423
	} else {
3424 3425 3426 3427 3428
		ret = 1;
	}

	udelay(10);

3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536
	return ret;
}


/**************************************************************************
 * Power Management
 */
#ifdef CONFIG_PM

/* Device suspended */
static int nsp32_suspend(struct pci_dev *pdev, u32 state)
{
	struct Scsi_Host *host = pci_get_drvdata(pdev);
	nsp32_hw_data    *data = (nsp32_hw_data *)host->hostdata;

	nsp32_msg(KERN_INFO, "pci-suspend: pdev=0x%p, state=%ld, slot=%s, host=0x%p", pdev, state, pci_name(pdev), host);

	pci_save_state     (pdev, data->PciState);
	pci_disable_device (pdev);
	pci_set_power_state(pdev, state);

	return 0;
}

/* Device woken up */
static int nsp32_resume(struct pci_dev *pdev)
{
	struct Scsi_Host *host = pci_get_drvdata(pdev);
	nsp32_hw_data    *data = (nsp32_hw_data *)host->hostdata;
	unsigned short    reg;

	nsp32_msg(KERN_INFO, "pci-resume: pdev=0x%p, slot=%s, host=0x%p", pdev, pci_name(pdev), host);

	pci_set_power_state(pdev, 0);
	pci_enable_wake    (pdev, 0, 0);
	pci_restore_state  (pdev, data->PciState);

	reg = nsp32_read2(data->BaseAddress, INDEX_REG);

	nsp32_msg(KERN_INFO, "io=0x%x reg=0x%x", data->BaseAddress, reg);

	if (reg == 0xffff) {
		nsp32_msg(KERN_INFO, "missing device. abort resume.");
		return 0;
	}

	nsp32hw_init      (data);
	nsp32_do_bus_reset(data);

	nsp32_msg(KERN_INFO, "resume success");

	return 0;
}

/* Enable wake event */
static int nsp32_enable_wake(struct pci_dev *pdev, u32 state, int enable)
{
	struct Scsi_Host *host = pci_get_drvdata(pdev);

	nsp32_msg(KERN_INFO, "pci-enable_wake: stub, pdev=0x%p, enable=%d, slot=%s, host=0x%p", pdev, enable, pci_name(pdev), host);

	return 0;
}
#endif

/************************************************************************
 * PCI/Cardbus probe/remove routine
 */
static int __devinit nsp32_probe(struct pci_dev *pdev, const struct pci_device_id *id)
{
	int ret;
	nsp32_hw_data *data = &nsp32_data_base;

	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");

        ret = pci_enable_device(pdev);
	if (ret) {
		nsp32_msg(KERN_ERR, "failed to enable pci device");
		return ret;
	}

	data->Pci         = pdev;
	data->pci_devid   = id;
	data->IrqNumber   = pdev->irq;
	data->BaseAddress = pci_resource_start(pdev, 0);
	data->NumAddress  = pci_resource_len  (pdev, 0);
	data->MmioAddress = 
		(unsigned long)ioremap_nocache(pci_resource_start(pdev, 1),
					       pci_resource_len  (pdev, 1));
	data->MmioLength  = pci_resource_len  (pdev, 1);

	pci_set_master(pdev);

#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
	ret = nsp32_detect(pdev);
#else
	ret = scsi_register_host(&nsp32_template);
#endif

	nsp32_msg(KERN_INFO, "irq: %i mmio: 0x%lx+0x%lx slot: %s model: %s",
		  pdev->irq,
		  data->MmioAddress, data->MmioLength,
		  pci_name(pdev),
		  nsp32_model[id->driver_data]);

	nsp32_dbg(NSP32_DEBUG_REGISTER, "exit %d", ret);

	return ret;
3537 3538
}

3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587
static void __devexit nsp32_remove(struct pci_dev *pdev)
{
#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
	struct Scsi_Host *host = pci_get_drvdata(pdev);
#endif

	nsp32_dbg(NSP32_DEBUG_REGISTER, "enter");

#if (LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
        scsi_remove_host(host);

	nsp32_release(host);

	scsi_host_put(host);
#else
	scsi_unregister_host(&nsp32_template);	
#endif
}



static struct pci_driver nsp32_driver = {
	.name		= "nsp32",
	.id_table	= nsp32_pci_table,
	.probe		= nsp32_probe,
	.remove		= __devexit_p(nsp32_remove),
#ifdef CONFIG_PM
	.suspend	= nsp32_suspend, 
	.resume		= nsp32_resume, 
	.enable_wake    = nsp32_enable_wake,
#endif
};

/*********************************************************************
 * Moule entry point
 */
static int __init init_nsp32(void) {
	nsp32_msg(KERN_INFO, "loading...");
	return pci_module_init(&nsp32_driver);
}

static void __exit exit_nsp32(void) {
	nsp32_msg(KERN_INFO, "unloading...");
	pci_unregister_driver(&nsp32_driver);
}

module_init(init_nsp32);
module_exit(exit_nsp32);

3588
/* end */