Linux Audio

Check our new training course

Linux BSP upgrade and security maintenance

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