patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / drivers / scsi / ncr53c8xx.c
1 /******************************************************************************
2 **  Device driver for the PCI-SCSI NCR538XX controller family.
3 **
4 **  Copyright (C) 1994  Wolfgang Stanglmeier
5 **
6 **  This program is free software; you can redistribute it and/or modify
7 **  it under the terms of the GNU General Public License as published by
8 **  the Free Software Foundation; either version 2 of the License, or
9 **  (at your option) any later version.
10 **
11 **  This program is distributed in the hope that it will be useful,
12 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
13 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 **  GNU General Public License for more details.
15 **
16 **  You should have received a copy of the GNU General Public License
17 **  along with this program; if not, write to the Free Software
18 **  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19 **
20 **-----------------------------------------------------------------------------
21 **
22 **  This driver has been ported to Linux from the FreeBSD NCR53C8XX driver
23 **  and is currently maintained by
24 **
25 **          Gerard Roudier              <groudier@free.fr>
26 **
27 **  Being given that this driver originates from the FreeBSD version, and
28 **  in order to keep synergy on both, any suggested enhancements and corrections
29 **  received on Linux are automatically a potential candidate for the FreeBSD 
30 **  version.
31 **
32 **  The original driver has been written for 386bsd and FreeBSD by
33 **          Wolfgang Stanglmeier        <wolf@cologne.de>
34 **          Stefan Esser                <se@mi.Uni-Koeln.de>
35 **
36 **  And has been ported to NetBSD by
37 **          Charles M. Hannum           <mycroft@gnu.ai.mit.edu>
38 **
39 **-----------------------------------------------------------------------------
40 **
41 **                     Brief history
42 **
43 **  December 10 1995 by Gerard Roudier:
44 **     Initial port to Linux.
45 **
46 **  June 23 1996 by Gerard Roudier:
47 **     Support for 64 bits architectures (Alpha).
48 **
49 **  November 30 1996 by Gerard Roudier:
50 **     Support for Fast-20 scsi.
51 **     Support for large DMA fifo and 128 dwords bursting.
52 **
53 **  February 27 1997 by Gerard Roudier:
54 **     Support for Fast-40 scsi.
55 **     Support for on-Board RAM.
56 **
57 **  May 3 1997 by Gerard Roudier:
58 **     Full support for scsi scripts instructions pre-fetching.
59 **
60 **  May 19 1997 by Richard Waltham <dormouse@farsrobt.demon.co.uk>:
61 **     Support for NvRAM detection and reading.
62 **
63 **  August 18 1997 by Cort <cort@cs.nmt.edu>:
64 **     Support for Power/PC (Big Endian).
65 **
66 **  June 20 1998 by Gerard Roudier
67 **     Support for up to 64 tags per lun.
68 **     O(1) everywhere (C and SCRIPTS) for normal cases.
69 **     Low PCI traffic for command handling when on-chip RAM is present.
70 **     Aggressive SCSI SCRIPTS optimizations.
71 **
72 *******************************************************************************
73 */
74
75 /*
76 **      Supported SCSI-II features:
77 **          Synchronous negotiation
78 **          Wide negotiation        (depends on the NCR Chip)
79 **          Enable disconnection
80 **          Tagged command queuing
81 **          Parity checking
82 **          Etc...
83 **
84 **      Supported NCR/SYMBIOS chips:
85 **              53C720          (Wide,   Fast SCSI-2, intfly problems)
86 **              53C810          (8 bits, Fast SCSI-2, no rom BIOS) 
87 **              53C815          (8 bits, Fast SCSI-2, on board rom BIOS)
88 **              53C820          (Wide,   Fast SCSI-2, no rom BIOS)
89 **              53C825          (Wide,   Fast SCSI-2, on board rom BIOS)
90 **              53C860          (8 bits, Fast 20,     no rom BIOS)
91 **              53C875          (Wide,   Fast 20,     on board rom BIOS)
92 **              53C895          (Wide,   Fast 40,     on board rom BIOS)
93 **              53C895A         (Wide,   Fast 40,     on board rom BIOS)
94 **              53C896          (Wide,   Fast 40,     on board rom BIOS)
95 **              53C897          (Wide,   Fast 40,     on board rom BIOS)
96 **              53C1510D        (Wide,   Fast 40,     on board rom BIOS)
97 **
98 **      Other features:
99 **              Memory mapped IO (linux-1.3.X and above only)
100 **              Module
101 **              Shared IRQ (since linux-1.3.72)
102 */
103
104 /*
105 **      Name and version of the driver
106 */
107 #define SCSI_NCR_DRIVER_NAME    "ncr53c8xx-3.4.3b-20010512"
108
109 #define SCSI_NCR_DEBUG_FLAGS    (0)
110
111 /*==========================================================
112 **
113 **      Include files
114 **
115 **==========================================================
116 */
117
118 #include <linux/blkdev.h>
119 #include <linux/delay.h>
120 #include <linux/dma-mapping.h>
121 #include <linux/errno.h>
122 #include <linux/init.h>
123 #include <linux/interrupt.h>
124 #include <linux/ioport.h>
125 #include <linux/mm.h>
126 #include <linux/module.h>
127 #include <linux/sched.h>
128 #include <linux/signal.h>
129 #include <linux/spinlock.h>
130 #include <linux/stat.h>
131 #include <linux/string.h>
132 #include <linux/time.h>
133 #include <linux/timer.h>
134 #include <linux/types.h>
135
136 #include <asm/dma.h>
137 #include <asm/io.h>
138 #include <asm/system.h>
139
140 #include "scsi.h"
141 #include "hosts.h"
142
143 #include "ncr53c8xx.h"
144
145 /*
146 **      Donnot compile integrity checking code for Linux-2.3.0 
147 **      and above since SCSI data structures are not ready yet.
148 */
149 /* #if LINUX_VERSION_CODE < KERNEL_VERSION(2,3,0) */
150 #if 0
151 #define SCSI_NCR_INTEGRITY_CHECKING
152 #endif
153
154 #define NAME53C                 "ncr53c"
155 #define NAME53C8XX              "ncr53c8xx"
156 #define DRIVER_SMP_LOCK         ncr53c8xx_lock
157
158 #include "sym53c8xx_comm.h"
159
160 int ncr53c8xx_slave_configure(Scsi_Device *device);
161 int ncr53c8xx_bus_reset(Scsi_Cmnd *cmd);
162 int ncr53c8xx_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *));
163 const char *ncr53c8xx_info (struct Scsi_Host *host);
164
165
166 /*==========================================================
167 **
168 **      The CCB done queue uses an array of CCB virtual 
169 **      addresses. Empty entries are flagged using the bogus 
170 **      virtual address 0xffffffff.
171 **
172 **      Since PCI ensures that only aligned DWORDs are accessed 
173 **      atomically, 64 bit little-endian architecture requires 
174 **      to test the high order DWORD of the entry to determine 
175 **      if it is empty or valid.
176 **
177 **      BTW, I will make things differently as soon as I will 
178 **      have a better idea, but this is simple and should work.
179 **
180 **==========================================================
181 */
182  
183 #define SCSI_NCR_CCB_DONE_SUPPORT
184 #ifdef  SCSI_NCR_CCB_DONE_SUPPORT
185
186 #define MAX_DONE 24
187 #define CCB_DONE_EMPTY 0xffffffffUL
188
189 /* All 32 bit architectures */
190 #if BITS_PER_LONG == 32
191 #define CCB_DONE_VALID(cp)  (((u_long) cp) != CCB_DONE_EMPTY)
192
193 /* All > 32 bit (64 bit) architectures regardless endian-ness */
194 #else
195 #define CCB_DONE_VALID(cp)  \
196         ((((u_long) cp) & 0xffffffff00000000ul) &&      \
197          (((u_long) cp) & 0xfffffffful) != CCB_DONE_EMPTY)
198 #endif
199
200 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
201
202 /*==========================================================
203 **
204 **      Configuration and Debugging
205 **
206 **==========================================================
207 */
208
209 /*
210 **    SCSI address of this device.
211 **    The boot routines should have set it.
212 **    If not, use this.
213 */
214
215 #ifndef SCSI_NCR_MYADDR
216 #define SCSI_NCR_MYADDR      (7)
217 #endif
218
219 /*
220 **    The maximum number of tags per logic unit.
221 **    Used only for disk devices that support tags.
222 */
223
224 #ifndef SCSI_NCR_MAX_TAGS
225 #define SCSI_NCR_MAX_TAGS    (8)
226 #endif
227
228 /*
229 **    TAGS are actually limited to 64 tags/lun.
230 **    We need to deal with power of 2, for alignment constraints.
231 */
232 #if     SCSI_NCR_MAX_TAGS > 64
233 #define MAX_TAGS (64)
234 #else
235 #define MAX_TAGS SCSI_NCR_MAX_TAGS
236 #endif
237
238 #define NO_TAG  (255)
239
240 /*
241 **      Choose appropriate type for tag bitmap.
242 */
243 #if     MAX_TAGS > 32
244 typedef u64 tagmap_t;
245 #else
246 typedef u32 tagmap_t;
247 #endif
248
249 /*
250 **    Number of targets supported by the driver.
251 **    n permits target numbers 0..n-1.
252 **    Default is 16, meaning targets #0..#15.
253 **    #7 .. is myself.
254 */
255
256 #ifdef SCSI_NCR_MAX_TARGET
257 #define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
258 #else
259 #define MAX_TARGET  (16)
260 #endif
261
262 /*
263 **    Number of logic units supported by the driver.
264 **    n enables logic unit numbers 0..n-1.
265 **    The common SCSI devices require only
266 **    one lun, so take 1 as the default.
267 */
268
269 #ifdef SCSI_NCR_MAX_LUN
270 #define MAX_LUN    SCSI_NCR_MAX_LUN
271 #else
272 #define MAX_LUN    (1)
273 #endif
274
275 /*
276 **    Asynchronous pre-scaler (ns). Shall be 40
277 */
278  
279 #ifndef SCSI_NCR_MIN_ASYNC
280 #define SCSI_NCR_MIN_ASYNC (40)
281 #endif
282
283 /*
284 **    The maximum number of jobs scheduled for starting.
285 **    There should be one slot per target, and one slot
286 **    for each tag of each target in use.
287 **    The calculation below is actually quite silly ...
288 */
289
290 #ifdef SCSI_NCR_CAN_QUEUE
291 #define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
292 #else
293 #define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
294 #endif
295
296 /*
297 **   We limit the max number of pending IO to 250.
298 **   since we donnot want to allocate more than 1 
299 **   PAGE for 'scripth'.
300 */
301 #if     MAX_START > 250
302 #undef  MAX_START
303 #define MAX_START 250
304 #endif
305
306 /*
307 **    The maximum number of segments a transfer is split into.
308 **    We support up to 127 segments for both read and write.
309 **    The data scripts are broken into 2 sub-scripts.
310 **    80 (MAX_SCATTERL) segments are moved from a sub-script
311 **    in on-chip RAM. This makes data transfers shorter than 
312 **    80k (assuming 1k fs) as fast as possible.
313 */
314
315 #define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
316
317 #if (MAX_SCATTER > 80)
318 #define MAX_SCATTERL    80
319 #define MAX_SCATTERH    (MAX_SCATTER - MAX_SCATTERL)
320 #else
321 #define MAX_SCATTERL    (MAX_SCATTER-1)
322 #define MAX_SCATTERH    1
323 #endif
324
325 /*
326 **      other
327 */
328
329 #define NCR_SNOOP_TIMEOUT (1000000)
330
331 /*
332 **      Other definitions
333 */
334
335 #define ScsiResult(host_code, scsi_code) (((host_code) << 16) + ((scsi_code) & 0x7f))
336
337 static void ncr53c8xx_timeout(unsigned long np);
338 static int ncr53c8xx_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
339                         int length, int func);
340
341 #define initverbose (driver_setup.verbose)
342 #define bootverbose (np->verbose)
343
344 #ifdef SCSI_NCR_NVRAM_SUPPORT
345 static u_char Tekram_sync[16] __initdata =
346         {25,31,37,43, 50,62,75,125, 12,15,18,21, 6,7,9,10};
347 #endif /* SCSI_NCR_NVRAM_SUPPORT */
348
349 /*==========================================================
350 **
351 **      Command control block states.
352 **
353 **==========================================================
354 */
355
356 #define HS_IDLE         (0)
357 #define HS_BUSY         (1)
358 #define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
359 #define HS_DISCONNECT   (3)     /* Disconnected by target */
360
361 #define HS_DONEMASK     (0x80)
362 #define HS_COMPLETE     (4|HS_DONEMASK)
363 #define HS_SEL_TIMEOUT  (5|HS_DONEMASK) /* Selection timeout      */
364 #define HS_RESET        (6|HS_DONEMASK) /* SCSI reset             */
365 #define HS_ABORTED      (7|HS_DONEMASK) /* Transfer aborted       */
366 #define HS_TIMEOUT      (8|HS_DONEMASK) /* Software timeout       */
367 #define HS_FAIL         (9|HS_DONEMASK) /* SCSI or PCI bus errors */
368 #define HS_UNEXPECTED   (10|HS_DONEMASK)/* Unexpected disconnect  */
369
370 /*
371 **      Invalid host status values used by the SCRIPTS processor 
372 **      when the nexus is not fully identified.
373 **      Shall never appear in a CCB.
374 */
375
376 #define HS_INVALMASK    (0x40)
377 #define HS_SELECTING    (0|HS_INVALMASK)
378 #define HS_IN_RESELECT  (1|HS_INVALMASK)
379 #define HS_STARTING     (2|HS_INVALMASK)
380
381 /*
382 **      Flags set by the SCRIPT processor for commands 
383 **      that have been skipped.
384 */
385 #define HS_SKIPMASK     (0x20)
386
387 /*==========================================================
388 **
389 **      Software Interrupt Codes
390 **
391 **==========================================================
392 */
393
394 #define SIR_BAD_STATUS          (1)
395 #define SIR_XXXXXXXXXX          (2)
396 #define SIR_NEGO_SYNC           (3)
397 #define SIR_NEGO_WIDE           (4)
398 #define SIR_NEGO_FAILED         (5)
399 #define SIR_NEGO_PROTO          (6)
400 #define SIR_REJECT_RECEIVED     (7)
401 #define SIR_REJECT_SENT         (8)
402 #define SIR_IGN_RESIDUE         (9)
403 #define SIR_MISSING_SAVE        (10)
404 #define SIR_RESEL_NO_MSG_IN     (11)
405 #define SIR_RESEL_NO_IDENTIFY   (12)
406 #define SIR_RESEL_BAD_LUN       (13)
407 #define SIR_RESEL_BAD_TARGET    (14)
408 #define SIR_RESEL_BAD_I_T_L     (15)
409 #define SIR_RESEL_BAD_I_T_L_Q   (16)
410 #define SIR_DONE_OVERFLOW       (17)
411 #define SIR_INTFLY              (18)
412 #define SIR_MAX                 (18)
413
414 /*==========================================================
415 **
416 **      Extended error codes.
417 **      xerr_status field of struct ccb.
418 **
419 **==========================================================
420 */
421
422 #define XE_OK           (0)
423 #define XE_EXTRA_DATA   (1)     /* unexpected data phase */
424 #define XE_BAD_PHASE    (2)     /* illegal phase (4/5)   */
425
426 /*==========================================================
427 **
428 **      Negotiation status.
429 **      nego_status field       of struct ccb.
430 **
431 **==========================================================
432 */
433
434 #define NS_NOCHANGE     (0)
435 #define NS_SYNC         (1)
436 #define NS_WIDE         (2)
437 #define NS_PPR          (4)
438
439 /*==========================================================
440 **
441 **      "Special features" of targets.
442 **      quirks field            of struct tcb.
443 **      actualquirks field      of struct ccb.
444 **
445 **==========================================================
446 */
447
448 #define QUIRK_AUTOSAVE  (0x01)
449 #define QUIRK_NOMSG     (0x02)
450 #define QUIRK_NOSYNC    (0x10)
451 #define QUIRK_NOWIDE16  (0x20)
452
453 /*==========================================================
454 **
455 **      Capability bits in Inquire response byte 7.
456 **
457 **==========================================================
458 */
459
460 #define INQ7_QUEUE      (0x02)
461 #define INQ7_SYNC       (0x10)
462 #define INQ7_WIDE16     (0x20)
463
464 /*==========================================================
465 **
466 **      Misc.
467 **
468 **==========================================================
469 */
470
471 #define CCB_MAGIC       (0xf2691ad2)
472
473 /*==========================================================
474 **
475 **      Declaration of structs.
476 **
477 **==========================================================
478 */
479
480 struct tcb;
481 struct lcb;
482 struct ccb;
483 struct ncb;
484 struct script;
485
486 typedef struct ncb * ncb_p;
487 typedef struct tcb * tcb_p;
488 typedef struct lcb * lcb_p;
489 typedef struct ccb * ccb_p;
490
491 struct link {
492         ncrcmd  l_cmd;
493         ncrcmd  l_paddr;
494 };
495
496 struct  usrcmd {
497         u_long  target;
498         u_long  lun;
499         u_long  data;
500         u_long  cmd;
501 };
502
503 #define UC_SETSYNC      10
504 #define UC_SETTAGS      11
505 #define UC_SETDEBUG     12
506 #define UC_SETORDER     13
507 #define UC_SETWIDE      14
508 #define UC_SETFLAG      15
509 #define UC_SETVERBOSE   17
510
511 #define UF_TRACE        (0x01)
512 #define UF_NODISC       (0x02)
513 #define UF_NOSCAN       (0x04)
514
515 /*========================================================================
516 **
517 **      Declaration of structs:         target control block
518 **
519 **========================================================================
520 */
521 struct tcb {
522         /*----------------------------------------------------------------
523         **      During reselection the ncr jumps to this point with SFBR 
524         **      set to the encoded target number with bit 7 set.
525         **      if it's not this target, jump to the next.
526         **
527         **      JUMP  IF (SFBR != #target#), @(next tcb)
528         **----------------------------------------------------------------
529         */
530         struct link   jump_tcb;
531
532         /*----------------------------------------------------------------
533         **      Load the actual values for the sxfer and the scntl3
534         **      register (sync/wide mode).
535         **
536         **      SCR_COPY (1), @(sval field of this tcb), @(sxfer  register)
537         **      SCR_COPY (1), @(wval field of this tcb), @(scntl3 register)
538         **----------------------------------------------------------------
539         */
540         ncrcmd  getscr[6];
541
542         /*----------------------------------------------------------------
543         **      Get the IDENTIFY message and load the LUN to SFBR.
544         **
545         **      CALL, <RESEL_LUN>
546         **----------------------------------------------------------------
547         */
548         struct link   call_lun;
549
550         /*----------------------------------------------------------------
551         **      Now look for the right lun.
552         **
553         **      For i = 0 to 3
554         **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(first lcb mod. i)
555         **
556         **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
557         **      It is kind of hashcoding.
558         **----------------------------------------------------------------
559         */
560         struct link     jump_lcb[4];    /* JUMPs for reselection        */
561         lcb_p           lp[MAX_LUN];    /* The lcb's of this tcb        */
562         u_char          inq_done;       /* Target capabilities received */
563         u_char          inq_byte7;      /* Contains these capabilities  */
564
565         /*----------------------------------------------------------------
566         **      Pointer to the ccb used for negotiation.
567         **      Prevent from starting a negotiation for all queued commands 
568         **      when tagged command queuing is enabled.
569         **----------------------------------------------------------------
570         */
571         ccb_p   nego_cp;
572
573         /*----------------------------------------------------------------
574         **      statistical data
575         **----------------------------------------------------------------
576         */
577         u_long  transfers;
578         u_long  bytes;
579
580         /*----------------------------------------------------------------
581         **      negotiation of wide and synch transfer and device quirks.
582         **----------------------------------------------------------------
583         */
584 #ifdef SCSI_NCR_BIG_ENDIAN
585 /*0*/   u_short period;
586 /*2*/   u_char  sval;
587 /*3*/   u_char  minsync;
588 /*0*/   u_char  wval;
589 /*1*/   u_char  widedone;
590 /*2*/   u_char  quirks;
591 /*3*/   u_char  maxoffs;
592 #else
593 /*0*/   u_char  minsync;
594 /*1*/   u_char  sval;
595 /*2*/   u_short period;
596 /*0*/   u_char  maxoffs;
597 /*1*/   u_char  quirks;
598 /*2*/   u_char  widedone;
599 /*3*/   u_char  wval;
600 #endif
601
602 #ifdef SCSI_NCR_INTEGRITY_CHECKING
603         u_char  ic_min_sync;
604         u_char  ic_max_width;
605         u_char  ic_maximums_set;
606         u_char  ic_done;
607 #endif
608
609         /*----------------------------------------------------------------
610         **      User settable limits and options.
611         **      These limits are read from the NVRAM if present.
612         **----------------------------------------------------------------
613         */
614         u_char  usrsync;
615         u_char  usrwide;
616         u_char  usrtags;
617         u_char  usrflag;
618 };
619
620 /*========================================================================
621 **
622 **      Declaration of structs:         lun control block
623 **
624 **========================================================================
625 */
626 struct lcb {
627         /*----------------------------------------------------------------
628         **      During reselection the ncr jumps to this point
629         **      with SFBR set to the "Identify" message.
630         **      if it's not this lun, jump to the next.
631         **
632         **      JUMP  IF (SFBR != #lun#), @(next lcb of this target)
633         **
634         **      It is this lun. Load TEMP with the nexus jumps table 
635         **      address and jump to RESEL_TAG (or RESEL_NOTAG).
636         **
637         **              SCR_COPY (4), p_jump_ccb, TEMP,
638         **              SCR_JUMP, <RESEL_TAG>
639         **----------------------------------------------------------------
640         */
641         struct link     jump_lcb;
642         ncrcmd          load_jump_ccb[3];
643         struct link     jump_tag;
644         ncrcmd          p_jump_ccb;     /* Jump table bus address       */
645
646         /*----------------------------------------------------------------
647         **      Jump table used by the script processor to directly jump 
648         **      to the CCB corresponding to the reselected nexus.
649         **      Address is allocated on 256 bytes boundary in order to 
650         **      allow 8 bit calculation of the tag jump entry for up to 
651         **      64 possible tags.
652         **----------------------------------------------------------------
653         */
654         u32             jump_ccb_0;     /* Default table if no tags     */
655         u32             *jump_ccb;      /* Virtual address              */
656
657         /*----------------------------------------------------------------
658         **      CCB queue management.
659         **----------------------------------------------------------------
660         */
661         XPT_QUEHEAD     free_ccbq;      /* Queue of available CCBs      */
662         XPT_QUEHEAD     busy_ccbq;      /* Queue of busy CCBs           */
663         XPT_QUEHEAD     wait_ccbq;      /* Queue of waiting for IO CCBs */
664         XPT_QUEHEAD     skip_ccbq;      /* Queue of skipped CCBs        */
665         u_char          actccbs;        /* Number of allocated CCBs     */
666         u_char          busyccbs;       /* CCBs busy for this lun       */
667         u_char          queuedccbs;     /* CCBs queued to the controller*/
668         u_char          queuedepth;     /* Queue depth for this lun     */
669         u_char          scdev_depth;    /* SCSI device queue depth      */
670         u_char          maxnxs;         /* Max possible nexuses         */
671
672         /*----------------------------------------------------------------
673         **      Control of tagged command queuing.
674         **      Tags allocation is performed using a circular buffer.
675         **      This avoids using a loop for tag allocation.
676         **----------------------------------------------------------------
677         */
678         u_char          ia_tag;         /* Allocation index             */
679         u_char          if_tag;         /* Freeing index                */
680         u_char cb_tags[MAX_TAGS];       /* Circular tags buffer */
681         u_char          usetags;        /* Command queuing is active    */
682         u_char          maxtags;        /* Max nr of tags asked by user */
683         u_char          numtags;        /* Current number of tags       */
684         u_char          inq_byte7;      /* Store unit CmdQ capabitility */
685
686         /*----------------------------------------------------------------
687         **      QUEUE FULL control and ORDERED tag control.
688         **----------------------------------------------------------------
689         */
690         /*----------------------------------------------------------------
691         **      QUEUE FULL and ORDERED tag control.
692         **----------------------------------------------------------------
693         */
694         u_short         num_good;       /* Nr of GOOD since QUEUE FULL  */
695         tagmap_t        tags_umap;      /* Used tags bitmap             */
696         tagmap_t        tags_smap;      /* Tags in use at 'tag_stime'   */
697         u_long          tags_stime;     /* Last time we set smap=umap   */
698         ccb_p           held_ccb;       /* CCB held for QUEUE FULL      */
699 };
700
701 /*========================================================================
702 **
703 **      Declaration of structs:     the launch script.
704 **
705 **========================================================================
706 **
707 **      It is part of the CCB and is called by the scripts processor to 
708 **      start or restart the data structure (nexus).
709 **      This 6 DWORDs mini script makes use of prefetching.
710 **
711 **------------------------------------------------------------------------
712 */
713 struct launch {
714         /*----------------------------------------------------------------
715         **      SCR_COPY(4),    @(p_phys), @(dsa register)
716         **      SCR_JUMP,       @(scheduler_point)
717         **----------------------------------------------------------------
718         */
719         ncrcmd          setup_dsa[3];   /* Copy 'phys' address to dsa   */
720         struct link     schedule;       /* Jump to scheduler point      */
721         ncrcmd          p_phys;         /* 'phys' header bus address    */
722 };
723
724 /*========================================================================
725 **
726 **      Declaration of structs:     global HEADER.
727 **
728 **========================================================================
729 **
730 **      This substructure is copied from the ccb to a global address after 
731 **      selection (or reselection) and copied back before disconnect.
732 **
733 **      These fields are accessible to the script processor.
734 **
735 **------------------------------------------------------------------------
736 */
737
738 struct head {
739         /*----------------------------------------------------------------
740         **      Saved data pointer.
741         **      Points to the position in the script responsible for the
742         **      actual transfer transfer of data.
743         **      It's written after reception of a SAVE_DATA_POINTER message.
744         **      The goalpointer points after the last transfer command.
745         **----------------------------------------------------------------
746         */
747         u32             savep;
748         u32             lastp;
749         u32             goalp;
750
751         /*----------------------------------------------------------------
752         **      Alternate data pointer.
753         **      They are copied back to savep/lastp/goalp by the SCRIPTS 
754         **      when the direction is unknown and the device claims data out.
755         **----------------------------------------------------------------
756         */
757         u32             wlastp;
758         u32             wgoalp;
759
760         /*----------------------------------------------------------------
761         **      The virtual address of the ccb containing this header.
762         **----------------------------------------------------------------
763         */
764         ccb_p   cp;
765
766         /*----------------------------------------------------------------
767         **      Status fields.
768         **----------------------------------------------------------------
769         */
770         u_char          scr_st[4];      /* script status                */
771         u_char          status[4];      /* host status. must be the     */
772                                         /*  last DWORD of the header.   */
773 };
774
775 /*
776 **      The status bytes are used by the host and the script processor.
777 **
778 **      The byte corresponding to the host_status must be stored in the 
779 **      last DWORD of the CCB header since it is used for command 
780 **      completion (ncr_wakeup()). Doing so, we are sure that the header 
781 **      has been entirely copied back to the CCB when the host_status is 
782 **      seen complete by the CPU.
783 **
784 **      The last four bytes (status[4]) are copied to the scratchb register
785 **      (declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
786 **      and copied back just after disconnecting.
787 **      Inside the script the XX_REG are used.
788 **
789 **      The first four bytes (scr_st[4]) are used inside the script by 
790 **      "COPY" commands.
791 **      Because source and destination must have the same alignment
792 **      in a DWORD, the fields HAVE to be at the choosen offsets.
793 **              xerr_st         0       (0x34)  scratcha
794 **              sync_st         1       (0x05)  sxfer
795 **              wide_st         3       (0x03)  scntl3
796 */
797
798 /*
799 **      Last four bytes (script)
800 */
801 #define  QU_REG scr0
802 #define  HS_REG scr1
803 #define  HS_PRT nc_scr1
804 #define  SS_REG scr2
805 #define  SS_PRT nc_scr2
806 #define  PS_REG scr3
807
808 /*
809 **      Last four bytes (host)
810 */
811 #ifdef SCSI_NCR_BIG_ENDIAN
812 #define  actualquirks  phys.header.status[3]
813 #define  host_status   phys.header.status[2]
814 #define  scsi_status   phys.header.status[1]
815 #define  parity_status phys.header.status[0]
816 #else
817 #define  actualquirks  phys.header.status[0]
818 #define  host_status   phys.header.status[1]
819 #define  scsi_status   phys.header.status[2]
820 #define  parity_status phys.header.status[3]
821 #endif
822
823 /*
824 **      First four bytes (script)
825 */
826 #define  xerr_st       header.scr_st[0]
827 #define  sync_st       header.scr_st[1]
828 #define  nego_st       header.scr_st[2]
829 #define  wide_st       header.scr_st[3]
830
831 /*
832 **      First four bytes (host)
833 */
834 #define  xerr_status   phys.xerr_st
835 #define  nego_status   phys.nego_st
836
837 #if 0
838 #define  sync_status   phys.sync_st
839 #define  wide_status   phys.wide_st
840 #endif
841
842 /*==========================================================
843 **
844 **      Declaration of structs:     Data structure block
845 **
846 **==========================================================
847 **
848 **      During execution of a ccb by the script processor,
849 **      the DSA (data structure address) register points
850 **      to this substructure of the ccb.
851 **      This substructure contains the header with
852 **      the script-processor-changable data and
853 **      data blocks for the indirect move commands.
854 **
855 **----------------------------------------------------------
856 */
857
858 struct dsb {
859
860         /*
861         **      Header.
862         */
863
864         struct head     header;
865
866         /*
867         **      Table data for Script
868         */
869
870         struct scr_tblsel  select;
871         struct scr_tblmove smsg  ;
872         struct scr_tblmove cmd   ;
873         struct scr_tblmove sense ;
874         struct scr_tblmove data [MAX_SCATTER];
875 };
876
877
878 /*========================================================================
879 **
880 **      Declaration of structs:     Command control block.
881 **
882 **========================================================================
883 */
884 struct ccb {
885         /*----------------------------------------------------------------
886         **      This is the data structure which is pointed by the DSA 
887         **      register when it is executed by the script processor.
888         **      It must be the first entry because it contains the header 
889         **      as first entry that must be cache line aligned.
890         **----------------------------------------------------------------
891         */
892         struct dsb      phys;
893
894         /*----------------------------------------------------------------
895         **      Mini-script used at CCB execution start-up.
896         **      Load the DSA with the data structure address (phys) and 
897         **      jump to SELECT. Jump to CANCEL if CCB is to be canceled.
898         **----------------------------------------------------------------
899         */
900         struct launch   start;
901
902         /*----------------------------------------------------------------
903         **      Mini-script used at CCB relection to restart the nexus.
904         **      Load the DSA with the data structure address (phys) and 
905         **      jump to RESEL_DSA. Jump to ABORT if CCB is to be aborted.
906         **----------------------------------------------------------------
907         */
908         struct launch   restart;
909
910         /*----------------------------------------------------------------
911         **      If a data transfer phase is terminated too early
912         **      (after reception of a message (i.e. DISCONNECT)),
913         **      we have to prepare a mini script to transfer
914         **      the rest of the data.
915         **----------------------------------------------------------------
916         */
917         ncrcmd          patch[8];
918
919         /*----------------------------------------------------------------
920         **      The general SCSI driver provides a
921         **      pointer to a control block.
922         **----------------------------------------------------------------
923         */
924         Scsi_Cmnd       *cmd;           /* SCSI command                 */
925         u_char          cdb_buf[16];    /* Copy of CDB                  */
926         u_char          sense_buf[64];
927         int             data_len;       /* Total data length            */
928
929         /*----------------------------------------------------------------
930         **      Message areas.
931         **      We prepare a message to be sent after selection.
932         **      We may use a second one if the command is rescheduled 
933         **      due to GETCC or QFULL.
934         **      Contents are IDENTIFY and SIMPLE_TAG.
935         **      While negotiating sync or wide transfer,
936         **      a SDTR or WDTR message is appended.
937         **----------------------------------------------------------------
938         */
939         u_char          scsi_smsg [8];
940         u_char          scsi_smsg2[8];
941
942         /*----------------------------------------------------------------
943         **      Other fields.
944         **----------------------------------------------------------------
945         */
946         u_long          p_ccb;          /* BUS address of this CCB      */
947         u_char          sensecmd[6];    /* Sense command                */
948         u_char          tag;            /* Tag for this transfer        */
949                                         /*  255 means no tag            */
950         u_char          target;
951         u_char          lun;
952         u_char          queued;
953         u_char          auto_sense;
954         ccb_p           link_ccb;       /* Host adapter CCB chain       */
955         XPT_QUEHEAD     link_ccbq;      /* Link to unit CCB queue       */
956         u32             startp;         /* Initial data pointer         */
957         u_long          magic;          /* Free / busy  CCB flag        */
958 };
959
960 #define CCB_PHYS(cp,lbl)        (cp->p_ccb + offsetof(struct ccb, lbl))
961
962
963 /*========================================================================
964 **
965 **      Declaration of structs:     NCR device descriptor
966 **
967 **========================================================================
968 */
969 struct ncb {
970         /*----------------------------------------------------------------
971         **      The global header.
972         **      It is accessible to both the host and the script processor.
973         **      Must be cache line size aligned (32 for x86) in order to 
974         **      allow cache line bursting when it is copied to/from CCB.
975         **----------------------------------------------------------------
976         */
977         struct head     header;
978
979         /*----------------------------------------------------------------
980         **      CCBs management queues.
981         **----------------------------------------------------------------
982         */
983         Scsi_Cmnd       *waiting_list;  /* Commands waiting for a CCB   */
984                                         /*  when lcb is not allocated.  */
985         Scsi_Cmnd       *done_list;     /* Commands waiting for done()  */
986                                         /* callback to be invoked.      */ 
987         spinlock_t      smp_lock;       /* Lock for SMP threading       */
988
989         /*----------------------------------------------------------------
990         **      Chip and controller indentification.
991         **----------------------------------------------------------------
992         */
993         int             unit;           /* Unit number                  */
994         char            chip_name[8];   /* Chip name                    */
995         char            inst_name[16];  /* ncb instance name            */
996
997         /*----------------------------------------------------------------
998         **      Initial value of some IO register bits.
999         **      These values are assumed to have been set by BIOS, and may 
1000         **      be used for probing adapter implementation differences.
1001         **----------------------------------------------------------------
1002         */
1003         u_char  sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest0, sv_ctest3,
1004                 sv_ctest4, sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4;
1005
1006         /*----------------------------------------------------------------
1007         **      Actual initial value of IO register bits used by the 
1008         **      driver. They are loaded at initialisation according to  
1009         **      features that are to be enabled.
1010         **----------------------------------------------------------------
1011         */
1012         u_char  rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest0, rv_ctest3,
1013                 rv_ctest4, rv_ctest5, rv_stest2;
1014
1015         /*----------------------------------------------------------------
1016         **      Targets management.
1017         **      During reselection the ncr jumps to jump_tcb.
1018         **      The SFBR register is loaded with the encoded target id.
1019         **      For i = 0 to 3
1020         **              SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(next tcb mod. i)
1021         **
1022         **      Recent chips will prefetch the 4 JUMPS using only 1 burst.
1023         **      It is kind of hashcoding.
1024         **----------------------------------------------------------------
1025         */
1026         struct link     jump_tcb[4];    /* JUMPs for reselection        */
1027         struct tcb  target[MAX_TARGET]; /* Target data                  */
1028
1029         /*----------------------------------------------------------------
1030         **      Virtual and physical bus addresses of the chip.
1031         **----------------------------------------------------------------
1032         */
1033         vm_offset_t     vaddr;          /* Virtual and bus address of   */
1034         vm_offset_t     paddr;          /*  chip's IO registers.        */
1035         vm_offset_t     paddr2;         /* On-chip RAM bus address.     */
1036         volatile                        /* Pointer to volatile for      */
1037         struct ncr_reg  *reg;           /*  memory mapped IO.           */
1038
1039         /*----------------------------------------------------------------
1040         **      SCRIPTS virtual and physical bus addresses.
1041         **      'script'  is loaded in the on-chip RAM if present.
1042         **      'scripth' stays in main memory.
1043         **----------------------------------------------------------------
1044         */
1045         struct script   *script0;       /* Copies of script and scripth */
1046         struct scripth  *scripth0;      /*  relocated for this ncb.     */
1047         struct scripth  *scripth;       /* Actual scripth virt. address */
1048         u_long          p_script;       /* Actual script and scripth    */
1049         u_long          p_scripth;      /*  bus addresses.              */
1050
1051         /*----------------------------------------------------------------
1052         **      General controller parameters and configuration.
1053         **----------------------------------------------------------------
1054         */
1055         struct device   *dev;
1056         u_short         device_id;      /* PCI device id                */
1057         u_char          revision_id;    /* PCI device revision id       */
1058         u_char          bus;            /* PCI BUS number               */
1059         u_char          device_fn;      /* PCI BUS device and function  */
1060         u_long          base_io;        /* IO space base address        */
1061         u_int           irq;            /* IRQ level                    */
1062         u_int           features;       /* Chip features map            */
1063         u_char          myaddr;         /* SCSI id of the adapter       */
1064         u_char          maxburst;       /* log base 2 of dwords burst   */
1065         u_char          maxwide;        /* Maximum transfer width       */
1066         u_char          minsync;        /* Minimum sync period factor   */
1067         u_char          maxsync;        /* Maximum sync period factor   */
1068         u_char          maxoffs;        /* Max scsi offset              */
1069         u_char          multiplier;     /* Clock multiplier (1,2,4)     */
1070         u_char          clock_divn;     /* Number of clock divisors     */
1071         u_long          clock_khz;      /* SCSI clock frequency in KHz  */
1072
1073         /*----------------------------------------------------------------
1074         **      Start queue management.
1075         **      It is filled up by the host processor and accessed by the 
1076         **      SCRIPTS processor in order to start SCSI commands.
1077         **----------------------------------------------------------------
1078         */
1079         u_short         squeueput;      /* Next free slot of the queue  */
1080         u_short         actccbs;        /* Number of allocated CCBs     */
1081         u_short         queuedccbs;     /* Number of CCBs in start queue*/
1082         u_short         queuedepth;     /* Start queue depth            */
1083
1084         /*----------------------------------------------------------------
1085         **      Timeout handler.
1086         **----------------------------------------------------------------
1087         */
1088         struct timer_list timer;        /* Timer handler link header    */
1089         u_long          lasttime;
1090         u_long          settle_time;    /* Resetting the SCSI BUS       */
1091
1092         /*----------------------------------------------------------------
1093         **      Debugging and profiling.
1094         **----------------------------------------------------------------
1095         */
1096         struct ncr_reg  regdump;        /* Register dump                */
1097         u_long          regtime;        /* Time it has been done        */
1098
1099         /*----------------------------------------------------------------
1100         **      Miscellaneous buffers accessed by the scripts-processor.
1101         **      They shall be DWORD aligned, because they may be read or 
1102         **      written with a SCR_COPY script command.
1103         **----------------------------------------------------------------
1104         */
1105         u_char          msgout[8];      /* Buffer for MESSAGE OUT       */
1106         u_char          msgin [8];      /* Buffer for MESSAGE IN        */
1107         u32             lastmsg;        /* Last SCSI message sent       */
1108         u_char          scratch;        /* Scratch for SCSI receive     */
1109
1110         /*----------------------------------------------------------------
1111         **      Miscellaneous configuration and status parameters.
1112         **----------------------------------------------------------------
1113         */
1114         u_char          disc;           /* Diconnection allowed         */
1115         u_char          scsi_mode;      /* Current SCSI BUS mode        */
1116         u_char          order;          /* Tag order to use             */
1117         u_char          verbose;        /* Verbosity for this controller*/
1118         int             ncr_cache;      /* Used for cache test at init. */
1119         u_long          p_ncb;          /* BUS address of this NCB      */
1120
1121         /*----------------------------------------------------------------
1122         **      Command completion handling.
1123         **----------------------------------------------------------------
1124         */
1125 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1126         struct ccb      *(ccb_done[MAX_DONE]);
1127         int             ccb_done_ic;
1128 #endif
1129         /*----------------------------------------------------------------
1130         **      Fields that should be removed or changed.
1131         **----------------------------------------------------------------
1132         */
1133         struct ccb      *ccb;           /* Global CCB                   */
1134         struct usrcmd   user;           /* Command from user            */
1135         volatile u_char release_stage;  /* Synchronisation stage on release  */
1136
1137 #ifdef SCSI_NCR_INTEGRITY_CHECKING
1138         /*----------------------------------------------------------------
1139         **      Fields that are used for integrity check
1140         **----------------------------------------------------------------
1141         */
1142         unsigned char check_integrity; /* Enable midlayer integ.check on
1143                                         * bus scan. */
1144         unsigned char check_integ_par;  /* Set if par or Init. Det. error
1145                                          * used only during integ check */
1146 #endif
1147 };
1148
1149 #define NCB_SCRIPT_PHYS(np,lbl)  (np->p_script  + offsetof (struct script, lbl))
1150 #define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1151
1152 /*==========================================================
1153 **
1154 **
1155 **      Script for NCR-Processor.
1156 **
1157 **      Use ncr_script_fill() to create the variable parts.
1158 **      Use ncr_script_copy_and_bind() to make a copy and
1159 **      bind to physical addresses.
1160 **
1161 **
1162 **==========================================================
1163 **
1164 **      We have to know the offsets of all labels before
1165 **      we reach them (for forward jumps).
1166 **      Therefore we declare a struct here.
1167 **      If you make changes inside the script,
1168 **      DONT FORGET TO CHANGE THE LENGTHS HERE!
1169 **
1170 **----------------------------------------------------------
1171 */
1172
1173 /*
1174 **      For HP Zalon/53c720 systems, the Zalon interface
1175 **      between CPU and 53c720 does prefetches, which causes
1176 **      problems with self modifying scripts.  The problem
1177 **      is overcome by calling a dummy subroutine after each
1178 **      modification, to force a refetch of the script on
1179 **      return from the subroutine.
1180 */
1181
1182 #ifdef CONFIG_NCR53C8XX_PREFETCH
1183 #define PREFETCH_FLUSH_CNT      2
1184 #define PREFETCH_FLUSH          SCR_CALL, PADDRH (wait_dma),
1185 #else
1186 #define PREFETCH_FLUSH_CNT      0
1187 #define PREFETCH_FLUSH
1188 #endif
1189
1190 /*
1191 **      Script fragments which are loaded into the on-chip RAM 
1192 **      of 825A, 875 and 895 chips.
1193 */
1194 struct script {
1195         ncrcmd  start           [  5];
1196         ncrcmd  startpos        [  1];
1197         ncrcmd  select          [  6];
1198         ncrcmd  select2         [  9 + PREFETCH_FLUSH_CNT];
1199         ncrcmd  loadpos         [  4];
1200         ncrcmd  send_ident      [  9];
1201         ncrcmd  prepare         [  6];
1202         ncrcmd  prepare2        [  7];
1203         ncrcmd  command         [  6];
1204         ncrcmd  dispatch        [ 32];
1205         ncrcmd  clrack          [  4];
1206         ncrcmd  no_data         [ 17];
1207         ncrcmd  status          [  8];
1208         ncrcmd  msg_in          [  2];
1209         ncrcmd  msg_in2         [ 16];
1210         ncrcmd  msg_bad         [  4];
1211         ncrcmd  setmsg          [  7];
1212         ncrcmd  cleanup         [  6];
1213         ncrcmd  complete        [  9];
1214         ncrcmd  cleanup_ok      [  8 + PREFETCH_FLUSH_CNT];
1215         ncrcmd  cleanup0        [  1];
1216 #ifndef SCSI_NCR_CCB_DONE_SUPPORT
1217         ncrcmd  signal          [ 12];
1218 #else
1219         ncrcmd  signal          [  9];
1220         ncrcmd  done_pos        [  1];
1221         ncrcmd  done_plug       [  2];
1222         ncrcmd  done_end        [  7];
1223 #endif
1224         ncrcmd  save_dp         [  7];
1225         ncrcmd  restore_dp      [  5];
1226         ncrcmd  disconnect      [ 17];
1227         ncrcmd  msg_out         [  9];
1228         ncrcmd  msg_out_done    [  7];
1229         ncrcmd  idle            [  2];
1230         ncrcmd  reselect        [  8];
1231         ncrcmd  reselected      [  8];
1232         ncrcmd  resel_dsa       [  6 + PREFETCH_FLUSH_CNT];
1233         ncrcmd  loadpos1        [  4];
1234         ncrcmd  resel_lun       [  6];
1235         ncrcmd  resel_tag       [  6];
1236         ncrcmd  jump_to_nexus   [  4 + PREFETCH_FLUSH_CNT];
1237         ncrcmd  nexus_indirect  [  4];
1238         ncrcmd  resel_notag     [  4];
1239         ncrcmd  data_in         [MAX_SCATTERL * 4];
1240         ncrcmd  data_in2        [  4];
1241         ncrcmd  data_out        [MAX_SCATTERL * 4];
1242         ncrcmd  data_out2       [  4];
1243 };
1244
1245 /*
1246 **      Script fragments which stay in main memory for all chips.
1247 */
1248 struct scripth {
1249         ncrcmd  tryloop         [MAX_START*2];
1250         ncrcmd  tryloop2        [  2];
1251 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1252         ncrcmd  done_queue      [MAX_DONE*5];
1253         ncrcmd  done_queue2     [  2];
1254 #endif
1255         ncrcmd  select_no_atn   [  8];
1256         ncrcmd  cancel          [  4];
1257         ncrcmd  skip            [  9 + PREFETCH_FLUSH_CNT];
1258         ncrcmd  skip2           [ 19];
1259         ncrcmd  par_err_data_in [  6];
1260         ncrcmd  par_err_other   [  4];
1261         ncrcmd  msg_reject      [  8];
1262         ncrcmd  msg_ign_residue [ 24];
1263         ncrcmd  msg_extended    [ 10];
1264         ncrcmd  msg_ext_2       [ 10];
1265         ncrcmd  msg_wdtr        [ 14];
1266         ncrcmd  send_wdtr       [  7];
1267         ncrcmd  msg_ext_3       [ 10];
1268         ncrcmd  msg_sdtr        [ 14];
1269         ncrcmd  send_sdtr       [  7];
1270         ncrcmd  nego_bad_phase  [  4];
1271         ncrcmd  msg_out_abort   [ 10];
1272         ncrcmd  hdata_in        [MAX_SCATTERH * 4];
1273         ncrcmd  hdata_in2       [  2];
1274         ncrcmd  hdata_out       [MAX_SCATTERH * 4];
1275         ncrcmd  hdata_out2      [  2];
1276         ncrcmd  reset           [  4];
1277         ncrcmd  aborttag        [  4];
1278         ncrcmd  abort           [  2];
1279         ncrcmd  abort_resel     [ 20];
1280         ncrcmd  resend_ident    [  4];
1281         ncrcmd  clratn_go_on    [  3];
1282         ncrcmd  nxtdsp_go_on    [  1];
1283         ncrcmd  sdata_in        [  8];
1284         ncrcmd  data_io         [ 18];
1285         ncrcmd  bad_identify    [ 12];
1286         ncrcmd  bad_i_t_l       [  4];
1287         ncrcmd  bad_i_t_l_q     [  4];
1288         ncrcmd  bad_target      [  8];
1289         ncrcmd  bad_status      [  8];
1290         ncrcmd  start_ram       [  4 + PREFETCH_FLUSH_CNT];
1291         ncrcmd  start_ram0      [  4];
1292         ncrcmd  sto_restart     [  5];
1293         ncrcmd  wait_dma        [  2];
1294         ncrcmd  snooptest       [  9];
1295         ncrcmd  snoopend        [  2];
1296 };
1297
1298 /*==========================================================
1299 **
1300 **
1301 **      Function headers.
1302 **
1303 **
1304 **==========================================================
1305 */
1306
1307 static  void    ncr_alloc_ccb   (ncb_p np, u_char tn, u_char ln);
1308 static  void    ncr_complete    (ncb_p np, ccb_p cp);
1309 static  void    ncr_exception   (ncb_p np);
1310 static  void    ncr_free_ccb    (ncb_p np, ccb_p cp);
1311 static  void    ncr_init_ccb    (ncb_p np, ccb_p cp);
1312 static  void    ncr_init_tcb    (ncb_p np, u_char tn);
1313 static  lcb_p   ncr_alloc_lcb   (ncb_p np, u_char tn, u_char ln);
1314 static  lcb_p   ncr_setup_lcb   (ncb_p np, u_char tn, u_char ln,
1315                                  u_char *inq_data);
1316 static  void    ncr_getclock    (ncb_p np, int mult);
1317 static  void    ncr_selectclock (ncb_p np, u_char scntl3);
1318 static  ccb_p   ncr_get_ccb     (ncb_p np, u_char tn, u_char ln);
1319 static  void    ncr_chip_reset  (ncb_p np, int delay);
1320 static  void    ncr_init        (ncb_p np, int reset, char * msg, u_long code);
1321 static  int     ncr_int_sbmc    (ncb_p np);
1322 static  int     ncr_int_par     (ncb_p np);
1323 static  void    ncr_int_ma      (ncb_p np);
1324 static  void    ncr_int_sir     (ncb_p np);
1325 static  void    ncr_int_sto     (ncb_p np);
1326 static  u_long  ncr_lookup      (char* id);
1327 static  void    ncr_negotiate   (struct ncb* np, struct tcb* tp);
1328 static  int     ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr);
1329 #ifdef SCSI_NCR_INTEGRITY_CHECKING
1330 static  int     ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr);
1331 #endif
1332
1333 static  void    ncr_script_copy_and_bind
1334                                 (ncb_p np, ncrcmd *src, ncrcmd *dst, int len);
1335 static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
1336 static  int     ncr_scatter     (ncb_p np, ccb_p cp, Scsi_Cmnd *cmd);
1337 static  void    ncr_getsync     (ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p);
1338 static  void    ncr_setsync     (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer);
1339 static  void    ncr_setup_tags  (ncb_p np, u_char tn, u_char ln);
1340 static  void    ncr_setwide     (ncb_p np, ccb_p cp, u_char wide, u_char ack);
1341 static  int     ncr_show_msg    (u_char * msg);
1342 static  void    ncr_print_msg   (ccb_p cp, char *label, u_char *msg);
1343 static  int     ncr_snooptest   (ncb_p np);
1344 static  void    ncr_timeout     (ncb_p np);
1345 static  void    ncr_wakeup      (ncb_p np, u_long code);
1346 static  void    ncr_wakeup_done (ncb_p np);
1347 static  void    ncr_start_next_ccb (ncb_p np, lcb_p lp, int maxn);
1348 static  void    ncr_put_start_queue(ncb_p np, ccb_p cp);
1349 static  void    ncr_start_reset (ncb_p np);
1350 static  int     ncr_reset_scsi_bus (ncb_p np, int enab_int, int settle_delay);
1351
1352 #ifdef SCSI_NCR_USER_COMMAND_SUPPORT
1353 static  void    ncr_usercmd     (ncb_p np);
1354 #endif
1355
1356 static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd);
1357 static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd);
1358 static void process_waiting_list(ncb_p np, int sts);
1359
1360 #define remove_from_waiting_list(np, cmd) \
1361                 retrieve_from_waiting_list(1, (np), (cmd))
1362 #define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
1363 #define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
1364
1365 static inline char *ncr_name (ncb_p np)
1366 {
1367         return np->inst_name;
1368 }
1369
1370
1371 /*==========================================================
1372 **
1373 **
1374 **      Scripts for NCR-Processor.
1375 **
1376 **      Use ncr_script_bind for binding to physical addresses.
1377 **
1378 **
1379 **==========================================================
1380 **
1381 **      NADDR generates a reference to a field of the controller data.
1382 **      PADDR generates a reference to another part of the script.
1383 **      RADDR generates a reference to a script processor register.
1384 **      FADDR generates a reference to a script processor register
1385 **              with offset.
1386 **
1387 **----------------------------------------------------------
1388 */
1389
1390 #define RELOC_SOFTC     0x40000000
1391 #define RELOC_LABEL     0x50000000
1392 #define RELOC_REGISTER  0x60000000
1393 #if 0
1394 #define RELOC_KVAR      0x70000000
1395 #endif
1396 #define RELOC_LABELH    0x80000000
1397 #define RELOC_MASK      0xf0000000
1398
1399 #define NADDR(label)    (RELOC_SOFTC | offsetof(struct ncb, label))
1400 #define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1401 #define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
1402 #define RADDR(label)    (RELOC_REGISTER | REG(label))
1403 #define FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1404 #if 0
1405 #define KVAR(which)     (RELOC_KVAR | (which))
1406 #endif
1407
1408 #if 0
1409 #define SCRIPT_KVAR_JIFFIES     (0)
1410 #define SCRIPT_KVAR_FIRST               SCRIPT_KVAR_JIFFIES
1411 #define SCRIPT_KVAR_LAST                SCRIPT_KVAR_JIFFIES
1412 /*
1413  * Kernel variables referenced in the scripts.
1414  * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
1415  */
1416 static void *script_kvars[] __initdata =
1417         { (void *)&jiffies };
1418 #endif
1419
1420 static  struct script script0 __initdata = {
1421 /*--------------------------< START >-----------------------*/ {
1422         /*
1423         **      This NOP will be patched with LED ON
1424         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
1425         */
1426         SCR_NO_OP,
1427                 0,
1428         /*
1429         **      Clear SIGP.
1430         */
1431         SCR_FROM_REG (ctest2),
1432                 0,
1433         /*
1434         **      Then jump to a certain point in tryloop.
1435         **      Due to the lack of indirect addressing the code
1436         **      is self modifying here.
1437         */
1438         SCR_JUMP,
1439 }/*-------------------------< STARTPOS >--------------------*/,{
1440                 PADDRH(tryloop),
1441
1442 }/*-------------------------< SELECT >----------------------*/,{
1443         /*
1444         **      DSA     contains the address of a scheduled
1445         **              data structure.
1446         **
1447         **      SCRATCHA contains the address of the script,
1448         **              which starts the next entry.
1449         **
1450         **      Set Initiator mode.
1451         **
1452         **      (Target mode is left as an exercise for the reader)
1453         */
1454
1455         SCR_CLR (SCR_TRG),
1456                 0,
1457         SCR_LOAD_REG (HS_REG, HS_SELECTING),
1458                 0,
1459
1460         /*
1461         **      And try to select this target.
1462         */
1463         SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1464                 PADDR (reselect),
1465
1466 }/*-------------------------< SELECT2 >----------------------*/,{
1467         /*
1468         **      Now there are 4 possibilities:
1469         **
1470         **      (1) The ncr loses arbitration.
1471         **      This is ok, because it will try again,
1472         **      when the bus becomes idle.
1473         **      (But beware of the timeout function!)
1474         **
1475         **      (2) The ncr is reselected.
1476         **      Then the script processor takes the jump
1477         **      to the RESELECT label.
1478         **
1479         **      (3) The ncr wins arbitration.
1480         **      Then it will execute SCRIPTS instruction until 
1481         **      the next instruction that checks SCSI phase.
1482         **      Then will stop and wait for selection to be 
1483         **      complete or selection time-out to occur.
1484         **      As a result the SCRIPTS instructions until 
1485         **      LOADPOS + 2 should be executed in parallel with 
1486         **      the SCSI core performing selection.
1487         */
1488
1489         /*
1490         **      The M_REJECT problem seems to be due to a selection 
1491         **      timing problem.
1492         **      Wait immediately for the selection to complete. 
1493         **      (2.5x behaves so)
1494         */
1495         SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
1496                 0,
1497
1498         /*
1499         **      Next time use the next slot.
1500         */
1501         SCR_COPY (4),
1502                 RADDR (temp),
1503                 PADDR (startpos),
1504         /*
1505         **      The ncr doesn't have an indirect load
1506         **      or store command. So we have to
1507         **      copy part of the control block to a
1508         **      fixed place, where we can access it.
1509         **
1510         **      We patch the address part of a
1511         **      COPY command with the DSA-register.
1512         */
1513         SCR_COPY_F (4),
1514                 RADDR (dsa),
1515                 PADDR (loadpos),
1516         /*
1517         **      Flush script prefetch if required
1518         */
1519         PREFETCH_FLUSH
1520         /*
1521         **      then we do the actual copy.
1522         */
1523         SCR_COPY (sizeof (struct head)),
1524         /*
1525         **      continued after the next label ...
1526         */
1527 }/*-------------------------< LOADPOS >---------------------*/,{
1528                 0,
1529                 NADDR (header),
1530         /*
1531         **      Wait for the next phase or the selection
1532         **      to complete or time-out.
1533         */
1534         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
1535                 PADDR (prepare),
1536
1537 }/*-------------------------< SEND_IDENT >----------------------*/,{
1538         /*
1539         **      Selection complete.
1540         **      Send the IDENTIFY and SIMPLE_TAG messages
1541         **      (and the M_X_SYNC_REQ message)
1542         */
1543         SCR_MOVE_TBL ^ SCR_MSG_OUT,
1544                 offsetof (struct dsb, smsg),
1545         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1546                 PADDRH (resend_ident),
1547         SCR_LOAD_REG (scratcha, 0x80),
1548                 0,
1549         SCR_COPY (1),
1550                 RADDR (scratcha),
1551                 NADDR (lastmsg),
1552 }/*-------------------------< PREPARE >----------------------*/,{
1553         /*
1554         **      load the savep (saved pointer) into
1555         **      the TEMP register (actual pointer)
1556         */
1557         SCR_COPY (4),
1558                 NADDR (header.savep),
1559                 RADDR (temp),
1560         /*
1561         **      Initialize the status registers
1562         */
1563         SCR_COPY (4),
1564                 NADDR (header.status),
1565                 RADDR (scr0),
1566 }/*-------------------------< PREPARE2 >---------------------*/,{
1567         /*
1568         **      Initialize the msgout buffer with a NOOP message.
1569         */
1570         SCR_LOAD_REG (scratcha, M_NOOP),
1571                 0,
1572         SCR_COPY (1),
1573                 RADDR (scratcha),
1574                 NADDR (msgout),
1575 #if 0
1576         SCR_COPY (1),
1577                 RADDR (scratcha),
1578                 NADDR (msgin),
1579 #endif
1580         /*
1581         **      Anticipate the COMMAND phase.
1582         **      This is the normal case for initial selection.
1583         */
1584         SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
1585                 PADDR (dispatch),
1586
1587 }/*-------------------------< COMMAND >--------------------*/,{
1588         /*
1589         **      ... and send the command
1590         */
1591         SCR_MOVE_TBL ^ SCR_COMMAND,
1592                 offsetof (struct dsb, cmd),
1593         /*
1594         **      If status is still HS_NEGOTIATE, negotiation failed.
1595         **      We check this here, since we want to do that 
1596         **      only once.
1597         */
1598         SCR_FROM_REG (HS_REG),
1599                 0,
1600         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
1601                 SIR_NEGO_FAILED,
1602
1603 }/*-----------------------< DISPATCH >----------------------*/,{
1604         /*
1605         **      MSG_IN is the only phase that shall be 
1606         **      entered at least once for each (re)selection.
1607         **      So we test it first.
1608         */
1609         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
1610                 PADDR (msg_in),
1611
1612         SCR_RETURN ^ IFTRUE (IF (SCR_DATA_OUT)),
1613                 0,
1614         /*
1615         **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 4.
1616         **      Possible data corruption during Memory Write and Invalidate.
1617         **      This work-around resets the addressing logic prior to the 
1618         **      start of the first MOVE of a DATA IN phase.
1619         **      (See Documentation/scsi/ncr53c8xx.txt for more information)
1620         */
1621         SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1622                 20,
1623         SCR_COPY (4),
1624                 RADDR (scratcha),
1625                 RADDR (scratcha),
1626         SCR_RETURN,
1627                 0,
1628         SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
1629                 PADDR (status),
1630         SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
1631                 PADDR (command),
1632         SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
1633                 PADDR (msg_out),
1634         /*
1635         **      Discard one illegal phase byte, if required.
1636         */
1637         SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
1638                 0,
1639         SCR_COPY (1),
1640                 RADDR (scratcha),
1641                 NADDR (xerr_st),
1642         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
1643                 8,
1644         SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
1645                 NADDR (scratch),
1646         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
1647                 8,
1648         SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
1649                 NADDR (scratch),
1650         SCR_JUMP,
1651                 PADDR (dispatch),
1652
1653 }/*-------------------------< CLRACK >----------------------*/,{
1654         /*
1655         **      Terminate possible pending message phase.
1656         */
1657         SCR_CLR (SCR_ACK),
1658                 0,
1659         SCR_JUMP,
1660                 PADDR (dispatch),
1661
1662 }/*-------------------------< NO_DATA >--------------------*/,{
1663         /*
1664         **      The target wants to tranfer too much data
1665         **      or in the wrong direction.
1666         **      Remember that in extended error.
1667         */
1668         SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
1669                 0,
1670         SCR_COPY (1),
1671                 RADDR (scratcha),
1672                 NADDR (xerr_st),
1673         /*
1674         **      Discard one data byte, if required.
1675         */
1676         SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
1677                 8,
1678         SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
1679                 NADDR (scratch),
1680         SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1681                 8,
1682         SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
1683                 NADDR (scratch),
1684         /*
1685         **      .. and repeat as required.
1686         */
1687         SCR_CALL,
1688                 PADDR (dispatch),
1689         SCR_JUMP,
1690                 PADDR (no_data),
1691
1692 }/*-------------------------< STATUS >--------------------*/,{
1693         /*
1694         **      get the status
1695         */
1696         SCR_MOVE_ABS (1) ^ SCR_STATUS,
1697                 NADDR (scratch),
1698         /*
1699         **      save status to scsi_status.
1700         **      mark as complete.
1701         */
1702         SCR_TO_REG (SS_REG),
1703                 0,
1704         SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1705                 0,
1706         SCR_JUMP,
1707                 PADDR (dispatch),
1708 }/*-------------------------< MSG_IN >--------------------*/,{
1709         /*
1710         **      Get the first byte of the message
1711         **      and save it to SCRATCHA.
1712         **
1713         **      The script processor doesn't negate the
1714         **      ACK signal after this transfer.
1715         */
1716         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
1717                 NADDR (msgin[0]),
1718 }/*-------------------------< MSG_IN2 >--------------------*/,{
1719         /*
1720         **      Handle this message.
1721         */
1722         SCR_JUMP ^ IFTRUE (DATA (M_COMPLETE)),
1723                 PADDR (complete),
1724         SCR_JUMP ^ IFTRUE (DATA (M_DISCONNECT)),
1725                 PADDR (disconnect),
1726         SCR_JUMP ^ IFTRUE (DATA (M_SAVE_DP)),
1727                 PADDR (save_dp),
1728         SCR_JUMP ^ IFTRUE (DATA (M_RESTORE_DP)),
1729                 PADDR (restore_dp),
1730         SCR_JUMP ^ IFTRUE (DATA (M_EXTENDED)),
1731                 PADDRH (msg_extended),
1732         SCR_JUMP ^ IFTRUE (DATA (M_NOOP)),
1733                 PADDR (clrack),
1734         SCR_JUMP ^ IFTRUE (DATA (M_REJECT)),
1735                 PADDRH (msg_reject),
1736         SCR_JUMP ^ IFTRUE (DATA (M_IGN_RESIDUE)),
1737                 PADDRH (msg_ign_residue),
1738         /*
1739         **      Rest of the messages left as
1740         **      an exercise ...
1741         **
1742         **      Unimplemented messages:
1743         **      fall through to MSG_BAD.
1744         */
1745 }/*-------------------------< MSG_BAD >------------------*/,{
1746         /*
1747         **      unimplemented message - reject it.
1748         */
1749         SCR_INT,
1750                 SIR_REJECT_SENT,
1751         SCR_LOAD_REG (scratcha, M_REJECT),
1752                 0,
1753 }/*-------------------------< SETMSG >----------------------*/,{
1754         SCR_COPY (1),
1755                 RADDR (scratcha),
1756                 NADDR (msgout),
1757         SCR_SET (SCR_ATN),
1758                 0,
1759         SCR_JUMP,
1760                 PADDR (clrack),
1761 }/*-------------------------< CLEANUP >-------------------*/,{
1762         /*
1763         **      dsa:    Pointer to ccb
1764         **            or xxxxxxFF (no ccb)
1765         **
1766         **      HS_REG:   Host-Status (<>0!)
1767         */
1768         SCR_FROM_REG (dsa),
1769                 0,
1770         SCR_JUMP ^ IFTRUE (DATA (0xff)),
1771                 PADDR (start),
1772         /*
1773         **      dsa is valid.
1774         **      complete the cleanup.
1775         */
1776         SCR_JUMP,
1777                 PADDR (cleanup_ok),
1778
1779 }/*-------------------------< COMPLETE >-----------------*/,{
1780         /*
1781         **      Complete message.
1782         **
1783         **      Copy TEMP register to LASTP in header.
1784         */
1785         SCR_COPY (4),
1786                 RADDR (temp),
1787                 NADDR (header.lastp),
1788         /*
1789         **      When we terminate the cycle by clearing ACK,
1790         **      the target may disconnect immediately.
1791         **
1792         **      We don't want to be told of an
1793         **      "unexpected disconnect",
1794         **      so we disable this feature.
1795         */
1796         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
1797                 0,
1798         /*
1799         **      Terminate cycle ...
1800         */
1801         SCR_CLR (SCR_ACK|SCR_ATN),
1802                 0,
1803         /*
1804         **      ... and wait for the disconnect.
1805         */
1806         SCR_WAIT_DISC,
1807                 0,
1808 }/*-------------------------< CLEANUP_OK >----------------*/,{
1809         /*
1810         **      Save host status to header.
1811         */
1812         SCR_COPY (4),
1813                 RADDR (scr0),
1814                 NADDR (header.status),
1815         /*
1816         **      and copy back the header to the ccb.
1817         */
1818         SCR_COPY_F (4),
1819                 RADDR (dsa),
1820                 PADDR (cleanup0),
1821         /*
1822         **      Flush script prefetch if required
1823         */
1824         PREFETCH_FLUSH
1825         SCR_COPY (sizeof (struct head)),
1826                 NADDR (header),
1827 }/*-------------------------< CLEANUP0 >--------------------*/,{
1828                 0,
1829 }/*-------------------------< SIGNAL >----------------------*/,{
1830         /*
1831         **      if job not completed ...
1832         */
1833         SCR_FROM_REG (HS_REG),
1834                 0,
1835         /*
1836         **      ... start the next command.
1837         */
1838         SCR_JUMP ^ IFTRUE (MASK (0, (HS_DONEMASK|HS_SKIPMASK))),
1839                 PADDR(start),
1840         /*
1841         **      If command resulted in not GOOD status,
1842         **      call the C code if needed.
1843         */
1844         SCR_FROM_REG (SS_REG),
1845                 0,
1846         SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
1847                 PADDRH (bad_status),
1848
1849 #ifndef SCSI_NCR_CCB_DONE_SUPPORT
1850
1851         /*
1852         **      ... signal completion to the host
1853         */
1854 #ifdef SIMULATED_INTFLY
1855         SCR_INT,
1856                 SIR_INTFLY,
1857 #else
1858         SCR_INT_FLY,
1859                 0,
1860 #endif
1861         /*
1862         **      Auf zu neuen Schandtaten!
1863         */
1864         SCR_JUMP,
1865                 PADDR(start),
1866
1867 #else   /* defined SCSI_NCR_CCB_DONE_SUPPORT */
1868
1869         /*
1870         **      ... signal completion to the host
1871         */
1872         SCR_JUMP,
1873 }/*------------------------< DONE_POS >---------------------*/,{
1874                 PADDRH (done_queue),
1875 }/*------------------------< DONE_PLUG >--------------------*/,{
1876         SCR_INT,
1877                 SIR_DONE_OVERFLOW,
1878 }/*------------------------< DONE_END >---------------------*/,{
1879 #ifdef SIMULATED_INTFLY
1880         SCR_INT,
1881                 SIR_INTFLY,
1882 #else
1883         SCR_INT_FLY,
1884                 0,
1885 #endif
1886         SCR_COPY (4),
1887                 RADDR (temp),
1888                 PADDR (done_pos),
1889         SCR_JUMP,
1890                 PADDR (start),
1891
1892 #endif  /* SCSI_NCR_CCB_DONE_SUPPORT */
1893
1894 }/*-------------------------< SAVE_DP >------------------*/,{
1895         /*
1896         **      SAVE_DP message:
1897         **      Copy TEMP register to SAVEP in header.
1898         */
1899         SCR_COPY (4),
1900                 RADDR (temp),
1901                 NADDR (header.savep),
1902         SCR_CLR (SCR_ACK),
1903                 0,
1904         SCR_JUMP,
1905                 PADDR (dispatch),
1906 }/*-------------------------< RESTORE_DP >---------------*/,{
1907         /*
1908         **      RESTORE_DP message:
1909         **      Copy SAVEP in header to TEMP register.
1910         */
1911         SCR_COPY (4),
1912                 NADDR (header.savep),
1913                 RADDR (temp),
1914         SCR_JUMP,
1915                 PADDR (clrack),
1916
1917 }/*-------------------------< DISCONNECT >---------------*/,{
1918         /*
1919         **      DISCONNECTing  ...
1920         **
1921         **      disable the "unexpected disconnect" feature,
1922         **      and remove the ACK signal.
1923         */
1924         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
1925                 0,
1926         SCR_CLR (SCR_ACK|SCR_ATN),
1927                 0,
1928         /*
1929         **      Wait for the disconnect.
1930         */
1931         SCR_WAIT_DISC,
1932                 0,
1933         /*
1934         **      Status is: DISCONNECTED.
1935         */
1936         SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
1937                 0,
1938         /*
1939         **      If QUIRK_AUTOSAVE is set,
1940         **      do an "save pointer" operation.
1941         */
1942         SCR_FROM_REG (QU_REG),
1943                 0,
1944         SCR_JUMP ^ IFFALSE (MASK (QUIRK_AUTOSAVE, QUIRK_AUTOSAVE)),
1945                 PADDR (cleanup_ok),
1946         /*
1947         **      like SAVE_DP message:
1948         **      Copy TEMP register to SAVEP in header.
1949         */
1950         SCR_COPY (4),
1951                 RADDR (temp),
1952                 NADDR (header.savep),
1953         SCR_JUMP,
1954                 PADDR (cleanup_ok),
1955
1956 }/*-------------------------< MSG_OUT >-------------------*/,{
1957         /*
1958         **      The target requests a message.
1959         */
1960         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
1961                 NADDR (msgout),
1962         SCR_COPY (1),
1963                 NADDR (msgout),
1964                 NADDR (lastmsg),
1965         /*
1966         **      If it was no ABORT message ...
1967         */
1968         SCR_JUMP ^ IFTRUE (DATA (M_ABORT)),
1969                 PADDRH (msg_out_abort),
1970         /*
1971         **      ... wait for the next phase
1972         **      if it's a message out, send it again, ...
1973         */
1974         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1975                 PADDR (msg_out),
1976 }/*-------------------------< MSG_OUT_DONE >--------------*/,{
1977         /*
1978         **      ... else clear the message ...
1979         */
1980         SCR_LOAD_REG (scratcha, M_NOOP),
1981                 0,
1982         SCR_COPY (4),
1983                 RADDR (scratcha),
1984                 NADDR (msgout),
1985         /*
1986         **      ... and process the next phase
1987         */
1988         SCR_JUMP,
1989                 PADDR (dispatch),
1990 }/*-------------------------< IDLE >------------------------*/,{
1991         /*
1992         **      Nothing to do?
1993         **      Wait for reselect.
1994         **      This NOP will be patched with LED OFF
1995         **      SCR_REG_REG (gpreg, SCR_OR, 0x01)
1996         */
1997         SCR_NO_OP,
1998                 0,
1999 }/*-------------------------< RESELECT >--------------------*/,{
2000         /*
2001         **      make the DSA invalid.
2002         */
2003         SCR_LOAD_REG (dsa, 0xff),
2004                 0,
2005         SCR_CLR (SCR_TRG),
2006                 0,
2007         SCR_LOAD_REG (HS_REG, HS_IN_RESELECT),
2008                 0,
2009         /*
2010         **      Sleep waiting for a reselection.
2011         **      If SIGP is set, special treatment.
2012         **
2013         **      Zu allem bereit ..
2014         */
2015         SCR_WAIT_RESEL,
2016                 PADDR(start),
2017 }/*-------------------------< RESELECTED >------------------*/,{
2018         /*
2019         **      This NOP will be patched with LED ON
2020         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2021         */
2022         SCR_NO_OP,
2023                 0,
2024         /*
2025         **      ... zu nichts zu gebrauchen ?
2026         **
2027         **      load the target id into the SFBR
2028         **      and jump to the control block.
2029         **
2030         **      Look at the declarations of
2031         **      - struct ncb
2032         **      - struct tcb
2033         **      - struct lcb
2034         **      - struct ccb
2035         **      to understand what's going on.
2036         */
2037         SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2038                 0,
2039         SCR_TO_REG (sdid),
2040                 0,
2041         SCR_JUMP,
2042                 NADDR (jump_tcb),
2043
2044 }/*-------------------------< RESEL_DSA >-------------------*/,{
2045         /*
2046         **      Ack the IDENTIFY or TAG previously received.
2047         */
2048         SCR_CLR (SCR_ACK),
2049                 0,
2050         /*
2051         **      The ncr doesn't have an indirect load
2052         **      or store command. So we have to
2053         **      copy part of the control block to a
2054         **      fixed place, where we can access it.
2055         **
2056         **      We patch the address part of a
2057         **      COPY command with the DSA-register.
2058         */
2059         SCR_COPY_F (4),
2060                 RADDR (dsa),
2061                 PADDR (loadpos1),
2062         /*
2063         **      Flush script prefetch if required
2064         */
2065         PREFETCH_FLUSH
2066         /*
2067         **      then we do the actual copy.
2068         */
2069         SCR_COPY (sizeof (struct head)),
2070         /*
2071         **      continued after the next label ...
2072         */
2073
2074 }/*-------------------------< LOADPOS1 >-------------------*/,{
2075                 0,
2076                 NADDR (header),
2077         /*
2078         **      The DSA contains the data structure address.
2079         */
2080         SCR_JUMP,
2081                 PADDR (prepare),
2082
2083 }/*-------------------------< RESEL_LUN >-------------------*/,{
2084         /*
2085         **      come back to this point
2086         **      to get an IDENTIFY message
2087         **      Wait for a msg_in phase.
2088         */
2089         SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2090                 SIR_RESEL_NO_MSG_IN,
2091         /*
2092         **      message phase.
2093         **      Read the data directly from the BUS DATA lines.
2094         **      This helps to support very old SCSI devices that 
2095         **      may reselect without sending an IDENTIFY.
2096         */
2097         SCR_FROM_REG (sbdl),
2098                 0,
2099         /*
2100         **      It should be an Identify message.
2101         */
2102         SCR_RETURN,
2103                 0,
2104 }/*-------------------------< RESEL_TAG >-------------------*/,{
2105         /*
2106         **      Read IDENTIFY + SIMPLE + TAG using a single MOVE.
2107         **      Agressive optimization, is'nt it?
2108         **      No need to test the SIMPLE TAG message, since the 
2109         **      driver only supports conformant devices for tags. ;-)
2110         */
2111         SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2112                 NADDR (msgin),
2113         /*
2114         **      Read the TAG from the SIDL.
2115         **      Still an aggressive optimization. ;-)
2116         **      Compute the CCB indirect jump address which 
2117         **      is (#TAG*2 & 0xfc) due to tag numbering using 
2118         **      1,3,5..MAXTAGS*2+1 actual values.
2119         */
2120         SCR_REG_SFBR (sidl, SCR_SHL, 0),
2121                 0,
2122         SCR_SFBR_REG (temp, SCR_AND, 0xfc),
2123                 0,
2124 }/*-------------------------< JUMP_TO_NEXUS >-------------------*/,{
2125         SCR_COPY_F (4),
2126                 RADDR (temp),
2127                 PADDR (nexus_indirect),
2128         /*
2129         **      Flush script prefetch if required
2130         */
2131         PREFETCH_FLUSH
2132         SCR_COPY (4),
2133 }/*-------------------------< NEXUS_INDIRECT >-------------------*/,{
2134                 0,
2135                 RADDR (temp),
2136         SCR_RETURN,
2137                 0,
2138 }/*-------------------------< RESEL_NOTAG >-------------------*/,{
2139         /*
2140         **      No tag expected.
2141         **      Read an throw away the IDENTIFY.
2142         */
2143         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2144                 NADDR (msgin),
2145         SCR_JUMP,
2146                 PADDR (jump_to_nexus),
2147 }/*-------------------------< DATA_IN >--------------------*/,{
2148 /*
2149 **      Because the size depends on the
2150 **      #define MAX_SCATTERL parameter,
2151 **      it is filled in at runtime.
2152 **
2153 **  ##===========< i=0; i<MAX_SCATTERL >=========
2154 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2155 **  ||          PADDR (dispatch),
2156 **  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2157 **  ||          offsetof (struct dsb, data[ i]),
2158 **  ##==========================================
2159 **
2160 **---------------------------------------------------------
2161 */
2162 0
2163 }/*-------------------------< DATA_IN2 >-------------------*/,{
2164         SCR_CALL,
2165                 PADDR (dispatch),
2166         SCR_JUMP,
2167                 PADDR (no_data),
2168 }/*-------------------------< DATA_OUT >--------------------*/,{
2169 /*
2170 **      Because the size depends on the
2171 **      #define MAX_SCATTERL parameter,
2172 **      it is filled in at runtime.
2173 **
2174 **  ##===========< i=0; i<MAX_SCATTERL >=========
2175 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2176 **  ||          PADDR (dispatch),
2177 **  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2178 **  ||          offsetof (struct dsb, data[ i]),
2179 **  ##==========================================
2180 **
2181 **---------------------------------------------------------
2182 */
2183 0
2184 }/*-------------------------< DATA_OUT2 >-------------------*/,{
2185         SCR_CALL,
2186                 PADDR (dispatch),
2187         SCR_JUMP,
2188                 PADDR (no_data),
2189 }/*--------------------------------------------------------*/
2190 };
2191
2192 static  struct scripth scripth0 __initdata = {
2193 /*-------------------------< TRYLOOP >---------------------*/{
2194 /*
2195 **      Start the next entry.
2196 **      Called addresses point to the launch script in the CCB.
2197 **      They are patched by the main processor.
2198 **
2199 **      Because the size depends on the
2200 **      #define MAX_START parameter, it is filled
2201 **      in at runtime.
2202 **
2203 **-----------------------------------------------------------
2204 **
2205 **  ##===========< I=0; i<MAX_START >===========
2206 **  ||  SCR_CALL,
2207 **  ||          PADDR (idle),
2208 **  ##==========================================
2209 **
2210 **-----------------------------------------------------------
2211 */
2212 0
2213 }/*------------------------< TRYLOOP2 >---------------------*/,{
2214         SCR_JUMP,
2215                 PADDRH(tryloop),
2216
2217 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
2218
2219 }/*------------------------< DONE_QUEUE >-------------------*/,{
2220 /*
2221 **      Copy the CCB address to the next done entry.
2222 **      Because the size depends on the
2223 **      #define MAX_DONE parameter, it is filled
2224 **      in at runtime.
2225 **
2226 **-----------------------------------------------------------
2227 **
2228 **  ##===========< I=0; i<MAX_DONE >===========
2229 **  ||  SCR_COPY (sizeof(ccb_p)),
2230 **  ||          NADDR (header.cp),
2231 **  ||          NADDR (ccb_done[i]),
2232 **  ||  SCR_CALL,
2233 **  ||          PADDR (done_end),
2234 **  ##==========================================
2235 **
2236 **-----------------------------------------------------------
2237 */
2238 0
2239 }/*------------------------< DONE_QUEUE2 >------------------*/,{
2240         SCR_JUMP,
2241                 PADDRH (done_queue),
2242
2243 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2244 }/*------------------------< SELECT_NO_ATN >-----------------*/,{
2245         /*
2246         **      Set Initiator mode.
2247         **      And try to select this target without ATN.
2248         */
2249
2250         SCR_CLR (SCR_TRG),
2251                 0,
2252         SCR_LOAD_REG (HS_REG, HS_SELECTING),
2253                 0,
2254         SCR_SEL_TBL ^ offsetof (struct dsb, select),
2255                 PADDR (reselect),
2256         SCR_JUMP,
2257                 PADDR (select2),
2258
2259 }/*-------------------------< CANCEL >------------------------*/,{
2260
2261         SCR_LOAD_REG (scratcha, HS_ABORTED),
2262                 0,
2263         SCR_JUMPR,
2264                 8,
2265 }/*-------------------------< SKIP >------------------------*/,{
2266         SCR_LOAD_REG (scratcha, 0),
2267                 0,
2268         /*
2269         **      This entry has been canceled.
2270         **      Next time use the next slot.
2271         */
2272         SCR_COPY (4),
2273                 RADDR (temp),
2274                 PADDR (startpos),
2275         /*
2276         **      The ncr doesn't have an indirect load
2277         **      or store command. So we have to
2278         **      copy part of the control block to a
2279         **      fixed place, where we can access it.
2280         **
2281         **      We patch the address part of a
2282         **      COPY command with the DSA-register.
2283         */
2284         SCR_COPY_F (4),
2285                 RADDR (dsa),
2286                 PADDRH (skip2),
2287         /*
2288         **      Flush script prefetch if required
2289         */
2290         PREFETCH_FLUSH
2291         /*
2292         **      then we do the actual copy.
2293         */
2294         SCR_COPY (sizeof (struct head)),
2295         /*
2296         **      continued after the next label ...
2297         */
2298 }/*-------------------------< SKIP2 >---------------------*/,{
2299                 0,
2300                 NADDR (header),
2301         /*
2302         **      Initialize the status registers
2303         */
2304         SCR_COPY (4),
2305                 NADDR (header.status),
2306                 RADDR (scr0),
2307         /*
2308         **      Force host status.
2309         */
2310         SCR_FROM_REG (scratcha),
2311                 0,
2312         SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2313                 16,
2314         SCR_REG_REG (HS_REG, SCR_OR, HS_SKIPMASK),
2315                 0,
2316         SCR_JUMPR,
2317                 8,
2318         SCR_TO_REG (HS_REG),
2319                 0,
2320         SCR_LOAD_REG (SS_REG, S_GOOD),
2321                 0,
2322         SCR_JUMP,
2323                 PADDR (cleanup_ok),
2324
2325 },/*-------------------------< PAR_ERR_DATA_IN >---------------*/{
2326         /*
2327         **      Ignore all data in byte, until next phase
2328         */
2329         SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2330                 PADDRH (par_err_other),
2331         SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2332                 NADDR (scratch),
2333         SCR_JUMPR,
2334                 -24,
2335 },/*-------------------------< PAR_ERR_OTHER >------------------*/{
2336         /*
2337         **      count it.
2338         */
2339         SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2340                 0,
2341         /*
2342         **      jump to dispatcher.
2343         */
2344         SCR_JUMP,
2345                 PADDR (dispatch),
2346 }/*-------------------------< MSG_REJECT >---------------*/,{
2347         /*
2348         **      If a negotiation was in progress,
2349         **      negotiation failed.
2350         **      Otherwise, let the C code print 
2351         **      some message.
2352         */
2353         SCR_FROM_REG (HS_REG),
2354                 0,
2355         SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2356                 SIR_REJECT_RECEIVED,
2357         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2358                 SIR_NEGO_FAILED,
2359         SCR_JUMP,
2360                 PADDR (clrack),
2361
2362 }/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2363         /*
2364         **      Terminate cycle
2365         */
2366         SCR_CLR (SCR_ACK),
2367                 0,
2368         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2369                 PADDR (dispatch),
2370         /*
2371         **      get residue size.
2372         */
2373         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2374                 NADDR (msgin[1]),
2375         /*
2376         **      Size is 0 .. ignore message.
2377         */
2378         SCR_JUMP ^ IFTRUE (DATA (0)),
2379                 PADDR (clrack),
2380         /*
2381         **      Size is not 1 .. have to interrupt.
2382         */
2383         SCR_JUMPR ^ IFFALSE (DATA (1)),
2384                 40,
2385         /*
2386         **      Check for residue byte in swide register
2387         */
2388         SCR_FROM_REG (scntl2),
2389                 0,
2390         SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2391                 16,
2392         /*
2393         **      There IS data in the swide register.
2394         **      Discard it.
2395         */
2396         SCR_REG_REG (scntl2, SCR_OR, WSR),
2397                 0,
2398         SCR_JUMP,
2399                 PADDR (clrack),
2400         /*
2401         **      Load again the size to the sfbr register.
2402         */
2403         SCR_FROM_REG (scratcha),
2404                 0,
2405         SCR_INT,
2406                 SIR_IGN_RESIDUE,
2407         SCR_JUMP,
2408                 PADDR (clrack),
2409
2410 }/*-------------------------< MSG_EXTENDED >-------------*/,{
2411         /*
2412         **      Terminate cycle
2413         */
2414         SCR_CLR (SCR_ACK),
2415                 0,
2416         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2417                 PADDR (dispatch),
2418         /*
2419         **      get length.
2420         */
2421         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2422                 NADDR (msgin[1]),
2423         /*
2424         */
2425         SCR_JUMP ^ IFTRUE (DATA (3)),
2426                 PADDRH (msg_ext_3),
2427         SCR_JUMP ^ IFFALSE (DATA (2)),
2428                 PADDR (msg_bad),
2429 }/*-------------------------< MSG_EXT_2 >----------------*/,{
2430         SCR_CLR (SCR_ACK),
2431                 0,
2432         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2433                 PADDR (dispatch),
2434         /*
2435         **      get extended message code.
2436         */
2437         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2438                 NADDR (msgin[2]),
2439         SCR_JUMP ^ IFTRUE (DATA (M_X_WIDE_REQ)),
2440                 PADDRH (msg_wdtr),
2441         /*
2442         **      unknown extended message
2443         */
2444         SCR_JUMP,
2445                 PADDR (msg_bad)
2446 }/*-------------------------< MSG_WDTR >-----------------*/,{
2447         SCR_CLR (SCR_ACK),
2448                 0,
2449         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2450                 PADDR (dispatch),
2451         /*
2452         **      get data bus width
2453         */
2454         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2455                 NADDR (msgin[3]),
2456         /*
2457         **      let the host do the real work.
2458         */
2459         SCR_INT,
2460                 SIR_NEGO_WIDE,
2461         /*
2462         **      let the target fetch our answer.
2463         */
2464         SCR_SET (SCR_ATN),
2465                 0,
2466         SCR_CLR (SCR_ACK),
2467                 0,
2468         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2469                 PADDRH (nego_bad_phase),
2470
2471 }/*-------------------------< SEND_WDTR >----------------*/,{
2472         /*
2473         **      Send the M_X_WIDE_REQ
2474         */
2475         SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
2476                 NADDR (msgout),
2477         SCR_COPY (1),
2478                 NADDR (msgout),
2479                 NADDR (lastmsg),
2480         SCR_JUMP,
2481                 PADDR (msg_out_done),
2482
2483 }/*-------------------------< MSG_EXT_3 >----------------*/,{
2484         SCR_CLR (SCR_ACK),
2485                 0,
2486         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2487                 PADDR (dispatch),
2488         /*
2489         **      get extended message code.
2490         */
2491         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2492                 NADDR (msgin[2]),
2493         SCR_JUMP ^ IFTRUE (DATA (M_X_SYNC_REQ)),
2494                 PADDRH (msg_sdtr),
2495         /*
2496         **      unknown extended message
2497         */
2498         SCR_JUMP,
2499                 PADDR (msg_bad)
2500
2501 }/*-------------------------< MSG_SDTR >-----------------*/,{
2502         SCR_CLR (SCR_ACK),
2503                 0,
2504         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2505                 PADDR (dispatch),
2506         /*
2507         **      get period and offset
2508         */
2509         SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2510                 NADDR (msgin[3]),
2511         /*
2512         **      let the host do the real work.
2513         */
2514         SCR_INT,
2515                 SIR_NEGO_SYNC,
2516         /*
2517         **      let the target fetch our answer.
2518         */
2519         SCR_SET (SCR_ATN),
2520                 0,
2521         SCR_CLR (SCR_ACK),
2522                 0,
2523         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2524                 PADDRH (nego_bad_phase),
2525
2526 }/*-------------------------< SEND_SDTR >-------------*/,{
2527         /*
2528         **      Send the M_X_SYNC_REQ
2529         */
2530         SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
2531                 NADDR (msgout),
2532         SCR_COPY (1),
2533                 NADDR (msgout),
2534                 NADDR (lastmsg),
2535         SCR_JUMP,
2536                 PADDR (msg_out_done),
2537
2538 }/*-------------------------< NEGO_BAD_PHASE >------------*/,{
2539         SCR_INT,
2540                 SIR_NEGO_PROTO,
2541         SCR_JUMP,
2542                 PADDR (dispatch),
2543
2544 }/*-------------------------< MSG_OUT_ABORT >-------------*/,{
2545         /*
2546         **      After ABORT message,
2547         **
2548         **      expect an immediate disconnect, ...
2549         */
2550         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2551                 0,
2552         SCR_CLR (SCR_ACK|SCR_ATN),
2553                 0,
2554         SCR_WAIT_DISC,
2555                 0,
2556         /*
2557         **      ... and set the status to "ABORTED"
2558         */
2559         SCR_LOAD_REG (HS_REG, HS_ABORTED),
2560                 0,
2561         SCR_JUMP,
2562                 PADDR (cleanup),
2563
2564 }/*-------------------------< HDATA_IN >-------------------*/,{
2565 /*
2566 **      Because the size depends on the
2567 **      #define MAX_SCATTERH parameter,
2568 **      it is filled in at runtime.
2569 **
2570 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
2571 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2572 **  ||          PADDR (dispatch),
2573 **  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2574 **  ||          offsetof (struct dsb, data[ i]),
2575 **  ##===================================================
2576 **
2577 **---------------------------------------------------------
2578 */
2579 0
2580 }/*-------------------------< HDATA_IN2 >------------------*/,{
2581         SCR_JUMP,
2582                 PADDR (data_in),
2583
2584 }/*-------------------------< HDATA_OUT >-------------------*/,{
2585 /*
2586 **      Because the size depends on the
2587 **      #define MAX_SCATTERH parameter,
2588 **      it is filled in at runtime.
2589 **
2590 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
2591 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2592 **  ||          PADDR (dispatch),
2593 **  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2594 **  ||          offsetof (struct dsb, data[ i]),
2595 **  ##===================================================
2596 **
2597 **---------------------------------------------------------
2598 */
2599 0
2600 }/*-------------------------< HDATA_OUT2 >------------------*/,{
2601         SCR_JUMP,
2602                 PADDR (data_out),
2603
2604 }/*-------------------------< RESET >----------------------*/,{
2605         /*
2606         **      Send a M_RESET message if bad IDENTIFY 
2607         **      received on reselection.
2608         */
2609         SCR_LOAD_REG (scratcha, M_ABORT_TAG),
2610                 0,
2611         SCR_JUMP,
2612                 PADDRH (abort_resel),
2613 }/*-------------------------< ABORTTAG >-------------------*/,{
2614         /*
2615         **      Abort a wrong tag received on reselection.
2616         */
2617         SCR_LOAD_REG (scratcha, M_ABORT_TAG),
2618                 0,
2619         SCR_JUMP,
2620                 PADDRH (abort_resel),
2621 }/*-------------------------< ABORT >----------------------*/,{
2622         /*
2623         **      Abort a reselection when no active CCB.
2624         */
2625         SCR_LOAD_REG (scratcha, M_ABORT),
2626                 0,
2627 }/*-------------------------< ABORT_RESEL >----------------*/,{
2628         SCR_COPY (1),
2629                 RADDR (scratcha),
2630                 NADDR (msgout),
2631         SCR_SET (SCR_ATN),
2632                 0,
2633         SCR_CLR (SCR_ACK),
2634                 0,
2635         /*
2636         **      and send it.
2637         **      we expect an immediate disconnect
2638         */
2639         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2640                 0,
2641         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2642                 NADDR (msgout),
2643         SCR_COPY (1),
2644                 NADDR (msgout),
2645                 NADDR (lastmsg),
2646         SCR_CLR (SCR_ACK|SCR_ATN),
2647                 0,
2648         SCR_WAIT_DISC,
2649                 0,
2650         SCR_JUMP,
2651                 PADDR (start),
2652 }/*-------------------------< RESEND_IDENT >-------------------*/,{
2653         /*
2654         **      The target stays in MSG OUT phase after having acked 
2655         **      Identify [+ Tag [+ Extended message ]]. Targets shall
2656         **      behave this way on parity error.
2657         **      We must send it again all the messages.
2658         */
2659         SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
2660                 0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
2661         SCR_JUMP,
2662                 PADDR (send_ident),
2663 }/*-------------------------< CLRATN_GO_ON >-------------------*/,{
2664         SCR_CLR (SCR_ATN),
2665                 0,
2666         SCR_JUMP,
2667 }/*-------------------------< NXTDSP_GO_ON >-------------------*/,{
2668                 0,
2669 }/*-------------------------< SDATA_IN >-------------------*/,{
2670         SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2671                 PADDR (dispatch),
2672         SCR_MOVE_TBL ^ SCR_DATA_IN,
2673                 offsetof (struct dsb, sense),
2674         SCR_CALL,
2675                 PADDR (dispatch),
2676         SCR_JUMP,
2677                 PADDR (no_data),
2678 }/*-------------------------< DATA_IO >--------------------*/,{
2679         /*
2680         **      We jump here if the data direction was unknown at the 
2681         **      time we had to queue the command to the scripts processor.
2682         **      Pointers had been set as follow in this situation:
2683         **        savep   -->   DATA_IO
2684         **        lastp   -->   start pointer when DATA_IN
2685         **        goalp   -->   goal  pointer when DATA_IN
2686         **        wlastp  -->   start pointer when DATA_OUT
2687         **        wgoalp  -->   goal  pointer when DATA_OUT
2688         **      This script sets savep/lastp/goalp according to the 
2689         **      direction chosen by the target.
2690         */
2691         SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_OUT)),
2692                 32,
2693         /*
2694         **      Direction is DATA IN.
2695         **      Warning: we jump here, even when phase is DATA OUT.
2696         */
2697         SCR_COPY (4),
2698                 NADDR (header.lastp),
2699                 NADDR (header.savep),
2700
2701         /*
2702         **      Jump to the SCRIPTS according to actual direction.
2703         */
2704         SCR_COPY (4),
2705                 NADDR (header.savep),
2706                 RADDR (temp),
2707         SCR_RETURN,
2708                 0,
2709         /*
2710         **      Direction is DATA OUT.
2711         */
2712         SCR_COPY (4),
2713                 NADDR (header.wlastp),
2714                 NADDR (header.lastp),
2715         SCR_COPY (4),
2716                 NADDR (header.wgoalp),
2717                 NADDR (header.goalp),
2718         SCR_JUMPR,
2719                 -64,
2720 }/*-------------------------< BAD_IDENTIFY >---------------*/,{
2721         /*
2722         **      If message phase but not an IDENTIFY,
2723         **      get some help from the C code.
2724         **      Old SCSI device may behave so.
2725         */
2726         SCR_JUMPR ^ IFTRUE (MASK (0x80, 0x80)),
2727                 16,
2728         SCR_INT,
2729                 SIR_RESEL_NO_IDENTIFY,
2730         SCR_JUMP,
2731                 PADDRH (reset),
2732         /*
2733         **      Message is an IDENTIFY, but lun is unknown.
2734         **      Read the message, since we got it directly 
2735         **      from the SCSI BUS data lines.
2736         **      Signal problem to C code for logging the event.
2737         **      Send a M_ABORT to clear all pending tasks.
2738         */
2739         SCR_INT,
2740                 SIR_RESEL_BAD_LUN,
2741         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2742                 NADDR (msgin),
2743         SCR_JUMP,
2744                 PADDRH (abort),
2745 }/*-------------------------< BAD_I_T_L >------------------*/,{
2746         /*
2747         **      We donnot have a task for that I_T_L.
2748         **      Signal problem to C code for logging the event.
2749         **      Send a M_ABORT message.
2750         */
2751         SCR_INT,
2752                 SIR_RESEL_BAD_I_T_L,
2753         SCR_JUMP,
2754                 PADDRH (abort),
2755 }/*-------------------------< BAD_I_T_L_Q >----------------*/,{
2756         /*
2757         **      We donnot have a task that matches the tag.
2758         **      Signal problem to C code for logging the event.
2759         **      Send a M_ABORTTAG message.
2760         */
2761         SCR_INT,
2762                 SIR_RESEL_BAD_I_T_L_Q,
2763         SCR_JUMP,
2764                 PADDRH (aborttag),
2765 }/*-------------------------< BAD_TARGET >-----------------*/,{
2766         /*
2767         **      We donnot know the target that reselected us.
2768         **      Grab the first message if any (IDENTIFY).
2769         **      Signal problem to C code for logging the event.
2770         **      M_RESET message.
2771         */
2772         SCR_INT,
2773                 SIR_RESEL_BAD_TARGET,
2774         SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2775                 8,
2776         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2777                 NADDR (msgin),
2778         SCR_JUMP,
2779                 PADDRH (reset),
2780 }/*-------------------------< BAD_STATUS >-----------------*/,{
2781         /*
2782         **      If command resulted in either QUEUE FULL,
2783         **      CHECK CONDITION or COMMAND TERMINATED,
2784         **      call the C code.
2785         */
2786         SCR_INT ^ IFTRUE (DATA (S_QUEUE_FULL)),
2787                 SIR_BAD_STATUS,
2788         SCR_INT ^ IFTRUE (DATA (S_CHECK_COND)),
2789                 SIR_BAD_STATUS,
2790         SCR_INT ^ IFTRUE (DATA (S_TERMINATED)),
2791                 SIR_BAD_STATUS,
2792         SCR_RETURN,
2793                 0,
2794 }/*-------------------------< START_RAM >-------------------*/,{
2795         /*
2796         **      Load the script into on-chip RAM, 
2797         **      and jump to start point.
2798         */
2799         SCR_COPY_F (4),
2800                 RADDR (scratcha),
2801                 PADDRH (start_ram0),
2802         /*
2803         **      Flush script prefetch if required
2804         */
2805         PREFETCH_FLUSH
2806         SCR_COPY (sizeof (struct script)),
2807 }/*-------------------------< START_RAM0 >--------------------*/,{
2808                 0,
2809                 PADDR (start),
2810         SCR_JUMP,
2811                 PADDR (start),
2812 }/*-------------------------< STO_RESTART >-------------------*/,{
2813         /*
2814         **
2815         **      Repair start queue (e.g. next time use the next slot) 
2816         **      and jump to start point.
2817         */
2818         SCR_COPY (4),
2819                 RADDR (temp),
2820                 PADDR (startpos),
2821         SCR_JUMP,
2822                 PADDR (start),
2823 }/*-------------------------< WAIT_DMA >-------------------*/,{
2824         /*
2825         **      For HP Zalon/53c720 systems, the Zalon interface
2826         **      between CPU and 53c720 does prefetches, which causes
2827         **      problems with self modifying scripts.  The problem
2828         **      is overcome by calling a dummy subroutine after each
2829         **      modification, to force a refetch of the script on
2830         **      return from the subroutine.
2831         */
2832         SCR_RETURN,
2833                 0,
2834 }/*-------------------------< SNOOPTEST >-------------------*/,{
2835         /*
2836         **      Read the variable.
2837         */
2838         SCR_COPY (4),
2839                 NADDR(ncr_cache),
2840                 RADDR (scratcha),
2841         /*
2842         **      Write the variable.
2843         */
2844         SCR_COPY (4),
2845                 RADDR (temp),
2846                 NADDR(ncr_cache),
2847         /*
2848         **      Read back the variable.
2849         */
2850         SCR_COPY (4),
2851                 NADDR(ncr_cache),
2852                 RADDR (temp),
2853 }/*-------------------------< SNOOPEND >-------------------*/,{
2854         /*
2855         **      And stop.
2856         */
2857         SCR_INT,
2858                 99,
2859 }/*--------------------------------------------------------*/
2860 };
2861
2862 /*==========================================================
2863 **
2864 **
2865 **      Fill in #define dependent parts of the script
2866 **
2867 **
2868 **==========================================================
2869 */
2870
2871 void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
2872 {
2873         int     i;
2874         ncrcmd  *p;
2875
2876         p = scrh->tryloop;
2877         for (i=0; i<MAX_START; i++) {
2878                 *p++ =SCR_CALL;
2879                 *p++ =PADDR (idle);
2880         };
2881
2882         assert ((u_long)p == (u_long)&scrh->tryloop + sizeof (scrh->tryloop));
2883
2884 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
2885
2886         p = scrh->done_queue;
2887         for (i = 0; i<MAX_DONE; i++) {
2888                 *p++ =SCR_COPY (sizeof(ccb_p));
2889                 *p++ =NADDR (header.cp);
2890                 *p++ =NADDR (ccb_done[i]);
2891                 *p++ =SCR_CALL;
2892                 *p++ =PADDR (done_end);
2893         }
2894
2895         assert ((u_long)p ==(u_long)&scrh->done_queue+sizeof(scrh->done_queue));
2896
2897 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2898
2899         p = scrh->hdata_in;
2900         for (i=0; i<MAX_SCATTERH; i++) {
2901                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
2902                 *p++ =PADDR (dispatch);
2903                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2904                 *p++ =offsetof (struct dsb, data[i]);
2905         };
2906         assert ((u_long)p == (u_long)&scrh->hdata_in + sizeof (scrh->hdata_in));
2907
2908         p = scr->data_in;
2909         for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
2910                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
2911                 *p++ =PADDR (dispatch);
2912                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2913                 *p++ =offsetof (struct dsb, data[i]);
2914         };
2915         assert ((u_long)p == (u_long)&scr->data_in + sizeof (scr->data_in));
2916
2917         p = scrh->hdata_out;
2918         for (i=0; i<MAX_SCATTERH; i++) {
2919                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
2920                 *p++ =PADDR (dispatch);
2921                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
2922                 *p++ =offsetof (struct dsb, data[i]);
2923         };
2924         assert ((u_long)p==(u_long)&scrh->hdata_out + sizeof (scrh->hdata_out));
2925
2926         p = scr->data_out;
2927         for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
2928                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
2929                 *p++ =PADDR (dispatch);
2930                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
2931                 *p++ =offsetof (struct dsb, data[i]);
2932         };
2933
2934         assert ((u_long)p == (u_long)&scr->data_out + sizeof (scr->data_out));
2935 }
2936
2937 /*==========================================================
2938 **
2939 **
2940 **      Copy and rebind a script.
2941 **
2942 **
2943 **==========================================================
2944 */
2945
2946 static void __init 
2947 ncr_script_copy_and_bind (ncb_p np, ncrcmd *src, ncrcmd *dst, int len)
2948 {
2949         ncrcmd  opcode, new, old, tmp1, tmp2;
2950         ncrcmd  *start, *end;
2951         int relocs;
2952         int opchanged = 0;
2953
2954         start = src;
2955         end = src + len/4;
2956
2957         while (src < end) {
2958
2959                 opcode = *src++;
2960                 *dst++ = cpu_to_scr(opcode);
2961
2962                 /*
2963                 **      If we forget to change the length
2964                 **      in struct script, a field will be
2965                 **      padded with 0. This is an illegal
2966                 **      command.
2967                 */
2968
2969                 if (opcode == 0) {
2970                         printk (KERN_ERR "%s: ERROR0 IN SCRIPT at %d.\n",
2971                                 ncr_name(np), (int) (src-start-1));
2972                         MDELAY (1000);
2973                 };
2974
2975                 if (DEBUG_FLAGS & DEBUG_SCRIPT)
2976                         printk (KERN_DEBUG "%p:  <%x>\n",
2977                                 (src-1), (unsigned)opcode);
2978
2979                 /*
2980                 **      We don't have to decode ALL commands
2981                 */
2982                 switch (opcode >> 28) {
2983
2984                 case 0xc:
2985                         /*
2986                         **      COPY has TWO arguments.
2987                         */
2988                         relocs = 2;
2989                         tmp1 = src[0];
2990 #ifdef  RELOC_KVAR
2991                         if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
2992                                 tmp1 = 0;
2993 #endif
2994                         tmp2 = src[1];
2995 #ifdef  RELOC_KVAR
2996                         if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
2997                                 tmp2 = 0;
2998 #endif
2999                         if ((tmp1 ^ tmp2) & 3) {
3000                                 printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
3001                                         ncr_name(np), (int) (src-start-1));
3002                                 MDELAY (1000);
3003                         }
3004                         /*
3005                         **      If PREFETCH feature not enabled, remove 
3006                         **      the NO FLUSH bit if present.
3007                         */
3008                         if ((opcode & SCR_NO_FLUSH) && !(np->features & FE_PFEN)) {
3009                                 dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3010                                 ++opchanged;
3011                         }
3012                         break;
3013
3014                 case 0x0:
3015                         /*
3016                         **      MOVE (absolute address)
3017                         */
3018                         relocs = 1;
3019                         break;
3020
3021                 case 0x8:
3022                         /*
3023                         **      JUMP / CALL
3024                         **      don't relocate if relative :-)
3025                         */
3026                         if (opcode & 0x00800000)
3027                                 relocs = 0;
3028                         else
3029                                 relocs = 1;
3030                         break;
3031
3032                 case 0x4:
3033                 case 0x5:
3034                 case 0x6:
3035                 case 0x7:
3036                         relocs = 1;
3037                         break;
3038
3039                 default:
3040                         relocs = 0;
3041                         break;
3042                 };
3043
3044                 if (relocs) {
3045                         while (relocs--) {
3046                                 old = *src++;
3047
3048                                 switch (old & RELOC_MASK) {
3049                                 case RELOC_REGISTER:
3050                                         new = (old & ~RELOC_MASK) + np->paddr;
3051                                         break;
3052                                 case RELOC_LABEL:
3053                                         new = (old & ~RELOC_MASK) + np->p_script;
3054                                         break;
3055                                 case RELOC_LABELH:
3056                                         new = (old & ~RELOC_MASK) + np->p_scripth;
3057                                         break;
3058                                 case RELOC_SOFTC:
3059                                         new = (old & ~RELOC_MASK) + np->p_ncb;
3060                                         break;
3061 #ifdef  RELOC_KVAR
3062                                 case RELOC_KVAR:
3063                                         if (((old & ~RELOC_MASK) <
3064                                              SCRIPT_KVAR_FIRST) ||
3065                                             ((old & ~RELOC_MASK) >
3066                                              SCRIPT_KVAR_LAST))
3067                                                 panic("ncr KVAR out of range");
3068                                         new = vtophys(script_kvars[old &
3069                                             ~RELOC_MASK]);
3070                                         break;
3071 #endif
3072                                 case 0:
3073                                         /* Don't relocate a 0 address. */
3074                                         if (old == 0) {
3075                                                 new = old;
3076                                                 break;
3077                                         }
3078                                         /* fall through */
3079                                 default:
3080                                         panic("ncr_script_copy_and_bind: weird relocation %x\n", old);
3081                                         break;
3082                                 }
3083
3084                                 *dst++ = cpu_to_scr(new);
3085                         }
3086                 } else
3087                         *dst++ = cpu_to_scr(*src++);
3088
3089         };
3090 }
3091
3092 /*==========================================================
3093 **
3094 **
3095 **      Auto configuration:  attach and init a host adapter.
3096 **
3097 **
3098 **==========================================================
3099 */
3100
3101 /*
3102 **      Linux host data structure
3103 **
3104 **      The script area is allocated in the host data structure
3105 **      because kmalloc() returns NULL during scsi initialisations
3106 **      with Linux 1.2.X
3107 */
3108
3109 struct host_data {
3110      struct ncb *ncb;
3111 };
3112
3113 /*
3114 **      Print something which allows to retrieve the controller type, unit,
3115 **      target, lun concerned by a kernel message.
3116 */
3117
3118 static void PRINT_TARGET(ncb_p np, int target)
3119 {
3120         printk(KERN_INFO "%s-<%d,*>: ", ncr_name(np), target);
3121 }
3122
3123 static void PRINT_LUN(ncb_p np, int target, int lun)
3124 {
3125         printk(KERN_INFO "%s-<%d,%d>: ", ncr_name(np), target, lun);
3126 }
3127
3128 static void PRINT_ADDR(Scsi_Cmnd *cmd)
3129 {
3130         struct host_data *host_data = (struct host_data *) cmd->device->host->hostdata;
3131         PRINT_LUN(host_data->ncb, cmd->device->id, cmd->device->lun);
3132 }
3133
3134 /*==========================================================
3135 **
3136 **      NCR chip clock divisor table.
3137 **      Divisors are multiplied by 10,000,000 in order to make 
3138 **      calculations more simple.
3139 **
3140 **==========================================================
3141 */
3142
3143 #define _5M 5000000
3144 static u_long div_10M[] =
3145         {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3146
3147
3148 /*===============================================================
3149 **
3150 **      Prepare io register values used by ncr_init() according 
3151 **      to selected and supported features.
3152 **
3153 **      NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128 
3154 **      transfers. 32,64,128 are only supported by 875 and 895 chips.
3155 **      We use log base 2 (burst length) as internal code, with 
3156 **      value 0 meaning "burst disabled".
3157 **
3158 **===============================================================
3159 */
3160
3161 /*
3162  *      Burst length from burst code.
3163  */
3164 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3165
3166 /*
3167  *      Burst code from io register bits.  Burst enable is ctest0 for c720,
3168  *      ctest4 for others.
3169  */
3170 #define burst_code(dmode, ctest0, ctest4, ctest5) \
3171         (np->device_id == PSEUDO_720_ID) ? \
3172         (ctest0) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + 1 : \
3173         (ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
3174
3175 /*
3176  *      Set initial io register bits from burst code.
3177  */
3178 static inline void ncr_init_burst(ncb_p np, u_char bc)
3179 {
3180         u_char *be = (np->device_id == PSEUDO_720_ID) ?
3181                 &np->rv_ctest0 : &np->rv_ctest4;
3182         *be             &= ~0x80;
3183         np->rv_dmode    &= ~(0x3 << 6);
3184         np->rv_ctest5   &= ~0x4;
3185
3186         if (!bc) {
3187                 *be             |= 0x80;
3188         }
3189         else {
3190                 --bc;
3191                 np->rv_dmode    |= ((bc & 0x3) << 6);
3192                 np->rv_ctest5   |= (bc & 0x4);
3193         }
3194 }
3195
3196 #ifdef SCSI_NCR_NVRAM_SUPPORT
3197
3198 /*
3199 **      Get target set-up from Symbios format NVRAM.
3200 */
3201
3202 static void __init 
3203 ncr_Symbios_setup_target(ncb_p np, int target, Symbios_nvram *nvram)
3204 {
3205         tcb_p tp = &np->target[target];
3206         Symbios_target *tn = &nvram->target[target];
3207
3208         tp->usrsync = tn->sync_period ? (tn->sync_period + 3) / 4 : 255;
3209         tp->usrwide = tn->bus_width == 0x10 ? 1 : 0;
3210         tp->usrtags =
3211                 (tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? MAX_TAGS : 0;
3212
3213         if (!(tn->flags & SYMBIOS_DISCONNECT_ENABLE))
3214                 tp->usrflag |= UF_NODISC;
3215         if (!(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME))
3216                 tp->usrflag |= UF_NOSCAN;
3217 }
3218
3219 /*
3220 **      Get target set-up from Tekram format NVRAM.
3221 */
3222
3223 static void __init 
3224 ncr_Tekram_setup_target(ncb_p np, int target, Tekram_nvram *nvram)
3225 {
3226         tcb_p tp = &np->target[target];
3227         struct Tekram_target *tn = &nvram->target[target];
3228         int i;
3229
3230         if (tn->flags & TEKRAM_SYNC_NEGO) {
3231                 i = tn->sync_index & 0xf;
3232                 tp->usrsync = Tekram_sync[i];
3233         }
3234
3235         tp->usrwide = (tn->flags & TEKRAM_WIDE_NEGO) ? 1 : 0;
3236
3237         if (tn->flags & TEKRAM_TAGGED_COMMANDS) {
3238                 tp->usrtags = 2 << nvram->max_tags_index;
3239         }
3240
3241         if (!(tn->flags & TEKRAM_DISCONNECT_ENABLE))
3242                 tp->usrflag = UF_NODISC;
3243  
3244         /* If any device does not support parity, we will not use this option */
3245         if (!(tn->flags & TEKRAM_PARITY_CHECK))
3246                 np->rv_scntl0  &= ~0x0a; /* SCSI parity checking disabled */
3247 }
3248 #endif /* SCSI_NCR_NVRAM_SUPPORT */
3249
3250 static int __init ncr_prepare_setting(ncb_p np, ncr_nvram *nvram)
3251 {
3252         u_char  burst_max;
3253         u_long  period;
3254         int i;
3255
3256         /*
3257         **      Save assumed BIOS setting
3258         */
3259
3260         np->sv_scntl0   = INB(nc_scntl0) & 0x0a;
3261         np->sv_scntl3   = INB(nc_scntl3) & 0x07;
3262         np->sv_dmode    = INB(nc_dmode)  & 0xce;
3263         np->sv_dcntl    = INB(nc_dcntl)  & 0xa8;
3264         np->sv_ctest0   = INB(nc_ctest0) & 0x84;
3265         np->sv_ctest3   = INB(nc_ctest3) & 0x01;
3266         np->sv_ctest4   = INB(nc_ctest4) & 0x80;
3267         np->sv_ctest5   = INB(nc_ctest5) & 0x24;
3268         np->sv_gpcntl   = INB(nc_gpcntl);
3269         np->sv_stest2   = INB(nc_stest2) & 0x20;
3270         np->sv_stest4   = INB(nc_stest4);
3271
3272         /*
3273         **      Wide ?
3274         */
3275
3276         np->maxwide     = (np->features & FE_WIDE)? 1 : 0;
3277
3278         /*
3279          *  Guess the frequency of the chip's clock.
3280          */
3281         if      (np->features & (FE_ULTRA3 | FE_ULTRA2))
3282                 np->clock_khz = 160000;
3283         else if (np->features & FE_ULTRA)
3284                 np->clock_khz = 80000;
3285         else
3286                 np->clock_khz = 40000;
3287
3288         /*
3289          *  Get the clock multiplier factor.
3290          */
3291         if      (np->features & FE_QUAD)
3292                 np->multiplier  = 4;
3293         else if (np->features & FE_DBLR)
3294                 np->multiplier  = 2;
3295         else
3296                 np->multiplier  = 1;
3297
3298         /*
3299          *  Measure SCSI clock frequency for chips 
3300          *  it may vary from assumed one.
3301          */
3302         if (np->features & FE_VARCLK)
3303                 ncr_getclock(np, np->multiplier);
3304
3305         /*
3306          * Divisor to be used for async (timer pre-scaler).
3307          */
3308         i = np->clock_divn - 1;
3309         while (--i >= 0) {
3310                 if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3311                         ++i;
3312                         break;
3313                 }
3314         }
3315         np->rv_scntl3 = i+1;
3316
3317         /*
3318          * Minimum synchronous period factor supported by the chip.
3319          * Btw, 'period' is in tenths of nanoseconds.
3320          */
3321
3322         period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3323         if      (period <= 250)         np->minsync = 10;
3324         else if (period <= 303)         np->minsync = 11;
3325         else if (period <= 500)         np->minsync = 12;
3326         else                            np->minsync = (period + 40 - 1) / 40;
3327
3328         /*
3329          * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3330          */
3331
3332         if      (np->minsync < 25 && !(np->features & (FE_ULTRA|FE_ULTRA2)))
3333                 np->minsync = 25;
3334         else if (np->minsync < 12 && !(np->features & FE_ULTRA2))
3335                 np->minsync = 12;
3336
3337         /*
3338          * Maximum synchronous period factor supported by the chip.
3339          */
3340
3341         period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3342         np->maxsync = period > 2540 ? 254 : period / 10;
3343
3344         /*
3345         **      Prepare initial value of other IO registers
3346         */
3347 #if defined SCSI_NCR_TRUST_BIOS_SETTING
3348         np->rv_scntl0   = np->sv_scntl0;
3349         np->rv_dmode    = np->sv_dmode;
3350         np->rv_dcntl    = np->sv_dcntl;
3351         np->rv_ctest0   = np->sv_ctest0;
3352         np->rv_ctest3   = np->sv_ctest3;
3353         np->rv_ctest4   = np->sv_ctest4;
3354         np->rv_ctest5   = np->sv_ctest5;
3355         burst_max       = burst_code(np->sv_dmode, np->sv_ctest0, np->sv_ctest4, np->sv_ctest5);
3356 #else
3357
3358         /*
3359         **      Select burst length (dwords)
3360         */
3361         burst_max       = driver_setup.burst_max;
3362         if (burst_max == 255)
3363                 burst_max = burst_code(np->sv_dmode, np->sv_ctest0, np->sv_ctest4, np->sv_ctest5);
3364         if (burst_max > 7)
3365                 burst_max = 7;
3366         if (burst_max > np->maxburst)
3367                 burst_max = np->maxburst;
3368
3369         /*
3370         **      Select all supported special features
3371         */
3372         if (np->features & FE_ERL)
3373                 np->rv_dmode    |= ERL;         /* Enable Read Line */
3374         if (np->features & FE_BOF)
3375                 np->rv_dmode    |= BOF;         /* Burst Opcode Fetch */
3376         if (np->features & FE_ERMP)
3377                 np->rv_dmode    |= ERMP;        /* Enable Read Multiple */
3378         if (np->features & FE_PFEN)
3379                 np->rv_dcntl    |= PFEN;        /* Prefetch Enable */
3380         if (np->features & FE_CLSE)
3381                 np->rv_dcntl    |= CLSE;        /* Cache Line Size Enable */
3382         if (np->features & FE_WRIE)
3383                 np->rv_ctest3   |= WRIE;        /* Write and Invalidate */
3384         if (np->features & FE_DFS)
3385                 np->rv_ctest5   |= DFS;         /* Dma Fifo Size */
3386         if (np->features & FE_MUX)
3387                 np->rv_ctest4   |= MUX;         /* Host bus multiplex mode */
3388         if (np->features & FE_EA)
3389                 np->rv_dcntl    |= EA;          /* Enable ACK */
3390         if (np->features & FE_EHP)
3391                 np->rv_ctest0   |= EHP;         /* Even host parity */
3392
3393         /*
3394         **      Select some other
3395         */
3396         if (driver_setup.master_parity)
3397                 np->rv_ctest4   |= MPEE;        /* Master parity checking */
3398         if (driver_setup.scsi_parity)
3399                 np->rv_scntl0   |= 0x0a;        /*  full arb., ena parity, par->ATN  */
3400
3401 #ifdef SCSI_NCR_NVRAM_SUPPORT
3402         /*
3403         **      Get parity checking, host ID and verbose mode from NVRAM
3404         **/
3405         if (nvram) {
3406                 switch(nvram->type) {
3407                 case SCSI_NCR_TEKRAM_NVRAM:
3408                         np->myaddr = nvram->data.Tekram.host_id & 0x0f;
3409                         break;
3410                 case SCSI_NCR_SYMBIOS_NVRAM:
3411                         if (!(nvram->data.Symbios.flags & SYMBIOS_PARITY_ENABLE))
3412                                 np->rv_scntl0  &= ~0x0a;
3413                         np->myaddr = nvram->data.Symbios.host_id & 0x0f;
3414                         if (nvram->data.Symbios.flags & SYMBIOS_VERBOSE_MSGS)
3415                                 np->verbose += 1;
3416                         break;
3417                 }
3418         }
3419 #endif
3420         /*
3421         **  Get SCSI addr of host adapter (set by bios?).
3422         */
3423         if (np->myaddr == 255) {
3424                 np->myaddr = INB(nc_scid) & 0x07;
3425                 if (!np->myaddr)
3426                         np->myaddr = SCSI_NCR_MYADDR;
3427         }
3428
3429 #endif /* SCSI_NCR_TRUST_BIOS_SETTING */
3430
3431         /*
3432          *      Prepare initial io register bits for burst length
3433          */
3434         ncr_init_burst(np, burst_max);
3435
3436         /*
3437         **      Set SCSI BUS mode.
3438         **
3439         **      - ULTRA2 chips (895/895A/896) report the current 
3440         **        BUS mode through the STEST4 IO register.
3441         **      - For previous generation chips (825/825A/875), 
3442         **        user has to tell us how to check against HVD, 
3443         **        since a 100% safe algorithm is not possible.
3444         */
3445         np->scsi_mode = SMODE_SE;
3446         if      (np->features & FE_ULTRA2)
3447                 np->scsi_mode = (np->sv_stest4 & SMODE);
3448         else if (np->features & FE_DIFF) {
3449                 switch(driver_setup.diff_support) {
3450                 case 4: /* Trust previous settings if present, then GPIO3 */
3451                         if (np->sv_scntl3) {
3452                                 if (np->sv_stest2 & 0x20)
3453                                         np->scsi_mode = SMODE_HVD;
3454                                 break;
3455                         }
3456                 case 3: /* SYMBIOS controllers report HVD through GPIO3 */
3457                         if (nvram && nvram->type != SCSI_NCR_SYMBIOS_NVRAM)
3458                                 break;
3459                         if (INB(nc_gpreg) & 0x08)
3460                                 break;
3461                 case 2: /* Set HVD unconditionally */
3462                         np->scsi_mode = SMODE_HVD;
3463                 case 1: /* Trust previous settings for HVD */
3464                         if (np->sv_stest2 & 0x20)
3465                                 np->scsi_mode = SMODE_HVD;
3466                         break;
3467                 default:/* Don't care about HVD */      
3468                         break;
3469                 }
3470         }
3471         if (np->scsi_mode == SMODE_HVD)
3472                 np->rv_stest2 |= 0x20;
3473
3474         /*
3475         **      Set LED support from SCRIPTS.
3476         **      Ignore this feature for boards known to use a 
3477         **      specific GPIO wiring and for the 895A or 896 
3478         **      that drive the LED directly.
3479         **      Also probe initial setting of GPIO0 as output.
3480         */
3481         if ((driver_setup.led_pin ||
3482              (nvram && nvram->type == SCSI_NCR_SYMBIOS_NVRAM)) &&
3483             !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
3484                 np->features |= FE_LED0;
3485
3486         /*
3487         **      Set irq mode.
3488         */
3489         switch(driver_setup.irqm & 3) {
3490         case 2:
3491                 np->rv_dcntl    |= IRQM;
3492                 break;
3493         case 1:
3494                 np->rv_dcntl    |= (np->sv_dcntl & IRQM);
3495                 break;
3496         default:
3497                 break;
3498         }
3499
3500         /*
3501         **      Configure targets according to driver setup.
3502         **      If NVRAM present get targets setup from NVRAM.
3503         **      Allow to override sync, wide and NOSCAN from 
3504         **      boot command line.
3505         */
3506         for (i = 0 ; i < MAX_TARGET ; i++) {
3507                 tcb_p tp = &np->target[i];
3508
3509                 tp->usrsync = 255;
3510 #ifdef SCSI_NCR_NVRAM_SUPPORT
3511                 if (nvram) {
3512                         switch(nvram->type) {
3513                         case SCSI_NCR_TEKRAM_NVRAM:
3514                                 ncr_Tekram_setup_target(np, i, &nvram->data.Tekram);
3515                                 break;
3516                         case SCSI_NCR_SYMBIOS_NVRAM:
3517                                 ncr_Symbios_setup_target(np, i, &nvram->data.Symbios);
3518                                 break;
3519                         }
3520                         if (driver_setup.use_nvram & 0x2)
3521                                 tp->usrsync = driver_setup.default_sync;
3522                         if (driver_setup.use_nvram & 0x4)
3523                                 tp->usrwide = driver_setup.max_wide;
3524                         if (driver_setup.use_nvram & 0x8)
3525                                 tp->usrflag &= ~UF_NOSCAN;
3526                 }
3527                 else {
3528 #else
3529                 if (1) {
3530 #endif
3531                         tp->usrsync = driver_setup.default_sync;
3532                         tp->usrwide = driver_setup.max_wide;
3533                         tp->usrtags = MAX_TAGS;
3534                         if (!driver_setup.disconnection)
3535                                 np->target[i].usrflag = UF_NODISC;
3536                 }
3537         }
3538
3539         /*
3540         **      Announce all that stuff to user.
3541         */
3542
3543         i = nvram ? nvram->type : 0;
3544         printk(KERN_INFO "%s: %sID %d, Fast-%d%s%s\n", ncr_name(np),
3545                 i  == SCSI_NCR_SYMBIOS_NVRAM ? "Symbios format NVRAM, " :
3546                 (i == SCSI_NCR_TEKRAM_NVRAM  ? "Tekram format NVRAM, " : ""),
3547                 np->myaddr,
3548                 np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10),
3549                 (np->rv_scntl0 & 0xa)   ? ", Parity Checking"   : ", NO Parity",
3550                 (np->rv_stest2 & 0x20)  ? ", Differential"      : "");
3551
3552         if (bootverbose > 1) {
3553                 printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3554                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3555                         ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
3556                         np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
3557
3558                 printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3559                         "(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3560                         ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
3561                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
3562         }
3563
3564         if (bootverbose && np->paddr2)
3565                 printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
3566                         ncr_name(np), np->paddr2);
3567
3568         return 0;
3569 }
3570
3571 /*
3572 **      Host attach and initialisations.
3573 **
3574 **      Allocate host data and ncb structure.
3575 **      Request IO region and remap MMIO region.
3576 **      Do chip initialization.
3577 **      If all is OK, install interrupt handling and
3578 **      start the timer daemon.
3579 */
3580
3581 struct Scsi_Host * __init 
3582 ncr_attach (Scsi_Host_Template *tpnt, int unit, struct ncr_device *device)
3583 {
3584         struct host_data *host_data;
3585         ncb_p np = 0;
3586         struct Scsi_Host *instance = 0;
3587         u_long flags = 0;
3588         ncr_nvram *nvram = device->nvram;
3589         int i;
3590
3591 #ifdef SCSI_NCR_PROC_INFO_SUPPORT
3592         tpnt->proc_info         = ncr53c8xx_proc_info,
3593 #endif
3594         tpnt->info              = ncr53c8xx_info;
3595         tpnt->queuecommand      = ncr53c8xx_queue_command;
3596         tpnt->slave_configure   = ncr53c8xx_slave_configure;
3597         tpnt->eh_bus_reset_handler      = ncr53c8xx_bus_reset;
3598         tpnt->can_queue         = SCSI_NCR_CAN_QUEUE;
3599         tpnt->this_id           = 7;
3600         tpnt->sg_tablesize      = SCSI_NCR_SG_TABLESIZE;
3601         tpnt->cmd_per_lun       = SCSI_NCR_CMD_PER_LUN;
3602         tpnt->use_clustering    = DISABLE_CLUSTERING;
3603
3604         if(device->differential)
3605                 driver_setup.diff_support = device->differential;
3606
3607         printk(KERN_INFO "ncr53c%s-%d: rev 0x%x on bus %d device %d function %d irq %d\n",
3608                 device->chip.name, unit, device->chip.revision_id,
3609                 device->slot.bus, (device->slot.device_fn & 0xf8) >> 3,
3610                 device->slot.device_fn & 7,
3611                 device->slot.irq);
3612
3613         /*
3614         **      Allocate host_data structure
3615         */
3616         if (!(instance = scsi_host_alloc(tpnt, sizeof(*host_data))))
3617                 goto attach_error;
3618         host_data = (struct host_data *) instance->hostdata;
3619
3620         /*
3621         **      Allocate the host control block.
3622         */
3623         np = __m_calloc_dma(device->dev, sizeof(struct ncb), "NCB");
3624         if (!np)
3625                 goto attach_error;
3626         NCR_INIT_LOCK_NCB(np);
3627         np->dev  = device->dev;
3628         np->p_ncb = vtobus(np);
3629         host_data->ncb = np;
3630
3631         /*
3632         **      Allocate the default CCB.
3633         */
3634         np->ccb = (ccb_p) m_calloc_dma(sizeof(struct ccb), "CCB");
3635         if (!np->ccb)
3636                 goto attach_error;
3637
3638         /*
3639         **      Store input informations in the host data structure.
3640         */
3641         strlcpy(np->chip_name, device->chip.name, sizeof(np->chip_name));
3642         np->unit        = unit;
3643         np->verbose     = driver_setup.verbose;
3644         sprintf(np->inst_name, "ncr53c%s-%d", np->chip_name, np->unit);
3645         np->device_id   = device->chip.device_id;
3646         np->revision_id = device->chip.revision_id;
3647         np->bus         = device->slot.bus;
3648         np->device_fn   = device->slot.device_fn;
3649         np->features    = device->chip.features;
3650         np->clock_divn  = device->chip.nr_divisor;
3651         np->maxoffs     = device->chip.offset_max;
3652         np->maxburst    = device->chip.burst_max;
3653         np->myaddr      = device->host_id;
3654
3655         /*
3656         **      Allocate SCRIPTS areas.
3657         */
3658         np->script0  = (struct script *)
3659                         m_calloc_dma(sizeof(struct script), "SCRIPT");
3660         if (!np->script0)
3661                 goto attach_error;
3662         np->scripth0  = (struct scripth *)
3663                         m_calloc_dma(sizeof(struct scripth), "SCRIPTH");
3664         if (!np->scripth0)
3665                 goto attach_error;
3666
3667         /*
3668         **    Initialize timer structure
3669         **
3670         */
3671         init_timer(&np->timer);
3672         np->timer.data     = (unsigned long) np;
3673         np->timer.function = ncr53c8xx_timeout;
3674
3675         /*
3676         **      Try to map the controller chip to
3677         **      virtual and physical memory.
3678         */
3679
3680         np->paddr       = device->slot.base;
3681         np->paddr2      = (np->features & FE_RAM)? device->slot.base_2 : 0;
3682
3683 #ifndef SCSI_NCR_IOMAPPED
3684         if(device->slot.base_v)
3685                 np->vaddr = device->slot.base_v;
3686         else
3687                 np->vaddr = (unsigned long)ioremap(device->slot.base_c, 128);
3688
3689         if (!np->vaddr) {
3690                 printk(KERN_ERR
3691                         "%s: can't map memory mapped IO region\n",ncr_name(np));
3692                 goto attach_error;
3693         }
3694         else
3695                 if (bootverbose > 1)
3696                         printk(KERN_INFO
3697                                 "%s: using memory mapped IO at virtual address 0x%lx\n", ncr_name(np), (u_long) np->vaddr);
3698
3699         /*
3700         **      Make the controller's registers available.
3701         **      Now the INB INW INL OUTB OUTW OUTL macros
3702         **      can be used safely.
3703         */
3704
3705         np->reg = (struct ncr_reg*) np->vaddr;
3706
3707 #else
3708
3709         /*
3710         **      Try to map the controller chip into iospace.
3711         */
3712
3713         np->base_io = device->slot.io_port;
3714 #endif /* !defined SCSI_NCR_IOMAPPED */
3715
3716 #ifdef SCSI_NCR_NVRAM_SUPPORT
3717         if (nvram) {
3718                 switch(nvram->type) {
3719                 case SCSI_NCR_SYMBIOS_NVRAM:
3720 #ifdef SCSI_NCR_DEBUG_NVRAM
3721                         ncr_display_Symbios_nvram(&nvram->data.Symbios);
3722 #endif
3723                         break;
3724                 case SCSI_NCR_TEKRAM_NVRAM:
3725 #ifdef SCSI_NCR_DEBUG_NVRAM
3726                         ncr_display_Tekram_nvram(&nvram->data.Tekram);
3727 #endif
3728                         break;
3729                 default:
3730                         nvram = 0;
3731 #ifdef SCSI_NCR_DEBUG_NVRAM
3732                         printk(KERN_DEBUG "%s: NVRAM: None or invalid data.\n", ncr_name(np));
3733 #endif
3734                 }
3735         }
3736 #endif
3737
3738         /*
3739         **      Do chip dependent initialization.
3740         */
3741         (void)ncr_prepare_setting(np, nvram);
3742
3743         if (np->paddr2 && sizeof(struct script) > 4096) {
3744                 np->paddr2 = 0;
3745                 printk(KERN_WARNING "%s: script too large, NOT using on chip RAM.\n",
3746                         ncr_name(np));
3747         }
3748
3749         /*
3750         **      Fill Linux host instance structure
3751         */
3752         instance->max_channel   = 0;
3753         instance->this_id       = np->myaddr;
3754         instance->max_id        = np->maxwide ? 16 : 8;
3755         instance->max_lun       = SCSI_NCR_MAX_LUN;
3756 #ifndef SCSI_NCR_IOMAPPED
3757         instance->base          = (unsigned long) np->reg;
3758 #endif
3759         instance->irq           = device->slot.irq;
3760         instance->unique_id     = device->slot.io_port;
3761         instance->io_port       = device->slot.io_port;
3762         instance->n_io_port     = 128;
3763         instance->dma_channel   = 0;
3764         instance->cmd_per_lun   = MAX_TAGS;
3765         instance->can_queue     = (MAX_START-4);
3766         scsi_set_device(instance, device->dev);
3767
3768 #ifdef SCSI_NCR_INTEGRITY_CHECKING
3769         np->check_integrity       = 0;
3770         instance->check_integrity = 0;
3771
3772 #ifdef SCSI_NCR_ENABLE_INTEGRITY_CHECK
3773         if ( !(driver_setup.bus_check & 0x04) ) {
3774                 np->check_integrity       = 1;
3775                 instance->check_integrity = 1;
3776         }
3777 #endif
3778 #endif
3779         /*
3780         **      Patch script to physical addresses
3781         */
3782         ncr_script_fill (&script0, &scripth0);
3783
3784         np->scripth     = np->scripth0;
3785         np->p_scripth   = vtobus(np->scripth);
3786
3787         np->p_script    = (np->paddr2) ?  np->paddr2 : vtobus(np->script0);
3788
3789         ncr_script_copy_and_bind (np, (ncrcmd *) &script0, (ncrcmd *) np->script0, sizeof(struct script));
3790         ncr_script_copy_and_bind (np, (ncrcmd *) &scripth0, (ncrcmd *) np->scripth0, sizeof(struct scripth));
3791         np->ccb->p_ccb          = vtobus (np->ccb);
3792
3793         /*
3794         **    Patch the script for LED support.
3795         */
3796
3797         if (np->features & FE_LED0) {
3798                 np->script0->idle[0]  =
3799                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
3800                 np->script0->reselected[0] =
3801                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3802                 np->script0->start[0] =
3803                                 cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3804         }
3805
3806         /*
3807         **      Look for the target control block of this nexus.
3808         **      For i = 0 to 3
3809         **              JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
3810         */
3811         for (i = 0 ; i < 4 ; i++) {
3812                 np->jump_tcb[i].l_cmd   =
3813                                 cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
3814                 np->jump_tcb[i].l_paddr =
3815                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_target));
3816         }
3817
3818         /*
3819         **      Reset chip.
3820         */
3821         ncr_chip_reset(np, 100);
3822
3823         /*
3824         **      Now check the cache handling of the chipset.
3825         */
3826
3827         if (ncr_snooptest (np)) {
3828                 printk (KERN_ERR "CACHE INCORRECTLY CONFIGURED.\n");
3829                 goto attach_error;
3830         };
3831
3832         /*
3833         **      Install the interrupt handler.
3834         */
3835
3836         np->irq = device->slot.irq;
3837
3838         /*
3839         **      Initialize the fixed part of the default ccb.
3840         */
3841         ncr_init_ccb(np, np->ccb);
3842
3843         /*
3844         **      After SCSI devices have been opened, we cannot
3845         **      reset the bus safely, so we do it here.
3846         **      Interrupt handler does the real work.
3847         **      Process the reset exception,
3848         **      if interrupts are not enabled yet.
3849         **      Then enable disconnects.
3850         */
3851         NCR_LOCK_NCB(np, flags);
3852         if (ncr_reset_scsi_bus(np, 0, driver_setup.settle_delay) != 0) {
3853                 printk(KERN_ERR "%s: FATAL ERROR: CHECK SCSI BUS - CABLES, TERMINATION, DEVICE POWER etc.!\n", ncr_name(np));
3854
3855                 NCR_UNLOCK_NCB(np, flags);
3856                 goto attach_error;
3857         }
3858         ncr_exception (np);
3859
3860         np->disc = 1;
3861
3862         /*
3863         **      The middle-level SCSI driver does not
3864         **      wait for devices to settle.
3865         **      Wait synchronously if more than 2 seconds.
3866         */
3867         if (driver_setup.settle_delay > 2) {
3868                 printk(KERN_INFO "%s: waiting %d seconds for scsi devices to settle...\n",
3869                         ncr_name(np), driver_setup.settle_delay);
3870                 MDELAY (1000 * driver_setup.settle_delay);
3871         }
3872
3873         /*
3874         **      Now let the generic SCSI driver
3875         **      look for the SCSI devices on the bus ..
3876         */
3877
3878         /*
3879         **      start the timeout daemon
3880         */
3881         np->lasttime=0;
3882         ncr_timeout (np);
3883
3884         /*
3885         **  use SIMPLE TAG messages by default
3886         */
3887 #ifdef SCSI_NCR_ALWAYS_SIMPLE_TAG
3888         np->order = M_SIMPLE_TAG;
3889 #endif
3890
3891         NCR_UNLOCK_NCB(np, flags);
3892
3893         return instance;
3894
3895 attach_error:
3896         if (!instance) return NULL;
3897         printk(KERN_INFO "%s: detaching...\n", ncr_name(np));
3898         if (!np)
3899                 goto unregister;
3900         if (np->scripth0)
3901                 m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
3902         if (np->script0)
3903                 m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
3904         if (np->ccb)
3905                 m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
3906         m_free_dma(np, sizeof(struct ncb), "NCB");
3907
3908 unregister:
3909         scsi_host_put(instance);
3910
3911         return NULL;
3912 }
3913
3914
3915 /*==========================================================
3916 **
3917 **
3918 **      Done SCSI commands list management.
3919 **
3920 **      We donnot enter the scsi_done() callback immediately 
3921 **      after a command has been seen as completed but we 
3922 **      insert it into a list which is flushed outside any kind 
3923 **      of driver critical section.
3924 **      This allows to do minimal stuff under interrupt and 
3925 **      inside critical sections and to also avoid locking up 
3926 **      on recursive calls to driver entry points under SMP.
3927 **      In fact, the only kernel point which is entered by the 
3928 **      driver with a driver lock set is kmalloc(GFP_ATOMIC) 
3929 **      that shall not reenter the driver under any circumstances,
3930 **      AFAIK.
3931 **
3932 **==========================================================
3933 */
3934 static inline void ncr_queue_done_cmd(ncb_p np, Scsi_Cmnd *cmd)
3935 {
3936         unmap_scsi_data(np, cmd);
3937         cmd->host_scribble = (char *) np->done_list;
3938         np->done_list = cmd;
3939 }
3940
3941 static inline void ncr_flush_done_cmds(Scsi_Cmnd *lcmd)
3942 {
3943         Scsi_Cmnd *cmd;
3944
3945         while (lcmd) {
3946                 cmd = lcmd;
3947                 lcmd = (Scsi_Cmnd *) cmd->host_scribble;
3948                 cmd->scsi_done(cmd);
3949         }
3950 }
3951
3952 /*==========================================================
3953 **
3954 **
3955 **      Prepare the next negotiation message for integrity check,
3956 **      if needed.
3957 **
3958 **      Fill in the part of message buffer that contains the 
3959 **      negotiation and the nego_status field of the CCB.
3960 **      Returns the size of the message in bytes.
3961 **
3962 **
3963 **==========================================================
3964 */
3965
3966 #ifdef SCSI_NCR_INTEGRITY_CHECKING
3967 static int ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr)
3968 {
3969         tcb_p tp = &np->target[cp->target];
3970         int msglen = 0;
3971         int nego = 0;
3972         u_char no_increase;
3973
3974         if (tp->inq_done) {
3975
3976                 if (!tp->ic_maximums_set) {
3977                         tp->ic_maximums_set = 1;
3978
3979                         /* check target and host adapter capabilities */
3980                         if ( (tp->inq_byte7 & INQ7_WIDE16) && 
3981                                         np->maxwide && tp->usrwide ) 
3982                                 tp->ic_max_width = 1;
3983                         else
3984                                 tp->ic_max_width = 0;
3985
3986                         if ((tp->inq_byte7 & INQ7_SYNC) && tp->maxoffs) {
3987                                 tp->ic_min_sync   = (tp->minsync < np->minsync) ?
3988                                                         np->minsync : tp->minsync;
3989                         }
3990                         else 
3991                                 tp->ic_min_sync   = 255;
3992                         
3993                         tp->period   = 1;
3994                         tp->widedone = 1;
3995                 }
3996
3997                 if (DEBUG_FLAGS & DEBUG_IC) {
3998                         printk("%s: cmd->ic_nego %d, 1st byte 0x%2X\n",
3999                                 ncr_name(np), cmd->ic_nego, cmd->cmnd[0]);
4000                 }
4001
4002                 /* First command from integrity check routine will request
4003                  * a PPR message.  Disable.
4004                  */
4005                 if ((cmd->ic_nego & NS_PPR) == NS_PPR)
4006                         cmd->ic_nego &= ~NS_PPR;
4007                 /* Previous command recorded a parity or an initiator
4008                  * detected error condition. Force bus to narrow for this
4009                  * target. Clear flag. Negotation on request sense.
4010                  * Note: kernel forces 2 bus resets :o( but clears itself out.
4011                  * Minor bug? in scsi_obsolete.c (ugly)
4012                  */
4013                 if (np->check_integ_par) {
4014                         printk("%s: Parity Error. Target set to narrow.\n",
4015                                 ncr_name(np));
4016                         tp->ic_max_width = 0;
4017                         tp->widedone = tp->period = 0;
4018                 }
4019                 
4020                 /* In case of a bus reset, ncr_negotiate will reset 
4021                  * the flags tp->widedone and tp->period to 0, forcing
4022                  * a new negotiation. 
4023                  */
4024                 no_increase = 0;
4025                 if (tp->widedone == 0) {
4026                         cmd->ic_nego = NS_WIDE;
4027                         tp->widedone = 1;
4028                         no_increase = 1;
4029                 }
4030                 else if (tp->period == 0) {
4031                         cmd->ic_nego = NS_SYNC;
4032                         tp->period = 1;
4033                         no_increase = 1;
4034                 }
4035                         
4036                 switch (cmd->ic_nego) {
4037                 case NS_WIDE:
4038                         /*
4039                         **      negotiate wide transfers ?
4040                         **      Do NOT negotiate if device only supports
4041                         **      narrow. 
4042                         */
4043                         if (tp->ic_max_width | np->check_integ_par) {
4044                                 nego = NS_WIDE;
4045
4046                                 msgptr[msglen++] = M_EXTENDED;
4047                                 msgptr[msglen++] = 2;
4048                                 msgptr[msglen++] = M_X_WIDE_REQ;
4049                                 msgptr[msglen++] = cmd->ic_nego_width & tp->ic_max_width;
4050                         }
4051                         else
4052                                 cmd->ic_nego_width &= tp->ic_max_width;
4053               
4054                         break;
4055
4056                 case NS_SYNC:
4057                         /*
4058                         **      negotiate synchronous transfers?
4059                         **      Target must support sync transfers.
4060                         **
4061                         **      If period becomes longer than max, reset to async
4062                         */
4063
4064                         if (tp->inq_byte7 & INQ7_SYNC) {
4065
4066                                 nego = NS_SYNC;
4067
4068                                 msgptr[msglen++] = M_EXTENDED;
4069                                 msgptr[msglen++] = 3;
4070                                 msgptr[msglen++] = M_X_SYNC_REQ;
4071
4072                                 switch (cmd->ic_nego_sync) {
4073                                 case 2: /* increase the period */
4074                                         if (!no_increase) {
4075                                           if (tp->ic_min_sync <= 0x0A)
4076                                               tp->ic_min_sync = 0x0C;
4077                                           else if (tp->ic_min_sync <= 0x0C)
4078                                               tp->ic_min_sync = 0x19;
4079                                           else if (tp->ic_min_sync <= 0x19)
4080                                               tp->ic_min_sync *= 2;
4081                                           else {
4082                                                 tp->ic_min_sync = 255;
4083                                                 cmd->ic_nego_sync = 0;
4084                                                 tp->maxoffs = 0;
4085                                            }
4086                                         }
4087                                         msgptr[msglen++] = tp->maxoffs?tp->ic_min_sync:0;
4088                                         msgptr[msglen++] = tp->maxoffs;
4089                                         break;
4090
4091                                 case 1: /* nego. to maximum */
4092                                         msgptr[msglen++] = tp->maxoffs?tp->ic_min_sync:0;
4093                                         msgptr[msglen++] = tp->maxoffs;
4094                                         break;
4095
4096                                 case 0: /* nego to async */
4097                                 default:
4098                                         msgptr[msglen++] = 0;
4099                                         msgptr[msglen++] = 0;
4100                                         break;
4101                                 };
4102                         }
4103                         else
4104                                 cmd->ic_nego_sync = 0;
4105                         break;
4106
4107                 case NS_NOCHANGE:
4108                 default:
4109                         break;
4110                 };
4111         };
4112
4113         cp->nego_status = nego;
4114         np->check_integ_par = 0;
4115
4116         if (nego) {
4117                 tp->nego_cp = cp;
4118                 if (DEBUG_FLAGS & DEBUG_NEGO) {
4119                         ncr_print_msg(cp, nego == NS_WIDE ?
4120                           "wide/narrow msgout": "sync/async msgout", msgptr);
4121                 };
4122         };
4123
4124         return msglen;
4125 }
4126 #endif /* SCSI_NCR_INTEGRITY_CHECKING */
4127
4128 /*==========================================================
4129 **
4130 **
4131 **      Prepare the next negotiation message if needed.
4132 **
4133 **      Fill in the part of message buffer that contains the 
4134 **      negotiation and the nego_status field of the CCB.
4135 **      Returns the size of the message in bytes.
4136 **
4137 **
4138 **==========================================================
4139 */
4140
4141
4142 static int ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr)
4143 {
4144         tcb_p tp = &np->target[cp->target];
4145         int msglen = 0;
4146         int nego = 0;
4147
4148         if (tp->inq_done) {
4149
4150                 /*
4151                 **      negotiate wide transfers ?
4152                 */
4153
4154                 if (!tp->widedone) {
4155                         if (tp->inq_byte7 & INQ7_WIDE16) {
4156                                 nego = NS_WIDE;
4157 #ifdef SCSI_NCR_INTEGRITY_CHECKING
4158                                 if (tp->ic_done)
4159                                          tp->usrwide &= tp->ic_max_width;
4160 #endif
4161                         } else
4162                                 tp->widedone=1;
4163
4164                 };
4165
4166                 /*
4167                 **      negotiate synchronous transfers?
4168                 */
4169
4170                 if (!nego && !tp->period) {
4171                         if (tp->inq_byte7 & INQ7_SYNC) {
4172                                 nego = NS_SYNC;
4173 #ifdef SCSI_NCR_INTEGRITY_CHECKING
4174                                 if ((tp->ic_done) &&
4175                                               (tp->minsync < tp->ic_min_sync))
4176                                          tp->minsync = tp->ic_min_sync;
4177 #endif
4178                         } else {
4179                                 tp->period  =0xffff;
4180                                 PRINT_TARGET(np, cp->target);
4181                                 printk ("target did not report SYNC.\n");
4182                         };
4183                 };
4184         };
4185
4186         switch (nego) {
4187         case NS_SYNC:
4188                 msgptr[msglen++] = M_EXTENDED;
4189                 msgptr[msglen++] = 3;
4190                 msgptr[msglen++] = M_X_SYNC_REQ;
4191                 msgptr[msglen++] = tp->maxoffs ? tp->minsync : 0;
4192                 msgptr[msglen++] = tp->maxoffs;
4193                 break;
4194         case NS_WIDE:
4195                 msgptr[msglen++] = M_EXTENDED;
4196                 msgptr[msglen++] = 2;
4197                 msgptr[msglen++] = M_X_WIDE_REQ;
4198                 msgptr[msglen++] = tp->usrwide;
4199                 break;
4200         };
4201
4202         cp->nego_status = nego;
4203
4204         if (nego) {
4205                 tp->nego_cp = cp;
4206                 if (DEBUG_FLAGS & DEBUG_NEGO) {
4207                         ncr_print_msg(cp, nego == NS_WIDE ?
4208                                           "wide msgout":"sync_msgout", msgptr);
4209                 };
4210         };
4211
4212         return msglen;
4213 }
4214
4215
4216
4217 /*==========================================================
4218 **
4219 **
4220 **      Start execution of a SCSI command.
4221 **      This is called from the generic SCSI driver.
4222 **
4223 **
4224 **==========================================================
4225 */
4226 static int ncr_queue_command (ncb_p np, Scsi_Cmnd *cmd)
4227 {
4228 /*      Scsi_Device        *device    = cmd->device; */
4229         tcb_p tp                      = &np->target[cmd->device->id];
4230         lcb_p lp                      = tp->lp[cmd->device->lun];
4231         ccb_p cp;
4232
4233         int     segments;
4234         u_char  idmsg, *msgptr;
4235         u_int  msglen;
4236         int     direction;
4237         u32     lastp, goalp;
4238
4239         /*---------------------------------------------
4240         **
4241         **      Some shortcuts ...
4242         **
4243         **---------------------------------------------
4244         */
4245         if ((cmd->device->id == np->myaddr        ) ||
4246                 (cmd->device->id >= MAX_TARGET) ||
4247                 (cmd->device->lun    >= MAX_LUN   )) {
4248                 return(DID_BAD_TARGET);
4249         }
4250
4251         /*---------------------------------------------
4252         **
4253         **      Complete the 1st TEST UNIT READY command
4254         **      with error condition if the device is 
4255         **      flagged NOSCAN, in order to speed up 
4256         **      the boot.
4257         **
4258         **---------------------------------------------
4259         */
4260         if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) && 
4261             (tp->usrflag & UF_NOSCAN)) {
4262                 tp->usrflag &= ~UF_NOSCAN;
4263                 return DID_BAD_TARGET;
4264         }
4265
4266         if (DEBUG_FLAGS & DEBUG_TINY) {
4267                 PRINT_ADDR(cmd);
4268                 printk ("CMD=%x ", cmd->cmnd[0]);
4269         }
4270
4271         /*---------------------------------------------------
4272         **
4273         **      Assign a ccb / bind cmd.
4274         **      If resetting, shorten settle_time if necessary
4275         **      in order to avoid spurious timeouts.
4276         **      If resetting or no free ccb,
4277         **      insert cmd into the waiting list.
4278         **
4279         **----------------------------------------------------
4280         */
4281         if (np->settle_time && cmd->timeout_per_command >= HZ) {
4282                 u_long tlimit = ktime_get(cmd->timeout_per_command - HZ);
4283                 if (ktime_dif(np->settle_time, tlimit) > 0)
4284                         np->settle_time = tlimit;
4285         }
4286
4287         if (np->settle_time || !(cp=ncr_get_ccb (np, cmd->device->id, cmd->device->lun))) {
4288                 insert_into_waiting_list(np, cmd);
4289                 return(DID_OK);
4290         }
4291         cp->cmd = cmd;
4292
4293         /*----------------------------------------------------
4294         **
4295         **      Build the identify / tag / sdtr message
4296         **
4297         **----------------------------------------------------
4298         */
4299
4300         idmsg = M_IDENTIFY | cmd->device->lun;
4301
4302         if (cp ->tag != NO_TAG ||
4303                 (cp != np->ccb && np->disc && !(tp->usrflag & UF_NODISC)))
4304                 idmsg |= 0x40;
4305
4306         msgptr = cp->scsi_smsg;
4307         msglen = 0;
4308         msgptr[msglen++] = idmsg;
4309
4310         if (cp->tag != NO_TAG) {
4311                 char order = np->order;
4312
4313                 /*
4314                 **      Force ordered tag if necessary to avoid timeouts 
4315                 **      and to preserve interactivity.
4316                 */
4317                 if (lp && ktime_exp(lp->tags_stime)) {
4318                         if (lp->tags_smap) {
4319                                 order = M_ORDERED_TAG;
4320                                 if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>2){ 
4321                                         PRINT_ADDR(cmd);
4322                                         printk("ordered tag forced.\n");
4323                                 }
4324                         }
4325                         lp->tags_stime = ktime_get(3*HZ);
4326                         lp->tags_smap = lp->tags_umap;
4327                 }
4328
4329                 if (order == 0) {
4330                         /*
4331                         **      Ordered write ops, unordered read ops.
4332                         */
4333                         switch (cmd->cmnd[0]) {
4334                         case 0x08:  /* READ_SMALL (6) */
4335                         case 0x28:  /* READ_BIG  (10) */
4336                         case 0xa8:  /* READ_HUGE (12) */
4337                                 order = M_SIMPLE_TAG;
4338                                 break;
4339                         default:
4340                                 order = M_ORDERED_TAG;
4341                         }
4342                 }
4343                 msgptr[msglen++] = order;
4344                 /*
4345                 **      Actual tags are numbered 1,3,5,..2*MAXTAGS+1,
4346                 **      since we may have to deal with devices that have 
4347                 **      problems with #TAG 0 or too great #TAG numbers.
4348                 */
4349                 msgptr[msglen++] = (cp->tag << 1) + 1;
4350         }
4351
4352         /*----------------------------------------------------
4353         **
4354         **      Build the data descriptors
4355         **
4356         **----------------------------------------------------
4357         */
4358
4359         direction = scsi_data_direction(cmd);
4360         if (direction != SCSI_DATA_NONE) {
4361                 segments = ncr_scatter (np, cp, cp->cmd);
4362                 if (segments < 0) {
4363                         ncr_free_ccb(np, cp);
4364                         return(DID_ERROR);
4365                 }
4366         }
4367         else {
4368                 cp->data_len = 0;
4369                 segments = 0;
4370         }
4371
4372         /*---------------------------------------------------
4373         **
4374         **      negotiation required?
4375         **
4376         **      (nego_status is filled by ncr_prepare_nego())
4377         **
4378         **---------------------------------------------------
4379         */
4380
4381         cp->nego_status = 0;
4382
4383 #ifdef SCSI_NCR_INTEGRITY_CHECKING
4384         if ((np->check_integrity && tp->ic_done) || !np->check_integrity) {
4385                  if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4386                         msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4387                  }
4388         }
4389         else if (np->check_integrity && (cmd->ic_in_progress)) { 
4390                 msglen += ncr_ic_nego (np, cp, cmd, msgptr + msglen);
4391         }
4392         else if (np->check_integrity && cmd->ic_complete) {
4393                 /*
4394                  * Midlayer signal to the driver that all of the scsi commands
4395                  * for the integrity check have completed. Save the negotiated
4396                  * parameters (extracted from sval and wval). 
4397                  */ 
4398
4399                 {
4400                         u_char idiv;
4401                         idiv = (tp->wval>>4) & 0x07;
4402                         if ((tp->sval&0x1f) && idiv )
4403                                 tp->period = (((tp->sval>>5)+4)  
4404                                                 *div_10M[idiv-1])/np->clock_khz;
4405                         else
4406                                 tp->period = 0xffff;
4407                 }
4408                 /*
4409                  * tp->period contains 10 times the transfer period, 
4410                  * which itself is 4 * the requested negotiation rate.
4411                  */
4412                 if      (tp->period <= 250)     tp->ic_min_sync = 10;
4413                 else if (tp->period <= 303)     tp->ic_min_sync = 11;
4414                 else if (tp->period <= 500)     tp->ic_min_sync = 12;
4415                 else                            
4416                                 tp->ic_min_sync = (tp->period + 40 - 1) / 40;
4417
4418
4419                 /*
4420                  * Negotiation for this target it complete.
4421                  */
4422                 tp->ic_max_width =  (tp->wval & EWS) ? 1: 0;
4423                 tp->ic_done = 1;
4424                 tp->widedone = 1;
4425
4426                 printk("%s: Integrity Check Complete: \n", ncr_name(np)); 
4427
4428                 printk("%s: %s %s SCSI", ncr_name(np), 
4429                                 (tp->sval&0x1f)?"SYNC":"ASYNC",
4430                                 tp->ic_max_width?"WIDE":"NARROW");
4431
4432                 if (tp->sval&0x1f) {
4433                         u_long mbs = 10000 * (tp->ic_max_width + 1);
4434
4435                         printk(" %d.%d  MB/s", 
4436                                 (int) (mbs / tp->period), (int) (mbs % tp->period));
4437
4438                         printk(" (%d ns, %d offset)\n", 
4439                                   tp->period/10, tp->sval&0x1f);
4440                 }
4441                 else
4442                         printk(" %d MB/s. \n ", (tp->ic_max_width+1)*5);
4443         }
4444 #else
4445         if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4446                 msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4447         }
4448 #endif /* SCSI_NCR_INTEGRITY_CHECKING */
4449
4450         /*----------------------------------------------------
4451         **
4452         **      Determine xfer direction.
4453         **
4454         **----------------------------------------------------
4455         */
4456         if (!cp->data_len)
4457                 direction = SCSI_DATA_NONE;
4458
4459         /*
4460         **      If data direction is UNKNOWN, speculate DATA_READ 
4461         **      but prepare alternate pointers for WRITE in case 
4462         **      of our speculation will be just wrong.
4463         **      SCRIPTS will swap values if needed.
4464         */
4465         switch(direction) {
4466         case SCSI_DATA_UNKNOWN:
4467         case SCSI_DATA_WRITE:
4468                 goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
4469                 if (segments <= MAX_SCATTERL)
4470                         lastp = goalp - 8 - (segments * 16);
4471                 else {
4472                         lastp = NCB_SCRIPTH_PHYS (np, hdata_out2);
4473                         lastp -= (segments - MAX_SCATTERL) * 16;
4474                 }
4475                 if (direction != SCSI_DATA_UNKNOWN)
4476                         break;
4477                 cp->phys.header.wgoalp  = cpu_to_scr(goalp);
4478                 cp->phys.header.wlastp  = cpu_to_scr(lastp);
4479                 /* fall through */
4480         case SCSI_DATA_READ:
4481                 goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
4482                 if (segments <= MAX_SCATTERL)
4483                         lastp = goalp - 8 - (segments * 16);
4484                 else {
4485                         lastp = NCB_SCRIPTH_PHYS (np, hdata_in2);
4486                         lastp -= (segments - MAX_SCATTERL) * 16;
4487                 }
4488                 break;
4489         default:
4490         case SCSI_DATA_NONE:
4491                 lastp = goalp = NCB_SCRIPT_PHYS (np, no_data);
4492                 break;
4493         }
4494
4495         /*
4496         **      Set all pointers values needed by SCRIPTS.
4497         **      If direction is unknown, start at data_io.
4498         */
4499         cp->phys.header.lastp = cpu_to_scr(lastp);
4500         cp->phys.header.goalp = cpu_to_scr(goalp);
4501
4502         if (direction == SCSI_DATA_UNKNOWN)
4503                 cp->phys.header.savep = 
4504                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
4505         else
4506                 cp->phys.header.savep= cpu_to_scr(lastp);
4507
4508         /*
4509         **      Save the initial data pointer in order to be able 
4510         **      to redo the command.
4511         */
4512         cp->startp = cp->phys.header.savep;
4513
4514         /*----------------------------------------------------
4515         **
4516         **      fill in ccb
4517         **
4518         **----------------------------------------------------
4519         **
4520         **
4521         **      physical -> virtual backlink
4522         **      Generic SCSI command
4523         */
4524
4525         /*
4526         **      Startqueue
4527         */
4528         cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4529         cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_dsa));
4530         /*
4531         **      select
4532         */
4533         cp->phys.select.sel_id          = cmd->device->id;
4534         cp->phys.select.sel_scntl3      = tp->wval;
4535         cp->phys.select.sel_sxfer       = tp->sval;
4536         /*
4537         **      message
4538         */
4539         cp->phys.smsg.addr              = cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
4540         cp->phys.smsg.size              = cpu_to_scr(msglen);
4541
4542         /*
4543         **      command
4544         */
4545         memcpy(cp->cdb_buf, cmd->cmnd, min_t(int, cmd->cmd_len, sizeof(cp->cdb_buf)));
4546         cp->phys.cmd.addr               = cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
4547         cp->phys.cmd.size               = cpu_to_scr(cmd->cmd_len);
4548
4549         /*
4550         **      status
4551         */
4552         cp->actualquirks                = tp->quirks;
4553         cp->host_status                 = cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4554         cp->scsi_status                 = S_ILLEGAL;
4555         cp->parity_status               = 0;
4556
4557         cp->xerr_status                 = XE_OK;
4558 #if 0
4559         cp->sync_status                 = tp->sval;
4560         cp->wide_status                 = tp->wval;
4561 #endif
4562
4563         /*----------------------------------------------------
4564         **
4565         **      Critical region: start this job.
4566         **
4567         **----------------------------------------------------
4568         */
4569
4570         /*
4571         **      activate this job.
4572         */
4573         cp->magic               = CCB_MAGIC;
4574
4575         /*
4576         **      insert next CCBs into start queue.
4577         **      2 max at a time is enough to flush the CCB wait queue.
4578         */
4579         cp->auto_sense = 0;
4580         if (lp)
4581                 ncr_start_next_ccb(np, lp, 2);
4582         else
4583                 ncr_put_start_queue(np, cp);
4584
4585         /*
4586         **      Command is successfully queued.
4587         */
4588
4589         return(DID_OK);
4590 }
4591
4592
4593 /*==========================================================
4594 **
4595 **
4596 **      Insert a CCB into the start queue and wake up the 
4597 **      SCRIPTS processor.
4598 **
4599 **
4600 **==========================================================
4601 */
4602
4603 static void ncr_start_next_ccb(ncb_p np, lcb_p lp, int maxn)
4604 {
4605         XPT_QUEHEAD *qp;
4606         ccb_p cp;
4607
4608         if (lp->held_ccb)
4609                 return;
4610
4611         while (maxn-- && lp->queuedccbs < lp->queuedepth) {
4612                 qp = xpt_remque_head(&lp->wait_ccbq);
4613                 if (!qp)
4614                         break;
4615                 ++lp->queuedccbs;
4616                 cp = xpt_que_entry(qp, struct ccb, link_ccbq);
4617                 xpt_insque_tail(qp, &lp->busy_ccbq);
4618                 lp->jump_ccb[cp->tag == NO_TAG ? 0 : cp->tag] =
4619                         cpu_to_scr(CCB_PHYS (cp, restart));
4620                 ncr_put_start_queue(np, cp);
4621         }
4622 }
4623
4624 static void ncr_put_start_queue(ncb_p np, ccb_p cp)
4625 {
4626         u_short qidx;
4627
4628         /*
4629         **      insert into start queue.
4630         */
4631         if (!np->squeueput) np->squeueput = 1;
4632         qidx = np->squeueput + 2;
4633         if (qidx >= MAX_START + MAX_START) qidx = 1;
4634
4635         np->scripth->tryloop [qidx] = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
4636         MEMORY_BARRIER();
4637         np->scripth->tryloop [np->squeueput] = cpu_to_scr(CCB_PHYS (cp, start));
4638
4639         np->squeueput = qidx;
4640         ++np->queuedccbs;
4641         cp->queued = 1;
4642
4643         if (DEBUG_FLAGS & DEBUG_QUEUE)
4644                 printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
4645
4646         /*
4647         **      Script processor may be waiting for reselect.
4648         **      Wake it up.
4649         */
4650         MEMORY_BARRIER();
4651         OUTB (nc_istat, SIGP);
4652 }
4653
4654
4655 /*==========================================================
4656 **
4657 **
4658 **      Start reset process.
4659 **      If reset in progress do nothing.
4660 **      The interrupt handler will reinitialize the chip.
4661 **      The timeout handler will wait for settle_time before 
4662 **      clearing it and so resuming command processing.
4663 **
4664 **
4665 **==========================================================
4666 */
4667 static void ncr_start_reset(ncb_p np)
4668 {
4669         if (!np->settle_time) {
4670                 (void) ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
4671         }
4672  }
4673  
4674 static int ncr_reset_scsi_bus(ncb_p np, int enab_int, int settle_delay)
4675 {
4676         u32 term;
4677         int retv = 0;
4678
4679         np->settle_time = ktime_get(settle_delay * HZ);
4680
4681         if (bootverbose > 1)
4682                 printk("%s: resetting, "
4683                         "command processing suspended for %d seconds\n",
4684                         ncr_name(np), settle_delay);
4685
4686         ncr_chip_reset(np, 100);
4687         UDELAY (2000);  /* The 895 needs time for the bus mode to settle */
4688         if (enab_int)
4689                 OUTW (nc_sien, RST);
4690         /*
4691         **      Enable Tolerant, reset IRQD if present and 
4692         **      properly set IRQ mode, prior to resetting the bus.
4693         */
4694         OUTB (nc_stest3, TE);
4695         if (np->device_id != PSEUDO_720_ID)
4696                 OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
4697         OUTB (nc_scntl1, CRST);
4698         UDELAY (200);
4699
4700         if (!driver_setup.bus_check)
4701                 goto out;
4702         /*
4703         **      Check for no terminators or SCSI bus shorts to ground.
4704         **      Read SCSI data bus, data parity bits and control signals.
4705         **      We are expecting RESET to be TRUE and other signals to be 
4706         **      FALSE.
4707         */
4708
4709         term =  INB(nc_sstat0);
4710         term =  ((term & 2) << 7) + ((term & 1) << 17); /* rst sdp0 */
4711         term |= ((INB(nc_sstat2) & 0x01) << 26) |       /* sdp1     */
4712                 ((INW(nc_sbdl) & 0xff)   << 9)  |       /* d7-0     */
4713                 ((INW(nc_sbdl) & 0xff00) << 10) |       /* d15-8    */
4714                 INB(nc_sbcl);   /* req ack bsy sel atn msg cd io    */
4715
4716         if (!(np->features & FE_WIDE))
4717                 term &= 0x3ffff;
4718
4719         if (term != (2<<7)) {
4720                 printk("%s: suspicious SCSI data while resetting the BUS.\n",
4721                         ncr_name(np));
4722                 printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4723                         "0x%lx, expecting 0x%lx\n",
4724                         ncr_name(np),
4725                         (np->features & FE_WIDE) ? "dp1,d15-8," : "",
4726                         (u_long)term, (u_long)(2<<7));
4727                 if (driver_setup.bus_check == 1)
4728                         retv = 1;
4729         }
4730 out:
4731         OUTB (nc_scntl1, 0);
4732         return retv;
4733 }
4734
4735 /*==========================================================
4736 **
4737 **
4738 **      Reset the SCSI BUS.
4739 **      This is called from the generic SCSI driver.
4740 **
4741 **
4742 **==========================================================
4743 */
4744 static int ncr_reset_bus (ncb_p np, Scsi_Cmnd *cmd, int sync_reset)
4745 {
4746 /*      Scsi_Device        *device    = cmd->device; */
4747         ccb_p cp;
4748         int found;
4749
4750 /*
4751  * Return immediately if reset is in progress.
4752  */
4753         if (np->settle_time) {
4754                 return FAILED;
4755         }
4756 /*
4757  * Start the reset process.
4758  * The script processor is then assumed to be stopped.
4759  * Commands will now be queued in the waiting list until a settle 
4760  * delay of 2 seconds will be completed.
4761  */
4762         ncr_start_reset(np);
4763 /*
4764  * First, look in the wakeup list
4765  */
4766         for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4767                 /*
4768                 **      look for the ccb of this command.
4769                 */
4770                 if (cp->host_status == HS_IDLE) continue;
4771                 if (cp->cmd == cmd) {
4772                         found = 1;
4773                         break;
4774                 }
4775         }
4776 /*
4777  * Then, look in the waiting list
4778  */
4779         if (!found && retrieve_from_waiting_list(0, np, cmd))
4780                 found = 1;
4781 /*
4782  * Wake-up all awaiting commands with DID_RESET.
4783  */
4784         reset_waiting_list(np);
4785 /*
4786  * Wake-up all pending commands with HS_RESET -> DID_RESET.
4787  */
4788         ncr_wakeup(np, HS_RESET);
4789 /*
4790  * If the involved command was not in a driver queue, and the 
4791  * scsi driver told us reset is synchronous, and the command is not 
4792  * currently in the waiting list, complete it with DID_RESET status,
4793  * in order to keep it alive.
4794  */
4795         if (!found && sync_reset && !retrieve_from_waiting_list(0, np, cmd)) {
4796                 cmd->result = ScsiResult(DID_RESET, 0);
4797                 ncr_queue_done_cmd(np, cmd);
4798         }
4799
4800         return SUCCESS;
4801 }
4802
4803 /*==========================================================
4804 **
4805 **
4806 **      Abort an SCSI command.
4807 **      This is called from the generic SCSI driver.
4808 **
4809 **
4810 **==========================================================
4811 */
4812 static int ncr_abort_command (ncb_p np, Scsi_Cmnd *cmd)
4813 {
4814 /*      Scsi_Device        *device    = cmd->device; */
4815         ccb_p cp;
4816         int found;
4817         int retv;
4818
4819 /*
4820  * First, look for the scsi command in the waiting list
4821  */
4822         if (remove_from_waiting_list(np, cmd)) {
4823                 cmd->result = ScsiResult(DID_ABORT, 0);
4824                 ncr_queue_done_cmd(np, cmd);
4825                 return SCSI_ABORT_SUCCESS;
4826         }
4827
4828 /*
4829  * Then, look in the wakeup list
4830  */
4831         for (found=0, cp=np->ccb; cp; cp=cp->link_ccb) {
4832                 /*
4833                 **      look for the ccb of this command.
4834                 */
4835                 if (cp->host_status == HS_IDLE) continue;
4836                 if (cp->cmd == cmd) {
4837                         found = 1;
4838                         break;
4839                 }
4840         }
4841
4842         if (!found) {
4843                 return SCSI_ABORT_NOT_RUNNING;
4844         }
4845
4846         if (np->settle_time) {
4847                 return SCSI_ABORT_SNOOZE;
4848         }
4849
4850         /*
4851         **      If the CCB is active, patch schedule jumps for the 
4852         **      script to abort the command.
4853         */
4854
4855         switch(cp->host_status) {
4856         case HS_BUSY:
4857         case HS_NEGOTIATE:
4858                 printk ("%s: abort ccb=%p (cancel)\n", ncr_name (np), cp);
4859                         cp->start.schedule.l_paddr =
4860                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, cancel));
4861                 retv = SCSI_ABORT_PENDING;
4862                 break;
4863         case HS_DISCONNECT:
4864                 cp->restart.schedule.l_paddr =
4865                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
4866                 retv = SCSI_ABORT_PENDING;
4867                 break;
4868         default:
4869                 retv = SCSI_ABORT_NOT_RUNNING;
4870                 break;
4871
4872         }
4873
4874         /*
4875         **      If there are no requests, the script
4876         **      processor will sleep on SEL_WAIT_RESEL.
4877         **      Let's wake it up, since it may have to work.
4878         */
4879         OUTB (nc_istat, SIGP);
4880
4881         return retv;
4882 }
4883
4884 /*==========================================================
4885 **
4886 **      Linux release module stuff.
4887 **
4888 **      Called before unloading the module
4889 **      Detach the host.
4890 **      We have to free resources and halt the NCR chip
4891 **
4892 **==========================================================
4893 */
4894
4895 static int ncr_detach(ncb_p np)
4896 {
4897         ccb_p cp;
4898         tcb_p tp;
4899         lcb_p lp;
4900         int target, lun;
4901         int i;
4902         char inst_name[16];
4903
4904         /* Local copy so we don't access np after freeing it! */
4905         strlcpy(inst_name, ncr_name(np), sizeof(inst_name));
4906
4907         printk("%s: releasing host resources\n", ncr_name(np));
4908
4909 /*
4910 **      Stop the ncr_timeout process
4911 **      Set release_stage to 1 and wait that ncr_timeout() set it to 2.
4912 */
4913
4914 #ifdef DEBUG_NCR53C8XX
4915         printk("%s: stopping the timer\n", ncr_name(np));
4916 #endif
4917         np->release_stage = 1;
4918         for (i = 50 ; i && np->release_stage != 2 ; i--) MDELAY (100);
4919         if (np->release_stage != 2)
4920                 printk("%s: the timer seems to be already stopped\n", ncr_name(np));
4921         else np->release_stage = 2;
4922
4923 /*
4924 **      Disable chip interrupts
4925 */
4926
4927 #ifdef DEBUG_NCR53C8XX
4928         printk("%s: disabling chip interrupts\n", ncr_name(np));
4929 #endif
4930         OUTW (nc_sien , 0);
4931         OUTB (nc_dien , 0);
4932
4933         /*
4934         **      Reset NCR chip
4935         **      Restore bios setting for automatic clock detection.
4936         */
4937
4938         printk("%s: resetting chip\n", ncr_name(np));
4939         ncr_chip_reset(np, 100);
4940
4941         OUTB(nc_dmode,  np->sv_dmode);
4942         OUTB(nc_dcntl,  np->sv_dcntl);
4943         OUTB(nc_ctest0, np->sv_ctest0);
4944         OUTB(nc_ctest3, np->sv_ctest3);
4945         OUTB(nc_ctest4, np->sv_ctest4);
4946         OUTB(nc_ctest5, np->sv_ctest5);
4947         OUTB(nc_gpcntl, np->sv_gpcntl);
4948         OUTB(nc_stest2, np->sv_stest2);
4949
4950         ncr_selectclock(np, np->sv_scntl3);
4951
4952         /*
4953         **      Free allocated ccb(s)
4954         */
4955
4956         while ((cp=np->ccb->link_ccb) != NULL) {
4957                 np->ccb->link_ccb = cp->link_ccb;
4958                 if (cp->host_status) {
4959                 printk("%s: shall free an active ccb (host_status=%d)\n",
4960                         ncr_name(np), cp->host_status);
4961                 }
4962 #ifdef DEBUG_NCR53C8XX
4963         printk("%s: freeing ccb (%lx)\n", ncr_name(np), (u_long) cp);
4964 #endif
4965                 m_free_dma(cp, sizeof(*cp), "CCB");
4966         }
4967
4968         /*
4969         **      Free allocated tp(s)
4970         */
4971
4972         for (target = 0; target < MAX_TARGET ; target++) {
4973                 tp=&np->target[target];
4974                 for (lun = 0 ; lun < MAX_LUN ; lun++) {
4975                         lp = tp->lp[lun];
4976                         if (lp) {
4977 #ifdef DEBUG_NCR53C8XX
4978         printk("%s: freeing lp (%lx)\n", ncr_name(np), (u_long) lp);
4979 #endif
4980                                 if (lp->jump_ccb != &lp->jump_ccb_0)
4981                                         m_free_dma(lp->jump_ccb,256,"JUMP_CCB");
4982                                 m_free_dma(lp, sizeof(*lp), "LCB");
4983                         }
4984                 }
4985         }
4986
4987         if (np->scripth0)
4988                 m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
4989         if (np->script0)
4990                 m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
4991         if (np->ccb)
4992                 m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
4993         m_free_dma(np, sizeof(struct ncb), "NCB");
4994
4995         printk("%s: host resources successfully released\n", inst_name);
4996
4997         return 1;
4998 }
4999
5000 /*==========================================================
5001 **
5002 **
5003 **      Complete execution of a SCSI command.
5004 **      Signal completion to the generic SCSI driver.
5005 **
5006 **
5007 **==========================================================
5008 */
5009
5010 void ncr_complete (ncb_p np, ccb_p cp)
5011 {
5012         Scsi_Cmnd *cmd;
5013         tcb_p tp;
5014         lcb_p lp;
5015
5016         /*
5017         **      Sanity check
5018         */
5019
5020         if (!cp || cp->magic != CCB_MAGIC || !cp->cmd)
5021                 return;
5022
5023         /*
5024         **      Print minimal debug information.
5025         */
5026
5027         if (DEBUG_FLAGS & DEBUG_TINY)
5028                 printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
5029                         cp->host_status,cp->scsi_status);
5030
5031         /*
5032         **      Get command, target and lun pointers.
5033         */
5034
5035         cmd = cp->cmd;
5036         cp->cmd = NULL;
5037         tp = &np->target[cmd->device->id];
5038         lp = tp->lp[cmd->device->lun];
5039
5040         /*
5041         **      We donnot queue more than 1 ccb per target 
5042         **      with negotiation at any time. If this ccb was 
5043         **      used for negotiation, clear this info in the tcb.
5044         */
5045
5046         if (cp == tp->nego_cp)
5047                 tp->nego_cp = 0;
5048
5049         /*
5050         **      If auto-sense performed, change scsi status.
5051         */
5052         if (cp->auto_sense) {
5053                 cp->scsi_status = cp->auto_sense;
5054         }
5055
5056         /*
5057         **      If we were recovering from queue full or performing 
5058         **      auto-sense, requeue skipped CCBs to the wait queue.
5059         */
5060
5061         if (lp && lp->held_ccb) {
5062                 if (cp == lp->held_ccb) {
5063                         xpt_que_splice(&lp->skip_ccbq, &lp->wait_ccbq);
5064                         xpt_que_init(&lp->skip_ccbq);
5065                         lp->held_ccb = 0;
5066                 }
5067         }
5068
5069         /*
5070         **      Check for parity errors.
5071         */
5072
5073         if (cp->parity_status > 1) {
5074                 PRINT_ADDR(cmd);
5075                 printk ("%d parity error(s).\n",cp->parity_status);
5076         }
5077
5078         /*
5079         **      Check for extended errors.
5080         */
5081
5082         if (cp->xerr_status != XE_OK) {
5083                 PRINT_ADDR(cmd);
5084                 switch (cp->xerr_status) {
5085                 case XE_EXTRA_DATA:
5086                         printk ("extraneous data discarded.\n");
5087                         break;
5088                 case XE_BAD_PHASE:
5089                         printk ("invalid scsi phase (4/5).\n");
5090                         break;
5091                 default:
5092                         printk ("extended error %d.\n", cp->xerr_status);
5093                         break;
5094                 }
5095                 if (cp->host_status==HS_COMPLETE)
5096                         cp->host_status = HS_FAIL;
5097         }
5098
5099         /*
5100         **      Print out any error for debugging purpose.
5101         */
5102         if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
5103                 if (cp->host_status!=HS_COMPLETE || cp->scsi_status!=S_GOOD) {
5104                         PRINT_ADDR(cmd);
5105                         printk ("ERROR: cmd=%x host_status=%x scsi_status=%x\n",
5106                                 cmd->cmnd[0], cp->host_status, cp->scsi_status);
5107                 }
5108         }
5109
5110         /*
5111         **      Check the status.
5112         */
5113         if (   (cp->host_status == HS_COMPLETE)
5114                 && (cp->scsi_status == S_GOOD ||
5115                     cp->scsi_status == S_COND_MET)) {
5116                 /*
5117                 **      All went well (GOOD status).
5118                 **      CONDITION MET status is returned on 
5119                 **      `Pre-Fetch' or `Search data' success.
5120                 */
5121                 cmd->result = ScsiResult(DID_OK, cp->scsi_status);
5122
5123                 /*
5124                 **      @RESID@
5125                 **      Could dig out the correct value for resid,
5126                 **      but it would be quite complicated.
5127                 */
5128                 /* if (cp->phys.header.lastp != cp->phys.header.goalp) */
5129
5130                 /*
5131                 **      Allocate the lcb if not yet.
5132                 */
5133                 if (!lp)
5134                         ncr_alloc_lcb (np, cmd->device->id, cmd->device->lun);
5135
5136                 /*
5137                 **      On standard INQUIRY response (EVPD and CmDt 
5138                 **      not set), setup logical unit according to 
5139                 **      announced capabilities (we need the 1rst 7 bytes).
5140                 */
5141                 if (cmd->cmnd[0] == 0x12 && !(cmd->cmnd[1] & 0x3) &&
5142                     cmd->cmnd[4] >= 7 && !cmd->use_sg) {
5143                         sync_scsi_data_for_cpu(np, cmd);        /* SYNC the data */
5144                         ncr_setup_lcb (np, cmd->device->id, cmd->device->lun,
5145                                        (char *) cmd->request_buffer);
5146                         sync_scsi_data_for_device(np, cmd);     /* SYNC the data */
5147                 }
5148
5149                 tp->bytes     += cp->data_len;
5150                 tp->transfers ++;
5151
5152                 /*
5153                 **      If tags was reduced due to queue full,
5154                 **      increase tags if 1000 good status received.
5155                 */
5156                 if (lp && lp->usetags && lp->numtags < lp->maxtags) {
5157                         ++lp->num_good;
5158                         if (lp->num_good >= 1000) {
5159                                 lp->num_good = 0;
5160                                 ++lp->numtags;
5161                                 ncr_setup_tags (np, cmd->device->id, cmd->device->lun);
5162                         }
5163                 }
5164         } else if ((cp->host_status == HS_COMPLETE)
5165                 && (cp->scsi_status == S_CHECK_COND)) {
5166                 /*
5167                 **   Check condition code
5168                 */
5169                 cmd->result = ScsiResult(DID_OK, S_CHECK_COND);
5170
5171                 /*
5172                 **      Copy back sense data to caller's buffer.
5173                 */
5174                 memcpy(cmd->sense_buffer, cp->sense_buf,
5175                        min(sizeof(cmd->sense_buffer), sizeof(cp->sense_buf)));
5176
5177                 if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
5178                         u_char * p = (u_char*) & cmd->sense_buffer;
5179                         int i;
5180                         PRINT_ADDR(cmd);
5181                         printk ("sense data:");
5182                         for (i=0; i<14; i++) printk (" %x", *p++);
5183                         printk (".\n");
5184                 }
5185         } else if ((cp->host_status == HS_COMPLETE)
5186                 && (cp->scsi_status == S_CONFLICT)) {
5187                 /*
5188                 **   Reservation Conflict condition code
5189                 */
5190                 cmd->result = ScsiResult(DID_OK, S_CONFLICT);
5191         
5192         } else if ((cp->host_status == HS_COMPLETE)
5193                 && (cp->scsi_status == S_BUSY ||
5194                     cp->scsi_status == S_QUEUE_FULL)) {
5195
5196                 /*
5197                 **   Target is busy.
5198                 */
5199                 cmd->result = ScsiResult(DID_OK, cp->scsi_status);
5200
5201         } else if ((cp->host_status == HS_SEL_TIMEOUT)
5202                 || (cp->host_status == HS_TIMEOUT)) {
5203
5204                 /*
5205                 **   No response
5206                 */
5207                 cmd->result = ScsiResult(DID_TIME_OUT, cp->scsi_status);
5208
5209         } else if (cp->host_status == HS_RESET) {
5210
5211                 /*
5212                 **   SCSI bus reset
5213                 */
5214                 cmd->result = ScsiResult(DID_RESET, cp->scsi_status);
5215
5216         } else if (cp->host_status == HS_ABORTED) {
5217
5218                 /*
5219                 **   Transfer aborted
5220                 */
5221                 cmd->result = ScsiResult(DID_ABORT, cp->scsi_status);
5222
5223         } else {
5224
5225                 /*
5226                 **  Other protocol messes
5227                 */
5228                 PRINT_ADDR(cmd);
5229                 printk ("COMMAND FAILED (%x %x) @%p.\n",
5230                         cp->host_status, cp->scsi_status, cp);
5231
5232                 cmd->result = ScsiResult(DID_ERROR, cp->scsi_status);
5233         }
5234
5235         /*
5236         **      trace output
5237         */
5238
5239         if (tp->usrflag & UF_TRACE) {
5240                 u_char * p;
5241                 int i;
5242                 PRINT_ADDR(cmd);
5243                 printk (" CMD:");
5244                 p = (u_char*) &cmd->cmnd[0];
5245                 for (i=0; i<cmd->cmd_len; i++) printk (" %x", *p++);
5246
5247                 if (cp->host_status==HS_COMPLETE) {
5248                         switch (cp->scsi_status) {
5249                         case S_GOOD:
5250                                 printk ("  GOOD");
5251                                 break;
5252                         case S_CHECK_COND:
5253                                 printk ("  SENSE:");
5254                                 p = (u_char*) &cmd->sense_buffer;
5255                                 for (i=0; i<14; i++)
5256                                         printk (" %x", *p++);
5257                                 break;
5258                         default:
5259                                 printk ("  STAT: %x\n", cp->scsi_status);
5260                                 break;
5261                         }
5262                 } else printk ("  HOSTERROR: %x", cp->host_status);
5263                 printk ("\n");
5264         }
5265
5266         /*
5267         **      Free this ccb
5268         */
5269         ncr_free_ccb (np, cp);
5270
5271         /*
5272         **      requeue awaiting scsi commands for this lun.
5273         */
5274         if (lp && lp->queuedccbs < lp->queuedepth &&
5275             !xpt_que_empty(&lp->wait_ccbq))
5276                 ncr_start_next_ccb(np, lp, 2);
5277
5278         /*
5279         **      requeue awaiting scsi commands for this controller.
5280         */
5281         if (np->waiting_list)
5282                 requeue_waiting_list(np);
5283
5284         /*
5285         **      signal completion to generic driver.
5286         */
5287         ncr_queue_done_cmd(np, cmd);
5288 }
5289
5290 /*==========================================================
5291 **
5292 **
5293 **      Signal all (or one) control block done.
5294 **
5295 **
5296 **==========================================================
5297 */
5298
5299 /*
5300 **      This CCB has been skipped by the NCR.
5301 **      Queue it in the correponding unit queue.
5302 */
5303 static void ncr_ccb_skipped(ncb_p np, ccb_p cp)
5304 {
5305         tcb_p tp = &np->target[cp->target];
5306         lcb_p lp = tp->lp[cp->lun];
5307
5308         if (lp && cp != np->ccb) {
5309                 cp->host_status &= ~HS_SKIPMASK;
5310                 cp->start.schedule.l_paddr = 
5311                         cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
5312                 xpt_remque(&cp->link_ccbq);
5313                 xpt_insque_tail(&cp->link_ccbq, &lp->skip_ccbq);
5314                 if (cp->queued) {
5315                         --lp->queuedccbs;
5316                 }
5317         }
5318         if (cp->queued) {
5319                 --np->queuedccbs;
5320                 cp->queued = 0;
5321         }
5322 }
5323
5324 /*
5325 **      The NCR has completed CCBs.
5326 **      Look at the DONE QUEUE if enabled, otherwise scan all CCBs
5327 */
5328 void ncr_wakeup_done (ncb_p np)
5329 {
5330         ccb_p cp;
5331 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
5332         int i, j;
5333
5334         i = np->ccb_done_ic;
5335         while (1) {
5336                 j = i+1;
5337                 if (j >= MAX_DONE)
5338                         j = 0;
5339
5340                 cp = np->ccb_done[j];
5341                 if (!CCB_DONE_VALID(cp))
5342                         break;
5343
5344                 np->ccb_done[j] = (ccb_p) CCB_DONE_EMPTY;
5345                 np->scripth->done_queue[5*j + 4] =
5346                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5347                 MEMORY_BARRIER();
5348                 np->scripth->done_queue[5*i + 4] =
5349                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5350
5351                 if (cp->host_status & HS_DONEMASK)
5352                         ncr_complete (np, cp);
5353                 else if (cp->host_status & HS_SKIPMASK)
5354                         ncr_ccb_skipped (np, cp);
5355
5356                 i = j;
5357         }
5358         np->ccb_done_ic = i;
5359 #else
5360         cp = np->ccb;
5361         while (cp) {
5362                 if (cp->host_status & HS_DONEMASK)
5363                         ncr_complete (np, cp);
5364                 else if (cp->host_status & HS_SKIPMASK)
5365                         ncr_ccb_skipped (np, cp);
5366                 cp = cp->link_ccb;
5367         }
5368 #endif
5369 }
5370
5371 /*
5372 **      Complete all active CCBs.
5373 */
5374 void ncr_wakeup (ncb_p np, u_long code)
5375 {
5376         ccb_p cp = np->ccb;
5377
5378         while (cp) {
5379                 if (cp->host_status != HS_IDLE) {
5380                         cp->host_status = code;
5381                         ncr_complete (np, cp);
5382                 }
5383                 cp = cp->link_ccb;
5384         }
5385 }
5386
5387 /*
5388 ** Reset ncr chip.
5389 */
5390
5391 /* Some initialisation must be done immediately following reset, for 53c720,
5392  * at least.  EA (dcntl bit 5) isn't set here as it is set once only in
5393  * the _detect function.
5394  */
5395 static void ncr_chip_reset(ncb_p np, int delay)
5396 {
5397         OUTB (nc_istat,  SRST);
5398         UDELAY (delay);
5399         OUTB (nc_istat,  0   );
5400
5401         if (np->features & FE_EHP)
5402                 OUTB (nc_ctest0, EHP);
5403         if (np->features & FE_MUX)
5404                 OUTB (nc_ctest4, MUX);
5405 }
5406
5407
5408 /*==========================================================
5409 **
5410 **
5411 **      Start NCR chip.
5412 **
5413 **
5414 **==========================================================
5415 */
5416
5417 void ncr_init (ncb_p np, int reset, char * msg, u_long code)
5418 {
5419         int     i;
5420
5421         /*
5422         **      Reset chip if asked, otherwise just clear fifos.
5423         */
5424
5425         if (reset) {
5426                 OUTB (nc_istat,  SRST);
5427                 UDELAY (100);
5428         }
5429         else {
5430                 OUTB (nc_stest3, TE|CSF);
5431                 OUTONB (nc_ctest3, CLF);
5432         }
5433  
5434         /*
5435         **      Message.
5436         */
5437
5438         if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
5439
5440         /*
5441         **      Clear Start Queue
5442         */
5443         np->queuedepth = MAX_START - 1; /* 1 entry needed as end marker */
5444         for (i = 1; i < MAX_START + MAX_START; i += 2)
5445                 np->scripth0->tryloop[i] =
5446                                 cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5447
5448         /*
5449         **      Start at first entry.
5450         */
5451         np->squeueput = 0;
5452         np->script0->startpos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np, tryloop));
5453
5454 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
5455         /*
5456         **      Clear Done Queue
5457         */
5458         for (i = 0; i < MAX_DONE; i++) {
5459                 np->ccb_done[i] = (ccb_p) CCB_DONE_EMPTY;
5460                 np->scripth0->done_queue[5*i + 4] =
5461                         cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5462         }
5463 #endif
5464
5465         /*
5466         **      Start at first entry.
5467         */
5468         np->script0->done_pos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np,done_queue));
5469         np->ccb_done_ic = MAX_DONE-1;
5470         np->scripth0->done_queue[5*(MAX_DONE-1) + 4] =
5471                         cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5472
5473         /*
5474         **      Wakeup all pending jobs.
5475         */
5476         ncr_wakeup (np, code);
5477
5478         /*
5479         **      Init chip.
5480         */
5481
5482         /*
5483         ** Remove reset; big delay because the 895 needs time for the
5484         ** bus mode to settle
5485         */
5486         ncr_chip_reset(np, 2000);
5487
5488         OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
5489                                         /*  full arb., ena parity, par->ATN  */
5490         OUTB (nc_scntl1, 0x00);         /*  odd parity, and remove CRST!! */
5491
5492         ncr_selectclock(np, np->rv_scntl3);     /* Select SCSI clock */
5493
5494         OUTB (nc_scid  , RRE|np->myaddr);       /* Adapter SCSI address */
5495         OUTW (nc_respid, 1ul<<np->myaddr);      /* Id to respond to */
5496         OUTB (nc_istat , SIGP   );              /*  Signal Process */
5497         OUTB (nc_dmode , np->rv_dmode);         /* Burst length, dma mode */
5498         OUTB (nc_ctest5, np->rv_ctest5);        /* Large fifo + large burst */
5499
5500         OUTB (nc_dcntl , NOCOM|np->rv_dcntl);   /* Protect SFBR */
5501         OUTB (nc_ctest0, np->rv_ctest0);        /* 720: CDIS and EHP */
5502         OUTB (nc_ctest3, np->rv_ctest3);        /* Write and invalidate */
5503         OUTB (nc_ctest4, np->rv_ctest4);        /* Master parity checking */
5504
5505         OUTB (nc_stest2, EXT|np->rv_stest2);    /* Extended Sreq/Sack filtering */
5506         OUTB (nc_stest3, TE);                   /* TolerANT enable */
5507         OUTB (nc_stime0, 0x0c   );              /* HTH disabled  STO 0.25 sec */
5508
5509         /*
5510         **      Disable disconnects.
5511         */
5512
5513         np->disc = 0;
5514
5515         /*
5516         **    Enable GPIO0 pin for writing if LED support.
5517         */
5518
5519         if (np->features & FE_LED0) {
5520                 OUTOFFB (nc_gpcntl, 0x01);
5521         }
5522
5523         /*
5524         **      enable ints
5525         */
5526
5527         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
5528         OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
5529
5530         /*
5531         **      For 895/6 enable SBMC interrupt and save current SCSI bus mode.
5532         */
5533         if (np->features & FE_ULTRA2) {
5534                 OUTONW (nc_sien, SBMC);
5535                 np->scsi_mode = INB (nc_stest4) & SMODE;
5536         }
5537
5538         /*
5539         **      DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
5540         **      Disable overlapped arbitration.
5541         **      All 896 chips are also affected by this errata.
5542         */
5543         if (np->device_id == PCI_DEVICE_ID_NCR_53C875)
5544                 OUTB (nc_ctest0, (1<<5));
5545         else if (np->device_id == PCI_DEVICE_ID_NCR_53C896)
5546                 OUTB (nc_ccntl0, DPR);
5547
5548         /*
5549         **      Fill in target structure.
5550         **      Reinitialize usrsync.
5551         **      Reinitialize usrwide.
5552         **      Prepare sync negotiation according to actual SCSI bus mode.
5553         */
5554
5555         for (i=0;i<MAX_TARGET;i++) {
5556                 tcb_p tp = &np->target[i];
5557
5558                 tp->sval    = 0;
5559                 tp->wval    = np->rv_scntl3;
5560
5561                 if (tp->usrsync != 255) {
5562                         if (tp->usrsync <= np->maxsync) {
5563                                 if (tp->usrsync < np->minsync) {
5564                                         tp->usrsync = np->minsync;
5565                                 }
5566                         }
5567                         else
5568                                 tp->usrsync = 255;
5569                 };
5570
5571                 if (tp->usrwide > np->maxwide)
5572                         tp->usrwide = np->maxwide;
5573
5574                 ncr_negotiate (np, tp);
5575         }
5576
5577         /*
5578         **    Start script processor.
5579         */
5580         if (np->paddr2) {
5581                 if (bootverbose)
5582                         printk ("%s: Downloading SCSI SCRIPTS.\n",
5583                                 ncr_name(np));
5584                 OUTL (nc_scratcha, vtobus(np->script0));
5585                 OUTL_DSP (NCB_SCRIPTH_PHYS (np, start_ram));
5586         }
5587         else
5588                 OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
5589 }
5590
5591 /*==========================================================
5592 **
5593 **      Prepare the negotiation values for wide and
5594 **      synchronous transfers.
5595 **
5596 **==========================================================
5597 */
5598
5599 static void ncr_negotiate (struct ncb* np, struct tcb* tp)
5600 {
5601         /*
5602         **      minsync unit is 4ns !
5603         */
5604
5605         u_long minsync = tp->usrsync;
5606
5607         /*
5608         **      SCSI bus mode limit
5609         */
5610
5611         if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
5612                 if (minsync < 12) minsync = 12;
5613         }
5614
5615         /*
5616         **      our limit ..
5617         */
5618
5619         if (minsync < np->minsync)
5620                 minsync = np->minsync;
5621
5622         /*
5623         **      divider limit
5624         */
5625
5626         if (minsync > np->maxsync)
5627                 minsync = 255;
5628
5629         tp->minsync = minsync;
5630         tp->maxoffs = (minsync<255 ? np->maxoffs : 0);
5631
5632         /*
5633         **      period=0: has to negotiate sync transfer
5634         */
5635
5636         tp->period=0;
5637
5638         /*
5639         **      widedone=0: has to negotiate wide transfer
5640         */
5641         tp->widedone=0;
5642 }
5643
5644 /*==========================================================
5645 **
5646 **      Get clock factor and sync divisor for a given 
5647 **      synchronous factor period.
5648 **      Returns the clock factor (in sxfer) and scntl3 
5649 **      synchronous divisor field.
5650 **
5651 **==========================================================
5652 */
5653
5654 static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
5655 {
5656         u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
5657         int     div = np->clock_divn;   /* Number of divisors supported */
5658         u_long  fak;                    /* Sync factor in sxfer         */
5659         u_long  per;                    /* Period in tenths of ns       */
5660         u_long  kpc;                    /* (per * clk)                  */
5661
5662         /*
5663         **      Compute the synchronous period in tenths of nano-seconds
5664         */
5665         if      (sfac <= 10)    per = 250;
5666         else if (sfac == 11)    per = 303;
5667         else if (sfac == 12)    per = 500;
5668         else                    per = 40 * sfac;
5669
5670         /*
5671         **      Look for the greatest clock divisor that allows an 
5672         **      input speed faster than the period.
5673         */
5674         kpc = per * clk;
5675         while (--div >= 0)
5676                 if (kpc >= (div_10M[div] << 2)) break;
5677
5678         /*
5679         **      Calculate the lowest clock factor that allows an output 
5680         **      speed not faster than the period.
5681         */
5682         fak = (kpc - 1) / div_10M[div] + 1;
5683
5684 #if 0   /* This optimization does not seem very useful */
5685
5686         per = (fak * div_10M[div]) / clk;
5687
5688         /*
5689         **      Why not to try the immediate lower divisor and to choose 
5690         **      the one that allows the fastest output speed ?
5691         **      We don't want input speed too much greater than output speed.
5692         */
5693         if (div >= 1 && fak < 8) {
5694                 u_long fak2, per2;
5695                 fak2 = (kpc - 1) / div_10M[div-1] + 1;
5696                 per2 = (fak2 * div_10M[div-1]) / clk;
5697                 if (per2 < per && fak2 <= 8) {
5698                         fak = fak2;
5699                         per = per2;
5700                         --div;
5701                 }
5702         }
5703 #endif
5704
5705         if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
5706
5707         /*
5708         **      Compute and return sync parameters for the ncr
5709         */
5710         *fakp           = fak - 4;
5711         *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
5712 }
5713
5714
5715 /*==========================================================
5716 **
5717 **      Set actual values, sync status and patch all ccbs of 
5718 **      a target according to new sync/wide agreement.
5719 **
5720 **==========================================================
5721 */
5722
5723 static void ncr_set_sync_wide_status (ncb_p np, u_char target)
5724 {
5725         ccb_p cp;
5726         tcb_p tp = &np->target[target];
5727
5728         /*
5729         **      set actual value and sync_status
5730         */
5731         OUTB (nc_sxfer, tp->sval);
5732         np->sync_st = tp->sval;
5733         OUTB (nc_scntl3, tp->wval);
5734         np->wide_st = tp->wval;
5735
5736         /*
5737         **      patch ALL ccbs of this target.
5738         */
5739         for (cp = np->ccb; cp; cp = cp->link_ccb) {
5740                 if (!cp->cmd) continue;
5741                 if (cp->cmd->device->id != target) continue;
5742 #if 0
5743                 cp->sync_status = tp->sval;
5744                 cp->wide_status = tp->wval;
5745 #endif
5746                 cp->phys.select.sel_scntl3 = tp->wval;
5747                 cp->phys.select.sel_sxfer  = tp->sval;
5748         };
5749 }
5750
5751 /*==========================================================
5752 **
5753 **      Switch sync mode for current job and it's target
5754 **
5755 **==========================================================
5756 */
5757
5758 static void ncr_setsync (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer)
5759 {
5760         Scsi_Cmnd *cmd;
5761         tcb_p tp;
5762         u_char target = INB (nc_sdid) & 0x0f;
5763         u_char idiv;
5764
5765         assert (cp && cp->cmd);
5766         if (!cp) return;
5767
5768         cmd = cp->cmd;
5769         if (!cmd) return;
5770
5771         assert (target == (cmd->device->id & 0xf));
5772
5773         tp = &np->target[target];
5774
5775         if (!scntl3 || !(sxfer & 0x1f))
5776                 scntl3 = np->rv_scntl3;
5777         scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) | (np->rv_scntl3 & 0x07);
5778
5779         /*
5780         **      Deduce the value of controller sync period from scntl3.
5781         **      period is in tenths of nano-seconds.
5782         */
5783
5784         idiv = ((scntl3 >> 4) & 0x7);
5785         if ((sxfer & 0x1f) && idiv)
5786                 tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
5787         else
5788                 tp->period = 0xffff;
5789
5790         /*
5791         **       Stop there if sync parameters are unchanged
5792         */
5793         if (tp->sval == sxfer && tp->wval == scntl3) return;
5794         tp->sval = sxfer;
5795         tp->wval = scntl3;
5796
5797         /*
5798         **      Bells and whistles   ;-)
5799         */
5800         PRINT_TARGET(np, target);
5801         if (sxfer & 0x01f) {
5802                 unsigned f10 = 100000 << (tp->widedone ? tp->widedone -1 : 0);
5803                 unsigned mb10 = (f10 + tp->period/2) / tp->period;
5804                 char *scsi;
5805
5806                 /*
5807                 **  Disable extended Sreq/Sack filtering
5808                 */
5809                 if (tp->period <= 2000) OUTOFFB (nc_stest2, EXT);
5810
5811                 /*
5812                 **      Bells and whistles   ;-)
5813                 */
5814                 if      (tp->period < 500)      scsi = "FAST-40";
5815                 else if (tp->period < 1000)     scsi = "FAST-20";
5816                 else if (tp->period < 2000)     scsi = "FAST-10";
5817                 else                            scsi = "FAST-5";
5818
5819                 printk ("%s %sSCSI %d.%d MB/s (%d ns, offset %d)\n", scsi,
5820                         tp->widedone > 1 ? "WIDE " : "",
5821                         mb10 / 10, mb10 % 10, tp->period / 10, sxfer & 0x1f);
5822         } else
5823                 printk ("%sasynchronous.\n", tp->widedone > 1 ? "wide " : "");
5824
5825         /*
5826         **      set actual value and sync_status
5827         **      patch ALL ccbs of this target.
5828         */
5829         ncr_set_sync_wide_status(np, target);
5830 }
5831
5832 /*==========================================================
5833 **
5834 **      Switch wide mode for current job and it's target
5835 **      SCSI specs say: a SCSI device that accepts a WDTR 
5836 **      message shall reset the synchronous agreement to 
5837 **      asynchronous mode.
5838 **
5839 **==========================================================
5840 */
5841
5842 static void ncr_setwide (ncb_p np, ccb_p cp, u_char wide, u_char ack)
5843 {
5844         Scsi_Cmnd *cmd;
5845         u_short target = INB (nc_sdid) & 0x0f;
5846         tcb_p tp;
5847         u_char  scntl3;
5848         u_char  sxfer;
5849
5850         assert (cp && cp->cmd);
5851         if (!cp) return;
5852
5853         cmd = cp->cmd;
5854         if (!cmd) return;
5855
5856         assert (target == (cmd->device->id & 0xf));
5857
5858         tp = &np->target[target];
5859         tp->widedone  =  wide+1;
5860         scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
5861
5862         sxfer = ack ? 0 : tp->sval;
5863
5864         /*
5865         **       Stop there if sync/wide parameters are unchanged
5866         */
5867         if (tp->sval == sxfer && tp->wval == scntl3) return;
5868         tp->sval = sxfer;
5869         tp->wval = scntl3;
5870
5871         /*
5872         **      Bells and whistles   ;-)
5873         */
5874         if (bootverbose >= 2) {
5875                 PRINT_TARGET(np, target);
5876                 if (scntl3 & EWS)
5877                         printk ("WIDE SCSI (16 bit) enabled.\n");
5878                 else
5879                         printk ("WIDE SCSI disabled.\n");
5880         }
5881
5882         /*
5883         **      set actual value and sync_status
5884         **      patch ALL ccbs of this target.
5885         */
5886         ncr_set_sync_wide_status(np, target);
5887 }
5888
5889 /*==========================================================
5890 **
5891 **      Switch tagged mode for a target.
5892 **
5893 **==========================================================
5894 */
5895
5896 static void ncr_setup_tags (ncb_p np, u_char tn, u_char ln)
5897 {
5898         tcb_p tp = &np->target[tn];
5899         lcb_p lp = tp->lp[ln];
5900         u_char   reqtags, maxdepth;
5901
5902         /*
5903         **      Just in case ...
5904         */
5905         if ((!tp) || (!lp))
5906                 return;
5907
5908         /*
5909         **      If SCSI device queue depth is not yet set, leave here.
5910         */
5911         if (!lp->scdev_depth)
5912                 return;
5913
5914         /*
5915         **      Donnot allow more tags than the SCSI driver can queue 
5916         **      for this device.
5917         **      Donnot allow more tags than we can handle.
5918         */
5919         maxdepth = lp->scdev_depth;
5920         if (maxdepth > lp->maxnxs)      maxdepth    = lp->maxnxs;
5921         if (lp->maxtags > maxdepth)     lp->maxtags = maxdepth;
5922         if (lp->numtags > maxdepth)     lp->numtags = maxdepth;
5923
5924         /*
5925         **      only devices conformant to ANSI Version >= 2
5926         **      only devices capable of tagged commands
5927         **      only if enabled by user ..
5928         */
5929         if ((lp->inq_byte7 & INQ7_QUEUE) && lp->numtags > 1) {
5930                 reqtags = lp->numtags;
5931         } else {
5932                 reqtags = 1;
5933         };
5934
5935         /*
5936         **      Update max number of tags
5937         */
5938         lp->numtags = reqtags;
5939         if (lp->numtags > lp->maxtags)
5940                 lp->maxtags = lp->numtags;
5941
5942         /*
5943         **      If we want to switch tag mode, we must wait 
5944         **      for no CCB to be active.
5945         */
5946         if      (reqtags > 1 && lp->usetags) {   /* Stay in tagged mode    */
5947                 if (lp->queuedepth == reqtags)   /* Already announced      */
5948                         return;
5949                 lp->queuedepth  = reqtags;
5950         }
5951         else if (reqtags <= 1 && !lp->usetags) { /* Stay in untagged mode  */
5952                 lp->queuedepth  = reqtags;
5953                 return;
5954         }
5955         else {                                   /* Want to switch tag mode */
5956                 if (lp->busyccbs)                /* If not yet safe, return */
5957                         return;
5958                 lp->queuedepth  = reqtags;
5959                 lp->usetags     = reqtags > 1 ? 1 : 0;
5960         }
5961
5962         /*
5963         **      Patch the lun mini-script, according to tag mode.
5964         */
5965         lp->jump_tag.l_paddr = lp->usetags?
5966                         cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_tag)) :
5967                         cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
5968
5969         /*
5970         **      Announce change to user.
5971         */
5972         if (bootverbose) {
5973                 PRINT_LUN(np, tn, ln);
5974                 if (lp->usetags) {
5975                         printk("tagged command queue depth set to %d\n", reqtags);
5976                 }
5977                 else {
5978                         printk("tagged command queueing disabled\n");
5979                 }
5980         }
5981 }
5982
5983 /*----------------------------------------------------
5984 **
5985 **      handle user commands
5986 **
5987 **----------------------------------------------------
5988 */
5989
5990 #ifdef SCSI_NCR_USER_COMMAND_SUPPORT
5991
5992 static void ncr_usercmd (ncb_p np)
5993 {
5994         u_char t;
5995         tcb_p tp;
5996
5997         switch (np->user.cmd) {
5998
5999         case 0: return;
6000
6001         case UC_SETSYNC:
6002                 for (t=0; t<MAX_TARGET; t++) {
6003                         if (!((np->user.target>>t)&1)) continue;
6004                         tp = &np->target[t];
6005                         tp->usrsync = np->user.data;
6006                         ncr_negotiate (np, tp);
6007                 };
6008                 break;
6009
6010         case UC_SETTAGS:
6011                 for (t=0; t<MAX_TARGET; t++) {
6012                         int ln;
6013                         if (!((np->user.target>>t)&1)) continue;
6014                         np->target[t].usrtags = np->user.data;
6015                         for (ln = 0; ln < MAX_LUN; ln++) {
6016                                 lcb_p lp = np->target[t].lp[ln];
6017                                 if (!lp)
6018                                         continue;
6019                                 lp->maxtags = lp->numtags = np->user.data;
6020                                 ncr_setup_tags (np, t, ln);
6021                         }
6022                 };
6023                 break;
6024
6025         case UC_SETDEBUG:
6026 #ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
6027                 ncr_debug = np->user.data;
6028 #endif
6029                 break;
6030
6031         case UC_SETORDER:
6032                 np->order = np->user.data;
6033                 break;
6034
6035         case UC_SETVERBOSE:
6036                 np->verbose = np->user.data;
6037                 break;
6038
6039         case UC_SETWIDE:
6040                 for (t=0; t<MAX_TARGET; t++) {
6041                         u_long size;
6042                         if (!((np->user.target>>t)&1)) continue;
6043                         tp = &np->target[t];
6044                         size = np->user.data;
6045                         if (size > np->maxwide) size=np->maxwide;
6046                         tp->usrwide = size;
6047                         ncr_negotiate (np, tp);
6048                 };
6049                 break;
6050
6051         case UC_SETFLAG:
6052                 for (t=0; t<MAX_TARGET; t++) {
6053                         if (!((np->user.target>>t)&1)) continue;
6054                         tp = &np->target[t];
6055                         tp->usrflag = np->user.data;
6056                 };
6057                 break;
6058         }
6059         np->user.cmd=0;
6060 }
6061 #endif
6062
6063 /*==========================================================
6064 **
6065 **
6066 **      ncr timeout handler.
6067 **
6068 **
6069 **==========================================================
6070 **
6071 **      Misused to keep the driver running when
6072 **      interrupts are not configured correctly.
6073 **
6074 **----------------------------------------------------------
6075 */
6076
6077 static void ncr_timeout (ncb_p np)
6078 {
6079         u_long  thistime = ktime_get(0);
6080
6081         /*
6082         **      If release process in progress, let's go
6083         **      Set the release stage from 1 to 2 to synchronize
6084         **      with the release process.
6085         */
6086
6087         if (np->release_stage) {
6088                 if (np->release_stage == 1) np->release_stage = 2;
6089                 return;
6090         }
6091
6092         np->timer.expires = ktime_get(SCSI_NCR_TIMER_INTERVAL);
6093         add_timer(&np->timer);
6094
6095         /*
6096         **      If we are resetting the ncr, wait for settle_time before 
6097         **      clearing it. Then command processing will be resumed.
6098         */
6099         if (np->settle_time) {
6100                 if (np->settle_time <= thistime) {
6101                         if (bootverbose > 1)
6102                                 printk("%s: command processing resumed\n", ncr_name(np));
6103                         np->settle_time = 0;
6104                         np->disc        = 1;
6105                         requeue_waiting_list(np);
6106                 }
6107                 return;
6108         }
6109
6110         /*
6111         **      Since the generic scsi driver only allows us 0.5 second 
6112         **      to perform abort of a command, we must look at ccbs about 
6113         **      every 0.25 second.
6114         */
6115         if (np->lasttime + 4*HZ < thistime) {
6116                 /*
6117                 **      block ncr interrupts
6118                 */
6119                 np->lasttime = thistime;
6120         }
6121
6122 #ifdef SCSI_NCR_BROKEN_INTR
6123         if (INB(nc_istat) & (INTF|SIP|DIP)) {
6124
6125                 /*
6126                 **      Process pending interrupts.
6127                 */
6128                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
6129                 ncr_exception (np);
6130                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
6131         }
6132 #endif /* SCSI_NCR_BROKEN_INTR */
6133 }
6134
6135 /*==========================================================
6136 **
6137 **      log message for real hard errors
6138 **
6139 **      "ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
6140 **      "             reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
6141 **
6142 **      exception register:
6143 **              ds:     dstat
6144 **              si:     sist
6145 **
6146 **      SCSI bus lines:
6147 **              so:     control lines as driver by NCR.
6148 **              si:     control lines as seen by NCR.
6149 **              sd:     scsi data lines as seen by NCR.
6150 **
6151 **      wide/fastmode:
6152 **              sxfer:  (see the manual)
6153 **              scntl3: (see the manual)
6154 **
6155 **      current script command:
6156 **              dsp:    script address (relative to start of script).
6157 **              dbc:    first word of script command.
6158 **
6159 **      First 16 register of the chip:
6160 **              r0..rf
6161 **
6162 **==========================================================
6163 */
6164
6165 static void ncr_log_hard_error(ncb_p np, u_short sist, u_char dstat)
6166 {
6167         u32     dsp;
6168         int     script_ofs;
6169         int     script_size;
6170         char    *script_name;
6171         u_char  *script_base;
6172         int     i;
6173
6174         dsp     = INL (nc_dsp);
6175
6176         if (dsp > np->p_script && dsp <= np->p_script + sizeof(struct script)) {
6177                 script_ofs      = dsp - np->p_script;
6178                 script_size     = sizeof(struct script);
6179                 script_base     = (u_char *) np->script0;
6180                 script_name     = "script";
6181         }
6182         else if (np->p_scripth < dsp && 
6183                  dsp <= np->p_scripth + sizeof(struct scripth)) {
6184                 script_ofs      = dsp - np->p_scripth;
6185                 script_size     = sizeof(struct scripth);
6186                 script_base     = (u_char *) np->scripth0;
6187                 script_name     = "scripth";
6188         } else {
6189                 script_ofs      = dsp;
6190                 script_size     = 0;
6191                 script_base     = 0;
6192                 script_name     = "mem";
6193         }
6194
6195         printk ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
6196                 ncr_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
6197                 (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
6198                 (unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
6199                 (unsigned)INL (nc_dbc));
6200
6201         if (((script_ofs & 3) == 0) &&
6202             (unsigned)script_ofs < script_size) {
6203                 printk ("%s: script cmd = %08x\n", ncr_name(np),
6204                         scr_to_cpu((int) *(ncrcmd *)(script_base + script_ofs)));
6205         }
6206
6207         printk ("%s: regdump:", ncr_name(np));
6208         for (i=0; i<16;i++)
6209             printk (" %02x", (unsigned)INB_OFF(i));
6210         printk (".\n");
6211 }
6212
6213 /*============================================================
6214 **
6215 **      ncr chip exception handler.
6216 **
6217 **============================================================
6218 **
6219 **      In normal cases, interrupt conditions occur one at a 
6220 **      time. The ncr is able to stack in some extra registers 
6221 **      other interrupts that will occurs after the first one.
6222 **      But severall interrupts may occur at the same time.
6223 **
6224 **      We probably should only try to deal with the normal 
6225 **      case, but it seems that multiple interrupts occur in 
6226 **      some cases that are not abnormal at all.
6227 **
6228 **      The most frequent interrupt condition is Phase Mismatch.
6229 **      We should want to service this interrupt quickly.
6230 **      A SCSI parity error may be delivered at the same time.
6231 **      The SIR interrupt is not very frequent in this driver, 
6232 **      since the INTFLY is likely used for command completion 
6233 **      signaling.
6234 **      The Selection Timeout interrupt may be triggered with 
6235 **      IID and/or UDC.
6236 **      The SBMC interrupt (SCSI Bus Mode Change) may probably 
6237 **      occur at any time.
6238 **
6239 **      This handler try to deal as cleverly as possible with all
6240 **      the above.
6241 **
6242 **============================================================
6243 */
6244
6245 void ncr_exception (ncb_p np)
6246 {
6247         u_char  istat, dstat;
6248         u_short sist;
6249         int     i;
6250
6251         /*
6252         **      interrupt on the fly ?
6253         **      Since the global header may be copied back to a CCB 
6254         **      using a posted PCI memory write, the last operation on 
6255         **      the istat register is a READ in order to flush posted 
6256         **      PCI write commands.
6257         */
6258         istat = INB (nc_istat);
6259         if (istat & INTF) {
6260                 OUTB (nc_istat, (istat & SIGP) | INTF);
6261                 istat = INB (nc_istat);
6262                 if (DEBUG_FLAGS & DEBUG_TINY) printk ("F ");
6263                 ncr_wakeup_done (np);
6264         };
6265
6266         if (!(istat & (SIP|DIP)))
6267                 return;
6268
6269         if (istat & CABRT)
6270                 OUTB (nc_istat, CABRT);
6271
6272         /*
6273         **      Steinbach's Guideline for Systems Programming:
6274         **      Never test for an error condition you don't know how to handle.
6275         */
6276
6277         sist  = (istat & SIP) ? INW (nc_sist)  : 0;
6278         dstat = (istat & DIP) ? INB (nc_dstat) : 0;
6279
6280         if (DEBUG_FLAGS & DEBUG_TINY)
6281                 printk ("<%d|%x:%x|%x:%x>",
6282                         (int)INB(nc_scr0),
6283                         dstat,sist,
6284                         (unsigned)INL(nc_dsp),
6285                         (unsigned)INL(nc_dbc));
6286
6287         /*========================================================
6288         **      First, interrupts we want to service cleanly.
6289         **
6290         **      Phase mismatch is the most frequent interrupt, and 
6291         **      so we have to service it as quickly and as cleanly 
6292         **      as possible.
6293         **      Programmed interrupts are rarely used in this driver,
6294         **      but we must handle them cleanly anyway.
6295         **      We try to deal with PAR and SBMC combined with 
6296         **      some other interrupt(s).
6297         **=========================================================
6298         */
6299
6300         if (!(sist  & (STO|GEN|HTH|SGE|UDC|RST)) &&
6301             !(dstat & (MDPE|BF|ABRT|IID))) {
6302                 if ((sist & SBMC) && ncr_int_sbmc (np))
6303                         return;
6304                 if ((sist & PAR)  && ncr_int_par  (np))
6305                         return;
6306                 if (sist & MA) {
6307                         ncr_int_ma (np);
6308                         return;
6309                 }
6310                 if (dstat & SIR) {
6311                         ncr_int_sir (np);
6312                         return;
6313                 }
6314                 /*
6315                 **  DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 2.
6316                 */
6317                 if (!(sist & (SBMC|PAR)) && !(dstat & SSI)) {
6318                         printk( "%s: unknown interrupt(s) ignored, "
6319                                 "ISTAT=%x DSTAT=%x SIST=%x\n",
6320                                 ncr_name(np), istat, dstat, sist);
6321                         return;
6322                 }
6323                 OUTONB_STD ();
6324                 return;
6325         };
6326
6327         /*========================================================
6328         **      Now, interrupts that need some fixing up.
6329         **      Order and multiple interrupts is so less important.
6330         **
6331         **      If SRST has been asserted, we just reset the chip.
6332         **
6333         **      Selection is intirely handled by the chip. If the 
6334         **      chip says STO, we trust it. Seems some other 
6335         **      interrupts may occur at the same time (UDC, IID), so 
6336         **      we ignore them. In any case we do enough fix-up 
6337         **      in the service routine.
6338         **      We just exclude some fatal dma errors.
6339         **=========================================================
6340         */
6341
6342         if (sist & RST) {
6343                 ncr_init (np, 1, bootverbose ? "scsi reset" : NULL, HS_RESET);
6344                 return;
6345         };
6346
6347         if ((sist & STO) &&
6348                 !(dstat & (MDPE|BF|ABRT))) {
6349         /*
6350         **      DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 1.
6351         */
6352                 OUTONB (nc_ctest3, CLF);
6353
6354                 ncr_int_sto (np);
6355                 return;
6356         };
6357
6358         /*=========================================================
6359         **      Now, interrupts we are not able to recover cleanly.
6360         **      (At least for the moment).
6361         **
6362         **      Do the register dump.
6363         **      Log message for real hard errors.
6364         **      Clear all fifos.
6365         **      For MDPE, BF, ABORT, IID, SGE and HTH we reset the 
6366         **      BUS and the chip.
6367         **      We are more soft for UDC.
6368         **=========================================================
6369         */
6370
6371         if (ktime_exp(np->regtime)) {
6372                 np->regtime = ktime_get(10*HZ);
6373                 for (i = 0; i<sizeof(np->regdump); i++)
6374                         ((char*)&np->regdump)[i] = INB_OFF(i);
6375                 np->regdump.nc_dstat = dstat;
6376                 np->regdump.nc_sist  = sist;
6377         };
6378
6379         ncr_log_hard_error(np, sist, dstat);
6380
6381         printk ("%s: have to clear fifos.\n", ncr_name (np));
6382         OUTB (nc_stest3, TE|CSF);
6383         OUTONB (nc_ctest3, CLF);
6384
6385         if ((sist & (SGE)) ||
6386                 (dstat & (MDPE|BF|ABRT|IID))) {
6387                 ncr_start_reset(np);
6388                 return;
6389         };
6390
6391         if (sist & HTH) {
6392                 printk ("%s: handshake timeout\n", ncr_name(np));
6393                 ncr_start_reset(np);
6394                 return;
6395         };
6396
6397         if (sist & UDC) {
6398                 printk ("%s: unexpected disconnect\n", ncr_name(np));
6399                 OUTB (HS_PRT, HS_UNEXPECTED);
6400                 OUTL_DSP (NCB_SCRIPT_PHYS (np, cleanup));
6401                 return;
6402         };
6403
6404         /*=========================================================
6405         **      We just miss the cause of the interrupt. :(
6406         **      Print a message. The timeout will do the real work.
6407         **=========================================================
6408         */
6409         printk ("%s: unknown interrupt\n", ncr_name(np));
6410 }
6411
6412 /*==========================================================
6413 **
6414 **      ncr chip exception handler for selection timeout
6415 **
6416 **==========================================================
6417 **
6418 **      There seems to be a bug in the 53c810.
6419 **      Although a STO-Interrupt is pending,
6420 **      it continues executing script commands.
6421 **      But it will fail and interrupt (IID) on
6422 **      the next instruction where it's looking
6423 **      for a valid phase.
6424 **
6425 **----------------------------------------------------------
6426 */
6427
6428 void ncr_int_sto (ncb_p np)
6429 {
6430         u_long dsa;
6431         ccb_p cp;
6432         if (DEBUG_FLAGS & DEBUG_TINY) printk ("T");
6433
6434         /*
6435         **      look for ccb and set the status.
6436         */
6437
6438         dsa = INL (nc_dsa);
6439         cp = np->ccb;
6440         while (cp && (CCB_PHYS (cp, phys) != dsa))
6441                 cp = cp->link_ccb;
6442
6443         if (cp) {
6444                 cp-> host_status = HS_SEL_TIMEOUT;
6445                 ncr_complete (np, cp);
6446         };
6447
6448         /*
6449         **      repair start queue and jump to start point.
6450         */
6451
6452         OUTL_DSP (NCB_SCRIPTH_PHYS (np, sto_restart));
6453         return;
6454 }
6455
6456 /*==========================================================
6457 **
6458 **      ncr chip exception handler for SCSI bus mode change
6459 **
6460 **==========================================================
6461 **
6462 **      spi2-r12 11.2.3 says a transceiver mode change must 
6463 **      generate a reset event and a device that detects a reset 
6464 **      event shall initiate a hard reset. It says also that a
6465 **      device that detects a mode change shall set data transfer 
6466 **      mode to eight bit asynchronous, etc...
6467 **      So, just resetting should be enough.
6468 **       
6469 **
6470 **----------------------------------------------------------
6471 */
6472
6473 static int ncr_int_sbmc (ncb_p np)
6474 {
6475         u_char scsi_mode = INB (nc_stest4) & SMODE;
6476
6477         if (scsi_mode != np->scsi_mode) {
6478                 printk("%s: SCSI bus mode change from %x to %x.\n",
6479                         ncr_name(np), np->scsi_mode, scsi_mode);
6480
6481                 np->scsi_mode = scsi_mode;
6482
6483
6484                 /*
6485                 **      Suspend command processing for 1 second and 
6486                 **      reinitialize all except the chip.
6487                 */
6488                 np->settle_time = ktime_get(1*HZ);
6489                 ncr_init (np, 0, bootverbose ? "scsi mode change" : NULL, HS_RESET);
6490                 return 1;
6491         }
6492         return 0;
6493 }
6494
6495 /*==========================================================
6496 **
6497 **      ncr chip exception handler for SCSI parity error.
6498 **
6499 **==========================================================
6500 **
6501 **
6502 **----------------------------------------------------------
6503 */
6504
6505 static int ncr_int_par (ncb_p np)
6506 {
6507         u_char  hsts    = INB (HS_PRT);
6508         u32     dbc     = INL (nc_dbc);
6509         u_char  sstat1  = INB (nc_sstat1);
6510         int phase       = -1;
6511         int msg         = -1;
6512         u32 jmp;
6513
6514         printk("%s: SCSI parity error detected: SCR1=%d DBC=%x SSTAT1=%x\n",
6515                 ncr_name(np), hsts, dbc, sstat1);
6516
6517         /*
6518          *      Ignore the interrupt if the NCR is not connected 
6519          *      to the SCSI bus, since the right work should have  
6520          *      been done on unexpected disconnection handling.
6521          */
6522         if (!(INB (nc_scntl1) & ISCON))
6523                 return 0;
6524
6525         /*
6526          *      If the nexus is not clearly identified, reset the bus.
6527          *      We will try to do better later.
6528          */
6529         if (hsts & HS_INVALMASK)
6530                 goto reset_all;
6531
6532         /*
6533          *      If the SCSI parity error occurs in MSG IN phase, prepare a 
6534          *      MSG PARITY message. Otherwise, prepare a INITIATOR DETECTED 
6535          *      ERROR message and let the device decide to retry the command 
6536          *      or to terminate with check condition. If we were in MSG IN 
6537          *      phase waiting for the response of a negotiation, we will 
6538          *      get SIR_NEGO_FAILED at dispatch.
6539          */
6540         if (!(dbc & 0xc0000000))
6541                 phase = (dbc >> 24) & 7;
6542         if (phase == 7)
6543                 msg = M_PARITY;
6544         else
6545                 msg = M_ID_ERROR;
6546
6547 #ifdef SCSI_NCR_INTEGRITY_CHECKING
6548         /*
6549         **      Save error message. For integrity check use only.
6550         */
6551         if (np->check_integrity)
6552                 np->check_integ_par = msg;
6553 #endif
6554
6555         /*
6556          *      If the NCR stopped on a MOVE ^ DATA_IN, we jump to a 
6557          *      script that will ignore all data in bytes until phase 
6558          *      change, since we are not sure the chip will wait the phase 
6559          *      change prior to delivering the interrupt.
6560          */
6561         if (phase == 1)
6562                 jmp = NCB_SCRIPTH_PHYS (np, par_err_data_in);
6563         else
6564                 jmp = NCB_SCRIPTH_PHYS (np, par_err_other);
6565
6566         OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6567         OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6568
6569         np->msgout[0] = msg;
6570         OUTL_DSP (jmp);
6571         return 1;
6572
6573 reset_all:
6574         ncr_start_reset(np);
6575         return 1;
6576 }
6577
6578 /*==========================================================
6579 **
6580 **
6581 **      ncr chip exception handler for phase errors.
6582 **
6583 **
6584 **==========================================================
6585 **
6586 **      We have to construct a new transfer descriptor,
6587 **      to transfer the rest of the current block.
6588 **
6589 **----------------------------------------------------------
6590 */
6591
6592 static void ncr_int_ma (ncb_p np)
6593 {
6594         u32     dbc;
6595         u32     rest;
6596         u32     dsp;
6597         u32     dsa;
6598         u32     nxtdsp;
6599         u32     newtmp;
6600         u32     *vdsp;
6601         u32     oadr, olen;
6602         u32     *tblp;
6603         ncrcmd *newcmd;
6604         u_char  cmd, sbcl;
6605         ccb_p   cp;
6606
6607         dsp     = INL (nc_dsp);
6608         dbc     = INL (nc_dbc);
6609         sbcl    = INB (nc_sbcl);
6610
6611         cmd     = dbc >> 24;
6612         rest    = dbc & 0xffffff;
6613
6614         /*
6615         **      Take into account dma fifo and various buffers and latches,
6616         **      only if the interrupted phase is an OUTPUT phase.
6617         */
6618
6619         if ((cmd & 1) == 0) {
6620                 u_char  ctest5, ss0, ss2;
6621                 u_short delta;
6622
6623                 ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
6624                 if (ctest5 & DFS)
6625                         delta=(((ctest5 << 8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
6626                 else
6627                         delta=(INB (nc_dfifo) - rest) & 0x7f;
6628
6629                 /*
6630                 **      The data in the dma fifo has not been transferred to
6631                 **      the target -> add the amount to the rest
6632                 **      and clear the data.
6633                 **      Check the sstat2 register in case of wide transfer.
6634                 */
6635
6636                 rest += delta;
6637                 ss0  = INB (nc_sstat0);
6638                 if (ss0 & OLF) rest++;
6639                 if (ss0 & ORF) rest++;
6640                 if (INB(nc_scntl3) & EWS) {
6641                         ss2 = INB (nc_sstat2);
6642                         if (ss2 & OLF1) rest++;
6643                         if (ss2 & ORF1) rest++;
6644                 };
6645
6646                 if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6647                         printk ("P%x%x RL=%d D=%d SS0=%x ", cmd&7, sbcl&7,
6648                                 (unsigned) rest, (unsigned) delta, ss0);
6649
6650         } else  {
6651                 if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6652                         printk ("P%x%x RL=%d ", cmd&7, sbcl&7, rest);
6653         }
6654
6655         /*
6656         **      Clear fifos.
6657         */
6658         OUTONB (nc_ctest3, CLF );       /* clear dma fifo  */
6659         OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
6660
6661         /*
6662         **      locate matching cp.
6663         **      if the interrupted phase is DATA IN or DATA OUT,
6664         **      trust the global header.
6665         */
6666         dsa = INL (nc_dsa);
6667         if (!(cmd & 6)) {
6668                 cp = np->header.cp;
6669                 if (CCB_PHYS(cp, phys) != dsa)
6670                         cp = 0;
6671         } else {
6672                 cp  = np->ccb;
6673                 while (cp && (CCB_PHYS (cp, phys) != dsa))
6674                         cp = cp->link_ccb;
6675         }
6676
6677         /*
6678         **      try to find the interrupted script command,
6679         **      and the address at which to continue.
6680         */
6681         vdsp    = 0;
6682         nxtdsp  = 0;
6683         if      (dsp >  np->p_script &&
6684                  dsp <= np->p_script + sizeof(struct script)) {
6685                 vdsp = (u32 *)((char*)np->script0 + (dsp-np->p_script-8));
6686                 nxtdsp = dsp;
6687         }
6688         else if (dsp >  np->p_scripth &&
6689                  dsp <= np->p_scripth + sizeof(struct scripth)) {
6690                 vdsp = (u32 *)((char*)np->scripth0 + (dsp-np->p_scripth-8));
6691                 nxtdsp = dsp;
6692         }
6693         else if (cp) {
6694                 if      (dsp == CCB_PHYS (cp, patch[2])) {
6695                         vdsp = &cp->patch[0];
6696                         nxtdsp = scr_to_cpu(vdsp[3]);
6697                 }
6698                 else if (dsp == CCB_PHYS (cp, patch[6])) {
6699                         vdsp = &cp->patch[4];
6700                         nxtdsp = scr_to_cpu(vdsp[3]);
6701                 }
6702         }
6703
6704         /*
6705         **      log the information
6706         */
6707
6708         if (DEBUG_FLAGS & DEBUG_PHASE) {
6709                 printk ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
6710                         cp, np->header.cp,
6711                         (unsigned)dsp,
6712                         (unsigned)nxtdsp, vdsp, cmd);
6713         };
6714
6715         /*
6716         **      cp=0 means that the DSA does not point to a valid control 
6717         **      block. This should not happen since we donnot use multi-byte 
6718         **      move while we are being reselected ot after command complete.
6719         **      We are not able to recover from such a phase error.
6720         */
6721         if (!cp) {
6722                 printk ("%s: SCSI phase error fixup: "
6723                         "CCB already dequeued (0x%08lx)\n", 
6724                         ncr_name (np), (u_long) np->header.cp);
6725                 goto reset_all;
6726         }
6727
6728         /*
6729         **      get old startaddress and old length.
6730         */
6731
6732         oadr = scr_to_cpu(vdsp[1]);
6733
6734         if (cmd & 0x10) {       /* Table indirect */
6735                 tblp = (u32 *) ((char*) &cp->phys + oadr);
6736                 olen = scr_to_cpu(tblp[0]);
6737                 oadr = scr_to_cpu(tblp[1]);
6738         } else {
6739                 tblp = (u32 *) 0;
6740                 olen = scr_to_cpu(vdsp[0]) & 0xffffff;
6741         };
6742
6743         if (DEBUG_FLAGS & DEBUG_PHASE) {
6744                 printk ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
6745                         (unsigned) (scr_to_cpu(vdsp[0]) >> 24),
6746                         tblp,
6747                         (unsigned) olen,
6748                         (unsigned) oadr);
6749         };
6750
6751         /*
6752         **      check cmd against assumed interrupted script command.
6753         */
6754
6755         if (cmd != (scr_to_cpu(vdsp[0]) >> 24)) {
6756                 PRINT_ADDR(cp->cmd);
6757                 printk ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
6758                         (unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
6759
6760                 goto reset_all;
6761         }
6762
6763         /*
6764         **      cp != np->header.cp means that the header of the CCB 
6765         **      currently being processed has not yet been copied to 
6766         **      the global header area. That may happen if the device did 
6767         **      not accept all our messages after having been selected.
6768         */
6769         if (cp != np->header.cp) {
6770                 printk ("%s: SCSI phase error fixup: "
6771                         "CCB address mismatch (0x%08lx != 0x%08lx)\n", 
6772                         ncr_name (np), (u_long) cp, (u_long) np->header.cp);
6773         }
6774
6775         /*
6776         **      if old phase not dataphase, leave here.
6777         */
6778
6779         if (cmd & 0x06) {
6780                 PRINT_ADDR(cp->cmd);
6781                 printk ("phase change %x-%x %d@%08x resid=%d.\n",
6782                         cmd&7, sbcl&7, (unsigned)olen,
6783                         (unsigned)oadr, (unsigned)rest);
6784                 goto unexpected_phase;
6785         };
6786
6787         /*
6788         **      choose the correct patch area.
6789         **      if savep points to one, choose the other.
6790         */
6791
6792         newcmd = cp->patch;
6793         newtmp = CCB_PHYS (cp, patch);
6794         if (newtmp == scr_to_cpu(cp->phys.header.savep)) {
6795                 newcmd = &cp->patch[4];
6796                 newtmp = CCB_PHYS (cp, patch[4]);
6797         }
6798
6799         /*
6800         **      fillin the commands
6801         */
6802
6803         newcmd[0] = cpu_to_scr(((cmd & 0x0f) << 24) | rest);
6804         newcmd[1] = cpu_to_scr(oadr + olen - rest);
6805         newcmd[2] = cpu_to_scr(SCR_JUMP);
6806         newcmd[3] = cpu_to_scr(nxtdsp);
6807
6808         if (DEBUG_FLAGS & DEBUG_PHASE) {
6809                 PRINT_ADDR(cp->cmd);
6810                 printk ("newcmd[%d] %x %x %x %x.\n",
6811                         (int) (newcmd - cp->patch),
6812                         (unsigned)scr_to_cpu(newcmd[0]),
6813                         (unsigned)scr_to_cpu(newcmd[1]),
6814                         (unsigned)scr_to_cpu(newcmd[2]),
6815                         (unsigned)scr_to_cpu(newcmd[3]));
6816         }
6817         /*
6818         **      fake the return address (to the patch).
6819         **      and restart script processor at dispatcher.
6820         */
6821         OUTL (nc_temp, newtmp);
6822         OUTL_DSP (NCB_SCRIPT_PHYS (np, dispatch));
6823         return;
6824
6825         /*
6826         **      Unexpected phase changes that occurs when the current phase 
6827         **      is not a DATA IN or DATA OUT phase are due to error conditions.
6828         **      Such event may only happen when the SCRIPTS is using a 
6829         **      multibyte SCSI MOVE.
6830         **
6831         **      Phase change            Some possible cause
6832         **
6833         **      COMMAND  --> MSG IN     SCSI parity error detected by target.
6834         **      COMMAND  --> STATUS     Bad command or refused by target.
6835         **      MSG OUT  --> MSG IN     Message rejected by target.
6836         **      MSG OUT  --> COMMAND    Bogus target that discards extended
6837         **                              negotiation messages.
6838         **
6839         **      The code below does not care of the new phase and so 
6840         **      trusts the target. Why to annoy it ?
6841         **      If the interrupted phase is COMMAND phase, we restart at
6842         **      dispatcher.
6843         **      If a target does not get all the messages after selection, 
6844         **      the code assumes blindly that the target discards extended 
6845         **      messages and clears the negotiation status.
6846         **      If the target does not want all our response to negotiation,
6847         **      we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids 
6848         **      bloat for such a should_not_happen situation).
6849         **      In all other situation, we reset the BUS.
6850         **      Are these assumptions reasonnable ? (Wait and see ...)
6851         */
6852 unexpected_phase:
6853         dsp -= 8;
6854         nxtdsp = 0;
6855
6856         switch (cmd & 7) {
6857         case 2: /* COMMAND phase */
6858                 nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6859                 break;
6860 #if 0
6861         case 3: /* STATUS  phase */
6862                 nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6863                 break;
6864 #endif
6865         case 6: /* MSG OUT phase */
6866                 np->scripth->nxtdsp_go_on[0] = cpu_to_scr(dsp + 8);
6867                 if      (dsp == NCB_SCRIPT_PHYS (np, send_ident)) {
6868                         cp->host_status = HS_BUSY;
6869                         nxtdsp = NCB_SCRIPTH_PHYS (np, clratn_go_on);
6870                 }
6871                 else if (dsp == NCB_SCRIPTH_PHYS (np, send_wdtr) ||
6872                          dsp == NCB_SCRIPTH_PHYS (np, send_sdtr)) {
6873                         nxtdsp = NCB_SCRIPTH_PHYS (np, nego_bad_phase);
6874                 }
6875                 break;
6876 #if 0
6877         case 7: /* MSG IN  phase */
6878                 nxtdsp = NCB_SCRIPT_PHYS (np, clrack);
6879                 break;
6880 #endif
6881         }
6882
6883         if (nxtdsp) {
6884                 OUTL_DSP (nxtdsp);
6885                 return;
6886         }
6887
6888 reset_all:
6889         ncr_start_reset(np);
6890 }
6891
6892
6893 static void ncr_sir_to_redo(ncb_p np, int num, ccb_p cp)
6894 {
6895         Scsi_Cmnd *cmd  = cp->cmd;
6896         tcb_p tp        = &np->target[cmd->device->id];
6897         lcb_p lp        = tp->lp[cmd->device->lun];
6898         XPT_QUEHEAD     *qp;
6899         ccb_p           cp2;
6900         int             disc_cnt = 0;
6901         int             busy_cnt = 0;
6902         u32             startp;
6903         u_char          s_status = INB (SS_PRT);
6904
6905         /*
6906         **      Let the SCRIPTS processor skip all not yet started CCBs,
6907         **      and count disconnected CCBs. Since the busy queue is in 
6908         **      the same order as the chip start queue, disconnected CCBs 
6909         **      are before cp and busy ones after.
6910         */
6911         if (lp) {
6912                 qp = lp->busy_ccbq.blink;
6913                 while (qp != &lp->busy_ccbq) {
6914                         cp2 = xpt_que_entry(qp, struct ccb, link_ccbq);
6915                         qp  = qp->blink;
6916                         ++busy_cnt;
6917                         if (cp2 == cp)
6918                                 break;
6919                         cp2->start.schedule.l_paddr =
6920                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, skip));
6921                 }
6922                 lp->held_ccb = cp;      /* Requeue when this one completes */
6923                 disc_cnt = lp->queuedccbs - busy_cnt;
6924         }
6925
6926         switch(s_status) {
6927         default:        /* Just for safety, should never happen */
6928         case S_QUEUE_FULL:
6929                 /*
6930                 **      Decrease number of tags to the number of 
6931                 **      disconnected commands.
6932                 */
6933                 if (!lp)
6934                         goto out;
6935                 if (bootverbose >= 1) {
6936                         PRINT_ADDR(cmd);
6937                         printk ("QUEUE FULL! %d busy, %d disconnected CCBs\n",
6938                                 busy_cnt, disc_cnt);
6939                 }
6940                 if (disc_cnt < lp->numtags) {
6941                         lp->numtags     = disc_cnt > 2 ? disc_cnt : 2;
6942                         lp->num_good    = 0;
6943                         ncr_setup_tags (np, cmd->device->id, cmd->device->lun);
6944                 }
6945                 /*
6946                 **      Requeue the command to the start queue.
6947                 **      If any disconnected commands,
6948                 **              Clear SIGP.
6949                 **              Jump to reselect.
6950                 */
6951                 cp->phys.header.savep = cp->startp;
6952                 cp->host_status = HS_BUSY;
6953                 cp->scsi_status = S_ILLEGAL;
6954
6955                 ncr_put_start_queue(np, cp);
6956                 if (disc_cnt)
6957                         INB (nc_ctest2);                /* Clear SIGP */
6958                 OUTL_DSP (NCB_SCRIPT_PHYS (np, reselect));
6959                 return;
6960         case S_TERMINATED:
6961         case S_CHECK_COND:
6962                 /*
6963                 **      If we were requesting sense, give up.
6964                 */
6965                 if (cp->auto_sense)
6966                         goto out;
6967
6968                 /*
6969                 **      Device returned CHECK CONDITION status.
6970                 **      Prepare all needed data strutures for getting 
6971                 **      sense data.
6972                 **
6973                 **      identify message
6974                 */
6975                 cp->scsi_smsg2[0]       = M_IDENTIFY | cmd->device->lun;
6976                 cp->phys.smsg.addr      = cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
6977                 cp->phys.smsg.size      = cpu_to_scr(1);
6978
6979                 /*
6980                 **      sense command
6981                 */
6982                 cp->phys.cmd.addr       = cpu_to_scr(CCB_PHYS (cp, sensecmd));
6983                 cp->phys.cmd.size       = cpu_to_scr(6);
6984
6985                 /*
6986                 **      patch requested size into sense command
6987                 */
6988                 cp->sensecmd[0]         = 0x03;
6989                 cp->sensecmd[1]         = cmd->device->lun << 5;
6990                 cp->sensecmd[4]         = sizeof(cp->sense_buf);
6991
6992                 /*
6993                 **      sense data
6994                 */
6995                 bzero(cp->sense_buf, sizeof(cp->sense_buf));
6996                 cp->phys.sense.addr     = cpu_to_scr(CCB_PHYS(cp,sense_buf[0]));
6997                 cp->phys.sense.size     = cpu_to_scr(sizeof(cp->sense_buf));
6998
6999                 /*
7000                 **      requeue the command.
7001                 */
7002                 startp = cpu_to_scr(NCB_SCRIPTH_PHYS (np, sdata_in));
7003
7004                 cp->phys.header.savep   = startp;
7005                 cp->phys.header.goalp   = startp + 24;
7006                 cp->phys.header.lastp   = startp;
7007                 cp->phys.header.wgoalp  = startp + 24;
7008                 cp->phys.header.wlastp  = startp;
7009
7010                 cp->host_status = HS_BUSY;
7011                 cp->scsi_status = S_ILLEGAL;
7012                 cp->auto_sense  = s_status;
7013
7014                 cp->start.schedule.l_paddr =
7015                         cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
7016
7017                 /*
7018                 **      Select without ATN for quirky devices.
7019                 */
7020                 if (tp->quirks & QUIRK_NOMSG)
7021                         cp->start.schedule.l_paddr =
7022                         cpu_to_scr(NCB_SCRIPTH_PHYS (np, select_no_atn));
7023
7024                 ncr_put_start_queue(np, cp);
7025
7026                 OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
7027                 return;
7028         }
7029
7030 out:
7031         OUTONB_STD ();
7032         return;
7033 }
7034
7035
7036 /*==========================================================
7037 **
7038 **
7039 **      ncr chip exception handler for programmed interrupts.
7040 **
7041 **
7042 **==========================================================
7043 */
7044
7045 static int ncr_show_msg (u_char * msg)
7046 {
7047         u_char i;
7048         printk ("%x",*msg);
7049         if (*msg==M_EXTENDED) {
7050                 for (i=1;i<8;i++) {
7051                         if (i-1>msg[1]) break;
7052                         printk ("-%x",msg[i]);
7053                 };
7054                 return (i+1);
7055         } else if ((*msg & 0xf0) == 0x20) {
7056                 printk ("-%x",msg[1]);
7057                 return (2);
7058         };
7059         return (1);
7060 }
7061
7062 static void ncr_print_msg ( ccb_p cp, char *label, u_char *msg)
7063 {
7064         if (cp)
7065                 PRINT_ADDR(cp->cmd);
7066         if (label)
7067                 printk("%s: ", label);
7068         
7069         (void) ncr_show_msg (msg);
7070         printk(".\n");
7071 }
7072
7073 void ncr_int_sir (ncb_p np)
7074 {
7075         u_char scntl3;
7076         u_char chg, ofs, per, fak, wide;
7077         u_char num = INB (nc_dsps);
7078         ccb_p   cp=0;
7079         u_long  dsa    = INL (nc_dsa);
7080         u_char  target = INB (nc_sdid) & 0x0f;
7081         tcb_p   tp     = &np->target[target];
7082
7083         if (DEBUG_FLAGS & DEBUG_TINY) printk ("I#%d", num);
7084
7085         switch (num) {
7086         case SIR_INTFLY:
7087                 /*
7088                 **      This is used for HP Zalon/53c720 where INTFLY
7089                 **      operation is currently broken.
7090                 */
7091                 ncr_wakeup_done(np);
7092 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
7093                 OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, done_end) + 8);
7094 #else
7095                 OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, start));
7096 #endif
7097                 return;
7098         case SIR_RESEL_NO_MSG_IN:
7099         case SIR_RESEL_NO_IDENTIFY:
7100                 /*
7101                 **      If devices reselecting without sending an IDENTIFY 
7102                 **      message still exist, this should help.
7103                 **      We just assume lun=0, 1 CCB, no tag.
7104                 */
7105                 if (tp->lp[0]) { 
7106                         OUTL_DSP (scr_to_cpu(tp->lp[0]->jump_ccb[0]));
7107                         return;
7108                 }
7109         case SIR_RESEL_BAD_TARGET:      /* Will send a TARGET RESET message */
7110         case SIR_RESEL_BAD_LUN:         /* Will send a TARGET RESET message */
7111         case SIR_RESEL_BAD_I_T_L_Q:     /* Will send an ABORT TAG message   */
7112         case SIR_RESEL_BAD_I_T_L:       /* Will send an ABORT message       */
7113                 printk ("%s:%d: SIR %d, "
7114                         "incorrect nexus identification on reselection\n",
7115                         ncr_name (np), target, num);
7116                 goto out;
7117         case SIR_DONE_OVERFLOW:
7118                 printk ("%s:%d: SIR %d, "
7119                         "CCB done queue overflow\n",
7120                         ncr_name (np), target, num);
7121                 goto out;
7122         case SIR_BAD_STATUS:
7123                 cp = np->header.cp;
7124                 if (!cp || CCB_PHYS (cp, phys) != dsa)
7125                         goto out;
7126                 ncr_sir_to_redo(np, num, cp);
7127                 return;
7128         default:
7129                 /*
7130                 **      lookup the ccb
7131                 */
7132                 cp = np->ccb;
7133                 while (cp && (CCB_PHYS (cp, phys) != dsa))
7134                         cp = cp->link_ccb;
7135
7136                 assert (cp && cp == np->header.cp);
7137
7138                 if (!cp || cp != np->header.cp)
7139                         goto out;
7140         }
7141
7142         switch (num) {
7143 /*-----------------------------------------------------------------------------
7144 **
7145 **      Was Sie schon immer ueber transfermode negotiation wissen wollten ...
7146 **
7147 **      We try to negotiate sync and wide transfer only after
7148 **      a successful inquire command. We look at byte 7 of the
7149 **      inquire data to determine the capabilities of the target.
7150 **
7151 **      When we try to negotiate, we append the negotiation message
7152 **      to the identify and (maybe) simple tag message.
7153 **      The host status field is set to HS_NEGOTIATE to mark this
7154 **      situation.
7155 **
7156 **      If the target doesn't answer this message immidiately
7157 **      (as required by the standard), the SIR_NEGO_FAIL interrupt
7158 **      will be raised eventually.
7159 **      The handler removes the HS_NEGOTIATE status, and sets the
7160 **      negotiated value to the default (async / nowide).
7161 **
7162 **      If we receive a matching answer immediately, we check it
7163 **      for validity, and set the values.
7164 **
7165 **      If we receive a Reject message immediately, we assume the
7166 **      negotiation has failed, and fall back to standard values.
7167 **
7168 **      If we receive a negotiation message while not in HS_NEGOTIATE
7169 **      state, it's a target initiated negotiation. We prepare a
7170 **      (hopefully) valid answer, set our parameters, and send back 
7171 **      this answer to the target.
7172 **
7173 **      If the target doesn't fetch the answer (no message out phase),
7174 **      we assume the negotiation has failed, and fall back to default
7175 **      settings.
7176 **
7177 **      When we set the values, we adjust them in all ccbs belonging 
7178 **      to this target, in the controller's register, and in the "phys"
7179 **      field of the controller's struct ncb.
7180 **
7181 **      Possible cases:            hs  sir   msg_in value  send   goto
7182 **      We try to negotiate:
7183 **      -> target doesn't msgin    NEG FAIL  noop   defa.  -      dispatch
7184 **      -> target rejected our msg NEG FAIL  reject defa.  -      dispatch
7185 **      -> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
7186 **      -> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
7187 **      -> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
7188 **      -> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
7189 **      -> any other msgin         NEG FAIL  noop   defa.  -      dispatch
7190 **
7191 **      Target tries to negotiate:
7192 **      -> incoming message        --- SYNC  sdtr   set    SDTR   -
7193 **      -> incoming message        --- WIDE  wdtr   set    WDTR   -
7194 **      We sent our answer:
7195 **      -> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
7196 **
7197 **-----------------------------------------------------------------------------
7198 */
7199
7200         case SIR_NEGO_FAILED:
7201                 /*-------------------------------------------------------
7202                 **
7203                 **      Negotiation failed.
7204                 **      Target doesn't send an answer message,
7205                 **      or target rejected our message.
7206                 **
7207                 **      Remove negotiation request.
7208                 **
7209                 **-------------------------------------------------------
7210                 */
7211                 OUTB (HS_PRT, HS_BUSY);
7212
7213                 /* fall through */
7214
7215         case SIR_NEGO_PROTO:
7216                 /*-------------------------------------------------------
7217                 **
7218                 **      Negotiation failed.
7219                 **      Target doesn't fetch the answer message.
7220                 **
7221                 **-------------------------------------------------------
7222                 */
7223
7224                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7225                         PRINT_ADDR(cp->cmd);
7226                         printk ("negotiation failed sir=%x status=%x.\n",
7227                                 num, cp->nego_status);
7228                 };
7229
7230                 /*
7231                 **      any error in negotiation:
7232                 **      fall back to default mode.
7233                 */
7234                 switch (cp->nego_status) {
7235
7236                 case NS_SYNC:
7237                         ncr_setsync (np, cp, 0, 0xe0);
7238                         break;
7239
7240                 case NS_WIDE:
7241                         ncr_setwide (np, cp, 0, 0);
7242                         break;
7243
7244                 };
7245                 np->msgin [0] = M_NOOP;
7246                 np->msgout[0] = M_NOOP;
7247                 cp->nego_status = 0;
7248                 break;
7249
7250         case SIR_NEGO_SYNC:
7251                 /*
7252                 **      Synchronous request message received.
7253                 */
7254
7255                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7256                         PRINT_ADDR(cp->cmd);
7257                         printk ("sync msgin: ");
7258                         (void) ncr_show_msg (np->msgin);
7259                         printk (".\n");
7260                 };
7261
7262                 /*
7263                 **      get requested values.
7264                 */
7265
7266                 chg = 0;
7267                 per = np->msgin[3];
7268                 ofs = np->msgin[4];
7269                 if (ofs==0) per=255;
7270
7271                 /*
7272                 **      if target sends SDTR message,
7273                 **            it CAN transfer synch.
7274                 */
7275
7276                 if (ofs)
7277                         tp->inq_byte7 |= INQ7_SYNC;
7278
7279                 /*
7280                 **      check values against driver limits.
7281                 */
7282
7283                 if (per < np->minsync)
7284                         {chg = 1; per = np->minsync;}
7285                 if (per < tp->minsync)
7286                         {chg = 1; per = tp->minsync;}
7287                 if (ofs > tp->maxoffs)
7288                         {chg = 1; ofs = tp->maxoffs;}
7289
7290                 /*
7291                 **      Check against controller limits.
7292                 */
7293                 fak     = 7;
7294                 scntl3  = 0;
7295                 if (ofs != 0) {
7296                         ncr_getsync(np, per, &fak, &scntl3);
7297                         if (fak > 7) {
7298                                 chg = 1;
7299                                 ofs = 0;
7300                         }
7301                 }
7302                 if (ofs == 0) {
7303                         fak     = 7;
7304                         per     = 0;
7305                         scntl3  = 0;
7306                         tp->minsync = 0;
7307                 }
7308
7309                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7310                         PRINT_ADDR(cp->cmd);
7311                         printk ("sync: per=%d scntl3=0x%x ofs=%d fak=%d chg=%d.\n",
7312                                 per, scntl3, ofs, fak, chg);
7313                 }
7314
7315                 if (INB (HS_PRT) == HS_NEGOTIATE) {
7316                         OUTB (HS_PRT, HS_BUSY);
7317                         switch (cp->nego_status) {
7318
7319                         case NS_SYNC:
7320                                 /*
7321                                 **      This was an answer message
7322                                 */
7323                                 if (chg) {
7324                                         /*
7325                                         **      Answer wasn't acceptable.
7326                                         */
7327                                         ncr_setsync (np, cp, 0, 0xe0);
7328                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7329                                 } else {
7330                                         /*
7331                                         **      Answer is ok.
7332                                         */
7333                                         ncr_setsync (np, cp, scntl3, (fak<<5)|ofs);
7334                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
7335                                 };
7336                                 return;
7337
7338                         case NS_WIDE:
7339                                 ncr_setwide (np, cp, 0, 0);
7340                                 break;
7341                         };
7342                 };
7343
7344                 /*
7345                 **      It was a request. Set value and
7346                 **      prepare an answer message
7347                 */
7348
7349                 ncr_setsync (np, cp, scntl3, (fak<<5)|ofs);
7350
7351                 np->msgout[0] = M_EXTENDED;
7352                 np->msgout[1] = 3;
7353                 np->msgout[2] = M_X_SYNC_REQ;
7354                 np->msgout[3] = per;
7355                 np->msgout[4] = ofs;
7356
7357                 cp->nego_status = NS_SYNC;
7358
7359                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7360                         PRINT_ADDR(cp->cmd);
7361                         printk ("sync msgout: ");
7362                         (void) ncr_show_msg (np->msgout);
7363                         printk (".\n");
7364                 }
7365
7366                 if (!ofs) {
7367                         OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7368                         return;
7369                 }
7370                 np->msgin [0] = M_NOOP;
7371
7372                 break;
7373
7374         case SIR_NEGO_WIDE:
7375                 /*
7376                 **      Wide request message received.
7377                 */
7378                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7379                         PRINT_ADDR(cp->cmd);
7380                         printk ("wide msgin: ");
7381                         (void) ncr_show_msg (np->msgin);
7382                         printk (".\n");
7383                 };
7384
7385                 /*
7386                 **      get requested values.
7387                 */
7388
7389                 chg  = 0;
7390                 wide = np->msgin[3];
7391
7392                 /*
7393                 **      if target sends WDTR message,
7394                 **            it CAN transfer wide.
7395                 */
7396
7397                 if (wide)
7398                         tp->inq_byte7 |= INQ7_WIDE16;
7399
7400                 /*
7401                 **      check values against driver limits.
7402                 */
7403
7404                 if (wide > tp->usrwide)
7405                         {chg = 1; wide = tp->usrwide;}
7406
7407                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7408                         PRINT_ADDR(cp->cmd);
7409                         printk ("wide: wide=%d chg=%d.\n", wide, chg);
7410                 }
7411
7412                 if (INB (HS_PRT) == HS_NEGOTIATE) {
7413                         OUTB (HS_PRT, HS_BUSY);
7414                         switch (cp->nego_status) {
7415
7416                         case NS_WIDE:
7417                                 /*
7418                                 **      This was an answer message
7419                                 */
7420                                 if (chg) {
7421                                         /*
7422                                         **      Answer wasn't acceptable.
7423                                         */
7424                                         ncr_setwide (np, cp, 0, 1);
7425                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
7426                                 } else {
7427                                         /*
7428                                         **      Answer is ok.
7429                                         */
7430                                         ncr_setwide (np, cp, wide, 1);
7431                                         OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
7432                                 };
7433                                 return;
7434
7435                         case NS_SYNC:
7436                                 ncr_setsync (np, cp, 0, 0xe0);
7437                                 break;
7438                         };
7439                 };
7440
7441                 /*
7442                 **      It was a request, set value and
7443                 **      prepare an answer message
7444                 */
7445
7446                 ncr_setwide (np, cp, wide, 1);
7447
7448                 np->msgout[0] = M_EXTENDED;
7449                 np->msgout[1] = 2;
7450                 np->msgout[2] = M_X_WIDE_REQ;
7451                 np->msgout[3] = wide;
7452
7453                 np->msgin [0] = M_NOOP;
7454
7455                 cp->nego_status = NS_WIDE;
7456
7457                 if (DEBUG_FLAGS & DEBUG_NEGO) {
7458                         PRINT_ADDR(cp->cmd);
7459                         printk ("wide msgout: ");
7460                         (void) ncr_show_msg (np->msgin);
7461                         printk (".\n");
7462                 }
7463                 break;
7464
7465 /*--------------------------------------------------------------------
7466 **
7467 **      Processing of special messages
7468 **
7469 **--------------------------------------------------------------------
7470 */
7471
7472         case SIR_REJECT_RECEIVED:
7473                 /*-----------------------------------------------
7474                 **
7475                 **      We received a M_REJECT message.
7476                 **
7477                 **-----------------------------------------------
7478                 */
7479
7480                 PRINT_ADDR(cp->cmd);
7481                 printk ("M_REJECT received (%x:%x).\n",
7482                         (unsigned)scr_to_cpu(np->lastmsg), np->msgout[0]);
7483                 break;
7484
7485         case SIR_REJECT_SENT:
7486                 /*-----------------------------------------------
7487                 **
7488                 **      We received an unknown message
7489                 **
7490                 **-----------------------------------------------
7491                 */
7492
7493                 PRINT_ADDR(cp->cmd);
7494                 printk ("M_REJECT sent for ");
7495                 (void) ncr_show_msg (np->msgin);
7496                 printk (".\n");
7497                 break;
7498
7499 /*--------------------------------------------------------------------
7500 **
7501 **      Processing of special messages
7502 **
7503 **--------------------------------------------------------------------
7504 */
7505
7506         case SIR_IGN_RESIDUE:
7507                 /*-----------------------------------------------
7508                 **
7509                 **      We received an IGNORE RESIDUE message,
7510                 **      which couldn't be handled by the script.
7511                 **
7512                 **-----------------------------------------------
7513                 */
7514
7515                 PRINT_ADDR(cp->cmd);
7516                 printk ("M_IGN_RESIDUE received, but not yet implemented.\n");
7517                 break;
7518 #if 0
7519         case SIR_MISSING_SAVE:
7520                 /*-----------------------------------------------
7521                 **
7522                 **      We received an DISCONNECT message,
7523                 **      but the datapointer wasn't saved before.
7524                 **
7525                 **-----------------------------------------------
7526                 */
7527
7528                 PRINT_ADDR(cp->cmd);
7529                 printk ("M_DISCONNECT received, but datapointer not saved: "
7530                         "data=%x save=%x goal=%x.\n",
7531                         (unsigned) INL (nc_temp),
7532                         (unsigned) scr_to_cpu(np->header.savep),
7533                         (unsigned) scr_to_cpu(np->header.goalp));
7534                 break;
7535 #endif
7536         };
7537
7538 out:
7539         OUTONB_STD ();
7540 }
7541
7542 /*==========================================================
7543 **
7544 **
7545 **      Acquire a control block
7546 **
7547 **
7548 **==========================================================
7549 */
7550
7551 static  ccb_p ncr_get_ccb (ncb_p np, u_char tn, u_char ln)
7552 {
7553         tcb_p tp = &np->target[tn];
7554         lcb_p lp = tp->lp[ln];
7555         u_char tag = NO_TAG;
7556         ccb_p cp = (ccb_p) 0;
7557
7558         /*
7559         **      Lun structure available ?
7560         */
7561         if (lp) {
7562                 XPT_QUEHEAD *qp;
7563                 /*
7564                 **      Keep from using more tags than we can handle.
7565                 */
7566                 if (lp->usetags && lp->busyccbs >= lp->maxnxs)
7567                         return (ccb_p) 0;
7568
7569                 /*
7570                 **      Allocate a new CCB if needed.
7571                 */
7572                 if (xpt_que_empty(&lp->free_ccbq))
7573                         ncr_alloc_ccb(np, tn, ln);
7574
7575                 /*
7576                 **      Tune tag mode if asked by user.
7577                 */
7578                 if (lp->queuedepth != lp->numtags) {
7579                         ncr_setup_tags(np, tn, ln);
7580                 }
7581                         
7582                 /*
7583                 **      Look for free CCB
7584                 */
7585                 qp = xpt_remque_head(&lp->free_ccbq);
7586                 if (qp) {
7587                         cp = xpt_que_entry(qp, struct ccb, link_ccbq);
7588                         if (cp->magic) {
7589                                 PRINT_LUN(np, tn, ln);
7590                                 printk ("ccb free list corrupted (@%p)\n", cp);
7591                                 cp = 0;
7592                         }
7593                         else {
7594                                 xpt_insque_tail(qp, &lp->wait_ccbq);
7595                                 ++lp->busyccbs;
7596                         }
7597                 }
7598
7599                 /*
7600                 **      If a CCB is available,
7601                 **      Get a tag for this nexus if required.
7602                 */
7603                 if (cp) {
7604                         if (lp->usetags)
7605                                 tag = lp->cb_tags[lp->ia_tag];
7606                 }
7607                 else if (lp->actccbs > 0)
7608                         return (ccb_p) 0;
7609         }
7610
7611         /*
7612         **      if nothing available, take the default.
7613         */
7614         if (!cp)
7615                 cp = np->ccb;
7616
7617         /*
7618         **      Wait until available.
7619         */
7620 #if 0
7621         while (cp->magic) {
7622                 if (flags & SCSI_NOSLEEP) break;
7623                 if (tsleep ((caddr_t)cp, PRIBIO|PCATCH, "ncr", 0))
7624                         break;
7625         };
7626 #endif
7627
7628         if (cp->magic)
7629                 return ((ccb_p) 0);
7630
7631         cp->magic = 1;
7632
7633         /*
7634         **      Move to next available tag if tag used.
7635         */
7636         if (lp) {
7637                 if (tag != NO_TAG) {
7638                         ++lp->ia_tag;
7639                         if (lp->ia_tag == MAX_TAGS)
7640                                 lp->ia_tag = 0;
7641                         lp->tags_umap |= (((tagmap_t) 1) << tag);
7642                 }
7643         }
7644
7645         /*
7646         **      Remember all informations needed to free this CCB.
7647         */
7648         cp->tag    = tag;
7649         cp->target = tn;
7650         cp->lun    = ln;
7651
7652         if (DEBUG_FLAGS & DEBUG_TAGS) {
7653                 PRINT_LUN(np, tn, ln);
7654                 printk ("ccb @%p using tag %d.\n", cp, tag);
7655         }
7656
7657         return cp;
7658 }
7659
7660 /*==========================================================
7661 **
7662 **
7663 **      Release one control block
7664 **
7665 **
7666 **==========================================================
7667 */
7668
7669 static void ncr_free_ccb (ncb_p np, ccb_p cp)
7670 {
7671         tcb_p tp = &np->target[cp->target];
7672         lcb_p lp = tp->lp[cp->lun];
7673
7674         if (DEBUG_FLAGS & DEBUG_TAGS) {
7675                 PRINT_LUN(np, cp->target, cp->lun);
7676                 printk ("ccb @%p freeing tag %d.\n", cp, cp->tag);
7677         }
7678
7679         /*
7680         **      If lun control block available,
7681         **      decrement active commands and increment credit, 
7682         **      free the tag if any and remove the JUMP for reselect.
7683         */
7684         if (lp) {
7685                 if (cp->tag != NO_TAG) {
7686                         lp->cb_tags[lp->if_tag++] = cp->tag;
7687                         if (lp->if_tag == MAX_TAGS)
7688                                 lp->if_tag = 0;
7689                         lp->tags_umap &= ~(((tagmap_t) 1) << cp->tag);
7690                         lp->tags_smap &= lp->tags_umap;
7691                         lp->jump_ccb[cp->tag] =
7692                                 cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l_q));
7693                 } else {
7694                         lp->jump_ccb[0] =
7695                                 cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l));
7696                 }
7697         }
7698
7699         /*
7700         **      Make this CCB available.
7701         */
7702
7703         if (lp) {
7704                 if (cp != np->ccb) {
7705                         xpt_remque(&cp->link_ccbq);
7706                         xpt_insque_head(&cp->link_ccbq, &lp->free_ccbq);
7707                 }
7708                 --lp->busyccbs;
7709                 if (cp->queued) {
7710                         --lp->queuedccbs;
7711                 }
7712         }
7713         cp -> host_status = HS_IDLE;
7714         cp -> magic = 0;
7715         if (cp->queued) {
7716                 --np->queuedccbs;
7717                 cp->queued = 0;
7718         }
7719
7720 #if 0
7721         if (cp == np->ccb)
7722                 wakeup ((caddr_t) cp);
7723 #endif
7724 }
7725
7726
7727 #define ncr_reg_bus_addr(r) (np->paddr + offsetof (struct ncr_reg, r))
7728
7729 /*------------------------------------------------------------------------
7730 **      Initialize the fixed part of a CCB structure.
7731 **------------------------------------------------------------------------
7732 **------------------------------------------------------------------------
7733 */
7734 static void ncr_init_ccb(ncb_p np, ccb_p cp)
7735 {
7736         ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7737
7738         /*
7739         **      Remember virtual and bus address of this ccb.
7740         */
7741         cp->p_ccb          = vtobus(cp);
7742         cp->phys.header.cp = cp;
7743
7744         /*
7745         **      This allows xpt_remque to work for the default ccb.
7746         */
7747         xpt_que_init(&cp->link_ccbq);
7748
7749         /*
7750         **      Initialyze the start and restart launch script.
7751         **
7752         **      COPY(4) @(...p_phys), @(dsa)
7753         **      JUMP @(sched_point)
7754         */
7755         cp->start.setup_dsa[0]   = cpu_to_scr(copy_4);
7756         cp->start.setup_dsa[1]   = cpu_to_scr(CCB_PHYS(cp, start.p_phys));
7757         cp->start.setup_dsa[2]   = cpu_to_scr(ncr_reg_bus_addr(nc_dsa));
7758         cp->start.schedule.l_cmd = cpu_to_scr(SCR_JUMP);
7759         cp->start.p_phys         = cpu_to_scr(CCB_PHYS(cp, phys));
7760
7761         memcpy(&cp->restart, &cp->start, sizeof(cp->restart));
7762
7763         cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
7764         cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
7765 }
7766
7767
7768 /*------------------------------------------------------------------------
7769 **      Allocate a CCB and initialize its fixed part.
7770 **------------------------------------------------------------------------
7771 **------------------------------------------------------------------------
7772 */
7773 static void ncr_alloc_ccb(ncb_p np, u_char tn, u_char ln)
7774 {
7775         tcb_p tp = &np->target[tn];
7776         lcb_p lp = tp->lp[ln];
7777         ccb_p cp = 0;
7778
7779         /*
7780         **      Allocate memory for this CCB.
7781         */
7782         cp = m_calloc_dma(sizeof(struct ccb), "CCB");
7783         if (!cp)
7784                 return;
7785
7786         /*
7787         **      Count it and initialyze it.
7788         */
7789         lp->actccbs++;
7790         np->actccbs++;
7791         bzero (cp, sizeof (*cp));
7792         ncr_init_ccb(np, cp);
7793
7794         /*
7795         **      Chain into wakeup list and free ccb queue and take it 
7796         **      into account for tagged commands.
7797         */
7798         cp->link_ccb      = np->ccb->link_ccb;
7799         np->ccb->link_ccb = cp;
7800
7801         xpt_insque_head(&cp->link_ccbq, &lp->free_ccbq);
7802         ncr_setup_tags (np, tn, ln);
7803 }
7804
7805 /*==========================================================
7806 **
7807 **
7808 **      Allocation of resources for Targets/Luns/Tags.
7809 **
7810 **
7811 **==========================================================
7812 */
7813
7814
7815 /*------------------------------------------------------------------------
7816 **      Target control block initialisation.
7817 **------------------------------------------------------------------------
7818 **      This data structure is fully initialized after a SCSI command 
7819 **      has been successfully completed for this target.
7820 **      It contains a SCRIPT that is called on target reselection.
7821 **------------------------------------------------------------------------
7822 */
7823 static void ncr_init_tcb (ncb_p np, u_char tn)
7824 {
7825         tcb_p tp = &np->target[tn];
7826         ncrcmd copy_1 = np->features & FE_PFEN ? SCR_COPY(1) : SCR_COPY_F(1);
7827         int th = tn & 3;
7828         int i;
7829
7830         /*
7831         **      Jump to next tcb if SFBR does not match this target.
7832         **      JUMP  IF (SFBR != #target#), @(next tcb)
7833         */
7834         tp->jump_tcb.l_cmd   =
7835                 cpu_to_scr((SCR_JUMP ^ IFFALSE (DATA (0x80 + tn))));
7836         tp->jump_tcb.l_paddr = np->jump_tcb[th].l_paddr;
7837
7838         /*
7839         **      Load the synchronous transfer register.
7840         **      COPY @(tp->sval), @(sxfer)
7841         */
7842         tp->getscr[0] = cpu_to_scr(copy_1);
7843         tp->getscr[1] = cpu_to_scr(vtobus (&tp->sval));
7844 #ifdef SCSI_NCR_BIG_ENDIAN
7845         tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer) ^ 3);
7846 #else
7847         tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer));
7848 #endif
7849
7850         /*
7851         **      Load the timing register.
7852         **      COPY @(tp->wval), @(scntl3)
7853         */
7854         tp->getscr[3] = cpu_to_scr(copy_1);
7855         tp->getscr[4] = cpu_to_scr(vtobus (&tp->wval));
7856 #ifdef SCSI_NCR_BIG_ENDIAN
7857         tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3) ^ 3);
7858 #else
7859         tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3));
7860 #endif
7861
7862         /*
7863         **      Get the IDENTIFY message and the lun.
7864         **      CALL @script(resel_lun)
7865         */
7866         tp->call_lun.l_cmd   = cpu_to_scr(SCR_CALL);
7867         tp->call_lun.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_lun));
7868
7869         /*
7870         **      Look for the lun control block of this nexus.
7871         **      For i = 0 to 3
7872         **              JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
7873         */
7874         for (i = 0 ; i < 4 ; i++) {
7875                 tp->jump_lcb[i].l_cmd   =
7876                                 cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
7877                 tp->jump_lcb[i].l_paddr =
7878                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_identify));
7879         }
7880
7881         /*
7882         **      Link this target control block to the JUMP chain.
7883         */
7884         np->jump_tcb[th].l_paddr = cpu_to_scr(vtobus (&tp->jump_tcb));
7885
7886         /*
7887         **      These assert's should be moved at driver initialisations.
7888         */
7889 #ifdef SCSI_NCR_BIG_ENDIAN
7890         assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
7891                 offsetof(struct tcb    , sval    )) &3) == 3);
7892         assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
7893                 offsetof(struct tcb    , wval    )) &3) == 3);
7894 #else
7895         assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
7896                 offsetof(struct tcb    , sval    )) &3) == 0);
7897         assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
7898                 offsetof(struct tcb    , wval    )) &3) == 0);
7899 #endif
7900 }
7901
7902
7903 /*------------------------------------------------------------------------
7904 **      Lun control block allocation and initialization.
7905 **------------------------------------------------------------------------
7906 **      This data structure is allocated and initialized after a SCSI 
7907 **      command has been successfully completed for this target/lun.
7908 **------------------------------------------------------------------------
7909 */
7910 static lcb_p ncr_alloc_lcb (ncb_p np, u_char tn, u_char ln)
7911 {
7912         tcb_p tp = &np->target[tn];
7913         lcb_p lp = tp->lp[ln];
7914         ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7915         int lh = ln & 3;
7916
7917         /*
7918         **      Already done, return.
7919         */
7920         if (lp)
7921                 return lp;
7922
7923         /*
7924         **      Allocate the lcb.
7925         */
7926         lp = m_calloc_dma(sizeof(struct lcb), "LCB");
7927         if (!lp)
7928                 goto fail;
7929         bzero(lp, sizeof(*lp));
7930         tp->lp[ln] = lp;
7931
7932         /*
7933         **      Initialize the target control block if not yet.
7934         */
7935         if (!tp->jump_tcb.l_cmd)
7936                 ncr_init_tcb(np, tn);
7937
7938         /*
7939         **      Initialize the CCB queue headers.
7940         */
7941         xpt_que_init(&lp->free_ccbq);
7942         xpt_que_init(&lp->busy_ccbq);
7943         xpt_que_init(&lp->wait_ccbq);
7944         xpt_que_init(&lp->skip_ccbq);
7945
7946         /*
7947         **      Set max CCBs to 1 and use the default 1 entry 
7948         **      jump table by default.
7949         */
7950         lp->maxnxs      = 1;
7951         lp->jump_ccb    = &lp->jump_ccb_0;
7952         lp->p_jump_ccb  = cpu_to_scr(vtobus(lp->jump_ccb));
7953
7954         /*
7955         **      Initilialyze the reselect script:
7956         **
7957         **      Jump to next lcb if SFBR does not match this lun.
7958         **      Load TEMP with the CCB direct jump table bus address.
7959         **      Get the SIMPLE TAG message and the tag.
7960         **
7961         **      JUMP  IF (SFBR != #lun#), @(next lcb)
7962         **      COPY @(lp->p_jump_ccb),   @(temp)
7963         **      JUMP @script(resel_notag)
7964         */
7965         lp->jump_lcb.l_cmd   =
7966                 cpu_to_scr((SCR_JUMP ^ IFFALSE (MASK (0x80+ln, 0xff))));
7967         lp->jump_lcb.l_paddr = tp->jump_lcb[lh].l_paddr;
7968
7969         lp->load_jump_ccb[0] = cpu_to_scr(copy_4);
7970         lp->load_jump_ccb[1] = cpu_to_scr(vtobus (&lp->p_jump_ccb));
7971         lp->load_jump_ccb[2] = cpu_to_scr(ncr_reg_bus_addr(nc_temp));
7972
7973         lp->jump_tag.l_cmd   = cpu_to_scr(SCR_JUMP);
7974         lp->jump_tag.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_notag));
7975
7976         /*
7977         **      Link this lun control block to the JUMP chain.
7978         */
7979         tp->jump_lcb[lh].l_paddr = cpu_to_scr(vtobus (&lp->jump_lcb));
7980
7981         /*
7982         **      Initialize command queuing control.
7983         */
7984         lp->busyccbs    = 1;
7985         lp->queuedccbs  = 1;
7986         lp->queuedepth  = 1;
7987 fail:
7988         return lp;
7989 }
7990
7991
7992 /*------------------------------------------------------------------------
7993 **      Lun control block setup on INQUIRY data received.
7994 **------------------------------------------------------------------------
7995 **      We only support WIDE, SYNC for targets and CMDQ for logical units.
7996 **      This setup is done on each INQUIRY since we are expecting user 
7997 **      will play with CHANGE DEFINITION commands. :-)
7998 **------------------------------------------------------------------------
7999 */
8000 static lcb_p ncr_setup_lcb (ncb_p np, u_char tn, u_char ln, u_char *inq_data)
8001 {
8002         tcb_p tp = &np->target[tn];
8003         lcb_p lp = tp->lp[ln];
8004         u_char inq_byte7;
8005
8006         /*
8007         **      If no lcb, try to allocate it.
8008         */
8009         if (!lp && !(lp = ncr_alloc_lcb(np, tn, ln)))
8010                 goto fail;
8011
8012         /*
8013         **      Get device quirks from a speciality table.
8014         */
8015         tp->quirks = ncr_lookup (inq_data);
8016         if (tp->quirks && bootverbose) {
8017                 PRINT_LUN(np, tn, ln);
8018                 printk ("quirks=%x.\n", tp->quirks);
8019         }
8020
8021         /*
8022         **      Evaluate trustable target/unit capabilities.
8023         **      We only believe device version >= SCSI-2 that 
8024         **      use appropriate response data format (2).
8025         **      But it seems that some CCS devices also 
8026         **      support SYNC and I donnot want to frustrate 
8027         **      anybody. ;-)
8028         */
8029         inq_byte7 = 0;
8030         if      ((inq_data[2] & 0x7) >= 2 && (inq_data[3] & 0xf) == 2)
8031                 inq_byte7 = inq_data[7];
8032         else if ((inq_data[2] & 0x7) == 1 && (inq_data[3] & 0xf) == 1)
8033                 inq_byte7 = INQ7_SYNC;
8034
8035         /*
8036         **      Throw away announced LUN capabilities if we are told 
8037         **      that there is no real device supported by the logical unit.
8038         */
8039         if ((inq_data[0] & 0xe0) > 0x20 || (inq_data[0] & 0x1f) == 0x1f)
8040                 inq_byte7 &= (INQ7_SYNC | INQ7_WIDE16);
8041
8042         /*
8043         **      If user is wanting SYNC, force this feature.
8044         */
8045         if (driver_setup.force_sync_nego)
8046                 inq_byte7 |= INQ7_SYNC;
8047
8048         /*
8049         **      Prepare negotiation if SIP capabilities have changed.
8050         */
8051         tp->inq_done = 1;
8052         if ((inq_byte7 ^ tp->inq_byte7) & (INQ7_SYNC | INQ7_WIDE16)) {
8053                 tp->inq_byte7 = inq_byte7;
8054                 ncr_negotiate(np, tp);
8055         }
8056
8057         /*
8058         **      If unit supports tagged commands, allocate the 
8059         **      CCB JUMP table if not yet.
8060         */
8061         if ((inq_byte7 & INQ7_QUEUE) && lp->jump_ccb == &lp->jump_ccb_0) {
8062                 int i;
8063                 lp->jump_ccb = m_calloc_dma(256, "JUMP_CCB");
8064                 if (!lp->jump_ccb) {
8065                         lp->jump_ccb = &lp->jump_ccb_0;
8066                         goto fail;
8067                 }
8068                 lp->p_jump_ccb = cpu_to_scr(vtobus(lp->jump_ccb));
8069                 for (i = 0 ; i < 64 ; i++)
8070                         lp->jump_ccb[i] =
8071                                 cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l_q));
8072                 for (i = 0 ; i < MAX_TAGS ; i++)
8073                         lp->cb_tags[i] = i;
8074                 lp->maxnxs = MAX_TAGS;
8075                 lp->tags_stime = ktime_get(3*HZ);
8076         }
8077
8078         /*
8079         **      Adjust tagged queueing status if needed.
8080         */
8081         if ((inq_byte7 ^ lp->inq_byte7) & INQ7_QUEUE) {
8082                 lp->inq_byte7 = inq_byte7;
8083                 lp->numtags   = lp->maxtags;
8084                 ncr_setup_tags (np, tn, ln);
8085         }
8086
8087 fail:
8088         return lp;
8089 }
8090
8091 /*==========================================================
8092 **
8093 **
8094 **      Build Scatter Gather Block
8095 **
8096 **
8097 **==========================================================
8098 **
8099 **      The transfer area may be scattered among
8100 **      several non adjacent physical pages.
8101 **
8102 **      We may use MAX_SCATTER blocks.
8103 **
8104 **----------------------------------------------------------
8105 */
8106
8107 /*
8108 **      We try to reduce the number of interrupts caused
8109 **      by unexpected phase changes due to disconnects.
8110 **      A typical harddisk may disconnect before ANY block.
8111 **      If we wanted to avoid unexpected phase changes at all
8112 **      we had to use a break point every 512 bytes.
8113 **      Of course the number of scatter/gather blocks is
8114 **      limited.
8115 **      Under Linux, the scatter/gatter blocks are provided by 
8116 **      the generic driver. We just have to copy addresses and 
8117 **      sizes to the data segment array.
8118 */
8119
8120 static  int     ncr_scatter(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd)
8121 {
8122         struct scr_tblmove *data;
8123         int segment     = 0;
8124         int use_sg      = (int) cmd->use_sg;
8125
8126         data            = cp->phys.data;
8127         cp->data_len    = 0;
8128
8129         if (!use_sg) {
8130                 if (cmd->request_bufflen) {
8131                         u_long baddr = map_scsi_single_data(np, cmd);
8132
8133                         data = &data[MAX_SCATTER - 1];
8134                         data[0].addr = cpu_to_scr(baddr);
8135                         data[0].size = cpu_to_scr(cmd->request_bufflen);
8136                         cp->data_len = cmd->request_bufflen;
8137                         segment = 1;
8138                 }
8139         }
8140         else if (use_sg <= MAX_SCATTER) {
8141                 struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
8142
8143                 use_sg = map_scsi_sg_data(np, cmd);
8144                 data = &data[MAX_SCATTER - use_sg];
8145
8146                 while (segment < use_sg) {
8147                         u_long baddr = scsi_sg_dma_address(&scatter[segment]);
8148                         unsigned int len = scsi_sg_dma_len(&scatter[segment]);
8149
8150                         data[segment].addr = cpu_to_scr(baddr);
8151                         data[segment].size = cpu_to_scr(len);
8152                         cp->data_len      += len;
8153                         ++segment;
8154                 }
8155         }
8156         else {
8157                 return -1;
8158         }
8159
8160         return segment;
8161 }
8162
8163 /*==========================================================
8164 **
8165 **
8166 **      Test the bus snoop logic :-(
8167 **
8168 **      Has to be called with interrupts disabled.
8169 **
8170 **
8171 **==========================================================
8172 */
8173
8174 #ifndef SCSI_NCR_IOMAPPED
8175 static int __init ncr_regtest (struct ncb* np)
8176 {
8177         register volatile u32 data;
8178         /*
8179         **      ncr registers may NOT be cached.
8180         **      write 0xffffffff to a read only register area,
8181         **      and try to read it back.
8182         */
8183         data = 0xffffffff;
8184         OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
8185         data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
8186 #if 1
8187         if (data == 0xffffffff) {
8188 #else
8189         if ((data & 0xe2f0fffd) != 0x02000080) {
8190 #endif
8191                 printk ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
8192                         (unsigned) data);
8193                 return (0x10);
8194         };
8195         return (0);
8196 }
8197 #endif
8198
8199 static int __init ncr_snooptest (struct ncb* np)
8200 {
8201         u32     ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
8202         int     i, err=0;
8203 #ifndef SCSI_NCR_IOMAPPED
8204         if (np->reg) {
8205             err |= ncr_regtest (np);
8206             if (err) return (err);
8207         }
8208 #endif
8209         /*
8210         **      init
8211         */
8212         pc  = NCB_SCRIPTH_PHYS (np, snooptest);
8213         host_wr = 1;
8214         ncr_wr  = 2;
8215         /*
8216         **      Set memory and register.
8217         */
8218         np->ncr_cache = cpu_to_scr(host_wr);
8219         OUTL (nc_temp, ncr_wr);
8220         /*
8221         **      Start script (exchange values)
8222         */
8223         OUTL_DSP (pc);
8224         /*
8225         **      Wait 'til done (with timeout)
8226         */
8227         for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
8228                 if (INB(nc_istat) & (INTF|SIP|DIP))
8229                         break;
8230         /*
8231         **      Save termination position.
8232         */
8233         pc = INL (nc_dsp);
8234         /*
8235         **      Read memory and register.
8236         */
8237         host_rd = scr_to_cpu(np->ncr_cache);
8238         ncr_rd  = INL (nc_scratcha);
8239         ncr_bk  = INL (nc_temp);
8240         /*
8241         **      Reset ncr chip
8242         */
8243         ncr_chip_reset(np, 100);
8244         /*
8245         **      check for timeout
8246         */
8247         if (i>=NCR_SNOOP_TIMEOUT) {
8248                 printk ("CACHE TEST FAILED: timeout.\n");
8249                 return (0x20);
8250         };
8251         /*
8252         **      Check termination position.
8253         */
8254         if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
8255                 printk ("CACHE TEST FAILED: script execution failed.\n");
8256                 printk ("start=%08lx, pc=%08lx, end=%08lx\n", 
8257                         (u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
8258                         (u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
8259                 return (0x40);
8260         };
8261         /*
8262         **      Show results.
8263         */
8264         if (host_wr != ncr_rd) {
8265                 printk ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
8266                         (int) host_wr, (int) ncr_rd);
8267                 err |= 1;
8268         };
8269         if (host_rd != ncr_wr) {
8270                 printk ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
8271                         (int) ncr_wr, (int) host_rd);
8272                 err |= 2;
8273         };
8274         if (ncr_bk != ncr_wr) {
8275                 printk ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
8276                         (int) ncr_wr, (int) ncr_bk);
8277                 err |= 4;
8278         };
8279         return (err);
8280 }
8281
8282 /*==========================================================
8283 **
8284 **
8285 **      Device lookup.
8286 **
8287 **      @GENSCSI@ should be integrated to scsiconf.c
8288 **
8289 **
8290 **==========================================================
8291 */
8292
8293 struct table_entry {
8294         char *  manufacturer;
8295         char *  model;
8296         char *  version;
8297         u_long  info;
8298 };
8299
8300 static struct table_entry device_tab[] =
8301 {
8302 #if 0
8303         {"", "", "", QUIRK_NOMSG},
8304 #endif
8305         {"SONY", "SDT-5000", "3.17", QUIRK_NOMSG},
8306         {"WangDAT", "Model 2600", "01.7", QUIRK_NOMSG},
8307         {"WangDAT", "Model 3200", "02.2", QUIRK_NOMSG},
8308         {"WangDAT", "Model 1300", "02.4", QUIRK_NOMSG},
8309         {"", "", "", 0} /* catch all: must be last entry. */
8310 };
8311
8312 static u_long ncr_lookup(char * id)
8313 {
8314         struct table_entry * p = device_tab;
8315         char *d, *r, c;
8316
8317         for (;;p++) {
8318
8319                 d = id+8;
8320                 r = p->manufacturer;
8321                 while ((c=*r++)) if (c!=*d++) break;
8322                 if (c) continue;
8323
8324                 d = id+16;
8325                 r = p->model;
8326                 while ((c=*r++)) if (c!=*d++) break;
8327                 if (c) continue;
8328
8329                 d = id+32;
8330                 r = p->version;
8331                 while ((c=*r++)) if (c!=*d++) break;
8332                 if (c) continue;
8333
8334                 return (p->info);
8335         }
8336 }
8337
8338 /*==========================================================
8339 **
8340 **      Determine the ncr's clock frequency.
8341 **      This is essential for the negotiation
8342 **      of the synchronous transfer rate.
8343 **
8344 **==========================================================
8345 **
8346 **      Note: we have to return the correct value.
8347 **      THERE IS NO SAVE DEFAULT VALUE.
8348 **
8349 **      Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
8350 **      53C860 and 53C875 rev. 1 support fast20 transfers but 
8351 **      do not have a clock doubler and so are provided with a 
8352 **      80 MHz clock. All other fast20 boards incorporate a doubler 
8353 **      and so should be delivered with a 40 MHz clock.
8354 **      The future fast40 chips (895/895) use a 40 Mhz base clock 
8355 **      and provide a clock quadrupler (160 Mhz). The code below 
8356 **      tries to deal as cleverly as possible with all this stuff.
8357 **
8358 **----------------------------------------------------------
8359 */
8360
8361 /*
8362  *      Select NCR SCSI clock frequency
8363  */
8364 static void ncr_selectclock(ncb_p np, u_char scntl3)
8365 {
8366         if (np->multiplier < 2) {
8367                 OUTB(nc_scntl3, scntl3);
8368                 return;
8369         }
8370
8371         if (bootverbose >= 2)
8372                 printk ("%s: enabling clock multiplier\n", ncr_name(np));
8373
8374         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
8375         if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
8376                 int i = 20;
8377                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
8378                         UDELAY (20);
8379                 if (!i)
8380                         printk("%s: the chip cannot lock the frequency\n", ncr_name(np));
8381         } else                  /* Wait 20 micro-seconds for doubler    */
8382                 UDELAY (20);
8383         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
8384         OUTB(nc_scntl3, scntl3);
8385         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
8386         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
8387 }
8388
8389
8390 /*
8391  *      calculate NCR SCSI clock frequency (in KHz)
8392  */
8393 static unsigned __init ncrgetfreq (ncb_p np, int gen)
8394 {
8395         unsigned ms = 0;
8396         char count = 0;
8397
8398         /*
8399          * Measure GEN timer delay in order 
8400          * to calculate SCSI clock frequency
8401          *
8402          * This code will never execute too
8403          * many loop iterations (if DELAY is 
8404          * reasonably correct). It could get
8405          * too low a delay (too high a freq.)
8406          * if the CPU is slow executing the 
8407          * loop for some reason (an NMI, for
8408          * example). For this reason we will
8409          * if multiple measurements are to be 
8410          * performed trust the higher delay 
8411          * (lower frequency returned).
8412          */
8413         OUTB (nc_stest1, 0);    /* make sure clock doubler is OFF */
8414         OUTW (nc_sien , 0);     /* mask all scsi interrupts */
8415         (void) INW (nc_sist);   /* clear pending scsi interrupt */
8416         OUTB (nc_dien , 0);     /* mask all dma interrupts */
8417         (void) INW (nc_sist);   /* another one, just to be sure :) */
8418         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3 */
8419         OUTB (nc_stime1, 0);    /* disable general purpose timer */
8420         OUTB (nc_stime1, gen);  /* set to nominal delay of 1<<gen * 125us */
8421         while (!(INW(nc_sist) & GEN) && ms++ < 100000) {
8422                 for (count = 0; count < 10; count ++)
8423                         UDELAY (100);   /* count ms */
8424         }
8425         OUTB (nc_stime1, 0);    /* disable general purpose timer */
8426         /*
8427          * set prescaler to divide by whatever 0 means
8428          * 0 ought to choose divide by 2, but appears
8429          * to set divide by 3.5 mode in my 53c810 ...
8430          */
8431         OUTB (nc_scntl3, 0);
8432
8433         if (bootverbose >= 2)
8434                 printk ("%s: Delay (GEN=%d): %u msec\n", ncr_name(np), gen, ms);
8435         /*
8436          * adjust for prescaler, and convert into KHz 
8437          */
8438         return ms ? ((1 << gen) * 4340) / ms : 0;
8439 }
8440
8441 /*
8442  *      Get/probe NCR SCSI clock frequency
8443  */
8444 static void __init ncr_getclock (ncb_p np, int mult)
8445 {
8446         unsigned char scntl3 = INB(nc_scntl3);
8447         unsigned char stest1 = INB(nc_stest1);
8448         unsigned f1;
8449
8450         np->multiplier = 1;
8451         f1 = 40000;
8452
8453         /*
8454         **      True with 875 or 895 with clock multiplier selected
8455         */
8456         if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
8457                 if (bootverbose >= 2)
8458                         printk ("%s: clock multiplier found\n", ncr_name(np));
8459                 np->multiplier = mult;
8460         }
8461
8462         /*
8463         **      If multiplier not found or scntl3 not 7,5,3,
8464         **      reset chip and get frequency from general purpose timer.
8465         **      Otherwise trust scntl3 BIOS setting.
8466         */
8467         if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
8468                 unsigned f2;
8469
8470                 ncr_chip_reset(np, 5);
8471
8472                 (void) ncrgetfreq (np, 11);     /* throw away first result */
8473                 f1 = ncrgetfreq (np, 11);
8474                 f2 = ncrgetfreq (np, 11);
8475
8476                 if(bootverbose)
8477                         printk ("%s: NCR clock is %uKHz, %uKHz\n", ncr_name(np), f1, f2);
8478
8479                 if (f1 > f2) f1 = f2;           /* trust lower result   */
8480
8481                 if      (f1 <   45000)          f1 =  40000;
8482                 else if (f1 <   55000)          f1 =  50000;
8483                 else                            f1 =  80000;
8484
8485                 if (f1 < 80000 && mult > 1) {
8486                         if (bootverbose >= 2)
8487                                 printk ("%s: clock multiplier assumed\n", ncr_name(np));
8488                         np->multiplier  = mult;
8489                 }
8490         } else {
8491                 if      ((scntl3 & 7) == 3)     f1 =  40000;
8492                 else if ((scntl3 & 7) == 5)     f1 =  80000;
8493                 else                            f1 = 160000;
8494
8495                 f1 /= np->multiplier;
8496         }
8497
8498         /*
8499         **      Compute controller synchronous parameters.
8500         */
8501         f1              *= np->multiplier;
8502         np->clock_khz   = f1;
8503 }
8504
8505 /*===================== LINUX ENTRY POINTS SECTION ==========================*/
8506
8507 /*
8508 **   Linux select queue depths function
8509 */
8510
8511 int ncr53c8xx_slave_configure(Scsi_Device *device)
8512 {
8513         struct Scsi_Host *host = device->host;
8514         ncb_p np;
8515         tcb_p tp;
8516         lcb_p lp;
8517         int numtags, depth_to_use;
8518
8519         np = ((struct host_data *) host->hostdata)->ncb;
8520         tp = &np->target[device->id];
8521         lp = tp->lp[device->lun];
8522
8523         /*
8524         **      Select queue depth from driver setup.
8525         **      Donnot use more than configured by user.
8526         **      Use at least 2.
8527         **      Donnot use more than our maximum.
8528         */
8529         numtags = device_queue_depth(np->unit, device->id, device->lun);
8530         if (numtags > tp->usrtags)
8531                 numtags = tp->usrtags;
8532         if (!device->tagged_supported)
8533                 numtags = 1;
8534         depth_to_use = numtags;
8535         if (depth_to_use < 2)
8536                 depth_to_use = 2;
8537         if (depth_to_use > MAX_TAGS)
8538                 depth_to_use = MAX_TAGS;
8539
8540         scsi_adjust_queue_depth(device,
8541                                 (device->tagged_supported ?
8542                                  MSG_SIMPLE_TAG : 0),
8543                                 depth_to_use);
8544
8545         /*
8546         **      Since the queue depth is not tunable under Linux,
8547         **      we need to know this value in order not to 
8548         **      announce stupid things to user.
8549         */
8550         if (lp) {
8551                 lp->numtags = lp->maxtags = numtags;
8552                 lp->scdev_depth = depth_to_use;
8553         }
8554         ncr_setup_tags (np, device->id, device->lun);
8555
8556 #ifdef DEBUG_NCR53C8XX
8557         printk("ncr53c8xx_select_queue_depth: host=%d, id=%d, lun=%d, depth=%d\n",
8558                np->unit, device->id, device->lun, depth_to_use);
8559 #endif
8560
8561         return 0;
8562 }
8563
8564 /*
8565 **   Linux entry point of queuecommand() function
8566 */
8567
8568 int ncr53c8xx_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *))
8569 {
8570      ncb_p np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8571      unsigned long flags;
8572      int sts;
8573
8574 #ifdef DEBUG_NCR53C8XX
8575 printk("ncr53c8xx_queue_command\n");
8576 #endif
8577
8578      cmd->scsi_done     = done;
8579      cmd->host_scribble = NULL;
8580 #ifdef SCSI_NCR_DYNAMIC_DMA_MAPPING
8581      cmd->__data_mapped = 0;
8582      cmd->__data_mapping = 0;
8583 #endif
8584
8585      NCR_LOCK_NCB(np, flags);
8586
8587      if ((sts = ncr_queue_command(np, cmd)) != DID_OK) {
8588           cmd->result = ScsiResult(sts, 0);
8589 #ifdef DEBUG_NCR53C8XX
8590 printk("ncr53c8xx : command not queued - result=%d\n", sts);
8591 #endif
8592      }
8593 #ifdef DEBUG_NCR53C8XX
8594      else
8595 printk("ncr53c8xx : command successfully queued\n");
8596 #endif
8597
8598      NCR_UNLOCK_NCB(np, flags);
8599
8600      if (sts != DID_OK) {
8601           unmap_scsi_data(np, cmd);
8602           done(cmd);
8603      }
8604
8605      return sts;
8606 }
8607
8608 /*
8609 **   Linux entry point of the interrupt handler.
8610 **   Since linux versions > 1.3.70, we trust the kernel for 
8611 **   passing the internal host descriptor as 'dev_id'.
8612 **   Otherwise, we scan the host list and call the interrupt 
8613 **   routine for each host that uses this IRQ.
8614 */
8615
8616 irqreturn_t ncr53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
8617 {
8618      unsigned long flags;
8619      struct Scsi_Host *shost = (struct Scsi_Host *)dev_id;
8620      struct host_data *host_data = (struct host_data *)shost->hostdata;
8621      ncb_p np = host_data->ncb;
8622      Scsi_Cmnd *done_list;
8623
8624 #ifdef DEBUG_NCR53C8XX
8625      printk("ncr53c8xx : interrupt received\n");
8626 #endif
8627
8628      if (DEBUG_FLAGS & DEBUG_TINY) printk ("[");
8629
8630      NCR_LOCK_NCB(np, flags);
8631      ncr_exception(np);
8632      done_list     = np->done_list;
8633      np->done_list = 0;
8634      NCR_UNLOCK_NCB(np, flags);
8635
8636      if (DEBUG_FLAGS & DEBUG_TINY) printk ("]\n");
8637
8638      if (done_list) {
8639           NCR_LOCK_SCSI_DONE(done_list->device->host, flags);
8640           ncr_flush_done_cmds(done_list);
8641           NCR_UNLOCK_SCSI_DONE(done_list->device->host, flags);
8642      }
8643      return IRQ_HANDLED;
8644 }
8645
8646 /*
8647 **   Linux entry point of the timer handler
8648 */
8649
8650 static void ncr53c8xx_timeout(unsigned long npref)
8651 {
8652      ncb_p np = (ncb_p) npref;
8653      unsigned long flags;
8654      Scsi_Cmnd *done_list;
8655
8656      NCR_LOCK_NCB(np, flags);
8657      ncr_timeout((ncb_p) np);
8658      done_list     = np->done_list;
8659      np->done_list = 0;
8660      NCR_UNLOCK_NCB(np, flags);
8661
8662      if (done_list) {
8663           NCR_LOCK_SCSI_DONE(done_list->device->host, flags);
8664           ncr_flush_done_cmds(done_list);
8665           NCR_UNLOCK_SCSI_DONE(done_list->device->host, flags);
8666      }
8667 }
8668
8669 /*
8670 **   Linux entry point of reset() function
8671 */
8672
8673 int ncr53c8xx_bus_reset(Scsi_Cmnd *cmd)
8674 {
8675         ncb_p np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8676         int sts;
8677         unsigned long flags;
8678         Scsi_Cmnd *done_list;
8679
8680         NCR_LOCK_NCB(np, flags);
8681
8682         /*
8683          * If the mid-level driver told us reset is synchronous, it seems 
8684          * that we must call the done() callback for the involved command, 
8685          * even if this command was not queued to the low-level driver, 
8686          * before returning SUCCESS.
8687          */
8688
8689         sts = ncr_reset_bus(np, cmd, 1);
8690
8691         done_list     = np->done_list;
8692         np->done_list = 0;
8693         NCR_UNLOCK_NCB(np, flags);
8694
8695         ncr_flush_done_cmds(done_list);
8696
8697         return sts;
8698 }
8699
8700 /*
8701 **   Linux entry point of abort() function
8702 */
8703
8704 int ncr53c8xx_abort(Scsi_Cmnd *cmd)
8705 {
8706         ncb_p np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
8707         int sts;
8708         unsigned long flags;
8709         Scsi_Cmnd *done_list;
8710
8711 #if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8712         printk("ncr53c8xx_abort: pid=%lu serial_number=%ld serial_number_at_timeout=%ld\n",
8713                 cmd->pid, cmd->serial_number, cmd->serial_number_at_timeout);
8714 #else
8715         printk("ncr53c8xx_abort: command pid %lu\n", cmd->pid);
8716 #endif
8717
8718         NCR_LOCK_NCB(np, flags);
8719
8720 #if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
8721         /*
8722          * We have to just ignore abort requests in some situations.
8723          */
8724         if (cmd->serial_number != cmd->serial_number_at_timeout) {
8725                 sts = SCSI_ABORT_NOT_RUNNING;
8726                 goto out;
8727         }
8728 #endif
8729
8730         sts = ncr_abort_command(np, cmd);
8731 out:
8732         done_list     = np->done_list;
8733         np->done_list = 0;
8734         NCR_UNLOCK_NCB(np, flags);
8735
8736         ncr_flush_done_cmds(done_list);
8737
8738         return sts;
8739 }
8740
8741
8742 int ncr53c8xx_release(struct Scsi_Host *host)
8743 {
8744 #ifdef DEBUG_NCR53C8XX
8745 printk("ncr53c8xx : release\n");
8746 #endif
8747      ncr_detach(((struct host_data *) host->hostdata)->ncb);
8748
8749      return 1;
8750 }
8751
8752
8753 /*
8754 **      Scsi command waiting list management.
8755 **
8756 **      It may happen that we cannot insert a scsi command into the start queue,
8757 **      in the following circumstances.
8758 **              Too few preallocated ccb(s), 
8759 **              maxtags < cmd_per_lun of the Linux host control block,
8760 **              etc...
8761 **      Such scsi commands are inserted into a waiting list.
8762 **      When a scsi command complete, we try to requeue the commands of the
8763 **      waiting list.
8764 */
8765
8766 #define next_wcmd host_scribble
8767
8768 static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd)
8769 {
8770         Scsi_Cmnd *wcmd;
8771
8772 #ifdef DEBUG_WAITING_LIST
8773         printk("%s: cmd %lx inserted into waiting list\n", ncr_name(np), (u_long) cmd);
8774 #endif
8775         cmd->next_wcmd = 0;
8776         if (!(wcmd = np->waiting_list)) np->waiting_list = cmd;
8777         else {
8778                 while ((wcmd->next_wcmd) != 0)
8779                         wcmd = (Scsi_Cmnd *) wcmd->next_wcmd;
8780                 wcmd->next_wcmd = (char *) cmd;
8781         }
8782 }
8783
8784 static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd)
8785 {
8786         Scsi_Cmnd **pcmd = &np->waiting_list;
8787
8788         while (*pcmd) {
8789                 if (cmd == *pcmd) {
8790                         if (to_remove) {
8791                                 *pcmd = (Scsi_Cmnd *) cmd->next_wcmd;
8792                                 cmd->next_wcmd = 0;
8793                         }
8794 #ifdef DEBUG_WAITING_LIST
8795         printk("%s: cmd %lx retrieved from waiting list\n", ncr_name(np), (u_long) cmd);
8796 #endif
8797                         return cmd;
8798                 }
8799                 pcmd = (Scsi_Cmnd **) &(*pcmd)->next_wcmd;
8800         }
8801         return 0;
8802 }
8803
8804 static void process_waiting_list(ncb_p np, int sts)
8805 {
8806         Scsi_Cmnd *waiting_list, *wcmd;
8807
8808         waiting_list = np->waiting_list;
8809         np->waiting_list = 0;
8810
8811 #ifdef DEBUG_WAITING_LIST
8812         if (waiting_list) printk("%s: waiting_list=%lx processing sts=%d\n", ncr_name(np), (u_long) waiting_list, sts);
8813 #endif
8814         while ((wcmd = waiting_list) != 0) {
8815                 waiting_list = (Scsi_Cmnd *) wcmd->next_wcmd;
8816                 wcmd->next_wcmd = 0;
8817                 if (sts == DID_OK) {
8818 #ifdef DEBUG_WAITING_LIST
8819         printk("%s: cmd %lx trying to requeue\n", ncr_name(np), (u_long) wcmd);
8820 #endif
8821                         sts = ncr_queue_command(np, wcmd);
8822                 }
8823                 if (sts != DID_OK) {
8824 #ifdef DEBUG_WAITING_LIST
8825         printk("%s: cmd %lx done forced sts=%d\n", ncr_name(np), (u_long) wcmd, sts);
8826 #endif
8827                         wcmd->result = ScsiResult(sts, 0);
8828                         ncr_queue_done_cmd(np, wcmd);
8829                 }
8830         }
8831 }
8832
8833 #undef next_wcmd
8834
8835 #ifdef SCSI_NCR_PROC_INFO_SUPPORT
8836
8837 /*=========================================================================
8838 **      Proc file system stuff
8839 **
8840 **      A read operation returns profile information.
8841 **      A write operation is a control command.
8842 **      The string is parsed in the driver code and the command is passed 
8843 **      to the ncr_usercmd() function.
8844 **=========================================================================
8845 */
8846
8847 #ifdef SCSI_NCR_USER_COMMAND_SUPPORT
8848
8849 #define is_digit(c)     ((c) >= '0' && (c) <= '9')
8850 #define digit_to_bin(c) ((c) - '0')
8851 #define is_space(c)     ((c) == ' ' || (c) == '\t')
8852
8853 static int skip_spaces(char *ptr, int len)
8854 {
8855         int cnt, c;
8856
8857         for (cnt = len; cnt > 0 && (c = *ptr++) && is_space(c); cnt--);
8858
8859         return (len - cnt);
8860 }
8861
8862 static int get_int_arg(char *ptr, int len, u_long *pv)
8863 {
8864         int     cnt, c;
8865         u_long  v;
8866
8867         for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && is_digit(c); cnt--) {
8868                 v = (v * 10) + digit_to_bin(c);
8869         }
8870
8871         if (pv)
8872                 *pv = v;
8873
8874         return (len - cnt);
8875 }
8876
8877 static int is_keyword(char *ptr, int len, char *verb)
8878 {
8879         int verb_len = strlen(verb);
8880
8881         if (len >= strlen(verb) && !memcmp(verb, ptr, verb_len))
8882                 return verb_len;
8883         else
8884                 return 0;
8885
8886 }
8887
8888 #define SKIP_SPACES(min_spaces)                                         \
8889         if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))           \
8890                 return -EINVAL;                                         \
8891         ptr += arg_len; len -= arg_len;
8892
8893 #define GET_INT_ARG(v)                                                  \
8894         if (!(arg_len = get_int_arg(ptr, len, &(v))))                   \
8895                 return -EINVAL;                                         \
8896         ptr += arg_len; len -= arg_len;
8897
8898
8899 /*
8900 **      Parse a control command
8901 */
8902
8903 static int ncr_user_command(ncb_p np, char *buffer, int length)
8904 {
8905         char *ptr       = buffer;
8906         int len         = length;
8907         struct usrcmd    *uc = &np->user;
8908         int             arg_len;
8909         u_long          target;
8910
8911         bzero(uc, sizeof(*uc));
8912
8913         if (len > 0 && ptr[len-1] == '\n')
8914                 --len;
8915
8916         if      ((arg_len = is_keyword(ptr, len, "setsync")) != 0)
8917                 uc->cmd = UC_SETSYNC;
8918         else if ((arg_len = is_keyword(ptr, len, "settags")) != 0)
8919                 uc->cmd = UC_SETTAGS;
8920         else if ((arg_len = is_keyword(ptr, len, "setorder")) != 0)
8921                 uc->cmd = UC_SETORDER;
8922         else if ((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
8923                 uc->cmd = UC_SETVERBOSE;
8924         else if ((arg_len = is_keyword(ptr, len, "setwide")) != 0)
8925                 uc->cmd = UC_SETWIDE;
8926         else if ((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
8927                 uc->cmd = UC_SETDEBUG;
8928         else if ((arg_len = is_keyword(ptr, len, "setflag")) != 0)
8929                 uc->cmd = UC_SETFLAG;
8930         else
8931                 arg_len = 0;
8932
8933 #ifdef DEBUG_PROC_INFO
8934 printk("ncr_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
8935 #endif
8936
8937         if (!arg_len)
8938                 return -EINVAL;
8939         ptr += arg_len; len -= arg_len;
8940
8941         switch(uc->cmd) {
8942         case UC_SETSYNC:
8943         case UC_SETTAGS:
8944         case UC_SETWIDE:
8945         case UC_SETFLAG:
8946                 SKIP_SPACES(1);
8947                 if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
8948                         ptr += arg_len; len -= arg_len;
8949                         uc->target = ~0;
8950                 } else {
8951                         GET_INT_ARG(target);
8952                         uc->target = (1<<target);
8953 #ifdef DEBUG_PROC_INFO
8954 printk("ncr_user_command: target=%ld\n", target);
8955 #endif
8956                 }
8957                 break;
8958         }
8959
8960         switch(uc->cmd) {
8961         case UC_SETVERBOSE:
8962         case UC_SETSYNC:
8963         case UC_SETTAGS:
8964         case UC_SETWIDE:
8965                 SKIP_SPACES(1);
8966                 GET_INT_ARG(uc->data);
8967 #ifdef DEBUG_PROC_INFO
8968 printk("ncr_user_command: data=%ld\n", uc->data);
8969 #endif
8970                 break;
8971         case UC_SETORDER:
8972                 SKIP_SPACES(1);
8973                 if      ((arg_len = is_keyword(ptr, len, "simple")))
8974                         uc->data = M_SIMPLE_TAG;
8975                 else if ((arg_len = is_keyword(ptr, len, "ordered")))
8976                         uc->data = M_ORDERED_TAG;
8977                 else if ((arg_len = is_keyword(ptr, len, "default")))
8978                         uc->data = 0;
8979                 else
8980                         return -EINVAL;
8981                 break;
8982         case UC_SETDEBUG:
8983                 while (len > 0) {
8984                         SKIP_SPACES(1);
8985                         if      ((arg_len = is_keyword(ptr, len, "alloc")))
8986                                 uc->data |= DEBUG_ALLOC;
8987                         else if ((arg_len = is_keyword(ptr, len, "phase")))
8988                                 uc->data |= DEBUG_PHASE;
8989                         else if ((arg_len = is_keyword(ptr, len, "queue")))
8990                                 uc->data |= DEBUG_QUEUE;
8991                         else if ((arg_len = is_keyword(ptr, len, "result")))
8992                                 uc->data |= DEBUG_RESULT;
8993                         else if ((arg_len = is_keyword(ptr, len, "scatter")))
8994                                 uc->data |= DEBUG_SCATTER;
8995                         else if ((arg_len = is_keyword(ptr, len, "script")))
8996                                 uc->data |= DEBUG_SCRIPT;
8997                         else if ((arg_len = is_keyword(ptr, len, "tiny")))
8998                                 uc->data |= DEBUG_TINY;
8999                         else if ((arg_len = is_keyword(ptr, len, "timing")))
9000                                 uc->data |= DEBUG_TIMING;
9001                         else if ((arg_len = is_keyword(ptr, len, "nego")))
9002                                 uc->data |= DEBUG_NEGO;
9003                         else if ((arg_len = is_keyword(ptr, len, "tags")))
9004                                 uc->data |= DEBUG_TAGS;
9005                         else
9006                                 return -EINVAL;
9007                         ptr += arg_len; len -= arg_len;
9008                 }
9009 #ifdef DEBUG_PROC_INFO
9010 printk("ncr_user_command: data=%ld\n", uc->data);
9011 #endif
9012                 break;
9013         case UC_SETFLAG:
9014                 while (len > 0) {
9015                         SKIP_SPACES(1);
9016                         if      ((arg_len = is_keyword(ptr, len, "trace")))
9017                                 uc->data |= UF_TRACE;
9018                         else if ((arg_len = is_keyword(ptr, len, "no_disc")))
9019                                 uc->data |= UF_NODISC;
9020                         else
9021                                 return -EINVAL;
9022                         ptr += arg_len; len -= arg_len;
9023                 }
9024                 break;
9025         default:
9026                 break;
9027         }
9028
9029         if (len)
9030                 return -EINVAL;
9031         else {
9032                 unsigned long flags;
9033
9034                 NCR_LOCK_NCB(np, flags);
9035                 ncr_usercmd (np);
9036                 NCR_UNLOCK_NCB(np, flags);
9037         }
9038         return length;
9039 }
9040
9041 #endif  /* SCSI_NCR_USER_COMMAND_SUPPORT */
9042
9043
9044 #ifdef SCSI_NCR_USER_INFO_SUPPORT
9045 /*
9046 **      Copy formatted information into the input buffer.
9047 */
9048
9049 static int ncr_host_info(ncb_p np, char *ptr, off_t offset, int len)
9050 {
9051         struct info_str info;
9052
9053         info.buffer     = ptr;
9054         info.length     = len;
9055         info.offset     = offset;
9056         info.pos        = 0;
9057
9058         copy_info(&info, "  Chip NCR53C%s, device id 0x%x, "
9059                          "revision id 0x%x\n",
9060                          np->chip_name, np->device_id,  np->revision_id);
9061         copy_info(&info, "  On PCI bus %d, device %d, function %d, IRQ %d\n",
9062                 np->bus, (np->device_fn & 0xf8) >> 3, np->device_fn & 7,
9063                 (int) np->irq);
9064         copy_info(&info, "  Synchronous period factor %d, "
9065                          "max commands per lun %d\n",
9066                          (int) np->minsync, MAX_TAGS);
9067
9068         if (driver_setup.debug || driver_setup.verbose > 1) {
9069                 copy_info(&info, "  Debug flags 0x%x, verbosity level %d\n",
9070                           driver_setup.debug, driver_setup.verbose);
9071         }
9072
9073         return info.pos > info.offset? info.pos - info.offset : 0;
9074 }
9075
9076 #endif /* SCSI_NCR_USER_INFO_SUPPORT */
9077
9078 /*
9079 **      Entry point of the scsi proc fs of the driver.
9080 **      - func = 0 means read  (returns profile data)
9081 **      - func = 1 means write (parse user control command)
9082 */
9083
9084 static int ncr53c8xx_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
9085                         int length, int func)
9086 {
9087         struct host_data *host_data;
9088         ncb_p ncb = 0;
9089         int retv;
9090
9091 #ifdef DEBUG_PROC_INFO
9092 printk("ncr53c8xx_proc_info: hostno=%d, func=%d\n", host->host_no, func);
9093 #endif
9094
9095         host_data = (struct host_data *) host->hostdata;
9096         ncb = host_data->ncb;
9097
9098         if (func) {
9099 #ifdef  SCSI_NCR_USER_COMMAND_SUPPORT
9100                 retv = ncr_user_command(ncb, buffer, length);
9101 #else
9102                 retv = -EINVAL;
9103 #endif
9104         }
9105         else {
9106                 if (start)
9107                         *start = buffer;
9108 #ifdef SCSI_NCR_USER_INFO_SUPPORT
9109                 retv = ncr_host_info(ncb, buffer, offset, length);
9110 #else
9111                 retv = -EINVAL;
9112 #endif
9113         }
9114
9115         return retv;
9116 }
9117
9118 /*=========================================================================
9119 **      End of proc file system stuff
9120 **=========================================================================
9121 */
9122 #endif
9123
9124
9125 /*==========================================================
9126 **
9127 **      Boot command line.
9128 **
9129 **==========================================================
9130 */
9131 #ifdef  MODULE
9132 char *ncr53c8xx = 0;    /* command line passed by insmod */
9133 MODULE_PARM(ncr53c8xx, "s");
9134 #endif
9135
9136 int __init ncr53c8xx_setup(char *str)
9137 {
9138         return sym53c8xx__setup(str);
9139 }
9140
9141 #ifndef MODULE
9142 __setup("ncr53c8xx=", ncr53c8xx_setup);
9143 #endif
9144
9145 /*==========================================================
9146 **
9147 **   Entry point for info() function
9148 **
9149 **==========================================================
9150 */
9151 const char *ncr53c8xx_info (struct Scsi_Host *host)
9152 {
9153         return SCSI_NCR_DRIVER_NAME;
9154 }