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