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