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