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