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