Linux Audio

Check our new training course

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