]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ncr/ncr.c
Retire scsi_low
[FreeBSD/FreeBSD.git] / sys / dev / ncr / ncr.c
1 /**************************************************************************
2 **
3 **
4 **  Device driver for the   NCR 53C8XX   PCI-SCSI-Controller Family.
5 **
6 **-------------------------------------------------------------------------
7 **
8 **  Written for 386bsd and FreeBSD by
9 **      Wolfgang Stanglmeier    <wolf@cologne.de>
10 **      Stefan Esser            <se@mi.Uni-Koeln.de>
11 **
12 **-------------------------------------------------------------------------
13 */
14 /*-
15 ** Copyright (c) 1994 Wolfgang Stanglmeier.  All rights reserved.
16 **
17 ** Redistribution and use in source and binary forms, with or without
18 ** modification, are permitted provided that the following conditions
19 ** are met:
20 ** 1. Redistributions of source code must retain the above copyright
21 **    notice, this list of conditions and the following disclaimer.
22 ** 2. Redistributions in binary form must reproduce the above copyright
23 **    notice, this list of conditions and the following disclaimer in the
24 **    documentation and/or other materials provided with the distribution.
25 ** 3. The name of the author may not be used to endorse or promote products
26 **    derived from this software without specific prior written permission.
27 **
28 ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
29 ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
38 **
39 ***************************************************************************
40 */
41
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44
45
46 #define NCR_GETCC_WITHMSG
47
48 #if defined (__FreeBSD__) && defined(_KERNEL)
49 #include "opt_ncr.h"
50 #endif
51
52 /*==========================================================
53 **
54 **      Configuration and Debugging
55 **
56 **      May be overwritten in <arch/conf/xxxx>
57 **
58 **==========================================================
59 */
60
61 /*
62 **    SCSI address of this device.
63 **    The boot routines should have set it.
64 **    If not, use this.
65 */
66
67 #ifndef SCSI_NCR_MYADDR
68 #define SCSI_NCR_MYADDR      (7)
69 #endif /* SCSI_NCR_MYADDR */
70
71 /*
72 **    The default synchronous period factor
73 **    (0=asynchronous)
74 **    If maximum synchronous frequency is defined, use it instead.
75 */
76
77 #ifndef SCSI_NCR_MAX_SYNC
78
79 #ifndef SCSI_NCR_DFLT_SYNC
80 #define SCSI_NCR_DFLT_SYNC   (12)
81 #endif /* SCSI_NCR_DFLT_SYNC */
82
83 #else
84
85 #if     SCSI_NCR_MAX_SYNC == 0
86 #define SCSI_NCR_DFLT_SYNC 0
87 #else
88 #define SCSI_NCR_DFLT_SYNC (250000 / SCSI_NCR_MAX_SYNC)
89 #endif
90
91 #endif
92
93 /*
94 **    The minimal asynchronous pre-scaler period (ns)
95 **    Shall be 40.
96 */
97
98 #ifndef SCSI_NCR_MIN_ASYNC
99 #define SCSI_NCR_MIN_ASYNC   (40)
100 #endif /* SCSI_NCR_MIN_ASYNC */
101
102 /*
103 **    The maximal bus with (in log2 byte)
104 **    (0=8 bit, 1=16 bit)
105 */
106
107 #ifndef SCSI_NCR_MAX_WIDE
108 #define SCSI_NCR_MAX_WIDE   (1)
109 #endif /* SCSI_NCR_MAX_WIDE */
110
111 /*==========================================================
112 **
113 **      Configuration and Debugging
114 **
115 **==========================================================
116 */
117
118 /*
119 **    Number of targets supported by the driver.
120 **    n permits target numbers 0..n-1.
121 **    Default is 7, meaning targets #0..#6.
122 **    #7 .. is myself.
123 */
124
125 #define MAX_TARGET  (16)
126
127 /*
128 **    Number of logic units supported by the driver.
129 **    n enables logic unit numbers 0..n-1.
130 **    The common SCSI devices require only
131 **    one lun, so take 1 as the default.
132 */
133
134 #ifndef MAX_LUN
135 #define MAX_LUN     (8)
136 #endif  /* MAX_LUN */
137
138 /*
139 **    The maximum number of jobs scheduled for starting.
140 **    There should be one slot per target, and one slot
141 **    for each tag of each target in use.
142 */
143
144 #define MAX_START   (256)
145
146 /*
147 **    The maximum number of segments a transfer is split into.
148 */
149
150 #define MAX_SCATTER (33)
151
152 /*
153 **    The maximum transfer length (should be >= 64k).
154 **    MUST NOT be greater than (MAX_SCATTER-1) * PAGE_SIZE.
155 */
156
157 #define MAX_SIZE  ((MAX_SCATTER-1) * (long) PAGE_SIZE)
158
159 /*
160 **      other
161 */
162
163 #define NCR_SNOOP_TIMEOUT (1000000)
164
165 /*==========================================================
166 **
167 **      Include files
168 **
169 **==========================================================
170 */
171
172 #include <sys/param.h>
173 #include <sys/time.h>
174
175 #ifdef _KERNEL
176 #include <sys/systm.h>
177 #include <sys/malloc.h>
178 #include <sys/kernel.h>
179 #include <sys/module.h>
180 #include <sys/sysctl.h>
181 #include <sys/lock.h>
182 #include <sys/mutex.h>
183 #include <sys/bus.h>
184 #include <machine/md_var.h>
185 #include <machine/bus.h>
186 #include <machine/resource.h>
187 #include <sys/rman.h>
188 #include <vm/vm.h>
189 #include <vm/pmap.h>
190 #include <vm/vm_extern.h>
191 #endif
192
193 #include <dev/pci/pcivar.h>
194 #include <dev/pci/pcireg.h>
195 #include <dev/ncr/ncrreg.h>
196
197 #include <cam/cam.h>
198 #include <cam/cam_ccb.h>
199 #include <cam/cam_sim.h>
200 #include <cam/cam_xpt_sim.h>
201 #include <cam/cam_debug.h>
202
203 #include <cam/scsi/scsi_all.h>
204 #include <cam/scsi/scsi_message.h>
205
206 /*==========================================================
207 **
208 **      Debugging tags
209 **
210 **==========================================================
211 */
212
213 #define DEBUG_ALLOC    (0x0001)
214 #define DEBUG_PHASE    (0x0002)
215 #define DEBUG_POLL     (0x0004)
216 #define DEBUG_QUEUE    (0x0008)
217 #define DEBUG_RESULT   (0x0010)
218 #define DEBUG_SCATTER  (0x0020)
219 #define DEBUG_SCRIPT   (0x0040)
220 #define DEBUG_TINY     (0x0080)
221 #define DEBUG_TIMING   (0x0100)
222 #define DEBUG_NEGO     (0x0200)
223 #define DEBUG_TAGS     (0x0400)
224 #define DEBUG_FREEZE   (0x0800)
225 #define DEBUG_RESTART  (0x1000)
226
227 /*
228 **    Enable/Disable debug messages.
229 **    Can be changed at runtime too.
230 */
231 #ifdef SCSI_NCR_DEBUG
232         #define DEBUG_FLAGS ncr_debug
233 #else /* SCSI_NCR_DEBUG */
234         #define SCSI_NCR_DEBUG  0
235         #define DEBUG_FLAGS     0
236 #endif /* SCSI_NCR_DEBUG */
237
238
239
240 /*==========================================================
241 **
242 **      assert ()
243 **
244 **==========================================================
245 **
246 **      modified copy from 386bsd:/usr/include/sys/assert.h
247 **
248 **----------------------------------------------------------
249 */
250
251 #ifdef DIAGNOSTIC
252 #define assert(expression) {                                    \
253         KASSERT(expression, ("%s", #expression));               \
254 }
255 #else
256 #define assert(expression) {                                    \
257         if (!(expression)) {                                    \
258                 (void)printf("assertion \"%s\" failed: "        \
259                              "file \"%s\", line %d\n",          \
260                              #expression, __FILE__, __LINE__);  \
261         }                                                       \
262 }
263 #endif
264
265 /*==========================================================
266 **
267 **      Access to the controller chip.
268 **
269 **==========================================================
270 */
271
272 #define INB(r) bus_read_1(np->reg_res, offsetof(struct ncr_reg, r))
273 #define INW(r) bus_read_2(np->reg_res, offsetof(struct ncr_reg, r))
274 #define INL(r) bus_read_4(np->reg_res, offsetof(struct ncr_reg, r))
275
276 #define OUTB(r, val) bus_write_1(np->reg_res, offsetof(struct ncr_reg, r), val)
277 #define OUTW(r, val) bus_write_2(np->reg_res, offsetof(struct ncr_reg, r), val)
278 #define OUTL(r, val) bus_write_4(np->reg_res, offsetof(struct ncr_reg, r), val)
279 #define OUTL_OFF(o, val) bus_write_4(np->reg_res, o, val)
280
281 #define INB_OFF(o) bus_read_1(np->reg_res, o)
282 #define INW_OFF(o) bus_read_2(np->reg_res, o)
283 #define INL_OFF(o) bus_read_4(np->reg_res, o)
284
285 #define READSCRIPT_OFF(base, off)                                       \
286     (base ? *((volatile u_int32_t *)((volatile char *)base + (off))) :  \
287     bus_read_4(np->sram_res, off))
288
289 #define WRITESCRIPT_OFF(base, off, val)                                 \
290     do {                                                                \
291         if (base)                                                       \
292                 *((volatile u_int32_t *)                                \
293                         ((volatile char *)base + (off))) = (val);       \
294         else                                                            \
295                 bus_write_4(np->sram_res, off, val);                    \
296     } while (0)
297
298 #define READSCRIPT(r) \
299     READSCRIPT_OFF(np->script, offsetof(struct script, r))
300
301 #define WRITESCRIPT(r, val) \
302     WRITESCRIPT_OFF(np->script, offsetof(struct script, r), val)
303
304 /*
305 **      Set bit field ON, OFF 
306 */
307
308 #define OUTONB(r, m)    OUTB(r, INB(r) | (m))
309 #define OUTOFFB(r, m)   OUTB(r, INB(r) & ~(m))
310 #define OUTONW(r, m)    OUTW(r, INW(r) | (m))
311 #define OUTOFFW(r, m)   OUTW(r, INW(r) & ~(m))
312 #define OUTONL(r, m)    OUTL(r, INL(r) | (m))
313 #define OUTOFFL(r, m)   OUTL(r, INL(r) & ~(m))
314
315 /*==========================================================
316 **
317 **      Command control block states.
318 **
319 **==========================================================
320 */
321
322 #define HS_IDLE         (0)
323 #define HS_BUSY         (1)
324 #define HS_NEGOTIATE    (2)     /* sync/wide data transfer*/
325 #define HS_DISCONNECT   (3)     /* Disconnected by target */
326
327 #define HS_COMPLETE     (4)
328 #define HS_SEL_TIMEOUT  (5)     /* Selection timeout      */
329 #define HS_RESET        (6)     /* SCSI reset        */
330 #define HS_ABORTED      (7)     /* Transfer aborted       */
331 #define HS_TIMEOUT      (8)     /* Software timeout       */
332 #define HS_FAIL         (9)     /* SCSI or PCI bus errors */
333 #define HS_UNEXPECTED   (10)    /* Unexpected disconnect  */
334 #define HS_STALL        (11)    /* QUEUE FULL or BUSY     */
335
336 #define HS_DONEMASK     (0xfc)
337
338 /*==========================================================
339 **
340 **      Software Interrupt Codes
341 **
342 **==========================================================
343 */
344
345 #define SIR_SENSE_RESTART       (1)
346 #define SIR_SENSE_FAILED        (2)
347 #define SIR_STALL_RESTART       (3)
348 #define SIR_STALL_QUEUE         (4)
349 #define SIR_NEGO_SYNC           (5)
350 #define SIR_NEGO_WIDE           (6)
351 #define SIR_NEGO_FAILED         (7)
352 #define SIR_NEGO_PROTO          (8)
353 #define SIR_REJECT_RECEIVED     (9)
354 #define SIR_REJECT_SENT         (10)
355 #define SIR_IGN_RESIDUE         (11)
356 #define SIR_MISSING_SAVE        (12)
357 #define SIR_MAX                 (12)
358
359 /*==========================================================
360 **
361 **      Extended error codes.
362 **      xerr_status field of struct nccb.
363 **
364 **==========================================================
365 */
366
367 #define XE_OK           (0)
368 #define XE_EXTRA_DATA   (1)     /* unexpected data phase */
369 #define XE_BAD_PHASE    (2)     /* illegal phase (4/5)   */
370
371 /*==========================================================
372 **
373 **      Negotiation status.
374 **      nego_status field       of struct nccb.
375 **
376 **==========================================================
377 */
378
379 #define NS_SYNC         (1)
380 #define NS_WIDE         (2)
381
382 /*==========================================================
383 **
384 **      XXX These are no longer used.  Remove once the
385 **          script is updated.
386 **      "Special features" of targets.
387 **      quirks field of struct tcb.
388 **      actualquirks field of struct nccb.
389 **
390 **==========================================================
391 */
392
393 #define QUIRK_AUTOSAVE  (0x01)
394 #define QUIRK_NOMSG     (0x02)
395 #define QUIRK_NOSYNC    (0x10)
396 #define QUIRK_NOWIDE16  (0x20)
397 #define QUIRK_NOTAGS    (0x40)
398 #define QUIRK_UPDATE    (0x80)
399
400 /*==========================================================
401 **
402 **      Misc.
403 **
404 **==========================================================
405 */
406
407 #define CCB_MAGIC       (0xf2691ad2)
408 #define MAX_TAGS        (32)            /* hard limit */
409
410 /*==========================================================
411 **
412 **      OS dependencies.
413 **
414 **==========================================================
415 */
416
417 #define PRINT_ADDR(ccb) xpt_print_path((ccb)->ccb_h.path)
418
419 /*==========================================================
420 **
421 **      Declaration of structs.
422 **
423 **==========================================================
424 */
425
426 struct tcb;
427 struct lcb;
428 struct nccb;
429 struct ncb;
430 struct script;
431
432 typedef struct ncb * ncb_p;
433 typedef struct tcb * tcb_p;
434 typedef struct lcb * lcb_p;
435 typedef struct nccb * nccb_p;
436
437 struct link {
438         ncrcmd  l_cmd;
439         ncrcmd  l_paddr;
440 };
441
442 struct  usrcmd {
443         u_long  target;
444         u_long  lun;
445         u_long  data;
446         u_long  cmd;
447 };
448
449 #define UC_SETSYNC      10
450 #define UC_SETTAGS      11
451 #define UC_SETDEBUG     12
452 #define UC_SETORDER     13
453 #define UC_SETWIDE      14
454 #define UC_SETFLAG      15
455
456 #define UF_TRACE        (0x01)
457
458 /*---------------------------------------
459 **
460 **      Timestamps for profiling
461 **
462 **---------------------------------------
463 */
464
465 /* Type of the kernel variable `ticks'.  XXX should be declared with the var. */
466 typedef int ticks_t;
467
468 struct tstamp {
469         ticks_t start;
470         ticks_t end;
471         ticks_t select;
472         ticks_t command;
473         ticks_t data;
474         ticks_t status;
475         ticks_t disconnect;
476 };
477
478 /*
479 **      profiling data (per device)
480 */
481
482 struct profile {
483         u_long  num_trans;
484         u_long  num_bytes;
485         u_long  num_disc;
486         u_long  num_break;
487         u_long  num_int;
488         u_long  num_fly;
489         u_long  ms_setup;
490         u_long  ms_data;
491         u_long  ms_disc;
492         u_long  ms_post;
493 };
494
495 /*==========================================================
496 **
497 **      Declaration of structs:         target control block
498 **
499 **==========================================================
500 */
501
502 #define NCR_TRANS_CUR           0x01    /* Modify current neogtiation status */
503 #define NCR_TRANS_ACTIVE        0x03    /* Assume this is the active target */
504 #define NCR_TRANS_GOAL          0x04    /* Modify negotiation goal */
505 #define NCR_TRANS_USER          0x08    /* Modify user negotiation settings */
506
507 struct ncr_transinfo {
508         u_int8_t width;
509         u_int8_t period;
510         u_int8_t offset;
511 };
512
513 struct ncr_target_tinfo {
514         /* Hardware version of our sync settings */
515         u_int8_t disc_tag;
516 #define         NCR_CUR_DISCENB 0x01
517 #define         NCR_CUR_TAGENB  0x02
518 #define         NCR_USR_DISCENB 0x04
519 #define         NCR_USR_TAGENB  0x08
520         u_int8_t sval;
521         struct   ncr_transinfo current;
522         struct   ncr_transinfo goal;
523         struct   ncr_transinfo user;
524         /* Hardware version of our wide settings */
525         u_int8_t wval;
526 };
527
528 struct tcb {
529         /*
530         **      during reselection the ncr jumps to this point
531         **      with SFBR set to the encoded target number
532         **      with bit 7 set.
533         **      if it's not this target, jump to the next.
534         **
535         **      JUMP  IF (SFBR != #target#)
536         **      @(next tcb)
537         */
538
539         struct link   jump_tcb;
540
541         /*
542         **      load the actual values for the sxfer and the scntl3
543         **      register (sync/wide mode).
544         **
545         **      SCR_COPY (1);
546         **      @(sval field of this tcb)
547         **      @(sxfer register)
548         **      SCR_COPY (1);
549         **      @(wval field of this tcb)
550         **      @(scntl3 register)
551         */
552
553         ncrcmd  getscr[6];
554
555         /*
556         **      if next message is "identify"
557         **      then load the message to SFBR,
558         **      else load 0 to SFBR.
559         **
560         **      CALL
561         **      <RESEL_LUN>
562         */
563
564         struct link   call_lun;
565
566         /*
567         **      now look for the right lun.
568         **
569         **      JUMP
570         **      @(first nccb of this lun)
571         */
572
573         struct link   jump_lcb;
574
575         /*
576         **      pointer to interrupted getcc nccb
577         */
578
579         nccb_p   hold_cp;
580
581         /*
582         **      pointer to nccb used for negotiating.
583         **      Avoid to start a nego for all queued commands 
584         **      when tagged command queuing is enabled.
585         */
586
587         nccb_p   nego_cp;
588
589         /*
590         **      statistical data
591         */
592
593         u_long  transfers;
594         u_long  bytes;
595
596         /*
597         **      user settable limits for sync transfer
598         **      and tagged commands.
599         */
600
601         struct   ncr_target_tinfo tinfo;
602
603         /*
604         **      the lcb's of this tcb
605         */
606
607         lcb_p   lp[MAX_LUN];
608 };
609
610 /*==========================================================
611 **
612 **      Declaration of structs:         lun control block
613 **
614 **==========================================================
615 */
616
617 struct lcb {
618         /*
619         **      during reselection the ncr jumps to this point
620         **      with SFBR set to the "Identify" message.
621         **      if it's not this lun, jump to the next.
622         **
623         **      JUMP  IF (SFBR != #lun#)
624         **      @(next lcb of this target)
625         */
626
627         struct link     jump_lcb;
628
629         /*
630         **      if next message is "simple tag",
631         **      then load the tag to SFBR,
632         **      else load 0 to SFBR.
633         **
634         **      CALL
635         **      <RESEL_TAG>
636         */
637
638         struct link     call_tag;
639
640         /*
641         **      now look for the right nccb.
642         **
643         **      JUMP
644         **      @(first nccb of this lun)
645         */
646
647         struct link     jump_nccb;
648
649         /*
650         **      start of the nccb chain
651         */
652
653         nccb_p  next_nccb;
654
655         /*
656         **      Control of tagged queueing
657         */
658
659         u_char          reqnccbs;
660         u_char          reqlink;
661         u_char          actlink;
662         u_char          usetags;
663         u_char          lasttag;
664 };
665
666 /*==========================================================
667 **
668 **      Declaration of structs:     COMMAND control block
669 **
670 **==========================================================
671 **
672 **      This substructure is copied from the nccb to a
673 **      global address after selection (or reselection)
674 **      and copied back before disconnect.
675 **
676 **      These fields are accessible to the script processor.
677 **
678 **----------------------------------------------------------
679 */
680
681 struct head {
682         /*
683         **      Execution of a nccb starts at this point.
684         **      It's a jump to the "SELECT" label
685         **      of the script.
686         **
687         **      After successful selection the script
688         **      processor overwrites it with a jump to
689         **      the IDLE label of the script.
690         */
691
692         struct link     launch;
693
694         /*
695         **      Saved data pointer.
696         **      Points to the position in the script
697         **      responsible for the actual transfer
698         **      of data.
699         **      It's written after reception of a
700         **      "SAVE_DATA_POINTER" message.
701         **      The goalpointer points after
702         **      the last transfer command.
703         */
704
705         u_int32_t       savep;
706         u_int32_t       lastp;
707         u_int32_t       goalp;
708
709         /*
710         **      The virtual address of the nccb
711         **      containing this header.
712         */
713
714         nccb_p  cp;
715
716         /*
717         **      space for some timestamps to gather
718         **      profiling data about devices and this driver.
719         */
720
721         struct tstamp   stamp;
722
723         /*
724         **      status fields.
725         */
726
727         u_char          status[8];
728 };
729
730 /*
731 **      The status bytes are used by the host and the script processor.
732 **
733 **      The first four byte are copied to the scratchb register
734 **      (declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
735 **      and copied back just after disconnecting.
736 **      Inside the script the XX_REG are used.
737 **
738 **      The last four bytes are used inside the script by "COPY" commands.
739 **      Because source and destination must have the same alignment
740 **      in a longword, the fields HAVE to be at the chosen offsets.
741 **              xerr_st (4)     0       (0x34)  scratcha
742 **              sync_st (5)     1       (0x05)  sxfer
743 **              wide_st (7)     3       (0x03)  scntl3
744 */
745
746 /*
747 **      First four bytes (script)
748 */
749 #define  QU_REG scr0
750 #define  HS_REG scr1
751 #define  HS_PRT nc_scr1
752 #define  SS_REG scr2
753 #define  PS_REG scr3
754
755 /*
756 **      First four bytes (host)
757 */
758 #define  actualquirks  phys.header.status[0]
759 #define  host_status   phys.header.status[1]
760 #define  s_status      phys.header.status[2]
761 #define  parity_status phys.header.status[3]
762
763 /*
764 **      Last four bytes (script)
765 */
766 #define  xerr_st       header.status[4] /* MUST be ==0 mod 4 */
767 #define  sync_st       header.status[5] /* MUST be ==1 mod 4 */
768 #define  nego_st       header.status[6]
769 #define  wide_st       header.status[7] /* MUST be ==3 mod 4 */
770
771 /*
772 **      Last four bytes (host)
773 */
774 #define  xerr_status   phys.xerr_st
775 #define  sync_status   phys.sync_st
776 #define  nego_status   phys.nego_st
777 #define  wide_status   phys.wide_st
778
779 /*==========================================================
780 **
781 **      Declaration of structs:     Data structure block
782 **
783 **==========================================================
784 **
785 **      During execution of a nccb by the script processor,
786 **      the DSA (data structure address) register points
787 **      to this substructure of the nccb.
788 **      This substructure contains the header with
789 **      the script-processor-changable data and
790 **      data blocks for the indirect move commands.
791 **
792 **----------------------------------------------------------
793 */
794
795 struct dsb {
796
797         /*
798         **      Header.
799         **      Has to be the first entry,
800         **      because it's jumped to by the
801         **      script processor
802         */
803
804         struct head     header;
805
806         /*
807         **      Table data for Script
808         */
809
810         struct scr_tblsel  select;
811         struct scr_tblmove smsg  ;
812         struct scr_tblmove smsg2 ;
813         struct scr_tblmove cmd   ;
814         struct scr_tblmove scmd  ;
815         struct scr_tblmove sense ;
816         struct scr_tblmove data [MAX_SCATTER];
817 };
818
819 /*==========================================================
820 **
821 **      Declaration of structs:     Command control block.
822 **
823 **==========================================================
824 **
825 **      During execution of a nccb by the script processor,
826 **      the DSA (data structure address) register points
827 **      to this substructure of the nccb.
828 **      This substructure contains the header with
829 **      the script-processor-changable data and then
830 **      data blocks for the indirect move commands.
831 **
832 **----------------------------------------------------------
833 */
834
835
836 struct nccb {
837         /*
838         **      This filler ensures that the global header is 
839         **      cache line size aligned.
840         */
841         ncrcmd  filler[4];
842
843         /*
844         **      during reselection the ncr jumps to this point.
845         **      If a "SIMPLE_TAG" message was received,
846         **      then SFBR is set to the tag.
847         **      else SFBR is set to 0
848         **      If looking for another tag, jump to the next nccb.
849         **
850         **      JUMP  IF (SFBR != #TAG#)
851         **      @(next nccb of this lun)
852         */
853
854         struct link             jump_nccb;
855
856         /*
857         **      After execution of this call, the return address
858         **      (in  the TEMP register) points to the following
859         **      data structure block.
860         **      So copy it to the DSA register, and start
861         **      processing of this data structure.
862         **
863         **      CALL
864         **      <RESEL_TMP>
865         */
866
867         struct link             call_tmp;
868
869         /*
870         **      This is the data structure which is
871         **      to be executed by the script processor.
872         */
873
874         struct dsb              phys;
875
876         /*
877         **      If a data transfer phase is terminated too early
878         **      (after reception of a message (i.e. DISCONNECT)),
879         **      we have to prepare a mini script to transfer
880         **      the rest of the data.
881         */
882
883         ncrcmd                  patch[8];
884
885         /*
886         **      The general SCSI driver provides a
887         **      pointer to a control block.
888         */
889
890         union   ccb *ccb;
891
892         /*
893         **      We prepare a message to be sent after selection,
894         **      and a second one to be sent after getcc selection.
895         **      Contents are IDENTIFY and SIMPLE_TAG.
896         **      While negotiating sync or wide transfer,
897         **      a SDTM or WDTM message is appended.
898         */
899
900         u_char                  scsi_smsg [8];
901         u_char                  scsi_smsg2[8];
902
903         /*
904         **      Lock this nccb.
905         **      Flag is used while looking for a free nccb.
906         */
907
908         u_long          magic;
909
910         /*
911         **      Physical address of this instance of nccb
912         */
913
914         u_long          p_nccb;
915
916         /*
917         **      Completion time out for this job.
918         **      It's set to time of start + allowed number of seconds.
919         */
920
921         time_t          tlimit;
922
923         /*
924         **      All nccbs of one hostadapter are chained.
925         */
926
927         nccb_p          link_nccb;
928
929         /*
930         **      All nccbs of one target/lun are chained.
931         */
932
933         nccb_p          next_nccb;
934
935         /*
936         **      Sense command
937         */
938
939         u_char          sensecmd[6];
940
941         /*
942         **      Tag for this transfer.
943         **      It's patched into jump_nccb.
944         **      If it's not zero, a SIMPLE_TAG
945         **      message is included in smsg.
946         */
947
948         u_char                  tag;
949 };
950
951 #define CCB_PHYS(cp,lbl)        (cp->p_nccb + offsetof(struct nccb, lbl))
952
953 /*==========================================================
954 **
955 **      Declaration of structs:     NCR device descriptor
956 **
957 **==========================================================
958 */
959
960 struct ncb {
961         /*
962         **      The global header.
963         **      Accessible to both the host and the
964         **      script-processor.
965         **      We assume it is cache line size aligned.
966         */
967         struct head     header;
968
969         device_t dev;
970
971         /*-----------------------------------------------
972         **      Scripts ..
973         **-----------------------------------------------
974         **
975         **      During reselection the ncr jumps to this point.
976         **      The SFBR register is loaded with the encoded target id.
977         **
978         **      Jump to the first target.
979         **
980         **      JUMP
981         **      @(next tcb)
982         */
983         struct link     jump_tcb;
984
985         /*-----------------------------------------------
986         **      Configuration ..
987         **-----------------------------------------------
988         **
989         **      virtual and physical addresses
990         **      of the 53c810 chip.
991         */
992         int             reg_rid;
993         struct resource *reg_res;
994
995         int             sram_rid;
996         struct resource *sram_res;
997
998         struct resource *irq_res;
999         void            *irq_handle;
1000
1001         /*
1002         **      Scripts instance virtual address.
1003         */
1004         struct script   *script;
1005         struct scripth  *scripth;
1006
1007         /*
1008         **      Scripts instance physical address.
1009         */
1010         u_long          p_script;
1011         u_long          p_scripth;
1012
1013         /*
1014         **      The SCSI address of the host adapter.
1015         */
1016         u_char          myaddr;
1017
1018         /*
1019         **      timing parameters
1020         */
1021         u_char          minsync;        /* Minimum sync period factor   */
1022         u_char          maxsync;        /* Maximum sync period factor   */
1023         u_char          maxoffs;        /* Max scsi offset              */
1024         u_char          clock_divn;     /* Number of clock divisors     */
1025         u_long          clock_khz;      /* SCSI clock frequency in KHz  */
1026         u_long          features;       /* Chip features map            */
1027         u_char          multiplier;     /* Clock multiplier (1,2,4)     */
1028
1029         u_char          maxburst;       /* log base 2 of dwords burst   */
1030
1031         /*
1032         **      BIOS supplied PCI bus options
1033         */
1034         u_char          rv_scntl3;
1035         u_char          rv_dcntl;
1036         u_char          rv_dmode;
1037         u_char          rv_ctest3;
1038         u_char          rv_ctest4;
1039         u_char          rv_ctest5;
1040         u_char          rv_gpcntl;
1041         u_char          rv_stest2;
1042
1043         /*-----------------------------------------------
1044         **      CAM SIM information for this instance
1045         **-----------------------------------------------
1046         */
1047
1048         struct          cam_sim  *sim;
1049         struct          cam_path *path;
1050
1051         /*-----------------------------------------------
1052         **      Job control
1053         **-----------------------------------------------
1054         **
1055         **      Commands from user
1056         */
1057         struct usrcmd   user;
1058
1059         /*
1060         **      Target data
1061         */
1062         struct tcb      target[MAX_TARGET];
1063
1064         /*
1065         **      Start queue.
1066         */
1067         u_int32_t       squeue [MAX_START];
1068         u_short         squeueput;
1069
1070         /*
1071         **      Timeout handler
1072         */
1073         time_t          heartbeat;
1074         u_short         ticks;
1075         u_short         latetime;
1076         time_t          lasttime;
1077         struct          callout timer;
1078
1079         /*-----------------------------------------------
1080         **      Debug and profiling
1081         **-----------------------------------------------
1082         **
1083         **      register dump
1084         */
1085         struct ncr_reg  regdump;
1086         time_t          regtime;
1087
1088         /*
1089         **      Profiling data
1090         */
1091         struct profile  profile;
1092         u_long          disc_phys;
1093         u_long          disc_ref;
1094
1095         /*
1096         **      Head of list of all nccbs for this controller.
1097         */
1098         nccb_p          link_nccb;
1099         
1100         /*
1101         **      message buffers.
1102         **      Should be longword aligned,
1103         **      because they're written with a
1104         **      COPY script command.
1105         */
1106         u_char          msgout[8];
1107         u_char          msgin [8];
1108         u_int32_t       lastmsg;
1109
1110         /*
1111         **      Buffer for STATUS_IN phase.
1112         */
1113         u_char          scratch;
1114
1115         /*
1116         **      controller chip dependent maximal transfer width.
1117         */
1118         u_char          maxwide;
1119
1120         struct mtx      lock;
1121 #ifdef NCR_IOMAPPED
1122         /*
1123         **      address of the ncr control registers in io space
1124         */
1125         pci_port_t      port;
1126 #endif
1127 };
1128
1129 #define NCB_SCRIPT_PHYS(np,lbl) (np->p_script + offsetof (struct script, lbl))
1130 #define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1131
1132 /*==========================================================
1133 **
1134 **
1135 **      Script for NCR-Processor.
1136 **
1137 **      Use ncr_script_fill() to create the variable parts.
1138 **      Use ncr_script_copy_and_bind() to make a copy and
1139 **      bind to physical addresses.
1140 **
1141 **
1142 **==========================================================
1143 **
1144 **      We have to know the offsets of all labels before
1145 **      we reach them (for forward jumps).
1146 **      Therefore we declare a struct here.
1147 **      If you make changes inside the script,
1148 **      DONT FORGET TO CHANGE THE LENGTHS HERE!
1149 **
1150 **----------------------------------------------------------
1151 */
1152
1153 /*
1154 **      Script fragments which are loaded into the on-board RAM 
1155 **      of 825A, 875 and 895 chips.
1156 */
1157 struct script {
1158         ncrcmd  start           [  7];
1159         ncrcmd  start0          [  2];
1160         ncrcmd  start1          [  3];
1161         ncrcmd  startpos        [  1];
1162         ncrcmd  trysel          [  8];
1163         ncrcmd  skip            [  8];
1164         ncrcmd  skip2           [  3];
1165         ncrcmd  idle            [  2];
1166         ncrcmd  select          [ 18];
1167         ncrcmd  prepare         [  4];
1168         ncrcmd  loadpos         [ 14];
1169         ncrcmd  prepare2        [ 24];
1170         ncrcmd  setmsg          [  5];
1171         ncrcmd  clrack          [  2];
1172         ncrcmd  dispatch        [ 33];
1173         ncrcmd  no_data         [ 17];
1174         ncrcmd  checkatn        [ 10];
1175         ncrcmd  command         [ 15];
1176         ncrcmd  status          [ 27];
1177         ncrcmd  msg_in          [ 26];
1178         ncrcmd  msg_bad         [  6];
1179         ncrcmd  complete        [ 13];
1180         ncrcmd  cleanup         [ 12];
1181         ncrcmd  cleanup0        [  9];
1182         ncrcmd  signal          [ 12];
1183         ncrcmd  save_dp         [  5];
1184         ncrcmd  restore_dp      [  5];
1185         ncrcmd  disconnect      [ 12];
1186         ncrcmd  disconnect0     [  5];
1187         ncrcmd  disconnect1     [ 23];
1188         ncrcmd  msg_out         [  9];
1189         ncrcmd  msg_out_done    [  7];
1190         ncrcmd  badgetcc        [  6];
1191         ncrcmd  reselect        [  8];
1192         ncrcmd  reselect1       [  8];
1193         ncrcmd  reselect2       [  8];
1194         ncrcmd  resel_tmp       [  5];
1195         ncrcmd  resel_lun       [ 18];
1196         ncrcmd  resel_tag       [ 24];
1197         ncrcmd  data_in         [MAX_SCATTER * 4 + 7];
1198         ncrcmd  data_out        [MAX_SCATTER * 4 + 7];
1199 };
1200
1201 /*
1202 **      Script fragments which stay in main memory for all chips.
1203 */
1204 struct scripth {
1205         ncrcmd  tryloop         [MAX_START*5+2];
1206         ncrcmd  msg_parity      [  6];
1207         ncrcmd  msg_reject      [  8];
1208         ncrcmd  msg_ign_residue [ 32];
1209         ncrcmd  msg_extended    [ 18];
1210         ncrcmd  msg_ext_2       [ 18];
1211         ncrcmd  msg_wdtr        [ 27];
1212         ncrcmd  msg_ext_3       [ 18];
1213         ncrcmd  msg_sdtr        [ 27];
1214         ncrcmd  msg_out_abort   [ 10];
1215         ncrcmd  getcc           [  4];
1216         ncrcmd  getcc1          [  5];
1217 #ifdef NCR_GETCC_WITHMSG
1218         ncrcmd  getcc2          [ 29];
1219 #else
1220         ncrcmd  getcc2          [ 14];
1221 #endif
1222         ncrcmd  getcc3          [  6];
1223         ncrcmd  aborttag        [  4];
1224         ncrcmd  abort           [ 22];
1225         ncrcmd  snooptest       [  9];
1226         ncrcmd  snoopend        [  2];
1227 };
1228
1229 /*==========================================================
1230 **
1231 **
1232 **      Function headers.
1233 **
1234 **
1235 **==========================================================
1236 */
1237
1238 #ifdef _KERNEL
1239 static  nccb_p  ncr_alloc_nccb(ncb_p np, u_long target, u_long lun);
1240 static  void    ncr_complete(ncb_p np, nccb_p cp);
1241 static  int     ncr_delta(int * from, int * to);
1242 static  void    ncr_exception(ncb_p np);
1243 static  void    ncr_free_nccb(ncb_p np, nccb_p cp);
1244 static  void    ncr_freeze_devq(ncb_p np, struct cam_path *path);
1245 static  void    ncr_selectclock(ncb_p np, u_char scntl3);
1246 static  void    ncr_getclock(ncb_p np, u_char multiplier);
1247 static  nccb_p  ncr_get_nccb(ncb_p np, u_long t,u_long l);
1248 #if 0
1249 static  u_int32_t ncr_info(int unit);
1250 #endif
1251 static  void    ncr_init(ncb_p np, char * msg, u_long code);
1252 static  void    ncr_intr(void *vnp);
1253 static  void    ncr_intr_locked(ncb_p np);
1254 static  void    ncr_int_ma(ncb_p np, u_char dstat);
1255 static  void    ncr_int_sir(ncb_p np);
1256 static  void    ncr_int_sto(ncb_p np);
1257 #if 0
1258 static  void    ncr_min_phys(struct buf *bp);
1259 #endif
1260 static  void    ncr_poll(struct cam_sim *sim);
1261 static  void    ncb_profile(ncb_p np, nccb_p cp);
1262 static  void    ncr_script_copy_and_bind(ncb_p np, ncrcmd *src, ncrcmd *dst,
1263                     int len);
1264 static  void    ncr_script_fill(struct script * scr, struct scripth *scrh);
1265 static  int     ncr_scatter(struct dsb* phys, vm_offset_t vaddr,
1266                     vm_size_t datalen);
1267 static  void    ncr_getsync(ncb_p np, u_char sfac, u_char *fakp,
1268                     u_char *scntl3p);
1269 static  void    ncr_setsync(ncb_p np, nccb_p cp,u_char scntl3,u_char sxfer,
1270                     u_char period);
1271 static  void    ncr_setwide(ncb_p np, nccb_p cp, u_char wide, u_char ack);
1272 static  int     ncr_show_msg(u_char * msg);
1273 static  int     ncr_snooptest(ncb_p np);
1274 static  void    ncr_action(struct cam_sim *sim, union ccb *ccb);
1275 static  void    ncr_timeout(void *arg);
1276 static  void    ncr_wakeup(ncb_p np, u_long code);
1277
1278 static  int     ncr_probe(device_t dev);
1279 static  int     ncr_attach(device_t dev);
1280
1281 #endif /* _KERNEL */
1282
1283 /*==========================================================
1284 **
1285 **
1286 **      Global static data.
1287 **
1288 **
1289 **==========================================================
1290 */
1291
1292 #ifdef _KERNEL
1293
1294 static int ncr_debug = SCSI_NCR_DEBUG;
1295 SYSCTL_INT(_debug, OID_AUTO, ncr_debug, CTLFLAG_RW, &ncr_debug, 0, "");
1296
1297 static int ncr_cache; /* to be aligned _NOT_ static */
1298
1299 /*==========================================================
1300 **
1301 **
1302 **      Global static data:     auto configure
1303 **
1304 **
1305 **==========================================================
1306 */
1307
1308 #define NCR_810_ID      (0x00011000ul)
1309 #define NCR_815_ID      (0x00041000ul)
1310 #define NCR_820_ID      (0x00021000ul)
1311 #define NCR_825_ID      (0x00031000ul)
1312 #define NCR_860_ID      (0x00061000ul)
1313 #define NCR_875_ID      (0x000f1000ul)
1314 #define NCR_875_ID2     (0x008f1000ul)
1315 #define NCR_885_ID      (0x000d1000ul)
1316 #define NCR_895_ID      (0x000c1000ul)
1317 #define NCR_896_ID      (0x000b1000ul)
1318 #define NCR_895A_ID     (0x00121000ul)
1319 #define NCR_1510D_ID    (0x000a1000ul)
1320
1321
1322 /*==========================================================
1323 **
1324 **
1325 **      Scripts for NCR-Processor.
1326 **
1327 **      Use ncr_script_bind for binding to physical addresses.
1328 **
1329 **
1330 **==========================================================
1331 **
1332 **      NADDR generates a reference to a field of the controller data.
1333 **      PADDR generates a reference to another part of the script.
1334 **      RADDR generates a reference to a script processor register.
1335 **      FADDR generates a reference to a script processor register
1336 **              with offset.
1337 **
1338 **----------------------------------------------------------
1339 */
1340
1341 #define RELOC_SOFTC     0x40000000
1342 #define RELOC_LABEL     0x50000000
1343 #define RELOC_REGISTER  0x60000000
1344 #define RELOC_KVAR      0x70000000
1345 #define RELOC_LABELH    0x80000000
1346 #define RELOC_MASK      0xf0000000
1347
1348 #define NADDR(label)    (RELOC_SOFTC | offsetof(struct ncb, label))
1349 #define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1350 #define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
1351 #define RADDR(label)    (RELOC_REGISTER | REG(label))
1352 #define FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1353 #define KVAR(which)     (RELOC_KVAR | (which))
1354
1355 #define KVAR_SECOND                     (0)
1356 #define KVAR_TICKS                      (1)
1357 #define KVAR_NCR_CACHE                  (2)
1358
1359 #define SCRIPT_KVAR_FIRST               (0)
1360 #define SCRIPT_KVAR_LAST                (3)
1361
1362 /*
1363  * Kernel variables referenced in the scripts.
1364  * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
1365  */
1366 static volatile void *script_kvars[] =
1367         { &time_second, &ticks, &ncr_cache };
1368
1369 static  struct script script0 = {
1370 /*--------------------------< START >-----------------------*/ {
1371         /*
1372         **      Claim to be still alive ...
1373         */
1374         SCR_COPY (sizeof (((struct ncb *)0)->heartbeat)),
1375                 KVAR (KVAR_SECOND),
1376                 NADDR (heartbeat),
1377         /*
1378         **      Make data structure address invalid.
1379         **      clear SIGP.
1380         */
1381         SCR_LOAD_REG (dsa, 0xff),
1382                 0,
1383         SCR_FROM_REG (ctest2),
1384                 0,
1385 }/*-------------------------< START0 >----------------------*/,{
1386         /*
1387         **      Hook for interrupted GetConditionCode.
1388         **      Will be patched to ... IFTRUE by
1389         **      the interrupt handler.
1390         */
1391         SCR_INT ^ IFFALSE (0),
1392                 SIR_SENSE_RESTART,
1393
1394 }/*-------------------------< START1 >----------------------*/,{
1395         /*
1396         **      Hook for stalled start queue.
1397         **      Will be patched to IFTRUE by the interrupt handler.
1398         */
1399         SCR_INT ^ IFFALSE (0),
1400                 SIR_STALL_RESTART,
1401         /*
1402         **      Then jump to a certain point in tryloop.
1403         **      Due to the lack of indirect addressing the code
1404         **      is self modifying here.
1405         */
1406         SCR_JUMP,
1407 }/*-------------------------< STARTPOS >--------------------*/,{
1408                 PADDRH(tryloop),
1409
1410 }/*-------------------------< TRYSEL >----------------------*/,{
1411         /*
1412         **      Now:
1413         **      DSA: Address of a Data Structure
1414         **      or   Address of the IDLE-Label.
1415         **
1416         **      TEMP:   Address of a script, which tries to
1417         **              start the NEXT entry.
1418         **
1419         **      Save the TEMP register into the SCRATCHA register.
1420         **      Then copy the DSA to TEMP and RETURN.
1421         **      This is kind of an indirect jump.
1422         **      (The script processor has NO stack, so the
1423         **      CALL is actually a jump and link, and the
1424         **      RETURN is an indirect jump.)
1425         **
1426         **      If the slot was empty, DSA contains the address
1427         **      of the IDLE part of this script. The processor
1428         **      jumps to IDLE and waits for a reselect.
1429         **      It will wake up and try the same slot again
1430         **      after the SIGP bit becomes set by the host.
1431         **
1432         **      If the slot was not empty, DSA contains
1433         **      the address of the phys-part of a nccb.
1434         **      The processor jumps to this address.
1435         **      phys starts with head,
1436         **      head starts with launch,
1437         **      so actually the processor jumps to
1438         **      the lauch part.
1439         **      If the entry is scheduled for execution,
1440         **      then launch contains a jump to SELECT.
1441         **      If it's not scheduled, it contains a jump to IDLE.
1442         */
1443         SCR_COPY (4),
1444                 RADDR (temp),
1445                 RADDR (scratcha),
1446         SCR_COPY (4),
1447                 RADDR (dsa),
1448                 RADDR (temp),
1449         SCR_RETURN,
1450                 0
1451
1452 }/*-------------------------< SKIP >------------------------*/,{
1453         /*
1454         **      This entry has been canceled.
1455         **      Next time use the next slot.
1456         */
1457         SCR_COPY (4),
1458                 RADDR (scratcha),
1459                 PADDR (startpos),
1460         /*
1461         **      patch the launch field.
1462         **      should look like an idle process.
1463         */
1464         SCR_COPY_F (4),
1465                 RADDR (dsa),
1466                 PADDR (skip2),
1467         SCR_COPY (8),
1468                 PADDR (idle),
1469 }/*-------------------------< SKIP2 >-----------------------*/,{
1470                 0,
1471         SCR_JUMP,
1472                 PADDR(start),
1473 }/*-------------------------< IDLE >------------------------*/,{
1474         /*
1475         **      Nothing to do?
1476         **      Wait for reselect.
1477         */
1478         SCR_JUMP,
1479                 PADDR(reselect),
1480
1481 }/*-------------------------< SELECT >----------------------*/,{
1482         /*
1483         **      DSA     contains the address of a scheduled
1484         **              data structure.
1485         **
1486         **      SCRATCHA contains the address of the script,
1487         **              which starts the next entry.
1488         **
1489         **      Set Initiator mode.
1490         **
1491         **      (Target mode is left as an exercise for the reader)
1492         */
1493
1494         SCR_CLR (SCR_TRG),
1495                 0,
1496         SCR_LOAD_REG (HS_REG, 0xff),
1497                 0,
1498
1499         /*
1500         **      And try to select this target.
1501         */
1502         SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1503                 PADDR (reselect),
1504
1505         /*
1506         **      Now there are 4 possibilities:
1507         **
1508         **      (1) The ncr loses arbitration.
1509         **      This is ok, because it will try again,
1510         **      when the bus becomes idle.
1511         **      (But beware of the timeout function!)
1512         **
1513         **      (2) The ncr is reselected.
1514         **      Then the script processor takes the jump
1515         **      to the RESELECT label.
1516         **
1517         **      (3) The ncr completes the selection.
1518         **      Then it will execute the next statement.
1519         **
1520         **      (4) There is a selection timeout.
1521         **      Then the ncr should interrupt the host and stop.
1522         **      Unfortunately, it seems to continue execution
1523         **      of the script. But it will fail with an
1524         **      IID-interrupt on the next WHEN.
1525         */
1526
1527         SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_IN)),
1528                 0,
1529
1530         /*
1531         **      Send the IDENTIFY and SIMPLE_TAG messages
1532         **      (and the MSG_EXT_SDTR message)
1533         */
1534         SCR_MOVE_TBL ^ SCR_MSG_OUT,
1535                 offsetof (struct dsb, smsg),
1536 #ifdef undef /* XXX better fail than try to deal with this ... */
1537         SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1538                 -16,
1539 #endif
1540         SCR_CLR (SCR_ATN),
1541                 0,
1542         SCR_COPY (1),
1543                 RADDR (sfbr),
1544                 NADDR (lastmsg),
1545         /*
1546         **      Selection complete.
1547         **      Next time use the next slot.
1548         */
1549         SCR_COPY (4),
1550                 RADDR (scratcha),
1551                 PADDR (startpos),
1552 }/*-------------------------< PREPARE >----------------------*/,{
1553         /*
1554         **      The ncr doesn't have an indirect load
1555         **      or store command. So we have to
1556         **      copy part of the control block to a
1557         **      fixed place, where we can access it.
1558         **
1559         **      We patch the address part of a
1560         **      COPY command with the DSA-register.
1561         */
1562         SCR_COPY_F (4),
1563                 RADDR (dsa),
1564                 PADDR (loadpos),
1565         /*
1566         **      then we do the actual copy.
1567         */
1568         SCR_COPY (sizeof (struct head)),
1569         /*
1570         **      continued after the next label ...
1571         */
1572
1573 }/*-------------------------< LOADPOS >---------------------*/,{
1574                 0,
1575                 NADDR (header),
1576         /*
1577         **      Mark this nccb as not scheduled.
1578         */
1579         SCR_COPY (8),
1580                 PADDR (idle),
1581                 NADDR (header.launch),
1582         /*
1583         **      Set a time stamp for this selection
1584         */
1585         SCR_COPY (sizeof (ticks)),
1586                 KVAR (KVAR_TICKS),
1587                 NADDR (header.stamp.select),
1588         /*
1589         **      load the savep (saved pointer) into
1590         **      the TEMP register (actual pointer)
1591         */
1592         SCR_COPY (4),
1593                 NADDR (header.savep),
1594                 RADDR (temp),
1595         /*
1596         **      Initialize the status registers
1597         */
1598         SCR_COPY (4),
1599                 NADDR (header.status),
1600                 RADDR (scr0),
1601
1602 }/*-------------------------< PREPARE2 >---------------------*/,{
1603         /*
1604         **      Load the synchronous mode register
1605         */
1606         SCR_COPY (1),
1607                 NADDR (sync_st),
1608                 RADDR (sxfer),
1609         /*
1610         **      Load the wide mode and timing register
1611         */
1612         SCR_COPY (1),
1613                 NADDR (wide_st),
1614                 RADDR (scntl3),
1615         /*
1616         **      Initialize the msgout buffer with a NOOP message.
1617         */
1618         SCR_LOAD_REG (scratcha, MSG_NOOP),
1619                 0,
1620         SCR_COPY (1),
1621                 RADDR (scratcha),
1622                 NADDR (msgout),
1623         SCR_COPY (1),
1624                 RADDR (scratcha),
1625                 NADDR (msgin),
1626         /*
1627         **      Message in phase ?
1628         */
1629         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
1630                 PADDR (dispatch),
1631         /*
1632         **      Extended or reject message ?
1633         */
1634         SCR_FROM_REG (sbdl),
1635                 0,
1636         SCR_JUMP ^ IFTRUE (DATA (MSG_EXTENDED)),
1637                 PADDR (msg_in),
1638         SCR_JUMP ^ IFTRUE (DATA (MSG_MESSAGE_REJECT)),
1639                 PADDRH (msg_reject),
1640         /*
1641         **      normal processing
1642         */
1643         SCR_JUMP,
1644                 PADDR (dispatch),
1645 }/*-------------------------< SETMSG >----------------------*/,{
1646         SCR_COPY (1),
1647                 RADDR (scratcha),
1648                 NADDR (msgout),
1649         SCR_SET (SCR_ATN),
1650                 0,
1651 }/*-------------------------< CLRACK >----------------------*/,{
1652         /*
1653         **      Terminate possible pending message phase.
1654         */
1655         SCR_CLR (SCR_ACK),
1656                 0,
1657
1658 }/*-----------------------< DISPATCH >----------------------*/,{
1659         SCR_FROM_REG (HS_REG),
1660                 0,
1661         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
1662                 SIR_NEGO_FAILED,
1663         /*
1664         **      remove bogus output signals
1665         */
1666         SCR_REG_REG (socl, SCR_AND, CACK|CATN),
1667                 0,
1668         SCR_RETURN ^ IFTRUE (WHEN (SCR_DATA_OUT)),
1669                 0,
1670         SCR_RETURN ^ IFTRUE (IF (SCR_DATA_IN)),
1671                 0,
1672         SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
1673                 PADDR (msg_out),
1674         SCR_JUMP ^ IFTRUE (IF (SCR_MSG_IN)),
1675                 PADDR (msg_in),
1676         SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
1677                 PADDR (command),
1678         SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
1679                 PADDR (status),
1680         /*
1681         **      Discard one illegal phase byte, if required.
1682         */
1683         SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
1684                 0,
1685         SCR_COPY (1),
1686                 RADDR (scratcha),
1687                 NADDR (xerr_st),
1688         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
1689                 8,
1690         SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
1691                 NADDR (scratch),
1692         SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
1693                 8,
1694         SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
1695                 NADDR (scratch),
1696         SCR_JUMP,
1697                 PADDR (dispatch),
1698
1699 }/*-------------------------< NO_DATA >--------------------*/,{
1700         /*
1701         **      The target wants to transfer too much data
1702         **      or in the wrong direction.
1703         **      Remember that in extended error.
1704         */
1705         SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
1706                 0,
1707         SCR_COPY (1),
1708                 RADDR (scratcha),
1709                 NADDR (xerr_st),
1710         /*
1711         **      Discard one data byte, if required.
1712         */
1713         SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
1714                 8,
1715         SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
1716                 NADDR (scratch),
1717         SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1718                 8,
1719         SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
1720                 NADDR (scratch),
1721         /*
1722         **      .. and repeat as required.
1723         */
1724         SCR_CALL,
1725                 PADDR (dispatch),
1726         SCR_JUMP,
1727                 PADDR (no_data),
1728 }/*-------------------------< CHECKATN >--------------------*/,{
1729         /*
1730         **      If AAP (bit 1 of scntl0 register) is set
1731         **      and a parity error is detected,
1732         **      the script processor asserts ATN.
1733         **
1734         **      The target should switch to a MSG_OUT phase
1735         **      to get the message.
1736         */
1737         SCR_FROM_REG (socl),
1738                 0,
1739         SCR_JUMP ^ IFFALSE (MASK (CATN, CATN)),
1740                 PADDR (dispatch),
1741         /*
1742         **      count it
1743         */
1744         SCR_REG_REG (PS_REG, SCR_ADD, 1),
1745                 0,
1746         /*
1747         **      Prepare a MSG_INITIATOR_DET_ERR message
1748         **      (initiator detected error).
1749         **      The target should retry the transfer.
1750         */
1751         SCR_LOAD_REG (scratcha, MSG_INITIATOR_DET_ERR),
1752                 0,
1753         SCR_JUMP,
1754                 PADDR (setmsg),
1755
1756 }/*-------------------------< COMMAND >--------------------*/,{
1757         /*
1758         **      If this is not a GETCC transfer ...
1759         */
1760         SCR_FROM_REG (SS_REG),
1761                 0,
1762 /*<<<*/ SCR_JUMPR ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
1763                 28,
1764         /*
1765         **      ... set a timestamp ...
1766         */
1767         SCR_COPY (sizeof (ticks)),
1768                 KVAR (KVAR_TICKS),
1769                 NADDR (header.stamp.command),
1770         /*
1771         **      ... and send the command
1772         */
1773         SCR_MOVE_TBL ^ SCR_COMMAND,
1774                 offsetof (struct dsb, cmd),
1775         SCR_JUMP,
1776                 PADDR (dispatch),
1777         /*
1778         **      Send the GETCC command
1779         */
1780 /*>>>*/ SCR_MOVE_TBL ^ SCR_COMMAND,
1781                 offsetof (struct dsb, scmd),
1782         SCR_JUMP,
1783                 PADDR (dispatch),
1784
1785 }/*-------------------------< STATUS >--------------------*/,{
1786         /*
1787         **      set the timestamp.
1788         */
1789         SCR_COPY (sizeof (ticks)),
1790                 KVAR (KVAR_TICKS),
1791                 NADDR (header.stamp.status),
1792         /*
1793         **      If this is a GETCC transfer,
1794         */
1795         SCR_FROM_REG (SS_REG),
1796                 0,
1797 /*<<<*/ SCR_JUMPR ^ IFFALSE (DATA (SCSI_STATUS_CHECK_COND)),
1798                 40,
1799         /*
1800         **      get the status
1801         */
1802         SCR_MOVE_ABS (1) ^ SCR_STATUS,
1803                 NADDR (scratch),
1804         /*
1805         **      Save status to scsi_status.
1806         **      Mark as complete.
1807         **      And wait for disconnect.
1808         */
1809         SCR_TO_REG (SS_REG),
1810                 0,
1811         SCR_REG_REG (SS_REG, SCR_OR, SCSI_STATUS_SENSE),
1812                 0,
1813         SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1814                 0,
1815         SCR_JUMP,
1816                 PADDR (checkatn),
1817         /*
1818         **      If it was no GETCC transfer,
1819         **      save the status to scsi_status.
1820         */
1821 /*>>>*/ SCR_MOVE_ABS (1) ^ SCR_STATUS,
1822                 NADDR (scratch),
1823         SCR_TO_REG (SS_REG),
1824                 0,
1825         /*
1826         **      if it was no check condition ...
1827         */
1828         SCR_JUMP ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
1829                 PADDR (checkatn),
1830         /*
1831         **      ... mark as complete.
1832         */
1833         SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1834                 0,
1835         SCR_JUMP,
1836                 PADDR (checkatn),
1837
1838 }/*-------------------------< MSG_IN >--------------------*/,{
1839         /*
1840         **      Get the first byte of the message
1841         **      and save it to SCRATCHA.
1842         **
1843         **      The script processor doesn't negate the
1844         **      ACK signal after this transfer.
1845         */
1846         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
1847                 NADDR (msgin[0]),
1848         /*
1849         **      Check for message parity error.
1850         */
1851         SCR_TO_REG (scratcha),
1852                 0,
1853         SCR_FROM_REG (socl),
1854                 0,
1855         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
1856                 PADDRH (msg_parity),
1857         SCR_FROM_REG (scratcha),
1858                 0,
1859         /*
1860         **      Parity was ok, handle this message.
1861         */
1862         SCR_JUMP ^ IFTRUE (DATA (MSG_CMDCOMPLETE)),
1863                 PADDR (complete),
1864         SCR_JUMP ^ IFTRUE (DATA (MSG_SAVEDATAPOINTER)),
1865                 PADDR (save_dp),
1866         SCR_JUMP ^ IFTRUE (DATA (MSG_RESTOREPOINTERS)),
1867                 PADDR (restore_dp),
1868         SCR_JUMP ^ IFTRUE (DATA (MSG_DISCONNECT)),
1869                 PADDR (disconnect),
1870         SCR_JUMP ^ IFTRUE (DATA (MSG_EXTENDED)),
1871                 PADDRH (msg_extended),
1872         SCR_JUMP ^ IFTRUE (DATA (MSG_NOOP)),
1873                 PADDR (clrack),
1874         SCR_JUMP ^ IFTRUE (DATA (MSG_MESSAGE_REJECT)),
1875                 PADDRH (msg_reject),
1876         SCR_JUMP ^ IFTRUE (DATA (MSG_IGN_WIDE_RESIDUE)),
1877                 PADDRH (msg_ign_residue),
1878         /*
1879         **      Rest of the messages left as
1880         **      an exercise ...
1881         **
1882         **      Unimplemented messages:
1883         **      fall through to MSG_BAD.
1884         */
1885 }/*-------------------------< MSG_BAD >------------------*/,{
1886         /*
1887         **      unimplemented message - reject it.
1888         */
1889         SCR_INT,
1890                 SIR_REJECT_SENT,
1891         SCR_LOAD_REG (scratcha, MSG_MESSAGE_REJECT),
1892                 0,
1893         SCR_JUMP,
1894                 PADDR (setmsg),
1895
1896 }/*-------------------------< COMPLETE >-----------------*/,{
1897         /*
1898         **      Complete message.
1899         **
1900         **      If it's not the get condition code,
1901         **      copy TEMP register to LASTP in header.
1902         */
1903         SCR_FROM_REG (SS_REG),
1904                 0,
1905 /*<<<*/ SCR_JUMPR ^ IFTRUE (MASK (SCSI_STATUS_SENSE, SCSI_STATUS_SENSE)),
1906                 12,
1907         SCR_COPY (4),
1908                 RADDR (temp),
1909                 NADDR (header.lastp),
1910 /*>>>*/ /*
1911         **      When we terminate the cycle by clearing ACK,
1912         **      the target may disconnect immediately.
1913         **
1914         **      We don't want to be told of an
1915         **      "unexpected disconnect",
1916         **      so we disable this feature.
1917         */
1918         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
1919                 0,
1920         /*
1921         **      Terminate cycle ...
1922         */
1923         SCR_CLR (SCR_ACK|SCR_ATN),
1924                 0,
1925         /*
1926         **      ... and wait for the disconnect.
1927         */
1928         SCR_WAIT_DISC,
1929                 0,
1930 }/*-------------------------< CLEANUP >-------------------*/,{
1931         /*
1932         **      dsa:    Pointer to nccb
1933         **            or xxxxxxFF (no nccb)
1934         **
1935         **      HS_REG:   Host-Status (<>0!)
1936         */
1937         SCR_FROM_REG (dsa),
1938                 0,
1939         SCR_JUMP ^ IFTRUE (DATA (0xff)),
1940                 PADDR (signal),
1941         /*
1942         **      dsa is valid.
1943         **      save the status registers
1944         */
1945         SCR_COPY (4),
1946                 RADDR (scr0),
1947                 NADDR (header.status),
1948         /*
1949         **      and copy back the header to the nccb.
1950         */
1951         SCR_COPY_F (4),
1952                 RADDR (dsa),
1953                 PADDR (cleanup0),
1954         SCR_COPY (sizeof (struct head)),
1955                 NADDR (header),
1956 }/*-------------------------< CLEANUP0 >--------------------*/,{
1957                 0,
1958
1959         /*
1960         **      If command resulted in "check condition"
1961         **      status and is not yet completed,
1962         **      try to get the condition code.
1963         */
1964         SCR_FROM_REG (HS_REG),
1965                 0,
1966 /*<<<*/ SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
1967                 16,
1968         SCR_FROM_REG (SS_REG),
1969                 0,
1970         SCR_JUMP ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
1971                 PADDRH(getcc2),
1972 }/*-------------------------< SIGNAL >----------------------*/,{
1973         /*
1974         **      if status = queue full,
1975         **      reinsert in startqueue and stall queue.
1976         */
1977 /*>>>*/ SCR_FROM_REG (SS_REG),
1978                 0,
1979         SCR_INT ^ IFTRUE (DATA (SCSI_STATUS_QUEUE_FULL)),
1980                 SIR_STALL_QUEUE,
1981         /*
1982         **      And make the DSA register invalid.
1983         */
1984         SCR_LOAD_REG (dsa, 0xff), /* invalid */
1985                 0,
1986         /*
1987         **      if job completed ...
1988         */
1989         SCR_FROM_REG (HS_REG),
1990                 0,
1991         /*
1992         **      ... signal completion to the host
1993         */
1994         SCR_INT_FLY ^ IFFALSE (MASK (0, HS_DONEMASK)),
1995                 0,
1996         /*
1997         **      Auf zu neuen Schandtaten!
1998         */
1999         SCR_JUMP,
2000                 PADDR(start),
2001
2002 }/*-------------------------< SAVE_DP >------------------*/,{
2003         /*
2004         **      SAVE_DP message:
2005         **      Copy TEMP register to SAVEP in header.
2006         */
2007         SCR_COPY (4),
2008                 RADDR (temp),
2009                 NADDR (header.savep),
2010         SCR_JUMP,
2011                 PADDR (clrack),
2012 }/*-------------------------< RESTORE_DP >---------------*/,{
2013         /*
2014         **      RESTORE_DP message:
2015         **      Copy SAVEP in header to TEMP register.
2016         */
2017         SCR_COPY (4),
2018                 NADDR (header.savep),
2019                 RADDR (temp),
2020         SCR_JUMP,
2021                 PADDR (clrack),
2022
2023 }/*-------------------------< DISCONNECT >---------------*/,{
2024         /*
2025         **      If QUIRK_AUTOSAVE is set,
2026         **      do a "save pointer" operation.
2027         */
2028         SCR_FROM_REG (QU_REG),
2029                 0,
2030 /*<<<*/ SCR_JUMPR ^ IFFALSE (MASK (QUIRK_AUTOSAVE, QUIRK_AUTOSAVE)),
2031                 12,
2032         /*
2033         **      like SAVE_DP message:
2034         **      Copy TEMP register to SAVEP in header.
2035         */
2036         SCR_COPY (4),
2037                 RADDR (temp),
2038                 NADDR (header.savep),
2039 /*>>>*/ /*
2040         **      Check if temp==savep or temp==goalp:
2041         **      if not, log a missing save pointer message.
2042         **      In fact, it's a comparison mod 256.
2043         **
2044         **      Hmmm, I hadn't thought that I would be urged to
2045         **      write this kind of ugly self modifying code.
2046         **
2047         **      It's unbelievable, but the ncr53c8xx isn't able
2048         **      to subtract one register from another.
2049         */
2050         SCR_FROM_REG (temp),
2051                 0,
2052         /*
2053         **      You are not expected to understand this ..
2054         **
2055         **      CAUTION: only little endian architectures supported! XXX
2056         */
2057         SCR_COPY_F (1),
2058                 NADDR (header.savep),
2059                 PADDR (disconnect0),
2060 }/*-------------------------< DISCONNECT0 >--------------*/,{
2061 /*<<<*/ SCR_JUMPR ^ IFTRUE (DATA (1)),
2062                 20,
2063         /*
2064         **      neither this
2065         */
2066         SCR_COPY_F (1),
2067                 NADDR (header.goalp),
2068                 PADDR (disconnect1),
2069 }/*-------------------------< DISCONNECT1 >--------------*/,{
2070         SCR_INT ^ IFFALSE (DATA (1)),
2071                 SIR_MISSING_SAVE,
2072 /*>>>*/
2073
2074         /*
2075         **      DISCONNECTing  ...
2076         **
2077         **      disable the "unexpected disconnect" feature,
2078         **      and remove the ACK signal.
2079         */
2080         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2081                 0,
2082         SCR_CLR (SCR_ACK|SCR_ATN),
2083                 0,
2084         /*
2085         **      Wait for the disconnect.
2086         */
2087         SCR_WAIT_DISC,
2088                 0,
2089         /*
2090         **      Profiling:
2091         **      Set a time stamp,
2092         **      and count the disconnects.
2093         */
2094         SCR_COPY (sizeof (ticks)),
2095                 KVAR (KVAR_TICKS),
2096                 NADDR (header.stamp.disconnect),
2097         SCR_COPY (4),
2098                 NADDR (disc_phys),
2099                 RADDR (temp),
2100         SCR_REG_REG (temp, SCR_ADD, 0x01),
2101                 0,
2102         SCR_COPY (4),
2103                 RADDR (temp),
2104                 NADDR (disc_phys),
2105         /*
2106         **      Status is: DISCONNECTED.
2107         */
2108         SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2109                 0,
2110         SCR_JUMP,
2111                 PADDR (cleanup),
2112
2113 }/*-------------------------< MSG_OUT >-------------------*/,{
2114         /*
2115         **      The target requests a message.
2116         */
2117         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2118                 NADDR (msgout),
2119         SCR_COPY (1),
2120                 RADDR (sfbr),
2121                 NADDR (lastmsg),
2122         /*
2123         **      If it was no ABORT message ...
2124         */
2125         SCR_JUMP ^ IFTRUE (DATA (MSG_ABORT)),
2126                 PADDRH (msg_out_abort),
2127         /*
2128         **      ... wait for the next phase
2129         **      if it's a message out, send it again, ...
2130         */
2131         SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2132                 PADDR (msg_out),
2133 }/*-------------------------< MSG_OUT_DONE >--------------*/,{
2134         /*
2135         **      ... else clear the message ...
2136         */
2137         SCR_LOAD_REG (scratcha, MSG_NOOP),
2138                 0,
2139         SCR_COPY (4),
2140                 RADDR (scratcha),
2141                 NADDR (msgout),
2142         /*
2143         **      ... and process the next phase
2144         */
2145         SCR_JUMP,
2146                 PADDR (dispatch),
2147
2148 }/*------------------------< BADGETCC >---------------------*/,{
2149         /*
2150         **      If SIGP was set, clear it and try again.
2151         */
2152         SCR_FROM_REG (ctest2),
2153                 0,
2154         SCR_JUMP ^ IFTRUE (MASK (CSIGP,CSIGP)),
2155                 PADDRH (getcc2),
2156         SCR_INT,
2157                 SIR_SENSE_FAILED,
2158 }/*-------------------------< RESELECT >--------------------*/,{
2159         /*
2160         **      This NOP will be patched with LED OFF
2161         **      SCR_REG_REG (gpreg, SCR_OR, 0x01)
2162         */
2163         SCR_NO_OP,
2164                 0,
2165
2166         /*
2167         **      make the DSA invalid.
2168         */
2169         SCR_LOAD_REG (dsa, 0xff),
2170                 0,
2171         SCR_CLR (SCR_TRG),
2172                 0,
2173         /*
2174         **      Sleep waiting for a reselection.
2175         **      If SIGP is set, special treatment.
2176         **
2177         **      Zu allem bereit ..
2178         */
2179         SCR_WAIT_RESEL,
2180                 PADDR(reselect2),
2181 }/*-------------------------< RESELECT1 >--------------------*/,{
2182         /*
2183         **      This NOP will be patched with LED ON
2184         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2185         */
2186         SCR_NO_OP,
2187                 0,
2188         /*
2189         **      ... zu nichts zu gebrauchen ?
2190         **
2191         **      load the target id into the SFBR
2192         **      and jump to the control block.
2193         **
2194         **      Look at the declarations of
2195         **      - struct ncb
2196         **      - struct tcb
2197         **      - struct lcb
2198         **      - struct nccb
2199         **      to understand what's going on.
2200         */
2201         SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2202                 0,
2203         SCR_TO_REG (sdid),
2204                 0,
2205         SCR_JUMP,
2206                 NADDR (jump_tcb),
2207 }/*-------------------------< RESELECT2 >-------------------*/,{
2208         /*
2209         **      This NOP will be patched with LED ON
2210         **      SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2211         */
2212         SCR_NO_OP,
2213                 0,
2214         /*
2215         **      If it's not connected :(
2216         **      -> interrupted by SIGP bit.
2217         **      Jump to start.
2218         */
2219         SCR_FROM_REG (ctest2),
2220                 0,
2221         SCR_JUMP ^ IFTRUE (MASK (CSIGP,CSIGP)),
2222                 PADDR (start),
2223         SCR_JUMP,
2224                 PADDR (reselect),
2225
2226 }/*-------------------------< RESEL_TMP >-------------------*/,{
2227         /*
2228         **      The return address in TEMP
2229         **      is in fact the data structure address,
2230         **      so copy it to the DSA register.
2231         */
2232         SCR_COPY (4),
2233                 RADDR (temp),
2234                 RADDR (dsa),
2235         SCR_JUMP,
2236                 PADDR (prepare),
2237
2238 }/*-------------------------< RESEL_LUN >-------------------*/,{
2239         /*
2240         **      come back to this point
2241         **      to get an IDENTIFY message
2242         **      Wait for a msg_in phase.
2243         */
2244 /*<<<*/ SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2245                 48,
2246         /*
2247         **      message phase
2248         **      It's not a sony, it's a trick:
2249         **      read the data without acknowledging it.
2250         */
2251         SCR_FROM_REG (sbdl),
2252                 0,
2253 /*<<<*/ SCR_JUMPR ^ IFFALSE (MASK (MSG_IDENTIFYFLAG, 0x98)),
2254                 32,
2255         /*
2256         **      It WAS an Identify message.
2257         **      get it and ack it!
2258         */
2259         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2260                 NADDR (msgin),
2261         SCR_CLR (SCR_ACK),
2262                 0,
2263         /*
2264         **      Mask out the lun.
2265         */
2266         SCR_REG_REG (sfbr, SCR_AND, 0x07),
2267                 0,
2268         SCR_RETURN,
2269                 0,
2270         /*
2271         **      No message phase or no IDENTIFY message:
2272         **      return 0.
2273         */
2274 /*>>>*/ SCR_LOAD_SFBR (0),
2275                 0,
2276         SCR_RETURN,
2277                 0,
2278
2279 }/*-------------------------< RESEL_TAG >-------------------*/,{
2280         /*
2281         **      come back to this point
2282         **      to get a SIMPLE_TAG message
2283         **      Wait for a MSG_IN phase.
2284         */
2285 /*<<<*/ SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2286                 64,
2287         /*
2288         **      message phase
2289         **      It's a trick - read the data
2290         **      without acknowledging it.
2291         */
2292         SCR_FROM_REG (sbdl),
2293                 0,
2294 /*<<<*/ SCR_JUMPR ^ IFFALSE (DATA (MSG_SIMPLE_Q_TAG)),
2295                 48,
2296         /*
2297         **      It WAS a SIMPLE_TAG message.
2298         **      get it and ack it!
2299         */
2300         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2301                 NADDR (msgin),
2302         SCR_CLR (SCR_ACK),
2303                 0,
2304         /*
2305         **      Wait for the second byte (the tag)
2306         */
2307 /*<<<*/ SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2308                 24,
2309         /*
2310         **      Get it and ack it!
2311         */
2312         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2313                 NADDR (msgin),
2314         SCR_CLR (SCR_ACK|SCR_CARRY),
2315                 0,
2316         SCR_RETURN,
2317                 0,
2318         /*
2319         **      No message phase or no SIMPLE_TAG message
2320         **      or no second byte: return 0.
2321         */
2322 /*>>>*/ SCR_LOAD_SFBR (0),
2323                 0,
2324         SCR_SET (SCR_CARRY),
2325                 0,
2326         SCR_RETURN,
2327                 0,
2328
2329 }/*-------------------------< DATA_IN >--------------------*/,{
2330 /*
2331 **      Because the size depends on the
2332 **      #define MAX_SCATTER parameter,
2333 **      it is filled in at runtime.
2334 **
2335 **      SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2336 **              PADDR (no_data),
2337 **      SCR_COPY (sizeof (ticks)),
2338 **              KVAR (KVAR_TICKS),
2339 **              NADDR (header.stamp.data),
2340 **      SCR_MOVE_TBL ^ SCR_DATA_IN,
2341 **              offsetof (struct dsb, data[ 0]),
2342 **
2343 **  ##===========< i=1; i<MAX_SCATTER >=========
2344 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2345 **  ||          PADDR (checkatn),
2346 **  ||  SCR_MOVE_TBL ^ SCR_DATA_IN,
2347 **  ||          offsetof (struct dsb, data[ i]),
2348 **  ##==========================================
2349 **
2350 **      SCR_CALL,
2351 **              PADDR (checkatn),
2352 **      SCR_JUMP,
2353 **              PADDR (no_data),
2354 */
2355 0
2356 }/*-------------------------< DATA_OUT >-------------------*/,{
2357 /*
2358 **      Because the size depends on the
2359 **      #define MAX_SCATTER parameter,
2360 **      it is filled in at runtime.
2361 **
2362 **      SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2363 **              PADDR (no_data),
2364 **      SCR_COPY (sizeof (ticks)),
2365 **              KVAR (KVAR_TICKS),
2366 **              NADDR (header.stamp.data),
2367 **      SCR_MOVE_TBL ^ SCR_DATA_OUT,
2368 **              offsetof (struct dsb, data[ 0]),
2369 **
2370 **  ##===========< i=1; i<MAX_SCATTER >=========
2371 **  ||  SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2372 **  ||          PADDR (dispatch),
2373 **  ||  SCR_MOVE_TBL ^ SCR_DATA_OUT,
2374 **  ||          offsetof (struct dsb, data[ i]),
2375 **  ##==========================================
2376 **
2377 **      SCR_CALL,
2378 **              PADDR (dispatch),
2379 **      SCR_JUMP,
2380 **              PADDR (no_data),
2381 **
2382 **---------------------------------------------------------
2383 */
2384 (u_long)0
2385
2386 }/*--------------------------------------------------------*/
2387 };
2388
2389
2390 static  struct scripth scripth0 = {
2391 /*-------------------------< TRYLOOP >---------------------*/{
2392 /*
2393 **      Load an entry of the start queue into dsa
2394 **      and try to start it by jumping to TRYSEL.
2395 **
2396 **      Because the size depends on the
2397 **      #define MAX_START parameter, it is filled
2398 **      in at runtime.
2399 **
2400 **-----------------------------------------------------------
2401 **
2402 **  ##===========< I=0; i<MAX_START >===========
2403 **  ||  SCR_COPY (4),
2404 **  ||          NADDR (squeue[i]),
2405 **  ||          RADDR (dsa),
2406 **  ||  SCR_CALL,
2407 **  ||          PADDR (trysel),
2408 **  ##==========================================
2409 **
2410 **      SCR_JUMP,
2411 **              PADDRH(tryloop),
2412 **
2413 **-----------------------------------------------------------
2414 */
2415 0
2416 }/*-------------------------< MSG_PARITY >---------------*/,{
2417         /*
2418         **      count it
2419         */
2420         SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2421                 0,
2422         /*
2423         **      send a "message parity error" message.
2424         */
2425         SCR_LOAD_REG (scratcha, MSG_PARITY_ERROR),
2426                 0,
2427         SCR_JUMP,
2428                 PADDR (setmsg),
2429 }/*-------------------------< MSG_MESSAGE_REJECT >---------------*/,{
2430         /*
2431         **      If a negotiation was in progress,
2432         **      negotiation failed.
2433         */
2434         SCR_FROM_REG (HS_REG),
2435                 0,
2436         SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2437                 SIR_NEGO_FAILED,
2438         /*
2439         **      else make host log this message
2440         */
2441         SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2442                 SIR_REJECT_RECEIVED,
2443         SCR_JUMP,
2444                 PADDR (clrack),
2445
2446 }/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2447         /*
2448         **      Terminate cycle
2449         */
2450         SCR_CLR (SCR_ACK),
2451                 0,
2452         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2453                 PADDR (dispatch),
2454         /*
2455         **      get residue size.
2456         */
2457         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2458                 NADDR (msgin[1]),
2459         /*
2460         **      Check for message parity error.
2461         */
2462         SCR_TO_REG (scratcha),
2463                 0,
2464         SCR_FROM_REG (socl),
2465                 0,
2466         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2467                 PADDRH (msg_parity),
2468         SCR_FROM_REG (scratcha),
2469                 0,
2470         /*
2471         **      Size is 0 .. ignore message.
2472         */
2473         SCR_JUMP ^ IFTRUE (DATA (0)),
2474                 PADDR (clrack),
2475         /*
2476         **      Size is not 1 .. have to interrupt.
2477         */
2478 /*<<<*/ SCR_JUMPR ^ IFFALSE (DATA (1)),
2479                 40,
2480         /*
2481         **      Check for residue byte in swide register
2482         */
2483         SCR_FROM_REG (scntl2),
2484                 0,
2485 /*<<<*/ SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2486                 16,
2487         /*
2488         **      There IS data in the swide register.
2489         **      Discard it.
2490         */
2491         SCR_REG_REG (scntl2, SCR_OR, WSR),
2492                 0,
2493         SCR_JUMP,
2494                 PADDR (clrack),
2495         /*
2496         **      Load again the size to the sfbr register.
2497         */
2498 /*>>>*/ SCR_FROM_REG (scratcha),
2499                 0,
2500 /*>>>*/ SCR_INT,
2501                 SIR_IGN_RESIDUE,
2502         SCR_JUMP,
2503                 PADDR (clrack),
2504
2505 }/*-------------------------< MSG_EXTENDED >-------------*/,{
2506         /*
2507         **      Terminate cycle
2508         */
2509         SCR_CLR (SCR_ACK),
2510                 0,
2511         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2512                 PADDR (dispatch),
2513         /*
2514         **      get length.
2515         */
2516         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2517                 NADDR (msgin[1]),
2518         /*
2519         **      Check for message parity error.
2520         */
2521         SCR_TO_REG (scratcha),
2522                 0,
2523         SCR_FROM_REG (socl),
2524                 0,
2525         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2526                 PADDRH (msg_parity),
2527         SCR_FROM_REG (scratcha),
2528                 0,
2529         /*
2530         */
2531         SCR_JUMP ^ IFTRUE (DATA (3)),
2532                 PADDRH (msg_ext_3),
2533         SCR_JUMP ^ IFFALSE (DATA (2)),
2534                 PADDR (msg_bad),
2535 }/*-------------------------< MSG_EXT_2 >----------------*/,{
2536         SCR_CLR (SCR_ACK),
2537                 0,
2538         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2539                 PADDR (dispatch),
2540         /*
2541         **      get extended message code.
2542         */
2543         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2544                 NADDR (msgin[2]),
2545         /*
2546         **      Check for message parity error.
2547         */
2548         SCR_TO_REG (scratcha),
2549                 0,
2550         SCR_FROM_REG (socl),
2551                 0,
2552         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2553                 PADDRH (msg_parity),
2554         SCR_FROM_REG (scratcha),
2555                 0,
2556         SCR_JUMP ^ IFTRUE (DATA (MSG_EXT_WDTR)),
2557                 PADDRH (msg_wdtr),
2558         /*
2559         **      unknown extended message
2560         */
2561         SCR_JUMP,
2562                 PADDR (msg_bad)
2563 }/*-------------------------< MSG_WDTR >-----------------*/,{
2564         SCR_CLR (SCR_ACK),
2565                 0,
2566         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2567                 PADDR (dispatch),
2568         /*
2569         **      get data bus width
2570         */
2571         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2572                 NADDR (msgin[3]),
2573         SCR_FROM_REG (socl),
2574                 0,
2575         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2576                 PADDRH (msg_parity),
2577         /*
2578         **      let the host do the real work.
2579         */
2580         SCR_INT,
2581                 SIR_NEGO_WIDE,
2582         /*
2583         **      let the target fetch our answer.
2584         */
2585         SCR_SET (SCR_ATN),
2586                 0,
2587         SCR_CLR (SCR_ACK),
2588                 0,
2589
2590         SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2591                 SIR_NEGO_PROTO,
2592         /*
2593         **      Send the MSG_EXT_WDTR
2594         */
2595         SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
2596                 NADDR (msgout),
2597         SCR_CLR (SCR_ATN),
2598                 0,
2599         SCR_COPY (1),
2600                 RADDR (sfbr),
2601                 NADDR (lastmsg),
2602         SCR_JUMP,
2603                 PADDR (msg_out_done),
2604
2605 }/*-------------------------< MSG_EXT_3 >----------------*/,{
2606         SCR_CLR (SCR_ACK),
2607                 0,
2608         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2609                 PADDR (dispatch),
2610         /*
2611         **      get extended message code.
2612         */
2613         SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2614                 NADDR (msgin[2]),
2615         /*
2616         **      Check for message parity error.
2617         */
2618         SCR_TO_REG (scratcha),
2619                 0,
2620         SCR_FROM_REG (socl),
2621                 0,
2622         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2623                 PADDRH (msg_parity),
2624         SCR_FROM_REG (scratcha),
2625                 0,
2626         SCR_JUMP ^ IFTRUE (DATA (MSG_EXT_SDTR)),
2627                 PADDRH (msg_sdtr),
2628         /*
2629         **      unknown extended message
2630         */
2631         SCR_JUMP,
2632                 PADDR (msg_bad)
2633
2634 }/*-------------------------< MSG_SDTR >-----------------*/,{
2635         SCR_CLR (SCR_ACK),
2636                 0,
2637         SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2638                 PADDR (dispatch),
2639         /*
2640         **      get period and offset
2641         */
2642         SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2643                 NADDR (msgin[3]),
2644         SCR_FROM_REG (socl),
2645                 0,
2646         SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2647                 PADDRH (msg_parity),
2648         /*
2649         **      let the host do the real work.
2650         */
2651         SCR_INT,
2652                 SIR_NEGO_SYNC,
2653         /*
2654         **      let the target fetch our answer.
2655         */
2656         SCR_SET (SCR_ATN),
2657                 0,
2658         SCR_CLR (SCR_ACK),
2659                 0,
2660
2661         SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2662                 SIR_NEGO_PROTO,
2663         /*
2664         **      Send the MSG_EXT_SDTR
2665         */
2666         SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
2667                 NADDR (msgout),
2668         SCR_CLR (SCR_ATN),
2669                 0,
2670         SCR_COPY (1),
2671                 RADDR (sfbr),
2672                 NADDR (lastmsg),
2673         SCR_JUMP,
2674                 PADDR (msg_out_done),
2675
2676 }/*-------------------------< MSG_OUT_ABORT >-------------*/,{
2677         /*
2678         **      After ABORT message,
2679         **
2680         **      expect an immediate disconnect, ...
2681         */
2682         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2683                 0,
2684         SCR_CLR (SCR_ACK|SCR_ATN),
2685                 0,
2686         SCR_WAIT_DISC,
2687                 0,
2688         /*
2689         **      ... and set the status to "ABORTED"
2690         */
2691         SCR_LOAD_REG (HS_REG, HS_ABORTED),
2692                 0,
2693         SCR_JUMP,
2694                 PADDR (cleanup),
2695
2696 }/*-------------------------< GETCC >-----------------------*/,{
2697         /*
2698         **      The ncr doesn't have an indirect load
2699         **      or store command. So we have to
2700         **      copy part of the control block to a
2701         **      fixed place, where we can modify it.
2702         **
2703         **      We patch the address part of a COPY command
2704         **      with the address of the dsa register ...
2705         */
2706         SCR_COPY_F (4),
2707                 RADDR (dsa),
2708                 PADDRH (getcc1),
2709         /*
2710         **      ... then we do the actual copy.
2711         */
2712         SCR_COPY (sizeof (struct head)),
2713 }/*-------------------------< GETCC1 >----------------------*/,{
2714                 0,
2715                 NADDR (header),
2716         /*
2717         **      Initialize the status registers
2718         */
2719         SCR_COPY (4),
2720                 NADDR (header.status),
2721                 RADDR (scr0),
2722 }/*-------------------------< GETCC2 >----------------------*/,{
2723         /*
2724         **      Get the condition code from a target.
2725         **
2726         **      DSA points to a data structure.
2727         **      Set TEMP to the script location
2728         **      that receives the condition code.
2729         **
2730         **      Because there is no script command
2731         **      to load a longword into a register,
2732         **      we use a CALL command.
2733         */
2734 /*<<<*/ SCR_CALLR,
2735                 24,
2736         /*
2737         **      Get the condition code.
2738         */
2739         SCR_MOVE_TBL ^ SCR_DATA_IN,
2740                 offsetof (struct dsb, sense),
2741         /*
2742         **      No data phase may follow!
2743         */
2744         SCR_CALL,
2745                 PADDR (checkatn),
2746         SCR_JUMP,
2747                 PADDR (no_data),
2748 /*>>>*/
2749
2750         /*
2751         **      The CALL jumps to this point.
2752         **      Prepare for a RESTORE_POINTER message.
2753         **      Save the TEMP register into the saved pointer.
2754         */
2755         SCR_COPY (4),
2756                 RADDR (temp),
2757                 NADDR (header.savep),
2758         /*
2759         **      Load scratcha, because in case of a selection timeout,
2760         **      the host will expect a new value for startpos in
2761         **      the scratcha register.
2762         */
2763         SCR_COPY (4),
2764                 PADDR (startpos),
2765                 RADDR (scratcha),
2766 #ifdef NCR_GETCC_WITHMSG
2767         /*
2768         **      If QUIRK_NOMSG is set, select without ATN.
2769         **      and don't send a message.
2770         */
2771         SCR_FROM_REG (QU_REG),
2772                 0,
2773         SCR_JUMP ^ IFTRUE (MASK (QUIRK_NOMSG, QUIRK_NOMSG)),
2774                 PADDRH(getcc3),
2775         /*
2776         **      Then try to connect to the target.
2777         **      If we are reselected, special treatment
2778         **      of the current job is required before
2779         **      accepting the reselection.
2780         */
2781         SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2782                 PADDR(badgetcc),
2783         /*
2784         **      Send the IDENTIFY message.
2785         **      In case of short transfer, remove ATN.
2786         */
2787         SCR_MOVE_TBL ^ SCR_MSG_OUT,
2788                 offsetof (struct dsb, smsg2),
2789         SCR_CLR (SCR_ATN),
2790                 0,
2791         /*
2792         **      save the first byte of the message.
2793         */
2794         SCR_COPY (1),
2795                 RADDR (sfbr),
2796                 NADDR (lastmsg),
2797         SCR_JUMP,
2798                 PADDR (prepare2),
2799
2800 #endif
2801 }/*-------------------------< GETCC3 >----------------------*/,{
2802         /*
2803         **      Try to connect to the target.
2804         **      If we are reselected, special treatment
2805         **      of the current job is required before
2806         **      accepting the reselection.
2807         **
2808         **      Silly target won't accept a message.
2809         **      Select without ATN.
2810         */
2811         SCR_SEL_TBL ^ offsetof (struct dsb, select),
2812                 PADDR(badgetcc),
2813         /*
2814         **      Force error if selection timeout
2815         */
2816         SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_IN)),
2817                 0,
2818         /*
2819         **      don't negotiate.
2820         */
2821         SCR_JUMP,
2822                 PADDR (prepare2),
2823 }/*-------------------------< ABORTTAG >-------------------*/,{
2824         /*
2825         **      Abort a bad reselection.
2826         **      Set the message to ABORT vs. ABORT_TAG
2827         */
2828         SCR_LOAD_REG (scratcha, MSG_ABORT_TAG),
2829                 0,
2830         SCR_JUMPR ^ IFFALSE (CARRYSET),
2831                 8,
2832 }/*-------------------------< ABORT >----------------------*/,{
2833         SCR_LOAD_REG (scratcha, MSG_ABORT),
2834                 0,
2835         SCR_COPY (1),
2836                 RADDR (scratcha),
2837                 NADDR (msgout),
2838         SCR_SET (SCR_ATN),
2839                 0,
2840         SCR_CLR (SCR_ACK),
2841                 0,
2842         /*
2843         **      and send it.
2844         **      we expect an immediate disconnect
2845         */
2846         SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2847                 0,
2848         SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2849                 NADDR (msgout),
2850         SCR_COPY (1),
2851                 RADDR (sfbr),
2852                 NADDR (lastmsg),
2853         SCR_CLR (SCR_ACK|SCR_ATN),
2854                 0,
2855         SCR_WAIT_DISC,
2856                 0,
2857         SCR_JUMP,
2858                 PADDR (start),
2859 }/*-------------------------< SNOOPTEST >-------------------*/,{
2860         /*
2861         **      Read the variable.
2862         */
2863         SCR_COPY (4),
2864                 KVAR (KVAR_NCR_CACHE),
2865                 RADDR (scratcha),
2866         /*
2867         **      Write the variable.
2868         */
2869         SCR_COPY (4),
2870                 RADDR (temp),
2871                 KVAR (KVAR_NCR_CACHE),
2872         /*
2873         **      Read back the variable.
2874         */
2875         SCR_COPY (4),
2876                 KVAR (KVAR_NCR_CACHE),
2877                 RADDR (temp),
2878 }/*-------------------------< SNOOPEND >-------------------*/,{
2879         /*
2880         **      And stop.
2881         */
2882         SCR_INT,
2883                 99,
2884 }/*--------------------------------------------------------*/
2885 };
2886
2887
2888 /*==========================================================
2889 **
2890 **
2891 **      Fill in #define dependent parts of the script
2892 **
2893 **
2894 **==========================================================
2895 */
2896
2897 static void ncr_script_fill (struct script * scr, struct scripth * scrh)
2898 {
2899         int     i;
2900         ncrcmd  *p;
2901
2902         p = scrh->tryloop;
2903         for (i=0; i<MAX_START; i++) {
2904                 *p++ =SCR_COPY (4);
2905                 *p++ =NADDR (squeue[i]);
2906                 *p++ =RADDR (dsa);
2907                 *p++ =SCR_CALL;
2908                 *p++ =PADDR (trysel);
2909         }
2910         *p++ =SCR_JUMP;
2911         *p++ =PADDRH(tryloop);
2912
2913         assert ((char *)p == (char *)&scrh->tryloop + sizeof (scrh->tryloop));
2914
2915         p = scr->data_in;
2916
2917         *p++ =SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN));
2918         *p++ =PADDR (no_data);
2919         *p++ =SCR_COPY (sizeof (ticks));
2920         *p++ =(ncrcmd) KVAR (KVAR_TICKS);
2921         *p++ =NADDR (header.stamp.data);
2922         *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2923         *p++ =offsetof (struct dsb, data[ 0]);
2924
2925         for (i=1; i<MAX_SCATTER; i++) {
2926                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
2927                 *p++ =PADDR (checkatn);
2928                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
2929                 *p++ =offsetof (struct dsb, data[i]);
2930         }
2931
2932         *p++ =SCR_CALL;
2933         *p++ =PADDR (checkatn);
2934         *p++ =SCR_JUMP;
2935         *p++ =PADDR (no_data);
2936
2937         assert ((char *)p == (char *)&scr->data_in + sizeof (scr->data_in));
2938
2939         p = scr->data_out;
2940
2941         *p++ =SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_OUT));
2942         *p++ =PADDR (no_data);
2943         *p++ =SCR_COPY (sizeof (ticks));
2944         *p++ =(ncrcmd) KVAR (KVAR_TICKS);
2945         *p++ =NADDR (header.stamp.data);
2946         *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
2947         *p++ =offsetof (struct dsb, data[ 0]);
2948
2949         for (i=1; i<MAX_SCATTER; i++) {
2950                 *p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
2951                 *p++ =PADDR (dispatch);
2952                 *p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
2953                 *p++ =offsetof (struct dsb, data[i]);
2954         }
2955
2956         *p++ =SCR_CALL;
2957         *p++ =PADDR (dispatch);
2958         *p++ =SCR_JUMP;
2959         *p++ =PADDR (no_data);
2960
2961         assert ((char *)p == (char *)&scr->data_out + sizeof (scr->data_out));
2962 }
2963
2964 /*==========================================================
2965 **
2966 **
2967 **      Copy and rebind a script.
2968 **
2969 **
2970 **==========================================================
2971 */
2972
2973 static void ncr_script_copy_and_bind (ncb_p np, ncrcmd *src, ncrcmd *dst, int len)
2974 {
2975         ncrcmd  opcode, new, old, tmp1, tmp2;
2976         ncrcmd  *start, *end;
2977         int relocs, offset;
2978
2979         start = src;
2980         end = src + len/4;
2981         offset = 0;
2982
2983         while (src < end) {
2984
2985                 opcode = *src++;
2986                 WRITESCRIPT_OFF(dst, offset, opcode);
2987                 offset += 4;
2988
2989                 /*
2990                 **      If we forget to change the length
2991                 **      in struct script, a field will be
2992                 **      padded with 0. This is an illegal
2993                 **      command.
2994                 */
2995
2996                 if (opcode == 0) {
2997                         device_printf(np->dev, "ERROR0 IN SCRIPT at %d.\n",
2998                             (int)(src - start - 1));
2999                         DELAY (1000000);
3000                 }
3001
3002                 if (DEBUG_FLAGS & DEBUG_SCRIPT)
3003                         printf ("%p:  <%x>\n",
3004                                 (src-1), (unsigned)opcode);
3005
3006                 /*
3007                 **      We don't have to decode ALL commands
3008                 */
3009                 switch (opcode >> 28) {
3010
3011                 case 0xc:
3012                         /*
3013                         **      COPY has TWO arguments.
3014                         */
3015                         relocs = 2;
3016                         tmp1 = src[0];
3017                         if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3018                                 tmp1 = 0;
3019                         tmp2 = src[1];
3020                         if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3021                                 tmp2 = 0;
3022                         if ((tmp1 ^ tmp2) & 3) {
3023                                 device_printf(np->dev,
3024                                     "ERROR1 IN SCRIPT at %d.\n",
3025                                     (int)(src - start - 1));
3026                                 DELAY (1000000);
3027                         }
3028                         /*
3029                         **      If PREFETCH feature not enabled, remove 
3030                         **      the NO FLUSH bit if present.
3031                         */
3032                         if ((opcode & SCR_NO_FLUSH) && !(np->features&FE_PFEN))
3033                                 WRITESCRIPT_OFF(dst, offset - 4,
3034                                     (opcode & ~SCR_NO_FLUSH));
3035                         break;
3036
3037                 case 0x0:
3038                         /*
3039                         **      MOVE (absolute address)
3040                         */
3041                         relocs = 1;
3042                         break;
3043
3044                 case 0x8:
3045                         /*
3046                         **      JUMP / CALL
3047                         **      dont't relocate if relative :-)
3048                         */
3049                         if (opcode & 0x00800000)
3050                                 relocs = 0;
3051                         else
3052                                 relocs = 1;
3053                         break;
3054
3055                 case 0x4:
3056                 case 0x5:
3057                 case 0x6:
3058                 case 0x7:
3059                         relocs = 1;
3060                         break;
3061
3062                 default:
3063                         relocs = 0;
3064                         break;
3065                 }
3066
3067                 if (relocs) {
3068                         while (relocs--) {
3069                                 old = *src++;
3070
3071                                 switch (old & RELOC_MASK) {
3072                                 case RELOC_REGISTER:
3073                                         new = (old & ~RELOC_MASK) + rman_get_start(np->reg_res);
3074                                         break;
3075                                 case RELOC_LABEL:
3076                                         new = (old & ~RELOC_MASK) + np->p_script;
3077                                         break;
3078                                 case RELOC_LABELH:
3079                                         new = (old & ~RELOC_MASK) + np->p_scripth;
3080                                         break;
3081                                 case RELOC_SOFTC:
3082                                         new = (old & ~RELOC_MASK) + vtophys(np);
3083                                         break;
3084                                 case RELOC_KVAR:
3085                                         if (((old & ~RELOC_MASK) <
3086                                              SCRIPT_KVAR_FIRST) ||
3087                                             ((old & ~RELOC_MASK) >
3088                                              SCRIPT_KVAR_LAST))
3089                                                 panic("ncr KVAR out of range");
3090                                         new = vtophys(script_kvars[old &
3091                                             ~RELOC_MASK]);
3092                                         break;
3093                                 case 0:
3094                                         /* Don't relocate a 0 address. */
3095                                         if (old == 0) {
3096                                                 new = old;
3097                                                 break;
3098                                         }
3099                                         /* FALLTHROUGH */
3100                                 default:
3101                                         panic("ncr_script_copy_and_bind: weird relocation %x @ %d\n", old, (int)(src - start));
3102                                         break;
3103                                 }
3104
3105                                 WRITESCRIPT_OFF(dst, offset, new);
3106                                 offset += 4;
3107                         }
3108                 } else {
3109                         WRITESCRIPT_OFF(dst, offset, *src++);
3110                         offset += 4;
3111                 }
3112
3113         }
3114 }
3115
3116 /*==========================================================
3117 **
3118 **
3119 **      Auto configuration.
3120 **
3121 **
3122 **==========================================================
3123 */
3124
3125 #if 0
3126 /*----------------------------------------------------------
3127 **
3128 **      Reduce the transfer length to the max value
3129 **      we can transfer safely.
3130 **
3131 **      Reading a block greater then MAX_SIZE from the
3132 **      raw (character) device exercises a memory leak
3133 **      in the vm subsystem. This is common to ALL devices.
3134 **      We have submitted a description of this bug to
3135 **      <FreeBSD-bugs@freefall.cdrom.com>.
3136 **      It should be fixed in the current release.
3137 **
3138 **----------------------------------------------------------
3139 */
3140
3141 void ncr_min_phys (struct  buf *bp)
3142 {
3143         if ((unsigned long)bp->b_bcount > MAX_SIZE) bp->b_bcount = MAX_SIZE;
3144 }
3145
3146 #endif
3147
3148 #if 0
3149 /*----------------------------------------------------------
3150 **
3151 **      Maximal number of outstanding requests per target.
3152 **
3153 **----------------------------------------------------------
3154 */
3155
3156 u_int32_t ncr_info (int unit)
3157 {
3158         return (1);   /* may be changed later */
3159 }
3160
3161 #endif
3162
3163 /*----------------------------------------------------------
3164 **
3165 **      NCR chip devices table and chip look up function.
3166 **      Features bit are defined in ncrreg.h. Is it the 
3167 **      right place?
3168 **
3169 **----------------------------------------------------------
3170 */
3171 typedef struct {
3172         uint32_t        device_id;
3173         uint16_t        minrevid;
3174         char           *name;
3175         unsigned char   maxburst;
3176         unsigned char   maxoffs;
3177         unsigned char   clock_divn;
3178         unsigned int    features;
3179 } ncr_chip;
3180
3181 static ncr_chip ncr_chip_table[] = {
3182  {NCR_810_ID, 0x00,     "ncr 53c810 fast10 scsi",               4,  8, 4,
3183  FE_ERL}
3184  ,
3185  {NCR_810_ID, 0x10,     "ncr 53c810a fast10 scsi",              4,  8, 4,
3186  FE_ERL|FE_LDSTR|FE_PFEN|FE_BOF}
3187  ,
3188  {NCR_815_ID, 0x00,     "ncr 53c815 fast10 scsi",               4,  8, 4,
3189  FE_ERL|FE_BOF}
3190  ,
3191  {NCR_820_ID, 0x00,     "ncr 53c820 fast10 wide scsi",          4,  8, 4,
3192  FE_WIDE|FE_ERL}
3193  ,
3194  {NCR_825_ID, 0x00,     "ncr 53c825 fast10 wide scsi",          4,  8, 4,
3195  FE_WIDE|FE_ERL|FE_BOF}
3196  ,
3197  {NCR_825_ID, 0x10,     "ncr 53c825a fast10 wide scsi",         7,  8, 4,
3198  FE_WIDE|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3199  ,
3200  {NCR_860_ID, 0x00,     "ncr 53c860 fast20 scsi",               4,  8, 5,
3201  FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_LDSTR|FE_PFEN}
3202  ,
3203  {NCR_875_ID, 0x00,     "ncr 53c875 fast20 wide scsi",          7, 16, 5,
3204  FE_WIDE|FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3205  ,
3206  {NCR_875_ID, 0x02,     "ncr 53c875 fast20 wide scsi",          7, 16, 5,
3207  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3208  ,
3209  {NCR_875_ID2, 0x00,    "ncr 53c875j fast20 wide scsi",         7, 16, 5,
3210  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3211  ,
3212  {NCR_885_ID, 0x00,     "ncr 53c885 fast20 wide scsi",          7, 16, 5,
3213  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3214  ,
3215  {NCR_895_ID, 0x00,     "ncr 53c895 fast40 wide scsi",          7, 31, 7,
3216  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3217  ,
3218  {NCR_896_ID, 0x00,     "ncr 53c896 fast40 wide scsi",          7, 31, 7,
3219  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3220  ,
3221  {NCR_895A_ID, 0x00,    "ncr 53c895a fast40 wide scsi",         7, 31, 7,
3222  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3223  ,
3224  {NCR_1510D_ID, 0x00,   "ncr 53c1510d fast40 wide scsi",        7, 31, 7,
3225  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3226 };
3227
3228 static int ncr_chip_lookup(uint32_t device_id, u_char revision_id)
3229 {
3230         int i, found;
3231         
3232         found = -1;
3233         for (i = 0; i < nitems(ncr_chip_table); i++) {
3234                 if (device_id   == ncr_chip_table[i].device_id &&
3235                     ncr_chip_table[i].minrevid <= revision_id) {
3236                         if (found < 0 || 
3237                             ncr_chip_table[found].minrevid 
3238                               < ncr_chip_table[i].minrevid) {
3239                                 found = i;
3240                         }
3241                 }
3242         }
3243         return found;
3244 }
3245
3246 /*----------------------------------------------------------
3247 **
3248 **      Probe the hostadapter.
3249 **
3250 **----------------------------------------------------------
3251 */
3252
3253
3254
3255 static  int ncr_probe (device_t dev)
3256 {
3257         int i;
3258
3259         i = ncr_chip_lookup(pci_get_devid(dev), pci_get_revid(dev));
3260         if (i >= 0) {
3261                 device_set_desc(dev, ncr_chip_table[i].name);
3262                 return (BUS_PROBE_DEFAULT);
3263         }
3264
3265         return (ENXIO);
3266 }
3267
3268
3269
3270 /*==========================================================
3271 **
3272 **      NCR chip clock divisor table.
3273 **      Divisors are multiplied by 10,000,000 in order to make 
3274 **      calculations more simple.
3275 **
3276 **==========================================================
3277 */
3278
3279 #define _5M 5000000
3280 static u_long div_10M[] =
3281         {2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3282
3283 /*===============================================================
3284 **
3285 **      NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128 
3286 **      transfers. 32,64,128 are only supported by 875 and 895 chips.
3287 **      We use log base 2 (burst length) as internal code, with 
3288 **      value 0 meaning "burst disabled".
3289 **
3290 **===============================================================
3291 */
3292
3293 /*
3294  *      Burst length from burst code.
3295  */
3296 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3297
3298 /*
3299  *      Burst code from io register bits.
3300  */
3301 #define burst_code(dmode, ctest4, ctest5) \
3302         (ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
3303
3304 /*
3305  *      Set initial io register bits from burst code.
3306  */
3307 static void
3308 ncr_init_burst(ncb_p np, u_char bc)
3309 {
3310         np->rv_ctest4   &= ~0x80;
3311         np->rv_dmode    &= ~(0x3 << 6);
3312         np->rv_ctest5   &= ~0x4;
3313
3314         if (!bc) {
3315                 np->rv_ctest4   |= 0x80;
3316         }
3317         else {
3318                 --bc;
3319                 np->rv_dmode    |= ((bc & 0x3) << 6);
3320                 np->rv_ctest5   |= (bc & 0x4);
3321         }
3322 }
3323
3324 /*==========================================================
3325 **
3326 **
3327 **      Auto configuration:  attach and init a host adapter.
3328 **
3329 **
3330 **==========================================================
3331 */
3332
3333
3334 static int
3335 ncr_attach (device_t dev)
3336 {
3337         ncb_p np = (struct ncb*) device_get_softc(dev);
3338         u_char   rev = 0;
3339         u_long   period;
3340         int      i, rid;
3341         u_int8_t usrsync;
3342         u_int8_t usrwide;
3343         struct cam_devq *devq;
3344
3345         /*
3346         **      allocate and initialize structures.
3347         */
3348
3349         np->dev = dev;
3350         mtx_init(&np->lock, "ncr", NULL, MTX_DEF);
3351         callout_init_mtx(&np->timer, &np->lock, 0);
3352
3353         /*
3354         **      Try to map the controller chip to
3355         **      virtual and physical memory.
3356         */
3357
3358         np->reg_rid = PCIR_BAR(1);
3359         np->reg_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
3360                                              &np->reg_rid, RF_ACTIVE);
3361         if (!np->reg_res) {
3362                 device_printf(dev, "could not map memory\n");
3363                 return ENXIO;
3364         }
3365
3366         /*
3367         **      Now the INB INW INL OUTB OUTW OUTL macros
3368         **      can be used safely.
3369         */
3370
3371 #ifdef NCR_IOMAPPED
3372         /*
3373         **      Try to map the controller chip into iospace.
3374         */
3375
3376         if (!pci_map_port (config_id, 0x10, &np->port))
3377                 return;
3378 #endif
3379
3380
3381         /*
3382         **      Save some controller register default values
3383         */
3384
3385         np->rv_scntl3   = INB(nc_scntl3) & 0x77;
3386         np->rv_dmode    = INB(nc_dmode)  & 0xce;
3387         np->rv_dcntl    = INB(nc_dcntl)  & 0xa9;
3388         np->rv_ctest3   = INB(nc_ctest3) & 0x01;
3389         np->rv_ctest4   = INB(nc_ctest4) & 0x88;
3390         np->rv_ctest5   = INB(nc_ctest5) & 0x24;
3391         np->rv_gpcntl   = INB(nc_gpcntl);
3392         np->rv_stest2   = INB(nc_stest2) & 0x20;
3393
3394         if (bootverbose >= 2) {
3395                 printf ("\tBIOS values:  SCNTL3:%02x DMODE:%02x  DCNTL:%02x\n",
3396                         np->rv_scntl3, np->rv_dmode, np->rv_dcntl);
3397                 printf ("\t              CTEST3:%02x CTEST4:%02x CTEST5:%02x\n",
3398                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
3399         }
3400
3401         np->rv_dcntl  |= NOCOM;
3402
3403         /*
3404         **      Do chip dependent initialization.
3405         */
3406
3407         rev = pci_get_revid(dev);
3408
3409         /*
3410         **      Get chip features from chips table.
3411         */
3412         i = ncr_chip_lookup(pci_get_devid(dev), rev);
3413
3414         if (i >= 0) {
3415                 np->maxburst    = ncr_chip_table[i].maxburst;
3416                 np->maxoffs     = ncr_chip_table[i].maxoffs;
3417                 np->clock_divn  = ncr_chip_table[i].clock_divn;
3418                 np->features    = ncr_chip_table[i].features;
3419         } else {        /* Should'nt happen if probe() is ok */
3420                 np->maxburst    = 4;
3421                 np->maxoffs     = 8;
3422                 np->clock_divn  = 4;
3423                 np->features    = FE_ERL;
3424         }
3425
3426         np->maxwide     = np->features & FE_WIDE ? 1 : 0;
3427         np->clock_khz   = np->features & FE_CLK80 ? 80000 : 40000;
3428         if      (np->features & FE_QUAD)        np->multiplier = 4;
3429         else if (np->features & FE_DBLR)        np->multiplier = 2;
3430         else                                    np->multiplier = 1;
3431
3432         /*
3433         **      Get the frequency of the chip's clock.
3434         **      Find the right value for scntl3.
3435         */
3436         if (np->features & (FE_ULTRA|FE_ULTRA2))
3437                 ncr_getclock(np, np->multiplier);
3438
3439 #ifdef NCR_TEKRAM_EEPROM
3440         if (bootverbose) {
3441                 device_printf(dev, "Tekram EEPROM read %s\n",
3442                         read_tekram_eeprom (np, NULL) ?
3443                         "succeeded" : "failed");
3444         }
3445 #endif /* NCR_TEKRAM_EEPROM */
3446
3447         /*
3448          *      If scntl3 != 0, we assume BIOS is present.
3449          */
3450         if (np->rv_scntl3)
3451                 np->features |= FE_BIOS;
3452
3453         /*
3454          * Divisor to be used for async (timer pre-scaler).
3455          */
3456         i = np->clock_divn - 1;
3457         while (i >= 0) {
3458                 --i;
3459                 if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3460                         ++i;
3461                         break;
3462                 }
3463         }
3464         np->rv_scntl3 = i+1;
3465
3466         /*
3467          * Minimum synchronous period factor supported by the chip.
3468          * Btw, 'period' is in tenths of nanoseconds.
3469          */
3470
3471         period = howmany(4 * div_10M[0], np->clock_khz);
3472         if      (period <= 250)         np->minsync = 10;
3473         else if (period <= 303)         np->minsync = 11;
3474         else if (period <= 500)         np->minsync = 12;
3475         else                            np->minsync = howmany(period, 40);
3476
3477         /*
3478          * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3479          */
3480
3481         if      (np->minsync < 25 && !(np->features & (FE_ULTRA|FE_ULTRA2)))
3482                 np->minsync = 25;
3483         else if (np->minsync < 12 && !(np->features & FE_ULTRA2))
3484                 np->minsync = 12;
3485
3486         /*
3487          * Maximum synchronous period factor supported by the chip.
3488          */
3489
3490         period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3491         np->maxsync = period > 2540 ? 254 : period / 10;
3492
3493         /*
3494          * Now, some features available with Symbios compatible boards.
3495          * LED support through GPIO0 and DIFF support.
3496          */
3497
3498 #ifdef  SCSI_NCR_SYMBIOS_COMPAT
3499         if (!(np->rv_gpcntl & 0x01))
3500                 np->features |= FE_LED0;
3501 #if 0   /* Not safe enough without NVRAM support or user settable option */
3502         if (!(INB(nc_gpreg) & 0x08))
3503                 np->features |= FE_DIFF;
3504 #endif
3505 #endif  /* SCSI_NCR_SYMBIOS_COMPAT */
3506
3507         /*
3508          * Prepare initial IO registers settings.
3509          * Trust BIOS only if we believe we have one and if we want to.
3510          */
3511 #ifdef  SCSI_NCR_TRUST_BIOS
3512         if (!(np->features & FE_BIOS)) {
3513 #else
3514         if (1) {
3515 #endif
3516                 np->rv_dmode = 0;
3517                 np->rv_dcntl = NOCOM;
3518                 np->rv_ctest3 = 0;
3519                 np->rv_ctest4 = MPEE;
3520                 np->rv_ctest5 = 0;
3521                 np->rv_stest2 = 0;
3522
3523                 if (np->features & FE_ERL)
3524                         np->rv_dmode    |= ERL;   /* Enable Read Line */
3525                 if (np->features & FE_BOF)
3526                         np->rv_dmode    |= BOF;   /* Burst Opcode Fetch */
3527                 if (np->features & FE_ERMP)
3528                         np->rv_dmode    |= ERMP;  /* Enable Read Multiple */
3529                 if (np->features & FE_CLSE)
3530                         np->rv_dcntl    |= CLSE;  /* Cache Line Size Enable */
3531                 if (np->features & FE_WRIE)
3532                         np->rv_ctest3   |= WRIE;  /* Write and Invalidate */
3533                 if (np->features & FE_PFEN)
3534                         np->rv_dcntl    |= PFEN;  /* Prefetch Enable */
3535                 if (np->features & FE_DFS)
3536                         np->rv_ctest5   |= DFS;   /* Dma Fifo Size */
3537                 if (np->features & FE_DIFF)     
3538                         np->rv_stest2   |= 0x20;  /* Differential mode */
3539                 ncr_init_burst(np, np->maxburst); /* Max dwords burst length */
3540         } else {
3541                 np->maxburst =
3542                         burst_code(np->rv_dmode, np->rv_ctest4, np->rv_ctest5);
3543         }
3544
3545         /*
3546         **      Get on-chip SRAM address, if supported
3547         */
3548         if ((np->features & FE_RAM) && sizeof(struct script) <= 4096) {
3549                 np->sram_rid = PCIR_BAR(2);
3550                 np->sram_res = bus_alloc_resource_any(dev, SYS_RES_MEMORY,
3551                                                       &np->sram_rid,
3552                                                       RF_ACTIVE);
3553         }
3554
3555         /*
3556         **      Allocate structure for script relocation.
3557         */
3558         if (np->sram_res != NULL) {
3559                 np->script = NULL;
3560                 np->p_script = rman_get_start(np->sram_res);
3561         } else if (sizeof (struct script) > PAGE_SIZE) {
3562                 np->script  = (struct script*) contigmalloc 
3563                         (round_page(sizeof (struct script)), M_DEVBUF, M_WAITOK,
3564                          0, 0xffffffff, PAGE_SIZE, 0);
3565         } else {
3566                 np->script  = (struct script *)
3567                         malloc (sizeof (struct script), M_DEVBUF, M_WAITOK);
3568         }
3569
3570         if (sizeof (struct scripth) > PAGE_SIZE) {
3571                 np->scripth = (struct scripth*) contigmalloc 
3572                         (round_page(sizeof (struct scripth)), M_DEVBUF, M_WAITOK,
3573                          0, 0xffffffff, PAGE_SIZE, 0);
3574         } else 
3575                 {
3576                 np->scripth = (struct scripth *)
3577                         malloc (sizeof (struct scripth), M_DEVBUF, M_WAITOK);
3578         }
3579
3580 #ifdef SCSI_NCR_PCI_CONFIG_FIXUP
3581         /*
3582         **      If cache line size is enabled, check PCI config space and 
3583         **      try to fix it up if necessary.
3584         */
3585 #ifdef PCIR_CACHELNSZ   /* To be sure that new PCI stuff is present */
3586         {
3587                 u_char cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
3588                 u_short command  = pci_read_config(dev, PCIR_COMMAND, 2);
3589
3590                 if (!cachelnsz) {
3591                         cachelnsz = 8;
3592                         device_printf(dev,
3593                             "setting PCI cache line size register to %d.\n",
3594                             (int)cachelnsz);
3595                         pci_write_config(dev, PCIR_CACHELNSZ, cachelnsz, 1);
3596                 }
3597
3598                 if (!(command & PCIM_CMD_MWRICEN)) {
3599                         command |= PCIM_CMD_MWRICEN;
3600                         device_printf(dev,
3601                             "setting PCI command write and invalidate.\n");
3602                         pci_write_config(dev, PCIR_COMMAND, command, 2);
3603                 }
3604         }
3605 #endif /* PCIR_CACHELNSZ */
3606
3607 #endif /* SCSI_NCR_PCI_CONFIG_FIXUP */
3608
3609         /* Initialize per-target user settings */
3610         usrsync = 0;
3611         if (SCSI_NCR_DFLT_SYNC) {
3612                 usrsync = SCSI_NCR_DFLT_SYNC;
3613                 if (usrsync > np->maxsync)
3614                         usrsync = np->maxsync;
3615                 if (usrsync < np->minsync)
3616                         usrsync = np->minsync;
3617         }
3618
3619         usrwide = (SCSI_NCR_MAX_WIDE);
3620         if (usrwide > np->maxwide) usrwide=np->maxwide;
3621
3622         for (i=0;i<MAX_TARGET;i++) {
3623                 tcb_p tp = &np->target[i];
3624
3625                 tp->tinfo.user.period = usrsync;
3626                 tp->tinfo.user.offset = usrsync != 0 ? np->maxoffs : 0;
3627                 tp->tinfo.user.width = usrwide;
3628                 tp->tinfo.disc_tag = NCR_CUR_DISCENB
3629                                    | NCR_CUR_TAGENB
3630                                    | NCR_USR_DISCENB
3631                                    | NCR_USR_TAGENB;
3632         }
3633
3634         /*
3635         **      Bells and whistles   ;-)
3636         */
3637         if (bootverbose)
3638                 device_printf(dev,
3639             "minsync=%d, maxsync=%d, maxoffs=%d, %d dwords burst, %s dma fifo\n",
3640                 np->minsync, np->maxsync, np->maxoffs,
3641                 burst_length(np->maxburst),
3642                 (np->rv_ctest5 & DFS) ? "large" : "normal");
3643
3644         /*
3645         **      Print some complementary information that can be helpful.
3646         */
3647         if (bootverbose)
3648                 device_printf(dev, "%s, %s IRQ driver%s\n",
3649                         np->rv_stest2 & 0x20 ? "differential" : "single-ended",
3650                         np->rv_dcntl & IRQM ? "totem pole" : "open drain",
3651                         np->sram_res ? ", using on-chip SRAM" : "");
3652                         
3653         /*
3654         **      Patch scripts to physical addresses
3655         */
3656         ncr_script_fill (&script0, &scripth0);
3657
3658         if (np->script)
3659                 np->p_script    = vtophys(np->script);
3660         np->p_scripth   = vtophys(np->scripth);
3661
3662         ncr_script_copy_and_bind (np, (ncrcmd *) &script0,
3663                         (ncrcmd *) np->script, sizeof(struct script));
3664
3665         ncr_script_copy_and_bind (np, (ncrcmd *) &scripth0,
3666                 (ncrcmd *) np->scripth, sizeof(struct scripth));
3667
3668         /*
3669         **    Patch the script for LED support.
3670         */
3671
3672         if (np->features & FE_LED0) {
3673                 WRITESCRIPT(reselect[0],  SCR_REG_REG(gpreg, SCR_OR,  0x01));
3674                 WRITESCRIPT(reselect1[0], SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3675                 WRITESCRIPT(reselect2[0], SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3676         }
3677
3678         /*
3679         **      init data structure
3680         */
3681
3682         np->jump_tcb.l_cmd      = SCR_JUMP;
3683         np->jump_tcb.l_paddr    = NCB_SCRIPTH_PHYS (np, abort);
3684
3685         /*
3686         **  Get SCSI addr of host adapter (set by bios?).
3687         */
3688
3689         np->myaddr = INB(nc_scid) & 0x07;
3690         if (!np->myaddr) np->myaddr = SCSI_NCR_MYADDR;
3691
3692 #ifdef NCR_DUMP_REG
3693         /*
3694         **      Log the initial register contents
3695         */
3696         {
3697                 int reg;
3698                 for (reg=0; reg<256; reg+=4) {
3699                         if (reg%16==0) printf ("reg[%2x]", reg);
3700                         printf (" %08x", (int)pci_conf_read (config_id, reg));
3701                         if (reg%16==12) printf ("\n");
3702                 }
3703         }
3704 #endif /* NCR_DUMP_REG */
3705
3706         /*
3707         **      Reset chip.
3708         */
3709
3710         OUTB (nc_istat,  SRST);
3711         DELAY (1000);
3712         OUTB (nc_istat,  0   );
3713
3714
3715         /*
3716         **      Now check the cache handling of the pci chipset.
3717         */
3718
3719         if (ncr_snooptest (np)) {
3720                 printf ("CACHE INCORRECTLY CONFIGURED.\n");
3721                 return EINVAL;
3722         }
3723
3724         /*
3725         **      Install the interrupt handler.
3726         */
3727
3728         rid = 0;
3729         np->irq_res = bus_alloc_resource_any(dev, SYS_RES_IRQ, &rid,
3730                                              RF_SHAREABLE | RF_ACTIVE);
3731         if (np->irq_res == NULL) {
3732                 device_printf(dev,
3733                               "interruptless mode: reduced performance.\n");
3734         } else {
3735                 bus_setup_intr(dev, np->irq_res, INTR_TYPE_CAM | INTR_ENTROPY |
3736                     INTR_MPSAFE, NULL, ncr_intr, np, &np->irq_handle);
3737         }
3738
3739         /*
3740         ** Create the device queue.  We only allow MAX_START-1 concurrent
3741         ** transactions so we can be sure to have one element free in our
3742         ** start queue to reset to the idle loop.
3743         */
3744         devq = cam_simq_alloc(MAX_START - 1);
3745         if (devq == NULL)
3746                 return ENOMEM;
3747
3748         /*
3749         **      Now tell the generic SCSI layer
3750         **      about our bus.
3751         */
3752         np->sim = cam_sim_alloc(ncr_action, ncr_poll, "ncr", np,
3753             device_get_unit(dev), &np->lock, 1, MAX_TAGS, devq);
3754         if (np->sim == NULL) {
3755                 cam_simq_free(devq);
3756                 return ENOMEM;
3757         }
3758
3759         mtx_lock(&np->lock);
3760         if (xpt_bus_register(np->sim, dev, 0) != CAM_SUCCESS) {
3761                 cam_sim_free(np->sim, /*free_devq*/ TRUE);
3762                 mtx_unlock(&np->lock);
3763                 return ENOMEM;
3764         }
3765         
3766         if (xpt_create_path(&np->path, /*periph*/NULL,
3767                             cam_sim_path(np->sim), CAM_TARGET_WILDCARD,
3768                             CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
3769                 xpt_bus_deregister(cam_sim_path(np->sim));
3770                 cam_sim_free(np->sim, /*free_devq*/TRUE);
3771                 mtx_unlock(&np->lock);
3772                 return ENOMEM;
3773         }
3774
3775         /*
3776         **      start the timeout daemon
3777         */
3778         ncr_timeout (np);
3779         np->lasttime=0;
3780         mtx_unlock(&np->lock);
3781         gone_in_dev(dev, 12, "ncr(4) driver, use sym(4) instead");
3782
3783         return 0;
3784 }
3785
3786 /*==========================================================
3787 **
3788 **
3789 **      Process pending device interrupts.
3790 **
3791 **
3792 **==========================================================
3793 */
3794
3795 static void
3796 ncr_intr(vnp)
3797         void *vnp;
3798 {
3799         ncb_p np = vnp;
3800
3801         mtx_lock(&np->lock);
3802         ncr_intr_locked(np);
3803         mtx_unlock(&np->lock);
3804 }
3805
3806 static void
3807 ncr_intr_locked(ncb_p np)
3808 {
3809
3810         if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
3811
3812         if (INB(nc_istat) & (INTF|SIP|DIP)) {
3813                 /*
3814                 **      Repeat until no outstanding ints
3815                 */
3816                 do {
3817                         ncr_exception (np);
3818                 } while (INB(nc_istat) & (INTF|SIP|DIP));
3819
3820                 np->ticks = 100;
3821         }
3822
3823         if (DEBUG_FLAGS & DEBUG_TINY) printf ("]\n");
3824 }
3825
3826 /*==========================================================
3827 **
3828 **
3829 **      Start execution of a SCSI command.
3830 **      This is called from the generic SCSI driver.
3831 **
3832 **
3833 **==========================================================
3834 */
3835
3836 static void
3837 ncr_action (struct cam_sim *sim, union ccb *ccb)
3838 {
3839         ncb_p np;
3840
3841         np = (ncb_p) cam_sim_softc(sim);
3842         mtx_assert(&np->lock, MA_OWNED);
3843
3844         switch (ccb->ccb_h.func_code) {
3845         /* Common cases first */
3846         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
3847         {
3848                 nccb_p cp;
3849                 lcb_p lp;
3850                 tcb_p tp;
3851                 struct ccb_scsiio *csio;
3852                 u_int8_t *msgptr;
3853                 u_int msglen;
3854                 u_int msglen2;
3855                 int segments;
3856                 u_int8_t nego;
3857                 u_int8_t idmsg;
3858                 int qidx;
3859                 
3860                 tp = &np->target[ccb->ccb_h.target_id];
3861                 csio = &ccb->csio;
3862
3863                 /*
3864                  * Make sure we support this request. We can't do
3865                  * PHYS pointers.
3866                  */
3867                 if (ccb->ccb_h.flags & CAM_CDB_PHYS) {
3868                         ccb->ccb_h.status = CAM_REQ_INVALID;
3869                         xpt_done(ccb);
3870                         return;
3871                 }
3872
3873                 /*
3874                  * Last time we need to check if this CCB needs to
3875                  * be aborted.
3876                  */
3877                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3878                         xpt_done(ccb);
3879                         return;
3880                 }
3881                 ccb->ccb_h.status |= CAM_SIM_QUEUED;
3882
3883                 /*---------------------------------------------------
3884                 **
3885                 **      Assign an nccb / bind ccb
3886                 **
3887                 **----------------------------------------------------
3888                 */
3889                 cp = ncr_get_nccb (np, ccb->ccb_h.target_id,
3890                                    ccb->ccb_h.target_lun);
3891                 if (cp == NULL) {
3892                         /* XXX JGibbs - Freeze SIMQ */
3893                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3894                         xpt_done(ccb);
3895                         return;
3896                 }
3897                 
3898                 cp->ccb = ccb;
3899                 
3900                 /*---------------------------------------------------
3901                 **
3902                 **      timestamp
3903                 **
3904                 **----------------------------------------------------
3905                 */
3906                 /*
3907                 ** XXX JGibbs - Isn't this expensive
3908                 **              enough to be conditionalized??
3909                 */
3910
3911                 bzero (&cp->phys.header.stamp, sizeof (struct tstamp));
3912                 cp->phys.header.stamp.start = ticks;
3913
3914                 nego = 0;
3915                 if (tp->nego_cp == NULL) {
3916                         
3917                         if (tp->tinfo.current.width
3918                          != tp->tinfo.goal.width) {
3919                                 tp->nego_cp = cp;
3920                                 nego = NS_WIDE;
3921                         } else if ((tp->tinfo.current.period
3922                                     != tp->tinfo.goal.period)
3923                                 || (tp->tinfo.current.offset
3924                                     != tp->tinfo.goal.offset)) {
3925                                 tp->nego_cp = cp;
3926                                 nego = NS_SYNC;
3927                         }
3928                 }
3929
3930                 /*---------------------------------------------------
3931                 **
3932                 **      choose a new tag ...
3933                 **
3934                 **----------------------------------------------------
3935                 */
3936                 lp = tp->lp[ccb->ccb_h.target_lun];
3937
3938                 if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0
3939                  && (ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3940                  && (nego == 0)) {
3941                         /*
3942                         **      assign a tag to this nccb
3943                         */
3944                         while (!cp->tag) {
3945                                 nccb_p cp2 = lp->next_nccb;
3946                                 lp->lasttag = lp->lasttag % 255 + 1;
3947                                 while (cp2 && cp2->tag != lp->lasttag)
3948                                         cp2 = cp2->next_nccb;
3949                                 if (cp2) continue;
3950                                 cp->tag=lp->lasttag;
3951                                 if (DEBUG_FLAGS & DEBUG_TAGS) {
3952                                         PRINT_ADDR(ccb);
3953                                         printf ("using tag #%d.\n", cp->tag);
3954                                 }
3955                         }
3956                 } else {
3957                         cp->tag=0;
3958                 }
3959
3960                 /*----------------------------------------------------
3961                 **
3962                 **      Build the identify / tag / sdtr message
3963                 **
3964                 **----------------------------------------------------
3965                 */
3966                 idmsg = MSG_IDENTIFYFLAG | ccb->ccb_h.target_lun;
3967                 if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
3968                         idmsg |= MSG_IDENTIFY_DISCFLAG;
3969
3970                 msgptr = cp->scsi_smsg;
3971                 msglen = 0;
3972                 msgptr[msglen++] = idmsg;
3973
3974                 if (cp->tag) {
3975                         msgptr[msglen++] = ccb->csio.tag_action;
3976                         msgptr[msglen++] = cp->tag;
3977                 }
3978
3979                 switch (nego) {
3980                 case NS_SYNC:
3981                         msgptr[msglen++] = MSG_EXTENDED;
3982                         msgptr[msglen++] = MSG_EXT_SDTR_LEN;
3983                         msgptr[msglen++] = MSG_EXT_SDTR;
3984                         msgptr[msglen++] = tp->tinfo.goal.period;
3985                         msgptr[msglen++] = tp->tinfo.goal.offset;
3986                         if (DEBUG_FLAGS & DEBUG_NEGO) {
3987                                 PRINT_ADDR(ccb);
3988                                 printf ("sync msgout: ");
3989                                 ncr_show_msg (&cp->scsi_smsg [msglen-5]);
3990                                 printf (".\n");
3991                         };
3992                         break;
3993                 case NS_WIDE:
3994                         msgptr[msglen++] = MSG_EXTENDED;
3995                         msgptr[msglen++] = MSG_EXT_WDTR_LEN;
3996                         msgptr[msglen++] = MSG_EXT_WDTR;
3997                         msgptr[msglen++] = tp->tinfo.goal.width;
3998                         if (DEBUG_FLAGS & DEBUG_NEGO) {
3999                                 PRINT_ADDR(ccb);
4000                                 printf ("wide msgout: ");
4001                                 ncr_show_msg (&cp->scsi_smsg [msglen-4]);
4002                                 printf (".\n");
4003                         };
4004                         break;
4005                 }
4006
4007                 /*----------------------------------------------------
4008                 **
4009                 **      Build the identify message for getcc.
4010                 **
4011                 **----------------------------------------------------
4012                 */
4013
4014                 cp->scsi_smsg2 [0] = idmsg;
4015                 msglen2 = 1;
4016
4017                 /*----------------------------------------------------
4018                 **
4019                 **      Build the data descriptors
4020                 **
4021                 **----------------------------------------------------
4022                 */
4023
4024                 /* XXX JGibbs - Handle other types of I/O */
4025                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
4026                         segments = ncr_scatter(&cp->phys,
4027                                                (vm_offset_t)csio->data_ptr,
4028                                                (vm_size_t)csio->dxfer_len);
4029
4030                         if (segments < 0) {
4031                                 ccb->ccb_h.status = CAM_REQ_TOO_BIG;
4032                                 ncr_free_nccb(np, cp);
4033                                 xpt_done(ccb);
4034                                 return;
4035                         }
4036                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4037                                 cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_in);
4038                                 cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4039                         } else { /* CAM_DIR_OUT */
4040                                 cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_out);
4041                                 cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4042                         }
4043                 } else {
4044                         cp->phys.header.savep = NCB_SCRIPT_PHYS (np, no_data);
4045                         cp->phys.header.goalp = cp->phys.header.savep;
4046                 }
4047
4048                 cp->phys.header.lastp = cp->phys.header.savep;
4049
4050
4051                 /*----------------------------------------------------
4052                 **
4053                 **      fill in nccb
4054                 **
4055                 **----------------------------------------------------
4056                 **
4057                 **
4058                 **      physical -> virtual backlink
4059                 **      Generic SCSI command
4060                 */
4061                 cp->phys.header.cp              = cp;
4062                 /*
4063                 **      Startqueue
4064                 */
4065                 cp->phys.header.launch.l_paddr  = NCB_SCRIPT_PHYS (np, select);
4066                 cp->phys.header.launch.l_cmd    = SCR_JUMP;
4067                 /*
4068                 **      select
4069                 */
4070                 cp->phys.select.sel_id          = ccb->ccb_h.target_id;
4071                 cp->phys.select.sel_scntl3      = tp->tinfo.wval;
4072                 cp->phys.select.sel_sxfer       = tp->tinfo.sval;
4073                 /*
4074                 **      message
4075                 */
4076                 cp->phys.smsg.addr              = CCB_PHYS (cp, scsi_smsg);
4077                 cp->phys.smsg.size              = msglen;
4078         
4079                 cp->phys.smsg2.addr             = CCB_PHYS (cp, scsi_smsg2);
4080                 cp->phys.smsg2.size             = msglen2;
4081                 /*
4082                 **      command
4083                 */
4084                 cp->phys.cmd.addr               = vtophys (scsiio_cdb_ptr(csio));
4085                 cp->phys.cmd.size               = csio->cdb_len;
4086                 /*
4087                 **      sense command
4088                 */
4089                 cp->phys.scmd.addr              = CCB_PHYS (cp, sensecmd);
4090                 cp->phys.scmd.size              = 6;
4091                 /*
4092                 **      patch requested size into sense command
4093                 */
4094                 cp->sensecmd[0]                 = 0x03;
4095                 cp->sensecmd[1]                 = ccb->ccb_h.target_lun << 5;
4096                 cp->sensecmd[4]                 = csio->sense_len;
4097                 /*
4098                 **      sense data
4099                 */
4100                 cp->phys.sense.addr             = vtophys (&csio->sense_data);
4101                 cp->phys.sense.size             = csio->sense_len;
4102                 /*
4103                 **      status
4104                 */
4105                 cp->actualquirks                = QUIRK_NOMSG;
4106                 cp->host_status                 = nego ? HS_NEGOTIATE : HS_BUSY;
4107                 cp->s_status                    = SCSI_STATUS_ILLEGAL;
4108                 cp->parity_status               = 0;
4109         
4110                 cp->xerr_status                 = XE_OK;
4111                 cp->sync_status                 = tp->tinfo.sval;
4112                 cp->nego_status                 = nego;
4113                 cp->wide_status                 = tp->tinfo.wval;
4114
4115                 /*----------------------------------------------------
4116                 **
4117                 **      Critical region: start this job.
4118                 **
4119                 **----------------------------------------------------
4120                 */
4121
4122                 /*
4123                 **      reselect pattern and activate this job.
4124                 */
4125
4126                 cp->jump_nccb.l_cmd     = (SCR_JUMP ^ IFFALSE (DATA (cp->tag)));
4127                 cp->tlimit              = time_second
4128                                         + ccb->ccb_h.timeout / 1000 + 2;
4129                 cp->magic               = CCB_MAGIC;
4130
4131                 /*
4132                 **      insert into start queue.
4133                 */
4134
4135                 qidx = np->squeueput + 1;
4136                 if (qidx >= MAX_START)
4137                         qidx = 0;
4138                 np->squeue [qidx         ] = NCB_SCRIPT_PHYS (np, idle);
4139                 np->squeue [np->squeueput] = CCB_PHYS (cp, phys);
4140                 np->squeueput = qidx;
4141
4142                 if(DEBUG_FLAGS & DEBUG_QUEUE)
4143                         device_printf(np->dev, "queuepos=%d tryoffset=%d.\n",
4144                                np->squeueput,
4145                                (unsigned)(READSCRIPT(startpos[0]) - 
4146                                (NCB_SCRIPTH_PHYS (np, tryloop))));
4147
4148                 /*
4149                 **      Script processor may be waiting for reselect.
4150                 **      Wake it up.
4151                 */
4152                 OUTB (nc_istat, SIGP);
4153                 break;
4154         }
4155         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
4156         case XPT_ABORT:                 /* Abort the specified CCB */
4157                 /* XXX Implement */
4158                 ccb->ccb_h.status = CAM_REQ_INVALID;
4159                 xpt_done(ccb);
4160                 break;
4161         case XPT_SET_TRAN_SETTINGS:
4162         {
4163                 struct  ccb_trans_settings *cts = &ccb->cts;
4164                 tcb_p   tp;
4165                 u_int   update_type;
4166                 struct ccb_trans_settings_scsi *scsi =
4167                     &cts->proto_specific.scsi;
4168                 struct ccb_trans_settings_spi *spi =
4169                     &cts->xport_specific.spi;
4170
4171                 update_type = 0;
4172                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
4173                         update_type |= NCR_TRANS_GOAL;
4174                 if (cts->type == CTS_TYPE_USER_SETTINGS)
4175                         update_type |= NCR_TRANS_USER;
4176
4177                 tp = &np->target[ccb->ccb_h.target_id];
4178                 /* Tag and disc enables */
4179                 if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
4180                         if (update_type & NCR_TRANS_GOAL) {
4181                                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
4182                                         tp->tinfo.disc_tag |= NCR_CUR_DISCENB;
4183                                 else
4184                                         tp->tinfo.disc_tag &= ~NCR_CUR_DISCENB;
4185                         }
4186
4187                         if (update_type & NCR_TRANS_USER) {
4188                                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
4189                                         tp->tinfo.disc_tag |= NCR_USR_DISCENB;
4190                                 else
4191                                         tp->tinfo.disc_tag &= ~NCR_USR_DISCENB;
4192                         }
4193
4194                 }
4195
4196                 if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
4197                         if (update_type & NCR_TRANS_GOAL) {
4198                                 if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
4199                                         tp->tinfo.disc_tag |= NCR_CUR_TAGENB;
4200                                 else
4201                                         tp->tinfo.disc_tag &= ~NCR_CUR_TAGENB;
4202                         }
4203
4204                         if (update_type & NCR_TRANS_USER) {
4205                                 if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
4206                                         tp->tinfo.disc_tag |= NCR_USR_TAGENB;
4207                                 else
4208                                         tp->tinfo.disc_tag &= ~NCR_USR_TAGENB;
4209                         }       
4210                 }
4211
4212                 /* Filter bus width and sync negotiation settings */
4213                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
4214                         if (spi->bus_width > np->maxwide)
4215                                 spi->bus_width = np->maxwide;
4216                 }
4217
4218                 if (((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4219                  || ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)) {
4220                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0) {
4221                                 if (spi->sync_period != 0
4222                                  && (spi->sync_period < np->minsync))
4223                                         spi->sync_period = np->minsync;
4224                         }
4225                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0) {
4226                                 if (spi->sync_offset == 0)
4227                                         spi->sync_period = 0;
4228                                 if (spi->sync_offset > np->maxoffs)
4229                                         spi->sync_offset = np->maxoffs;
4230                         }
4231                 }
4232                 if ((update_type & NCR_TRANS_USER) != 0) {
4233                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4234                                 tp->tinfo.user.period = spi->sync_period;
4235                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)
4236                                 tp->tinfo.user.offset = spi->sync_offset;
4237                         if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
4238                                 tp->tinfo.user.width = spi->bus_width;
4239                 }
4240                 if ((update_type & NCR_TRANS_GOAL) != 0) {
4241                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4242                                 tp->tinfo.goal.period = spi->sync_period;
4243
4244                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)
4245                                 tp->tinfo.goal.offset = spi->sync_offset;
4246
4247                         if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
4248                                 tp->tinfo.goal.width = spi->bus_width;
4249                 }
4250                 ccb->ccb_h.status = CAM_REQ_CMP;
4251                 xpt_done(ccb);
4252                 break;
4253         }
4254         case XPT_GET_TRAN_SETTINGS:
4255         /* Get default/user set transfer settings for the target */
4256         {
4257                 struct  ccb_trans_settings *cts = &ccb->cts;
4258                 struct  ncr_transinfo *tinfo;
4259                 tcb_p   tp = &np->target[ccb->ccb_h.target_id];
4260                 struct ccb_trans_settings_scsi *scsi =
4261                     &cts->proto_specific.scsi;
4262                 struct ccb_trans_settings_spi *spi =
4263                     &cts->xport_specific.spi;
4264
4265                 cts->protocol = PROTO_SCSI;
4266                 cts->protocol_version = SCSI_REV_2;
4267                 cts->transport = XPORT_SPI;
4268                 cts->transport_version = 2;
4269
4270                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
4271                         tinfo = &tp->tinfo.current;
4272                         if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
4273                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
4274                         else
4275                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
4276
4277                         if (tp->tinfo.disc_tag & NCR_CUR_TAGENB)
4278                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
4279                         else
4280                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
4281                 } else {
4282                         tinfo = &tp->tinfo.user;
4283                         if (tp->tinfo.disc_tag & NCR_USR_DISCENB)
4284                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
4285                         else
4286                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
4287
4288                         if (tp->tinfo.disc_tag & NCR_USR_TAGENB)
4289                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
4290                         else
4291                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
4292                 }
4293
4294                 spi->sync_period = tinfo->period;
4295                 spi->sync_offset = tinfo->offset;
4296                 spi->bus_width = tinfo->width;
4297
4298                 spi->valid = CTS_SPI_VALID_SYNC_RATE
4299                            | CTS_SPI_VALID_SYNC_OFFSET
4300                            | CTS_SPI_VALID_BUS_WIDTH
4301                            | CTS_SPI_VALID_DISC;
4302                 scsi->valid = CTS_SCSI_VALID_TQ;
4303
4304                 ccb->ccb_h.status = CAM_REQ_CMP;
4305                 xpt_done(ccb);
4306                 break;
4307         }
4308         case XPT_CALC_GEOMETRY:
4309         {
4310                 /* XXX JGibbs - I'm sure the NCR uses a different strategy,
4311                  *              but it should be able to deal with Adaptec
4312                  *              geometry too.
4313                  */
4314                 cam_calc_geometry(&ccb->ccg, /*extended*/1);
4315                 xpt_done(ccb);
4316                 break;
4317         }
4318         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
4319         {
4320                 OUTB (nc_scntl1, CRST);
4321                 ccb->ccb_h.status = CAM_REQ_CMP;
4322                 DELAY(10000);   /* Wait until our interrupt handler sees it */ 
4323                 xpt_done(ccb);
4324                 break;
4325         }
4326         case XPT_TERM_IO:               /* Terminate the I/O process */
4327                 /* XXX Implement */
4328                 ccb->ccb_h.status = CAM_REQ_INVALID;
4329                 xpt_done(ccb);
4330                 break;
4331         case XPT_PATH_INQ:              /* Path routing inquiry */
4332         {
4333                 struct ccb_pathinq *cpi = &ccb->cpi;
4334                 
4335                 cpi->version_num = 1; /* XXX??? */
4336                 cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE;
4337                 if ((np->features & FE_WIDE) != 0)
4338                         cpi->hba_inquiry |= PI_WIDE_16;
4339                 cpi->target_sprt = 0;
4340                 cpi->hba_misc = 0;
4341                 cpi->hba_eng_cnt = 0;
4342                 cpi->max_target = (np->features & FE_WIDE) ? 15 : 7;
4343                 cpi->max_lun = MAX_LUN - 1;
4344                 cpi->initiator_id = np->myaddr;
4345                 cpi->bus_id = cam_sim_bus(sim);
4346                 cpi->base_transfer_speed = 3300;
4347                 strlcpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4348                 strlcpy(cpi->hba_vid, "Symbios", HBA_IDLEN);
4349                 strlcpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
4350                 cpi->unit_number = cam_sim_unit(sim);
4351                 cpi->transport = XPORT_SPI;
4352                 cpi->transport_version = 2;
4353                 cpi->protocol = PROTO_SCSI;
4354                 cpi->protocol_version = SCSI_REV_2;
4355                 cpi->ccb_h.status = CAM_REQ_CMP;
4356                 xpt_done(ccb);
4357                 break;
4358         }
4359         default:
4360                 ccb->ccb_h.status = CAM_REQ_INVALID;
4361                 xpt_done(ccb);
4362                 break;
4363         }
4364 }
4365
4366 /*==========================================================
4367 **
4368 **
4369 **      Complete execution of a SCSI command.
4370 **      Signal completion to the generic SCSI driver.
4371 **
4372 **
4373 **==========================================================
4374 */
4375
4376 static void
4377 ncr_complete (ncb_p np, nccb_p cp)
4378 {
4379         union ccb *ccb;
4380         tcb_p tp;
4381
4382         /*
4383         **      Sanity check
4384         */
4385
4386         if (!cp || (cp->magic!=CCB_MAGIC) || !cp->ccb) return;
4387         cp->magic = 1;
4388         cp->tlimit= 0;
4389
4390         /*
4391         **      No Reselect anymore.
4392         */
4393         cp->jump_nccb.l_cmd = (SCR_JUMP);
4394
4395         /*
4396         **      No starting.
4397         */
4398         cp->phys.header.launch.l_paddr= NCB_SCRIPT_PHYS (np, idle);
4399
4400         /*
4401         **      timestamp
4402         */
4403         ncb_profile (np, cp);
4404
4405         if (DEBUG_FLAGS & DEBUG_TINY)
4406                 printf ("CCB=%x STAT=%x/%x\n", (int)(intptr_t)cp & 0xfff,
4407                         cp->host_status,cp->s_status);
4408
4409         ccb = cp->ccb;
4410         cp->ccb = NULL;
4411         tp = &np->target[ccb->ccb_h.target_id];
4412
4413         /*
4414         **      We do not queue more than 1 nccb per target 
4415         **      with negotiation at any time. If this nccb was 
4416         **      used for negotiation, clear this info in the tcb.
4417         */
4418
4419         if (cp == tp->nego_cp)
4420                 tp->nego_cp = NULL;
4421
4422         /*
4423         **      Check for parity errors.
4424         */
4425         /* XXX JGibbs - What about reporting them??? */
4426
4427         if (cp->parity_status) {
4428                 PRINT_ADDR(ccb);
4429                 printf ("%d parity error(s), fallback.\n", cp->parity_status);
4430                 /*
4431                 **      fallback to asynch transfer.
4432                 */
4433                 tp->tinfo.goal.period = 0;
4434                 tp->tinfo.goal.offset = 0;
4435         }
4436
4437         /*
4438         **      Check for extended errors.
4439         */
4440
4441         if (cp->xerr_status != XE_OK) {
4442                 PRINT_ADDR(ccb);
4443                 switch (cp->xerr_status) {
4444                 case XE_EXTRA_DATA:
4445                         printf ("extraneous data discarded.\n");
4446                         break;
4447                 case XE_BAD_PHASE:
4448                         printf ("illegal scsi phase (4/5).\n");
4449                         break;
4450                 default:
4451                         printf ("extended error %d.\n", cp->xerr_status);
4452                         break;
4453                 }
4454                 if (cp->host_status==HS_COMPLETE)
4455                         cp->host_status = HS_FAIL;
4456         }
4457
4458         /*
4459         **      Check the status.
4460         */
4461         if (cp->host_status == HS_COMPLETE) {
4462
4463                 if (cp->s_status == SCSI_STATUS_OK) {
4464
4465                         /*
4466                         **      All went well.
4467                         */
4468                         /* XXX JGibbs - Properly calculate residual */
4469
4470                         tp->bytes     += ccb->csio.dxfer_len;
4471                         tp->transfers ++;
4472
4473                         ccb->ccb_h.status = CAM_REQ_CMP;
4474                 } else if ((cp->s_status & SCSI_STATUS_SENSE) != 0) {
4475
4476                         /*
4477                          * XXX Could be TERMIO too.  Should record
4478                          * original status.
4479                          */
4480                         ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
4481                         cp->s_status &= ~SCSI_STATUS_SENSE;
4482                         if (cp->s_status == SCSI_STATUS_OK) {
4483                                 ccb->ccb_h.status =
4484                                     CAM_AUTOSNS_VALID|CAM_SCSI_STATUS_ERROR;
4485                         } else {
4486                                 ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
4487                         }
4488                 } else {
4489                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;                      
4490                         ccb->csio.scsi_status = cp->s_status;
4491                 }
4492                 
4493                 
4494         } else if (cp->host_status == HS_SEL_TIMEOUT) {
4495
4496                 /*
4497                 **   Device failed selection
4498                 */
4499                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
4500
4501         } else if (cp->host_status == HS_TIMEOUT) {
4502
4503                 /*
4504                 **   No response
4505                 */
4506                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4507         } else if (cp->host_status == HS_STALL) {
4508                 ccb->ccb_h.status = CAM_REQUEUE_REQ;
4509         } else {
4510
4511                 /*
4512                 **  Other protocol messes
4513                 */
4514                 PRINT_ADDR(ccb);
4515                 printf ("COMMAND FAILED (%x %x) @%p.\n",
4516                         cp->host_status, cp->s_status, cp);
4517
4518                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4519         }
4520
4521         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4522                 xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
4523                 ccb->ccb_h.status |= CAM_DEV_QFRZN;
4524         }
4525
4526         /*
4527         **      Free this nccb
4528         */
4529         ncr_free_nccb (np, cp);
4530
4531         /*
4532         **      signal completion to generic driver.
4533         */
4534         xpt_done (ccb);
4535 }
4536
4537 /*==========================================================
4538 **
4539 **
4540 **      Signal all (or one) control block done.
4541 **
4542 **
4543 **==========================================================
4544 */
4545
4546 static void
4547 ncr_wakeup (ncb_p np, u_long code)
4548 {
4549         /*
4550         **      Starting at the default nccb and following
4551         **      the links, complete all jobs with a
4552         **      host_status greater than "disconnect".
4553         **
4554         **      If the "code" parameter is not zero,
4555         **      complete all jobs that are not IDLE.
4556         */
4557
4558         nccb_p cp = np->link_nccb;
4559         while (cp) {
4560                 switch (cp->host_status) {
4561
4562                 case HS_IDLE:
4563                         break;
4564
4565                 case HS_DISCONNECT:
4566                         if(DEBUG_FLAGS & DEBUG_TINY) printf ("D");
4567                         /* FALLTHROUGH */
4568
4569                 case HS_BUSY:
4570                 case HS_NEGOTIATE:
4571                         if (!code) break;
4572                         cp->host_status = code;
4573
4574                         /* FALLTHROUGH */
4575
4576                 default:
4577                         ncr_complete (np, cp);
4578                         break;
4579                 }
4580                 cp = cp -> link_nccb;
4581         }
4582 }
4583
4584 static void
4585 ncr_freeze_devq (ncb_p np, struct cam_path *path)
4586 {
4587         nccb_p  cp;
4588         int     i;
4589         int     count;
4590         int     firstskip;
4591         /*
4592         **      Starting at the first nccb and following
4593         **      the links, complete all jobs that match
4594         **      the passed in path and are in the start queue.
4595         */
4596
4597         cp = np->link_nccb;
4598         count = 0;
4599         firstskip = 0;
4600         while (cp) {
4601                 switch (cp->host_status) {
4602
4603                 case HS_BUSY:
4604                 case HS_NEGOTIATE:
4605                         if ((cp->phys.header.launch.l_paddr
4606                             == NCB_SCRIPT_PHYS (np, select))
4607                          && (xpt_path_comp(path, cp->ccb->ccb_h.path) >= 0)) {
4608
4609                                 /* Mark for removal from the start queue */
4610                                 for (i = 1; i < MAX_START; i++) {
4611                                         int idx;
4612
4613                                         idx = np->squeueput - i;
4614                                 
4615                                         if (idx < 0)
4616                                                 idx = MAX_START + idx;
4617                                         if (np->squeue[idx]
4618                                          == CCB_PHYS(cp, phys)) {
4619                                                 np->squeue[idx] =
4620                                                     NCB_SCRIPT_PHYS (np, skip);
4621                                                 if (i > firstskip)
4622                                                         firstskip = i;
4623                                                 break;
4624                                         }
4625                                 }
4626                                 cp->host_status=HS_STALL;
4627                                 ncr_complete (np, cp);
4628                                 count++;
4629                         }
4630                         break;
4631                 default:
4632                         break;
4633                 }
4634                 cp = cp->link_nccb;
4635         }
4636
4637         if (count > 0) {
4638                 int j;
4639                 int bidx;
4640
4641                 /* Compress the start queue */
4642                 j = 0;
4643                 bidx = np->squeueput;
4644                 i = np->squeueput - firstskip;
4645                 if (i < 0)
4646                         i = MAX_START + i;
4647                 for (;;) {
4648
4649                         bidx = i - j;
4650                         if (bidx < 0)
4651                                 bidx = MAX_START + bidx;
4652                         
4653                         if (np->squeue[i] == NCB_SCRIPT_PHYS (np, skip)) {
4654                                 j++;
4655                         } else if (j != 0) {
4656                                 np->squeue[bidx] = np->squeue[i];
4657                                 if (np->squeue[bidx]
4658                                  == NCB_SCRIPT_PHYS(np, idle))
4659                                         break;
4660                         }
4661                         i = (i + 1) % MAX_START;
4662                 }
4663                 np->squeueput = bidx;
4664         }
4665 }
4666
4667 /*==========================================================
4668 **
4669 **
4670 **      Start NCR chip.
4671 **
4672 **
4673 **==========================================================
4674 */
4675
4676 static void
4677 ncr_init(ncb_p np, char * msg, u_long code)
4678 {
4679         int     i;
4680
4681         /*
4682         **      Reset chip.
4683         */
4684
4685         OUTB (nc_istat,  SRST);
4686         DELAY (1000);
4687         OUTB (nc_istat, 0);
4688
4689         /*
4690         **      Message.
4691         */
4692
4693         if (msg)
4694                 device_printf(np->dev, "restart (%s).\n", msg);
4695
4696         /*
4697         **      Clear Start Queue
4698         */
4699
4700         for (i=0;i<MAX_START;i++)
4701                 np -> squeue [i] = NCB_SCRIPT_PHYS (np, idle);
4702
4703         /*
4704         **      Start at first entry.
4705         */
4706
4707         np->squeueput = 0;
4708         WRITESCRIPT(startpos[0], NCB_SCRIPTH_PHYS (np, tryloop));
4709         WRITESCRIPT(start0  [0], SCR_INT ^ IFFALSE (0));
4710
4711         /*
4712         **      Wakeup all pending jobs.
4713         */
4714
4715         ncr_wakeup (np, code);
4716
4717         /*
4718         **      Init chip.
4719         */
4720
4721         OUTB (nc_istat,  0x00   );      /*  Remove Reset, abort ...          */
4722         OUTB (nc_scntl0, 0xca   );      /*  full arb., ena parity, par->ATN  */
4723         OUTB (nc_scntl1, 0x00   );      /*  odd parity, and remove CRST!!    */
4724         ncr_selectclock(np, np->rv_scntl3); /* Select SCSI clock             */
4725         OUTB (nc_scid  , RRE|np->myaddr);/*  host adapter SCSI address       */
4726         OUTW (nc_respid, 1ul<<np->myaddr);/*  id to respond to               */
4727         OUTB (nc_istat , SIGP   );      /*  Signal Process                   */
4728         OUTB (nc_dmode , np->rv_dmode); /* XXX modify burstlen ??? */
4729         OUTB (nc_dcntl , np->rv_dcntl);
4730         OUTB (nc_ctest3, np->rv_ctest3);
4731         OUTB (nc_ctest5, np->rv_ctest5);
4732         OUTB (nc_ctest4, np->rv_ctest4);/*  enable master parity checking    */
4733         OUTB (nc_stest2, np->rv_stest2|EXT); /* Extended Sreq/Sack filtering */
4734         OUTB (nc_stest3, TE     );      /*  TolerANT enable                  */
4735         OUTB (nc_stime0, 0x0b   );      /*  HTH = disabled, STO = 0.1 sec.   */
4736
4737         if (bootverbose >= 2) {
4738                 printf ("\tACTUAL values:SCNTL3:%02x DMODE:%02x  DCNTL:%02x\n",
4739                         np->rv_scntl3, np->rv_dmode, np->rv_dcntl);
4740                 printf ("\t              CTEST3:%02x CTEST4:%02x CTEST5:%02x\n",
4741                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4742         }
4743
4744         /*
4745         **    Enable GPIO0 pin for writing if LED support.
4746         */
4747
4748         if (np->features & FE_LED0) {
4749                 OUTOFFB (nc_gpcntl, 0x01);
4750         }
4751
4752         /*
4753         **      Fill in target structure.
4754         */
4755         for (i=0;i<MAX_TARGET;i++) {
4756                 tcb_p tp = &np->target[i];
4757
4758                 tp->tinfo.sval    = 0;
4759                 tp->tinfo.wval    = np->rv_scntl3;
4760
4761                 tp->tinfo.current.period = 0;
4762                 tp->tinfo.current.offset = 0;
4763                 tp->tinfo.current.width = MSG_EXT_WDTR_BUS_8_BIT;
4764         }
4765
4766         /*
4767         **      enable ints
4768         */
4769
4770         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST);
4771         OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
4772
4773         /*
4774         **    Start script processor.
4775         */
4776
4777         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
4778
4779         /*
4780          * Notify the XPT of the event
4781          */
4782         if (code == HS_RESET)
4783                 xpt_async(AC_BUS_RESET, np->path, NULL);
4784 }
4785
4786 static void
4787 ncr_poll(struct cam_sim *sim)
4788 {       
4789         ncr_intr_locked(cam_sim_softc(sim));  
4790 }
4791
4792
4793 /*==========================================================
4794 **
4795 **      Get clock factor and sync divisor for a given 
4796 **      synchronous factor period.
4797 **      Returns the clock factor (in sxfer) and scntl3 
4798 **      synchronous divisor field.
4799 **
4800 **==========================================================
4801 */
4802
4803 static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
4804 {
4805         u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
4806         int     div = np->clock_divn;   /* Number of divisors supported */
4807         u_long  fak;                    /* Sync factor in sxfer         */
4808         u_long  per;                    /* Period in tenths of ns       */
4809         u_long  kpc;                    /* (per * clk)                  */
4810
4811         /*
4812         **      Compute the synchronous period in tenths of nano-seconds
4813         */
4814         if      (sfac <= 10)    per = 250;
4815         else if (sfac == 11)    per = 303;
4816         else if (sfac == 12)    per = 500;
4817         else                    per = 40 * sfac;
4818
4819         /*
4820         **      Look for the greatest clock divisor that allows an 
4821         **      input speed faster than the period.
4822         */
4823         kpc = per * clk;
4824         while (--div >= 0)
4825                 if (kpc >= (div_10M[div] * 4)) break;
4826
4827         /*
4828         **      Calculate the lowest clock factor that allows an output 
4829         **      speed not faster than the period.
4830         */
4831         fak = (kpc - 1) / div_10M[div] + 1;
4832
4833 #if 0   /* You can #if 1 if you think this optimization is useful */
4834
4835         per = (fak * div_10M[div]) / clk;
4836
4837         /*
4838         **      Why not to try the immediate lower divisor and to choose 
4839         **      the one that allows the fastest output speed ?
4840         **      We dont want input speed too much greater than output speed.
4841         */
4842         if (div >= 1 && fak < 6) {
4843                 u_long fak2, per2;
4844                 fak2 = (kpc - 1) / div_10M[div-1] + 1;
4845                 per2 = (fak2 * div_10M[div-1]) / clk;
4846                 if (per2 < per && fak2 <= 6) {
4847                         fak = fak2;
4848                         per = per2;
4849                         --div;
4850                 }
4851         }
4852 #endif
4853
4854         if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
4855
4856         /*
4857         **      Compute and return sync parameters for the ncr
4858         */
4859         *fakp           = fak - 4;
4860         *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
4861 }
4862
4863 /*==========================================================
4864 **
4865 **      Switch sync mode for current job and its target
4866 **
4867 **==========================================================
4868 */
4869
4870 static void
4871 ncr_setsync(ncb_p np, nccb_p cp, u_char scntl3, u_char sxfer, u_char period)
4872 {
4873         union   ccb *ccb;
4874         struct  ccb_trans_settings neg; 
4875         tcb_p   tp;
4876         int     div;
4877         u_int   target = INB (nc_sdid) & 0x0f;
4878         u_int   period_10ns;
4879
4880         assert (cp);
4881         if (!cp) return;
4882
4883         ccb = cp->ccb;
4884         assert (ccb);
4885         if (!ccb) return;
4886         assert (target == ccb->ccb_h.target_id);
4887
4888         tp = &np->target[target];
4889
4890         if (!scntl3 || !(sxfer & 0x1f))
4891                 scntl3 = np->rv_scntl3;
4892         scntl3 = (scntl3 & 0xf0) | (tp->tinfo.wval & EWS)
4893                | (np->rv_scntl3 & 0x07);
4894
4895         /*
4896         **      Deduce the value of controller sync period from scntl3.
4897         **      period is in tenths of nano-seconds.
4898         */
4899
4900         div = ((scntl3 >> 4) & 0x7);
4901         if ((sxfer & 0x1f) && div)
4902                 period_10ns =
4903                     (((sxfer>>5)+4)*div_10M[div-1])/np->clock_khz;
4904         else
4905                 period_10ns = 0;
4906
4907         tp->tinfo.goal.period = period;
4908         tp->tinfo.goal.offset = sxfer & 0x1f;
4909         tp->tinfo.current.period = period;
4910         tp->tinfo.current.offset = sxfer & 0x1f;
4911
4912         /*
4913         **       Stop there if sync parameters are unchanged
4914         */
4915         if (tp->tinfo.sval == sxfer && tp->tinfo.wval == scntl3) return;
4916         tp->tinfo.sval = sxfer;
4917         tp->tinfo.wval = scntl3;
4918
4919         if (sxfer & 0x1f) {
4920                 /*
4921                 **  Disable extended Sreq/Sack filtering
4922                 */
4923                 if (period_10ns <= 2000) OUTOFFB (nc_stest2, EXT);
4924         }
4925
4926         /*
4927         ** Tell the SCSI layer about the
4928         ** new transfer parameters.
4929         */
4930         memset(&neg, 0, sizeof (neg));
4931         neg.protocol = PROTO_SCSI;
4932         neg.protocol_version = SCSI_REV_2;
4933         neg.transport = XPORT_SPI;
4934         neg.transport_version = 2;
4935         neg.xport_specific.spi.sync_period = period;
4936         neg.xport_specific.spi.sync_offset = sxfer & 0x1f;
4937         neg.xport_specific.spi.valid = CTS_SPI_VALID_SYNC_RATE
4938                 | CTS_SPI_VALID_SYNC_OFFSET;
4939         xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path,
4940                       /*priority*/1);
4941         xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
4942         
4943         /*
4944         **      set actual value and sync_status
4945         */
4946         OUTB (nc_sxfer, sxfer);
4947         np->sync_st = sxfer;
4948         OUTB (nc_scntl3, scntl3);
4949         np->wide_st = scntl3;
4950
4951         /*
4952         **      patch ALL nccbs of this target.
4953         */
4954         for (cp = np->link_nccb; cp; cp = cp->link_nccb) {
4955                 if (!cp->ccb) continue;
4956                 if (cp->ccb->ccb_h.target_id != target) continue;
4957                 cp->sync_status = sxfer;
4958                 cp->wide_status = scntl3;
4959         }
4960 }
4961
4962 /*==========================================================
4963 **
4964 **      Switch wide mode for current job and its target
4965 **      SCSI specs say: a SCSI device that accepts a WDTR 
4966 **      message shall reset the synchronous agreement to 
4967 **      asynchronous mode.
4968 **
4969 **==========================================================
4970 */
4971
4972 static void ncr_setwide (ncb_p np, nccb_p cp, u_char wide, u_char ack)
4973 {
4974         union   ccb *ccb;
4975         struct  ccb_trans_settings neg;         
4976         u_int   target = INB (nc_sdid) & 0x0f;
4977         tcb_p   tp;
4978         u_char  scntl3;
4979         u_char  sxfer;
4980
4981         assert (cp);
4982         if (!cp) return;
4983
4984         ccb = cp->ccb;
4985         assert (ccb);
4986         if (!ccb) return;
4987         assert (target == ccb->ccb_h.target_id);
4988
4989         tp = &np->target[target];
4990         tp->tinfo.current.width = wide;
4991         tp->tinfo.goal.width = wide;
4992         tp->tinfo.current.period = 0;
4993         tp->tinfo.current.offset = 0;
4994
4995         scntl3 = (tp->tinfo.wval & (~EWS)) | (wide ? EWS : 0);
4996
4997         sxfer = ack ? 0 : tp->tinfo.sval;
4998
4999         /*
5000         **       Stop there if sync/wide parameters are unchanged
5001         */
5002         if (tp->tinfo.sval == sxfer && tp->tinfo.wval == scntl3) return;
5003         tp->tinfo.sval = sxfer;
5004         tp->tinfo.wval = scntl3;
5005
5006         /* Tell the SCSI layer about the new transfer params */
5007         memset(&neg, 0, sizeof (neg));
5008         neg.protocol = PROTO_SCSI;
5009         neg.protocol_version = SCSI_REV_2;
5010         neg.transport = XPORT_SPI;
5011         neg.transport_version = 2;
5012         neg.xport_specific.spi.bus_width = (scntl3 & EWS) ?
5013             MSG_EXT_WDTR_BUS_16_BIT : MSG_EXT_WDTR_BUS_8_BIT;
5014         neg.xport_specific.spi.sync_period = 0;
5015         neg.xport_specific.spi.sync_offset = 0;
5016         neg.xport_specific.spi.valid = CTS_SPI_VALID_SYNC_RATE
5017                 | CTS_SPI_VALID_SYNC_OFFSET
5018                 | CTS_SPI_VALID_BUS_WIDTH;
5019         xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path, /*priority*/1);
5020         xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);      
5021
5022         /*
5023         **      set actual value and sync_status
5024         */
5025         OUTB (nc_sxfer, sxfer);
5026         np->sync_st = sxfer;
5027         OUTB (nc_scntl3, scntl3);
5028         np->wide_st = scntl3;
5029
5030         /*
5031         **      patch ALL nccbs of this target.
5032         */
5033         for (cp = np->link_nccb; cp; cp = cp->link_nccb) {
5034                 if (!cp->ccb) continue;
5035                 if (cp->ccb->ccb_h.target_id != target) continue;
5036                 cp->sync_status = sxfer;
5037                 cp->wide_status = scntl3;
5038         }
5039 }
5040
5041 /*==========================================================
5042 **
5043 **
5044 **      ncr timeout handler.
5045 **
5046 **
5047 **==========================================================
5048 **
5049 **      Misused to keep the driver running when
5050 **      interrupts are not configured correctly.
5051 **
5052 **----------------------------------------------------------
5053 */
5054
5055 static void
5056 ncr_timeout (void *arg)
5057 {
5058         ncb_p   np = arg;
5059         time_t  thistime = time_second;
5060         ticks_t step  = np->ticks;
5061         u_long  count = 0;
5062         long signed   t;
5063         nccb_p cp;
5064
5065         mtx_assert(&np->lock, MA_OWNED);
5066         if (np->lasttime != thistime) {
5067                 np->lasttime = thistime;
5068
5069                 /*----------------------------------------------------
5070                 **
5071                 **      handle ncr chip timeouts
5072                 **
5073                 **      Assumption:
5074                 **      We have a chance to arbitrate for the
5075                 **      SCSI bus at least every 10 seconds.
5076                 **
5077                 **----------------------------------------------------
5078                 */
5079
5080                 t = thistime - np->heartbeat;
5081
5082                 if (t<2) np->latetime=0; else np->latetime++;
5083
5084                 if (np->latetime>2) {
5085                         /*
5086                         **      If there are no requests, the script
5087                         **      processor will sleep on SEL_WAIT_RESEL.
5088                         **      But we have to check whether it died.
5089                         **      Let's try to wake it up.
5090                         */
5091                         OUTB (nc_istat, SIGP);
5092                 }
5093
5094                 /*----------------------------------------------------
5095                 **
5096                 **      handle nccb timeouts
5097                 **
5098                 **----------------------------------------------------
5099                 */
5100
5101                 for (cp=np->link_nccb; cp; cp=cp->link_nccb) {
5102                         /*
5103                         **      look for timed out nccbs.
5104                         */
5105                         if (!cp->host_status) continue;
5106                         count++;
5107                         if (cp->tlimit > thistime) continue;
5108
5109                         /*
5110                         **      Disable reselect.
5111                         **      Remove it from startqueue.
5112                         */
5113                         cp->jump_nccb.l_cmd = (SCR_JUMP);
5114                         if (cp->phys.header.launch.l_paddr ==
5115                                 NCB_SCRIPT_PHYS (np, select)) {
5116                                 device_printf(np->dev,
5117                                     "timeout nccb=%p (skip)\n", cp);
5118                                 cp->phys.header.launch.l_paddr
5119                                 = NCB_SCRIPT_PHYS (np, skip);
5120                         }
5121
5122                         switch (cp->host_status) {
5123
5124                         case HS_BUSY:
5125                         case HS_NEGOTIATE:
5126                                 /* FALLTHROUGH */
5127                         case HS_DISCONNECT:
5128                                 cp->host_status=HS_TIMEOUT;
5129                         }
5130                         cp->tag = 0;
5131
5132                         /*
5133                         **      wakeup this nccb.
5134                         */
5135                         ncr_complete (np, cp);
5136                 }
5137         }
5138
5139         callout_reset(&np->timer, step ? step : 1, ncr_timeout, np);
5140
5141         if (INB(nc_istat) & (INTF|SIP|DIP)) {
5142
5143                 /*
5144                 **      Process pending interrupts.
5145                 */
5146
5147                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("{");
5148                 ncr_exception (np);
5149                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("}");
5150         }
5151 }
5152
5153 /*==========================================================
5154 **
5155 **      log message for real hard errors
5156 **
5157 **      "ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
5158 **      "             reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
5159 **
5160 **      exception register:
5161 **              ds:     dstat
5162 **              si:     sist
5163 **
5164 **      SCSI bus lines:
5165 **              so:     control lines as driver by NCR.
5166 **              si:     control lines as seen by NCR.
5167 **              sd:     scsi data lines as seen by NCR.
5168 **
5169 **      wide/fastmode:
5170 **              sxfer:  (see the manual)
5171 **              scntl3: (see the manual)
5172 **
5173 **      current script command:
5174 **              dsp:    script address (relative to start of script).
5175 **              dbc:    first word of script command.
5176 **
5177 **      First 16 register of the chip:
5178 **              r0..rf
5179 **
5180 **==========================================================
5181 */
5182
5183 static void ncr_log_hard_error(ncb_p np, u_short sist, u_char dstat)
5184 {
5185         u_int32_t dsp;
5186         int     script_ofs;
5187         int     script_size;
5188         char    *script_name;
5189         u_char  *script_base;
5190         int     i;
5191
5192         dsp     = INL (nc_dsp);
5193
5194         if (np->p_script < dsp && 
5195             dsp <= np->p_script + sizeof(struct script)) {
5196                 script_ofs      = dsp - np->p_script;
5197                 script_size     = sizeof(struct script);
5198                 script_base     = (u_char *) np->script;
5199                 script_name     = "script";
5200         }
5201         else if (np->p_scripth < dsp && 
5202                  dsp <= np->p_scripth + sizeof(struct scripth)) {
5203                 script_ofs      = dsp - np->p_scripth;
5204                 script_size     = sizeof(struct scripth);
5205                 script_base     = (u_char *) np->scripth;
5206                 script_name     = "scripth";
5207         } else {
5208                 script_ofs      = dsp;
5209                 script_size     = 0;
5210                 script_base     = NULL;
5211                 script_name     = "mem";
5212         }
5213
5214         device_printf(np->dev,
5215                 "%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
5216                 (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
5217                 (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
5218                 (unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
5219                 (unsigned)INL (nc_dbc));
5220
5221         if (((script_ofs & 3) == 0) &&
5222             (unsigned)script_ofs < script_size) {
5223                 device_printf(np->dev, "script cmd = %08x\n",
5224                         (int)READSCRIPT_OFF(script_base, script_ofs));
5225         }
5226
5227         device_printf(np->dev, "regdump:");
5228         for (i=0; i<16;i++)
5229             printf (" %02x", (unsigned)INB_OFF(i));
5230         printf (".\n");
5231 }
5232
5233 /*==========================================================
5234 **
5235 **
5236 **      ncr chip exception handler.
5237 **
5238 **
5239 **==========================================================
5240 */
5241
5242 static void ncr_exception (ncb_p np)
5243 {
5244         u_char  istat, dstat;
5245         u_short sist;
5246
5247         /*
5248         **      interrupt on the fly ?
5249         */
5250         while ((istat = INB (nc_istat)) & INTF) {
5251                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
5252                 OUTB (nc_istat, INTF);
5253                 np->profile.num_fly++;
5254                 ncr_wakeup (np, 0);
5255         }
5256         if (!(istat & (SIP|DIP))) {
5257                 return;
5258         }
5259
5260         /*
5261         **      Steinbach's Guideline for Systems Programming:
5262         **      Never test for an error condition you don't know how to handle.
5263         */
5264
5265         sist  = (istat & SIP) ? INW (nc_sist)  : 0;
5266         dstat = (istat & DIP) ? INB (nc_dstat) : 0;
5267         np->profile.num_int++;
5268
5269         if (DEBUG_FLAGS & DEBUG_TINY)
5270                 printf ("<%d|%x:%x|%x:%x>",
5271                         INB(nc_scr0),
5272                         dstat,sist,
5273                         (unsigned)INL(nc_dsp),
5274                         (unsigned)INL(nc_dbc));
5275         if ((dstat==DFE) && (sist==PAR)) return;
5276
5277 /*==========================================================
5278 **
5279 **      First the normal cases.
5280 **
5281 **==========================================================
5282 */
5283         /*-------------------------------------------
5284         **      SCSI reset
5285         **-------------------------------------------
5286         */
5287
5288         if (sist & RST) {
5289                 ncr_init (np, bootverbose ? "scsi reset" : NULL, HS_RESET);
5290                 return;
5291         }
5292
5293         /*-------------------------------------------
5294         **      selection timeout
5295         **
5296         **      IID excluded from dstat mask!
5297         **      (chip bug)
5298         **-------------------------------------------
5299         */
5300
5301         if ((sist  & STO) &&
5302                 !(sist  & (GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5303                 !(dstat & (MDPE|BF|ABRT|SIR))) {
5304                 ncr_int_sto (np);
5305                 return;
5306         }
5307
5308         /*-------------------------------------------
5309         **      Phase mismatch.
5310         **-------------------------------------------
5311         */
5312
5313         if ((sist  & MA) &&
5314                 !(sist  & (STO|GEN|HTH|SGE|UDC|RST|PAR)) &&
5315                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5316                 ncr_int_ma (np, dstat);
5317                 return;
5318         }
5319
5320         /*----------------------------------------
5321         **      move command with length 0
5322         **----------------------------------------
5323         */
5324
5325         if ((dstat & IID) &&
5326                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5327                 !(dstat & (MDPE|BF|ABRT|SIR)) &&
5328                 ((INL(nc_dbc) & 0xf8000000) == SCR_MOVE_TBL)) {
5329                 /*
5330                 **      Target wants more data than available.
5331                 **      The "no_data" script will do it.
5332                 */
5333                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, no_data));
5334                 return;
5335         }
5336
5337         /*-------------------------------------------
5338         **      Programmed interrupt
5339         **-------------------------------------------
5340         */
5341
5342         if ((dstat & SIR) &&
5343                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5344                 !(dstat & (MDPE|BF|ABRT|IID)) &&
5345                 (INB(nc_dsps) <= SIR_MAX)) {
5346                 ncr_int_sir (np);
5347                 return;
5348         }
5349
5350         /*========================================
5351         **      log message for real hard errors
5352         **========================================
5353         */
5354
5355         ncr_log_hard_error(np, sist, dstat);
5356
5357         /*========================================
5358         **      do the register dump
5359         **========================================
5360         */
5361
5362         if (time_second - np->regtime > 10) {
5363                 int i;
5364                 np->regtime = time_second;
5365                 for (i=0; i<sizeof(np->regdump); i++)
5366                         ((volatile char*)&np->regdump)[i] = INB_OFF(i);
5367                 np->regdump.nc_dstat = dstat;
5368                 np->regdump.nc_sist  = sist;
5369         }
5370
5371
5372         /*----------------------------------------
5373         **      clean up the dma fifo
5374         **----------------------------------------
5375         */
5376
5377         if ( (INB(nc_sstat0) & (ILF|ORF|OLF)   ) ||
5378              (INB(nc_sstat1) & (FF3210) ) ||
5379              (INB(nc_sstat2) & (ILF1|ORF1|OLF1)) ||     /* wide .. */
5380              !(dstat & DFE)) {
5381                 device_printf(np->dev, "have to clear fifos.\n");
5382                 OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
5383                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);
5384                                                 /* clear dma fifo  */
5385         }
5386
5387         /*----------------------------------------
5388         **      handshake timeout
5389         **----------------------------------------
5390         */
5391
5392         if (sist & HTH) {
5393                 device_printf(np->dev, "handshake timeout\n");
5394                 OUTB (nc_scntl1, CRST);
5395                 DELAY (1000);
5396                 OUTB (nc_scntl1, 0x00);
5397                 OUTB (nc_scr0, HS_FAIL);
5398                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5399                 return;
5400         }
5401
5402         /*----------------------------------------
5403         **      unexpected disconnect
5404         **----------------------------------------
5405         */
5406
5407         if ((sist  & UDC) &&
5408                 !(sist  & (STO|GEN|HTH|MA|SGE|RST|PAR)) &&
5409                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5410                 OUTB (nc_scr0, HS_UNEXPECTED);
5411                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5412                 return;
5413         }
5414
5415         /*----------------------------------------
5416         **      cannot disconnect
5417         **----------------------------------------
5418         */
5419
5420         if ((dstat & IID) &&
5421                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5422                 !(dstat & (MDPE|BF|ABRT|SIR)) &&
5423                 ((INL(nc_dbc) & 0xf8000000) == SCR_WAIT_DISC)) {
5424                 /*
5425                 **      Unexpected data cycle while waiting for disconnect.
5426                 */
5427                 if (INB(nc_sstat2) & LDSC) {
5428                         /*
5429                         **      It's an early reconnect.
5430                         **      Let's continue ...
5431                         */
5432                         OUTB (nc_dcntl, np->rv_dcntl | STD);
5433                         /*
5434                         **      info message
5435                         */
5436                         device_printf(np->dev, "INFO: LDSC while IID.\n");
5437                         return;
5438                 }
5439                 device_printf(np->dev, "target %d doesn't release the bus.\n",
5440                         INB (nc_sdid)&0x0f);
5441                 /*
5442                 **      return without restarting the NCR.
5443                 **      timeout will do the real work.
5444                 */
5445                 return;
5446         }
5447
5448         /*----------------------------------------
5449         **      single step
5450         **----------------------------------------
5451         */
5452
5453         if ((dstat & SSI) &&
5454                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5455                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5456                 OUTB (nc_dcntl, np->rv_dcntl | STD);
5457                 return;
5458         }
5459
5460 /*
5461 **      @RECOVER@ HTH, SGE, ABRT.
5462 **
5463 **      We should try to recover from these interrupts.
5464 **      They may occur if there are problems with synch transfers, or 
5465 **      if targets are switched on or off while the driver is running.
5466 */
5467
5468         if (sist & SGE) {
5469                 /* clear scsi offsets */
5470                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);
5471         }
5472
5473         /*
5474         **      Freeze controller to be able to read the messages.
5475         */
5476
5477         if (DEBUG_FLAGS & DEBUG_FREEZE) {
5478                 int i;
5479                 unsigned char val;
5480                 for (i=0; i<0x60; i++) {
5481                         switch (i%16) {
5482
5483                         case 0:
5484                                 device_printf(np->dev, "reg[%d0]: ", i / 16);
5485                                 break;
5486                         case 4:
5487                         case 8:
5488                         case 12:
5489                                 printf (" ");
5490                                 break;
5491                         }
5492                         val = bus_read_1(np->reg_res, i);
5493                         printf (" %x%x", val/16, val%16);
5494                         if (i%16==15) printf (".\n");
5495                 }
5496
5497                 callout_stop(&np->timer);
5498
5499                 device_printf(np->dev, "halted!\n");
5500                 /*
5501                 **      don't restart controller ...
5502                 */
5503                 OUTB (nc_istat,  SRST);
5504                 return;
5505         }
5506
5507 #ifdef NCR_FREEZE
5508         /*
5509         **      Freeze system to be able to read the messages.
5510         */
5511         printf ("ncr: fatal error: system halted - press reset to reboot ...");
5512         for (;;);
5513 #endif
5514
5515         /*
5516         **      sorry, have to kill ALL jobs ...
5517         */
5518
5519         ncr_init (np, "fatal error", HS_FAIL);
5520 }
5521
5522 /*==========================================================
5523 **
5524 **      ncr chip exception handler for selection timeout
5525 **
5526 **==========================================================
5527 **
5528 **      There seems to be a bug in the 53c810.
5529 **      Although a STO-Interrupt is pending,
5530 **      it continues executing script commands.
5531 **      But it will fail and interrupt (IID) on
5532 **      the next instruction where it's looking
5533 **      for a valid phase.
5534 **
5535 **----------------------------------------------------------
5536 */
5537
5538 static void ncr_int_sto (ncb_p np)
5539 {
5540         u_long dsa, scratcha, diff;
5541         nccb_p cp;
5542         if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
5543
5544         /*
5545         **      look for nccb and set the status.
5546         */
5547
5548         dsa = INL (nc_dsa);
5549         cp = np->link_nccb;
5550         while (cp && (CCB_PHYS (cp, phys) != dsa))
5551                 cp = cp->link_nccb;
5552
5553         if (cp) {
5554                 cp-> host_status = HS_SEL_TIMEOUT;
5555                 ncr_complete (np, cp);
5556         }
5557
5558         /*
5559         **      repair start queue
5560         */
5561
5562         scratcha = INL (nc_scratcha);
5563         diff = scratcha - NCB_SCRIPTH_PHYS (np, tryloop);
5564
5565 /*      assert ((diff <= MAX_START * 20) && !(diff % 20));*/
5566
5567         if ((diff <= MAX_START * 20) && !(diff % 20)) {
5568                 WRITESCRIPT(startpos[0], scratcha);
5569                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
5570                 return;
5571         }
5572         ncr_init (np, "selection timeout", HS_FAIL);
5573 }
5574
5575 /*==========================================================
5576 **
5577 **
5578 **      ncr chip exception handler for phase errors.
5579 **
5580 **
5581 **==========================================================
5582 **
5583 **      We have to construct a new transfer descriptor,
5584 **      to transfer the rest of the current block.
5585 **
5586 **----------------------------------------------------------
5587 */
5588
5589 static void ncr_int_ma (ncb_p np, u_char dstat)
5590 {
5591         u_int32_t       dbc;
5592         u_int32_t       rest;
5593         u_int32_t       dsa;
5594         u_int32_t       dsp;
5595         u_int32_t       nxtdsp;
5596         volatile void   *vdsp_base;
5597         size_t          vdsp_off;
5598         u_int32_t       oadr, olen;
5599         u_int32_t       *tblp, *newcmd;
5600         u_char  cmd, sbcl, ss0, ss2, ctest5;
5601         u_short delta;
5602         nccb_p  cp;
5603
5604         dsp = INL (nc_dsp);
5605         dsa = INL (nc_dsa);
5606         dbc = INL (nc_dbc);
5607         ss0 = INB (nc_sstat0);
5608         ss2 = INB (nc_sstat2);
5609         sbcl= INB (nc_sbcl);
5610
5611         cmd = dbc >> 24;
5612         rest= dbc & 0xffffff;
5613
5614         ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
5615         if (ctest5 & DFS)
5616                 delta=(((ctest5<<8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
5617         else
5618                 delta=(INB (nc_dfifo) - rest) & 0x7f;
5619
5620
5621         /*
5622         **      The data in the dma fifo has not been transferred to
5623         **      the target -> add the amount to the rest
5624         **      and clear the data.
5625         **      Check the sstat2 register in case of wide transfer.
5626         */
5627
5628         if (!(dstat & DFE)) rest += delta;
5629         if (ss0 & OLF) rest++;
5630         if (ss0 & ORF) rest++;
5631         if (INB(nc_scntl3) & EWS) {
5632                 if (ss2 & OLF1) rest++;
5633                 if (ss2 & ORF1) rest++;
5634         }
5635         OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
5636         OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
5637
5638         /*
5639         **      locate matching cp
5640         */
5641         cp = np->link_nccb;
5642         while (cp && (CCB_PHYS (cp, phys) != dsa))
5643                 cp = cp->link_nccb;
5644
5645         if (!cp) {
5646                 device_printf(np->dev,
5647                     "SCSI phase error fixup: CCB already dequeued (%p)\n", 
5648                     (void *)np->header.cp);
5649                 return;
5650         }
5651         if (cp != np->header.cp) {
5652                 device_printf(np->dev,
5653                     "SCSI phase error fixup: CCB address mismatch "
5654                     "(%p != %p) np->nccb = %p\n", 
5655                     (void *)cp, (void *)np->header.cp,
5656                     (void *)np->link_nccb);
5657 /*          return;*/
5658         }
5659
5660         /*
5661         **      find the interrupted script command,
5662         **      and the address at which to continue.
5663         */
5664
5665         if (dsp == vtophys (&cp->patch[2])) {
5666                 vdsp_base = cp;
5667                 vdsp_off = offsetof(struct nccb, patch[0]);
5668                 nxtdsp = READSCRIPT_OFF(vdsp_base, vdsp_off + 3*4);
5669         } else if (dsp == vtophys (&cp->patch[6])) {
5670                 vdsp_base = cp;
5671                 vdsp_off = offsetof(struct nccb, patch[4]);
5672                 nxtdsp = READSCRIPT_OFF(vdsp_base, vdsp_off + 3*4);
5673         } else if (dsp > np->p_script &&
5674                    dsp <= np->p_script + sizeof(struct script)) {
5675                 vdsp_base = np->script;
5676                 vdsp_off = dsp - np->p_script - 8;
5677                 nxtdsp = dsp;
5678         } else {
5679                 vdsp_base = np->scripth;
5680                 vdsp_off = dsp - np->p_scripth - 8;
5681                 nxtdsp = dsp;
5682         }
5683
5684         /*
5685         **      log the information
5686         */
5687         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE)) {
5688                 printf ("P%x%x ",cmd&7, sbcl&7);
5689                 printf ("RL=%d D=%d SS0=%x ",
5690                         (unsigned) rest, (unsigned) delta, ss0);
5691         }
5692         if (DEBUG_FLAGS & DEBUG_PHASE) {
5693                 printf ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
5694                         cp, np->header.cp,
5695                         dsp,
5696                         nxtdsp, (volatile char*)vdsp_base+vdsp_off, cmd);
5697         }
5698
5699         /*
5700         **      get old startaddress and old length.
5701         */
5702
5703         oadr = READSCRIPT_OFF(vdsp_base, vdsp_off + 1*4);
5704
5705         if (cmd & 0x10) {       /* Table indirect */
5706                 tblp = (u_int32_t *) ((char*) &cp->phys + oadr);
5707                 olen = tblp[0];
5708                 oadr = tblp[1];
5709         } else {
5710                 tblp = (u_int32_t *) 0;
5711                 olen = READSCRIPT_OFF(vdsp_base, vdsp_off) & 0xffffff;
5712         }
5713
5714         if (DEBUG_FLAGS & DEBUG_PHASE) {
5715                 printf ("OCMD=%x\nTBLP=%p OLEN=%lx OADR=%lx\n",
5716                         (unsigned) (READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24),
5717                         (void *) tblp,
5718                         (u_long) olen,
5719                         (u_long) oadr);
5720         }
5721
5722         /*
5723         **      if old phase not dataphase, leave here.
5724         */
5725
5726         if (cmd != (READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24)) {
5727                 PRINT_ADDR(cp->ccb);
5728                 printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
5729                         (unsigned)cmd,
5730                         (unsigned)READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24);
5731                 
5732                 return;
5733         }
5734         if (cmd & 0x06) {
5735                 PRINT_ADDR(cp->ccb);
5736                 printf ("phase change %x-%x %d@%08x resid=%d.\n",
5737                         cmd&7, sbcl&7, (unsigned)olen,
5738                         (unsigned)oadr, (unsigned)rest);
5739
5740                 OUTB (nc_dcntl, np->rv_dcntl | STD);
5741                 return;
5742         }
5743
5744         /*
5745         **      choose the correct patch area.
5746         **      if savep points to one, choose the other.
5747         */
5748
5749         newcmd = cp->patch;
5750         if (cp->phys.header.savep == vtophys (newcmd)) newcmd+=4;
5751
5752         /*
5753         **      fillin the commands
5754         */
5755
5756         newcmd[0] = ((cmd & 0x0f) << 24) | rest;
5757         newcmd[1] = oadr + olen - rest;
5758         newcmd[2] = SCR_JUMP;
5759         newcmd[3] = nxtdsp;
5760
5761         if (DEBUG_FLAGS & DEBUG_PHASE) {
5762                 PRINT_ADDR(cp->ccb);
5763                 printf ("newcmd[%d] %x %x %x %x.\n",
5764                         (int)(newcmd - cp->patch),
5765                         (unsigned)newcmd[0],
5766                         (unsigned)newcmd[1],
5767                         (unsigned)newcmd[2],
5768                         (unsigned)newcmd[3]);
5769         }
5770         /*
5771         **      fake the return address (to the patch).
5772         **      and restart script processor at dispatcher.
5773         */
5774         np->profile.num_break++;
5775         OUTL (nc_temp, vtophys (newcmd));
5776         if ((cmd & 7) == 0)
5777                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
5778         else
5779                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, checkatn));
5780 }
5781
5782 /*==========================================================
5783 **
5784 **
5785 **      ncr chip exception handler for programmed interrupts.
5786 **
5787 **
5788 **==========================================================
5789 */
5790
5791 static int ncr_show_msg (u_char * msg)
5792 {
5793         u_char i;
5794         printf ("%x",*msg);
5795         if (*msg==MSG_EXTENDED) {
5796                 for (i=1;i<8;i++) {
5797                         if (i-1>msg[1]) break;
5798                         printf ("-%x",msg[i]);
5799                 }
5800                 return (i+1);
5801         } else if ((*msg & 0xf0) == 0x20) {
5802                 printf ("-%x",msg[1]);
5803                 return (2);
5804         }
5805         return (1);
5806 }
5807
5808 static void ncr_int_sir (ncb_p np)
5809 {
5810         u_char scntl3;
5811         u_char chg, ofs, per, fak, wide;
5812         u_char num = INB (nc_dsps);
5813         nccb_p  cp = NULL;
5814         u_long  dsa;
5815         u_int   target = INB (nc_sdid) & 0x0f;
5816         tcb_p   tp     = &np->target[target];
5817         int     i;
5818         if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
5819
5820         switch (num) {
5821         case SIR_SENSE_RESTART:
5822         case SIR_STALL_RESTART:
5823                 break;
5824
5825         default:
5826                 /*
5827                 **      lookup the nccb
5828                 */
5829                 dsa = INL (nc_dsa);
5830                 cp = np->link_nccb;
5831                 while (cp && (CCB_PHYS (cp, phys) != dsa))
5832                         cp = cp->link_nccb;
5833
5834                 assert (cp);
5835                 if (!cp)
5836                         goto out;
5837                 assert (cp == np->header.cp);
5838                 if (cp != np->header.cp)
5839                         goto out;
5840         }
5841
5842         switch (num) {
5843
5844 /*--------------------------------------------------------------------
5845 **
5846 **      Processing of interrupted getcc selects
5847 **
5848 **--------------------------------------------------------------------
5849 */
5850
5851         case SIR_SENSE_RESTART:
5852                 /*------------------------------------------
5853                 **      Script processor is idle.
5854                 **      Look for interrupted "check cond"
5855                 **------------------------------------------
5856                 */
5857
5858                 if (DEBUG_FLAGS & DEBUG_RESTART)
5859                         device_printf(np->dev, "int#%d", num);
5860                 cp = (nccb_p) 0;
5861                 for (i=0; i<MAX_TARGET; i++) {
5862                         if (DEBUG_FLAGS & DEBUG_RESTART) printf (" t%d", i);
5863                         tp = &np->target[i];
5864                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5865                         cp = tp->hold_cp;
5866                         if (!cp) continue;
5867                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5868                         if ((cp->host_status==HS_BUSY) &&
5869                                 (cp->s_status==SCSI_STATUS_CHECK_COND))
5870                                 break;
5871                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("- (remove)");
5872                         tp->hold_cp = cp = (nccb_p) 0;
5873                 }
5874
5875                 if (cp) {
5876                         if (DEBUG_FLAGS & DEBUG_RESTART)
5877                                 printf ("+ restart job ..\n");
5878                         OUTL (nc_dsa, CCB_PHYS (cp, phys));
5879                         OUTL (nc_dsp, NCB_SCRIPTH_PHYS (np, getcc));
5880                         return;
5881                 }
5882
5883                 /*
5884                 **      no job, resume normal processing
5885                 */
5886                 if (DEBUG_FLAGS & DEBUG_RESTART) printf (" -- remove trap\n");
5887                 WRITESCRIPT(start0[0], SCR_INT ^ IFFALSE (0));
5888                 break;
5889
5890         case SIR_SENSE_FAILED:
5891                 /*-------------------------------------------
5892                 **      While trying to select for
5893                 **      getting the condition code,
5894                 **      a target reselected us.
5895                 **-------------------------------------------
5896                 */
5897                 if (DEBUG_FLAGS & DEBUG_RESTART) {
5898                         PRINT_ADDR(cp->ccb);
5899                         printf ("in getcc reselect by t%d.\n",
5900                                 INB(nc_ssid) & 0x0f);
5901                 }
5902
5903                 /*
5904                 **      Mark this job
5905                 */
5906                 cp->host_status = HS_BUSY;
5907                 cp->s_status = SCSI_STATUS_CHECK_COND;
5908                 np->target[cp->ccb->ccb_h.target_id].hold_cp = cp;
5909
5910                 /*
5911                 **      And patch code to restart it.
5912                 */
5913                 WRITESCRIPT(start0[0], SCR_INT);
5914                 break;
5915
5916 /*-----------------------------------------------------------------------------
5917 **
5918 **      Was Sie schon immer ueber transfermode negotiation wissen wollten ...
5919 **
5920 **      We try to negotiate sync and wide transfer only after
5921 **      a successful inquire command. We look at byte 7 of the
5922 **      inquire data to determine the capabilities if the target.
5923 **
5924 **      When we try to negotiate, we append the negotiation message
5925 **      to the identify and (maybe) simple tag message.
5926 **      The host status field is set to HS_NEGOTIATE to mark this
5927 **      situation.
5928 **
5929 **      If the target doesn't answer this message immediately
5930 **      (as required by the standard), the SIR_NEGO_FAIL interrupt
5931 **      will be raised eventually.
5932 **      The handler removes the HS_NEGOTIATE status, and sets the
5933 **      negotiated value to the default (async / nowide).
5934 **
5935 **      If we receive a matching answer immediately, we check it
5936 **      for validity, and set the values.
5937 **
5938 **      If we receive a Reject message immediately, we assume the
5939 **      negotiation has failed, and fall back to standard values.
5940 **
5941 **      If we receive a negotiation message while not in HS_NEGOTIATE
5942 **      state, it's a target initiated negotiation. We prepare a
5943 **      (hopefully) valid answer, set our parameters, and send back 
5944 **      this answer to the target.
5945 **
5946 **      If the target doesn't fetch the answer (no message out phase),
5947 **      we assume the negotiation has failed, and fall back to default
5948 **      settings.
5949 **
5950 **      When we set the values, we adjust them in all nccbs belonging 
5951 **      to this target, in the controller's register, and in the "phys"
5952 **      field of the controller's struct ncb.
5953 **
5954 **      Possible cases:            hs  sir   msg_in value  send   goto
5955 **      We try try to negotiate:
5956 **      -> target doesnt't msgin   NEG FAIL  noop   defa.  -      dispatch
5957 **      -> target rejected our msg NEG FAIL  reject defa.  -      dispatch
5958 **      -> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
5959 **      -> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
5960 **      -> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
5961 **      -> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
5962 **      -> any other msgin         NEG FAIL  noop   defa.  -      dispatch
5963 **
5964 **      Target tries to negotiate:
5965 **      -> incoming message        --- SYNC  sdtr   set    SDTR   -
5966 **      -> incoming message        --- WIDE  wdtr   set    WDTR   -
5967 **      We sent our answer:
5968 **      -> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
5969 **
5970 **-----------------------------------------------------------------------------
5971 */
5972
5973         case SIR_NEGO_FAILED:
5974                 /*-------------------------------------------------------
5975                 **
5976                 **      Negotiation failed.
5977                 **      Target doesn't send an answer message,
5978                 **      or target rejected our message.
5979                 **
5980                 **      Remove negotiation request.
5981                 **
5982                 **-------------------------------------------------------
5983                 */
5984                 OUTB (HS_PRT, HS_BUSY);
5985
5986                 /* FALLTHROUGH */
5987
5988         case SIR_NEGO_PROTO:
5989                 /*-------------------------------------------------------
5990                 **
5991                 **      Negotiation failed.
5992                 **      Target doesn't fetch the answer message.
5993                 **
5994                 **-------------------------------------------------------
5995                 */
5996
5997                 if (DEBUG_FLAGS & DEBUG_NEGO) {
5998                         PRINT_ADDR(cp->ccb);
5999                         printf ("negotiation failed sir=%x status=%x.\n",
6000                                 num, cp->nego_status);
6001                 }
6002
6003                 /*
6004                 **      any error in negotiation:
6005                 **      fall back to default mode.
6006                 */
6007                 switch (cp->nego_status) {
6008
6009                 case NS_SYNC:
6010                         ncr_setsync (np, cp, 0, 0xe0, 0);
6011                         break;
6012
6013                 case NS_WIDE:
6014                         ncr_setwide (np, cp, 0, 0);
6015                         break;
6016
6017                 }
6018                 np->msgin [0] = MSG_NOOP;
6019                 np->msgout[0] = MSG_NOOP;
6020                 cp->nego_status = 0;
6021                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
6022                 break;
6023
6024         case SIR_NEGO_SYNC:
6025                 /*
6026                 **      Synchronous request message received.
6027                 */
6028
6029                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6030                         PRINT_ADDR(cp->ccb);
6031                         printf ("sync msgin: ");
6032                         (void) ncr_show_msg (np->msgin);
6033                         printf (".\n");
6034                 }
6035
6036                 /*
6037                 **      get requested values.
6038                 */
6039
6040                 chg = 0;
6041                 per = np->msgin[3];
6042                 ofs = np->msgin[4];
6043                 if (ofs==0) per=255;
6044
6045                 /*
6046                 **      check values against driver limits.
6047                 */
6048                 if (per < np->minsync)
6049                         {chg = 1; per = np->minsync;}
6050                 if (per < tp->tinfo.user.period)
6051                         {chg = 1; per = tp->tinfo.user.period;}
6052                 if (ofs > tp->tinfo.user.offset)
6053                         {chg = 1; ofs = tp->tinfo.user.offset;}
6054
6055                 /*
6056                 **      Check against controller limits.
6057                 */
6058
6059                 fak     = 7;
6060                 scntl3  = 0;
6061                 if (ofs != 0) {
6062                         ncr_getsync(np, per, &fak, &scntl3);
6063                         if (fak > 7) {
6064                                 chg = 1;
6065                                 ofs = 0;
6066                         }
6067                 }
6068                 if (ofs == 0) {
6069                         fak     = 7;
6070                         per     = 0;
6071                         scntl3  = 0;
6072                 }
6073
6074                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6075                         PRINT_ADDR(cp->ccb);
6076                         printf ("sync: per=%d scntl3=0x%x ofs=%d fak=%d chg=%d.\n",
6077                                 per, scntl3, ofs, fak, chg);
6078                 }
6079
6080                 if (INB (HS_PRT) == HS_NEGOTIATE) {
6081                         OUTB (HS_PRT, HS_BUSY);
6082                         switch (cp->nego_status) {
6083
6084                         case NS_SYNC:
6085                                 /*
6086                                 **      This was an answer message
6087                                 */
6088                                 if (chg) {
6089                                         /*
6090                                         **      Answer wasn't acceptable.
6091                                         */
6092                                         ncr_setsync (np, cp, 0, 0xe0, 0);
6093                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6094                                 } else {
6095                                         /*
6096                                         **      Answer is ok.
6097                                         */
6098                                         ncr_setsync (np,cp,scntl3,(fak<<5)|ofs, per);
6099                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
6100                                 }
6101                                 return;
6102
6103                         case NS_WIDE:
6104                                 ncr_setwide (np, cp, 0, 0);
6105                                 break;
6106                         }
6107                 }
6108
6109                 /*
6110                 **      It was a request. Set value and
6111                 **      prepare an answer message
6112                 */
6113
6114                 ncr_setsync (np, cp, scntl3, (fak<<5)|ofs, per);
6115
6116                 np->msgout[0] = MSG_EXTENDED;
6117                 np->msgout[1] = 3;
6118                 np->msgout[2] = MSG_EXT_SDTR;
6119                 np->msgout[3] = per;
6120                 np->msgout[4] = ofs;
6121
6122                 cp->nego_status = NS_SYNC;
6123
6124                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6125                         PRINT_ADDR(cp->ccb);
6126                         printf ("sync msgout: ");
6127                         (void) ncr_show_msg (np->msgout);
6128                         printf (".\n");
6129                 }
6130
6131                 if (!ofs) {
6132                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6133                         return;
6134                 }
6135                 np->msgin [0] = MSG_NOOP;
6136
6137                 break;
6138
6139         case SIR_NEGO_WIDE:
6140                 /*
6141                 **      Wide request message received.
6142                 */
6143                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6144                         PRINT_ADDR(cp->ccb);
6145                         printf ("wide msgin: ");
6146                         (void) ncr_show_msg (np->msgin);
6147                         printf (".\n");
6148                 }
6149
6150                 /*
6151                 **      get requested values.
6152                 */
6153
6154                 chg  = 0;
6155                 wide = np->msgin[3];
6156
6157                 /*
6158                 **      check values against driver limits.
6159                 */
6160
6161                 if (wide > tp->tinfo.user.width)
6162                         {chg = 1; wide = tp->tinfo.user.width;}
6163
6164                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6165                         PRINT_ADDR(cp->ccb);
6166                         printf ("wide: wide=%d chg=%d.\n", wide, chg);
6167                 }
6168
6169                 if (INB (HS_PRT) == HS_NEGOTIATE) {
6170                         OUTB (HS_PRT, HS_BUSY);
6171                         switch (cp->nego_status) {
6172
6173                         case NS_WIDE:
6174                                 /*
6175                                 **      This was an answer message
6176                                 */
6177                                 if (chg) {
6178                                         /*
6179                                         **      Answer wasn't acceptable.
6180                                         */
6181                                         ncr_setwide (np, cp, 0, 1);
6182                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6183                                 } else {
6184                                         /*
6185                                         **      Answer is ok.
6186                                         */
6187                                         ncr_setwide (np, cp, wide, 1);
6188                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
6189                                 }
6190                                 return;
6191
6192                         case NS_SYNC:
6193                                 ncr_setsync (np, cp, 0, 0xe0, 0);
6194                                 break;
6195                         }
6196                 }
6197
6198                 /*
6199                 **      It was a request, set value and
6200                 **      prepare an answer message
6201                 */
6202
6203                 ncr_setwide (np, cp, wide, 1);
6204
6205                 np->msgout[0] = MSG_EXTENDED;
6206                 np->msgout[1] = 2;
6207                 np->msgout[2] = MSG_EXT_WDTR;
6208                 np->msgout[3] = wide;
6209
6210                 np->msgin [0] = MSG_NOOP;
6211
6212                 cp->nego_status = NS_WIDE;
6213
6214                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6215                         PRINT_ADDR(cp->ccb);
6216                         printf ("wide msgout: ");
6217                         (void) ncr_show_msg (np->msgout);
6218                         printf (".\n");
6219                 }
6220                 break;
6221
6222 /*--------------------------------------------------------------------
6223 **
6224 **      Processing of special messages
6225 **
6226 **--------------------------------------------------------------------
6227 */
6228
6229         case SIR_REJECT_RECEIVED:
6230                 /*-----------------------------------------------
6231                 **
6232                 **      We received a MSG_MESSAGE_REJECT message.
6233                 **
6234                 **-----------------------------------------------
6235                 */
6236
6237                 PRINT_ADDR(cp->ccb);
6238                 printf ("MSG_MESSAGE_REJECT received (%x:%x).\n",
6239                         (unsigned)np->lastmsg, np->msgout[0]);
6240                 break;
6241
6242         case SIR_REJECT_SENT:
6243                 /*-----------------------------------------------
6244                 **
6245                 **      We received an unknown message
6246                 **
6247                 **-----------------------------------------------
6248                 */
6249
6250                 PRINT_ADDR(cp->ccb);
6251                 printf ("MSG_MESSAGE_REJECT sent for ");
6252                 (void) ncr_show_msg (np->msgin);
6253                 printf (".\n");
6254                 break;
6255
6256 /*--------------------------------------------------------------------
6257 **
6258 **      Processing of special messages
6259 **
6260 **--------------------------------------------------------------------
6261 */
6262
6263         case SIR_IGN_RESIDUE:
6264                 /*-----------------------------------------------
6265                 **
6266                 **      We received an IGNORE RESIDUE message,
6267                 **      which couldn't be handled by the script.
6268                 **
6269                 **-----------------------------------------------
6270                 */
6271
6272                 PRINT_ADDR(cp->ccb);
6273                 printf ("MSG_IGN_WIDE_RESIDUE received, but not yet implemented.\n");
6274                 break;
6275
6276         case SIR_MISSING_SAVE:
6277                 /*-----------------------------------------------
6278                 **
6279                 **      We received an DISCONNECT message,
6280                 **      but the datapointer wasn't saved before.
6281                 **
6282                 **-----------------------------------------------
6283                 */
6284
6285                 PRINT_ADDR(cp->ccb);
6286                 printf ("MSG_DISCONNECT received, but datapointer not saved:\n"
6287                         "\tdata=%x save=%x goal=%x.\n",
6288                         (unsigned) INL (nc_temp),
6289                         (unsigned) np->header.savep,
6290                         (unsigned) np->header.goalp);
6291                 break;
6292
6293 /*--------------------------------------------------------------------
6294 **
6295 **      Processing of a "SCSI_STATUS_QUEUE_FULL" status.
6296 **
6297 **      XXX JGibbs - We should do the same thing for BUSY status.
6298 **
6299 **      The current command has been rejected,
6300 **      because there are too many in the command queue.
6301 **      We have started too many commands for that target.
6302 **
6303 **--------------------------------------------------------------------
6304 */
6305         case SIR_STALL_QUEUE:
6306                 cp->xerr_status = XE_OK;
6307                 cp->host_status = HS_COMPLETE;
6308                 cp->s_status = SCSI_STATUS_QUEUE_FULL;
6309                 ncr_freeze_devq(np, cp->ccb->ccb_h.path);
6310                 ncr_complete(np, cp);
6311
6312                 /* FALLTHROUGH */
6313
6314         case SIR_STALL_RESTART:
6315                 /*-----------------------------------------------
6316                 **
6317                 **      Enable selecting again,
6318                 **      if NO disconnected jobs.
6319                 **
6320                 **-----------------------------------------------
6321                 */
6322                 /*
6323                 **      Look for a disconnected job.
6324                 */
6325                 cp = np->link_nccb;
6326                 while (cp && cp->host_status != HS_DISCONNECT)
6327                         cp = cp->link_nccb;
6328
6329                 /*
6330                 **      if there is one, ...
6331                 */
6332                 if (cp) {
6333                         /*
6334                         **      wait for reselection
6335                         */
6336                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, reselect));
6337                         return;
6338                 }
6339
6340                 /*
6341                 **      else remove the interrupt.
6342                 */
6343
6344                 device_printf(np->dev, "queue empty.\n");
6345                 WRITESCRIPT(start1[0], SCR_INT ^ IFFALSE (0));
6346                 break;
6347         }
6348
6349 out:
6350         OUTB (nc_dcntl, np->rv_dcntl | STD);
6351 }
6352
6353 /*==========================================================
6354 **
6355 **
6356 **      Acquire a control block
6357 **
6358 **
6359 **==========================================================
6360 */
6361
6362 static  nccb_p ncr_get_nccb
6363         (ncb_p np, u_long target, u_long lun)
6364 {
6365         lcb_p lp;
6366         nccb_p cp = NULL;
6367
6368         /*
6369         **      Lun structure available ?
6370         */
6371
6372         lp = np->target[target].lp[lun];
6373         if (lp) {
6374                 cp = lp->next_nccb;
6375
6376                 /*
6377                 **      Look for free CCB
6378                 */
6379
6380                 while (cp && cp->magic) {
6381                         cp = cp->next_nccb;
6382                 }
6383         }
6384
6385         /*
6386         **      if nothing available, create one.
6387         */
6388
6389         if (cp == NULL)
6390                 cp = ncr_alloc_nccb(np, target, lun);
6391
6392         if (cp != NULL) {
6393                 if (cp->magic) {
6394                         device_printf(np->dev, "Bogus free cp found\n");
6395                         return (NULL);
6396                 }
6397                 cp->magic = 1;
6398         }
6399         return (cp);
6400 }
6401
6402 /*==========================================================
6403 **
6404 **
6405 **      Release one control block
6406 **
6407 **
6408 **==========================================================
6409 */
6410
6411 static void ncr_free_nccb (ncb_p np, nccb_p cp)
6412 {
6413         /*
6414         **    sanity
6415         */
6416
6417         assert (cp != NULL);
6418
6419         cp -> host_status = HS_IDLE;
6420         cp -> magic = 0;
6421 }
6422
6423 /*==========================================================
6424 **
6425 **
6426 **      Allocation of resources for Targets/Luns/Tags.
6427 **
6428 **
6429 **==========================================================
6430 */
6431
6432 static nccb_p
6433 ncr_alloc_nccb (ncb_p np, u_long target, u_long lun)
6434 {
6435         tcb_p tp;
6436         lcb_p lp;
6437         nccb_p cp;
6438
6439         assert (np != NULL);
6440
6441         if (target>=MAX_TARGET) return(NULL);
6442         if (lun   >=MAX_LUN   ) return(NULL);
6443
6444         tp=&np->target[target];
6445
6446         if (!tp->jump_tcb.l_cmd) {
6447
6448                 /*
6449                 **      initialize it.
6450                 */
6451                 tp->jump_tcb.l_cmd   = (SCR_JUMP^IFFALSE (DATA (0x80 + target)));
6452                 tp->jump_tcb.l_paddr = np->jump_tcb.l_paddr;
6453
6454                 tp->getscr[0] =
6455                         (np->features & FE_PFEN)? SCR_COPY(1) : SCR_COPY_F(1);
6456                 tp->getscr[1] = vtophys (&tp->tinfo.sval);
6457                 tp->getscr[2] = rman_get_start(np->reg_res) + offsetof (struct ncr_reg, nc_sxfer);
6458                 tp->getscr[3] =
6459                         (np->features & FE_PFEN)? SCR_COPY(1) : SCR_COPY_F(1);
6460                 tp->getscr[4] = vtophys (&tp->tinfo.wval);
6461                 tp->getscr[5] = rman_get_start(np->reg_res) + offsetof (struct ncr_reg, nc_scntl3);
6462
6463                 assert (((offsetof(struct ncr_reg, nc_sxfer) ^
6464                          (offsetof(struct tcb ,tinfo)
6465                         + offsetof(struct ncr_target_tinfo, sval))) & 3) == 0);
6466                 assert (((offsetof(struct ncr_reg, nc_scntl3) ^
6467                          (offsetof(struct tcb, tinfo)
6468                         + offsetof(struct ncr_target_tinfo, wval))) &3) == 0);
6469
6470                 tp->call_lun.l_cmd   = (SCR_CALL);
6471                 tp->call_lun.l_paddr = NCB_SCRIPT_PHYS (np, resel_lun);
6472
6473                 tp->jump_lcb.l_cmd   = (SCR_JUMP);
6474                 tp->jump_lcb.l_paddr = NCB_SCRIPTH_PHYS (np, abort);
6475                 np->jump_tcb.l_paddr = vtophys (&tp->jump_tcb);
6476         }
6477
6478         /*
6479         **      Logic unit control block
6480         */
6481         lp = tp->lp[lun];
6482         if (!lp) {
6483                 /*
6484                 **      Allocate a lcb
6485                 */
6486                 lp = (lcb_p) malloc (sizeof (struct lcb), M_DEVBUF,
6487                         M_NOWAIT | M_ZERO);
6488                 if (!lp) return(NULL);
6489
6490                 /*
6491                 **      Initialize it
6492                 */
6493                 lp->jump_lcb.l_cmd   = (SCR_JUMP ^ IFFALSE (DATA (lun)));
6494                 lp->jump_lcb.l_paddr = tp->jump_lcb.l_paddr;
6495
6496                 lp->call_tag.l_cmd   = (SCR_CALL);
6497                 lp->call_tag.l_paddr = NCB_SCRIPT_PHYS (np, resel_tag);
6498
6499                 lp->jump_nccb.l_cmd   = (SCR_JUMP);
6500                 lp->jump_nccb.l_paddr = NCB_SCRIPTH_PHYS (np, aborttag);
6501
6502                 lp->actlink = 1;
6503
6504                 /*
6505                 **   Chain into LUN list
6506                 */
6507                 tp->jump_lcb.l_paddr = vtophys (&lp->jump_lcb);
6508                 tp->lp[lun] = lp;
6509
6510         }
6511
6512         /*
6513         **      Allocate a nccb
6514         */
6515         cp = (nccb_p) malloc (sizeof (struct nccb), M_DEVBUF, M_NOWAIT|M_ZERO);
6516
6517         if (!cp)
6518                 return (NULL);
6519
6520         if (DEBUG_FLAGS & DEBUG_ALLOC) { 
6521                 printf ("new nccb @%p.\n", cp);
6522         }
6523
6524         /*
6525         **      Fill in physical addresses
6526         */
6527
6528         cp->p_nccb           = vtophys (cp);
6529
6530         /*
6531         **      Chain into reselect list
6532         */
6533         cp->jump_nccb.l_cmd   = SCR_JUMP;
6534         cp->jump_nccb.l_paddr = lp->jump_nccb.l_paddr;
6535         lp->jump_nccb.l_paddr = CCB_PHYS (cp, jump_nccb);
6536         cp->call_tmp.l_cmd   = SCR_CALL;
6537         cp->call_tmp.l_paddr = NCB_SCRIPT_PHYS (np, resel_tmp);
6538
6539         /*
6540         **      Chain into wakeup list
6541         */
6542         cp->link_nccb      = np->link_nccb;
6543         np->link_nccb      = cp;
6544
6545         /*
6546         **      Chain into CCB list
6547         */
6548         cp->next_nccb   = lp->next_nccb;
6549         lp->next_nccb   = cp;
6550
6551         return (cp);
6552 }
6553
6554 /*==========================================================
6555 **
6556 **
6557 **      Build Scatter Gather Block
6558 **
6559 **
6560 **==========================================================
6561 **
6562 **      The transfer area may be scattered among
6563 **      several non adjacent physical pages.
6564 **
6565 **      We may use MAX_SCATTER blocks.
6566 **
6567 **----------------------------------------------------------
6568 */
6569
6570 static  int     ncr_scatter
6571         (struct dsb* phys, vm_offset_t vaddr, vm_size_t datalen)
6572 {
6573         u_long  paddr, pnext;
6574
6575         u_short segment  = 0;
6576         u_long  segsize, segaddr;
6577         u_long  size, csize    = 0;
6578         u_long  chunk = MAX_SIZE;
6579         int     free;
6580
6581         bzero (&phys->data, sizeof (phys->data));
6582         if (!datalen) return (0);
6583
6584         paddr = vtophys (vaddr);
6585
6586         /*
6587         **      insert extra break points at a distance of chunk.
6588         **      We try to reduce the number of interrupts caused
6589         **      by unexpected phase changes due to disconnects.
6590         **      A typical harddisk may disconnect before ANY block.
6591         **      If we wanted to avoid unexpected phase changes at all
6592         **      we had to use a break point every 512 bytes.
6593         **      Of course the number of scatter/gather blocks is
6594         **      limited.
6595         */
6596
6597         free = MAX_SCATTER - 1;
6598
6599         if (vaddr & PAGE_MASK) free -= datalen / PAGE_SIZE;
6600
6601         if (free>1)
6602                 while ((chunk * free >= 2 * datalen) && (chunk>=1024))
6603                         chunk /= 2;
6604
6605         if(DEBUG_FLAGS & DEBUG_SCATTER)
6606                 printf("ncr?:\tscattering virtual=%p size=%d chunk=%d.\n",
6607                        (void *) vaddr, (unsigned) datalen, (unsigned) chunk);
6608
6609         /*
6610         **   Build data descriptors.
6611         */
6612         while (datalen && (segment < MAX_SCATTER)) {
6613
6614                 /*
6615                 **      this segment is empty
6616                 */
6617                 segsize = 0;
6618                 segaddr = paddr;
6619                 pnext   = paddr;
6620
6621                 if (!csize) csize = chunk;
6622
6623                 while ((datalen) && (paddr == pnext) && (csize)) {
6624
6625                         /*
6626                         **      continue this segment
6627                         */
6628                         pnext = (paddr & (~PAGE_MASK)) + PAGE_SIZE;
6629
6630                         /*
6631                         **      Compute max size
6632                         */
6633
6634                         size = pnext - paddr;           /* page size */
6635                         if (size > datalen) size = datalen;  /* data size */
6636                         if (size > csize  ) size = csize  ;  /* chunksize */
6637
6638                         segsize += size;
6639                         vaddr   += size;
6640                         csize   -= size;
6641                         datalen -= size;
6642                         paddr    = vtophys (vaddr);
6643                 }
6644
6645                 if(DEBUG_FLAGS & DEBUG_SCATTER)
6646                         printf ("\tseg #%d  addr=%x  size=%d  (rest=%d).\n",
6647                         segment,
6648                         (unsigned) segaddr,
6649                         (unsigned) segsize,
6650                         (unsigned) datalen);
6651
6652                 phys->data[segment].addr = segaddr;
6653                 phys->data[segment].size = segsize;
6654                 segment++;
6655         }
6656
6657         if (datalen) {
6658                 printf("ncr?: scatter/gather failed (residue=%d).\n",
6659                         (unsigned) datalen);
6660                 return (-1);
6661         }
6662
6663         return (segment);
6664 }
6665
6666 /*==========================================================
6667 **
6668 **
6669 **      Test the pci bus snoop logic :-(
6670 **
6671 **      Has to be called with interrupts disabled.
6672 **
6673 **
6674 **==========================================================
6675 */
6676
6677 #ifndef NCR_IOMAPPED
6678 static int ncr_regtest (struct ncb* np)
6679 {
6680         register volatile u_int32_t data;
6681         /*
6682         **      ncr registers may NOT be cached.
6683         **      write 0xffffffff to a read only register area,
6684         **      and try to read it back.
6685         */
6686         data = 0xffffffff;
6687         OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
6688         data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
6689 #if 1
6690         if (data == 0xffffffff) {
6691 #else
6692         if ((data & 0xe2f0fffd) != 0x02000080) {
6693 #endif
6694                 printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
6695                         (unsigned) data);
6696                 return (0x10);
6697         }
6698         return (0);
6699 }
6700 #endif
6701
6702 static int ncr_snooptest (struct ncb* np)
6703 {
6704         u_int32_t ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
6705         int     i, err=0;
6706 #ifndef NCR_IOMAPPED
6707         err |= ncr_regtest (np);
6708         if (err) return (err);
6709 #endif
6710         /*
6711         **      init
6712         */
6713         pc  = NCB_SCRIPTH_PHYS (np, snooptest);
6714         host_wr = 1;
6715         ncr_wr  = 2;
6716         /*
6717         **      Set memory and register.
6718         */
6719         ncr_cache = host_wr;
6720         OUTL (nc_temp, ncr_wr);
6721         /*
6722         **      Start script (exchange values)
6723         */
6724         OUTL (nc_dsp, pc);
6725         /*
6726         **      Wait 'til done (with timeout)
6727         */
6728         for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
6729                 if (INB(nc_istat) & (INTF|SIP|DIP))
6730                         break;
6731         /*
6732         **      Save termination position.
6733         */
6734         pc = INL (nc_dsp);
6735         /*
6736         **      Read memory and register.
6737         */
6738         host_rd = ncr_cache;
6739         ncr_rd  = INL (nc_scratcha);
6740         ncr_bk  = INL (nc_temp);
6741         /*
6742         **      Reset ncr chip
6743         */
6744         OUTB (nc_istat,  SRST);
6745         DELAY (1000);
6746         OUTB (nc_istat,  0   );
6747         /*
6748         **      check for timeout
6749         */
6750         if (i>=NCR_SNOOP_TIMEOUT) {
6751                 printf ("CACHE TEST FAILED: timeout.\n");
6752                 return (0x20);
6753         }
6754         /*
6755         **      Check termination position.
6756         */
6757         if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
6758                 printf ("CACHE TEST FAILED: script execution failed.\n");
6759                 printf ("start=%08lx, pc=%08lx, end=%08lx\n", 
6760                         (u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
6761                         (u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
6762                 return (0x40);
6763         }
6764         /*
6765         **      Show results.
6766         */
6767         if (host_wr != ncr_rd) {
6768                 printf ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
6769                         (int) host_wr, (int) ncr_rd);
6770                 err |= 1;
6771         }
6772         if (host_rd != ncr_wr) {
6773                 printf ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
6774                         (int) ncr_wr, (int) host_rd);
6775                 err |= 2;
6776         }
6777         if (ncr_bk != ncr_wr) {
6778                 printf ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
6779                         (int) ncr_wr, (int) ncr_bk);
6780                 err |= 4;
6781         }
6782         return (err);
6783 }
6784
6785 /*==========================================================
6786 **
6787 **
6788 **      Profiling the drivers and targets performance.
6789 **
6790 **
6791 **==========================================================
6792 */
6793
6794 /*
6795 **      Compute the difference in milliseconds.
6796 **/
6797
6798 static  int ncr_delta (int *from, int *to)
6799 {
6800         if (!from) return (-1);
6801         if (!to)   return (-2);
6802         return ((to - from) * 1000 / hz);
6803 }
6804
6805 #define PROFILE  cp->phys.header.stamp
6806 static  void ncb_profile (ncb_p np, nccb_p cp)
6807 {
6808         int co, da, st, en, di, se, post,work,disc;
6809         u_long diff;
6810
6811         PROFILE.end = ticks;
6812
6813         st = ncr_delta (&PROFILE.start,&PROFILE.status);
6814         if (st<0) return;       /* status  not reached  */
6815
6816         da = ncr_delta (&PROFILE.start,&PROFILE.data);
6817         if (da<0) return;       /* No data transfer phase */
6818
6819         co = ncr_delta (&PROFILE.start,&PROFILE.command);
6820         if (co<0) return;       /* command not executed */
6821
6822         en = ncr_delta (&PROFILE.start,&PROFILE.end),
6823         di = ncr_delta (&PROFILE.start,&PROFILE.disconnect),
6824         se = ncr_delta (&PROFILE.start,&PROFILE.select);
6825         post = en - st;
6826
6827         /*
6828         **      @PROFILE@  Disconnect time invalid if multiple disconnects
6829         */
6830
6831         if (di>=0) disc = se-di; else  disc = 0;
6832
6833         work = (st - co) - disc;
6834
6835         diff = (np->disc_phys - np->disc_ref) & 0xff;
6836         np->disc_ref += diff;
6837
6838         np->profile.num_trans   += 1;
6839         if (cp->ccb)
6840                 np->profile.num_bytes   += cp->ccb->csio.dxfer_len;
6841         np->profile.num_disc    += diff;
6842         np->profile.ms_setup    += co;
6843         np->profile.ms_data     += work;
6844         np->profile.ms_disc     += disc;
6845         np->profile.ms_post     += post;
6846 }
6847 #undef PROFILE
6848
6849 /*==========================================================
6850 **
6851 **      Determine the ncr's clock frequency.
6852 **      This is essential for the negotiation
6853 **      of the synchronous transfer rate.
6854 **
6855 **==========================================================
6856 **
6857 **      Note: we have to return the correct value.
6858 **      THERE IS NO SAVE DEFAULT VALUE.
6859 **
6860 **      Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
6861 **      53C860 and 53C875 rev. 1 support fast20 transfers but 
6862 **      do not have a clock doubler and so are provided with a 
6863 **      80 MHz clock. All other fast20 boards incorporate a doubler 
6864 **      and so should be delivered with a 40 MHz clock.
6865 **      The future fast40 chips (895/895) use a 40 Mhz base clock 
6866 **      and provide a clock quadrupler (160 Mhz). The code below 
6867 **      tries to deal as cleverly as possible with all this stuff.
6868 **
6869 **----------------------------------------------------------
6870 */
6871
6872 /*
6873  *      Select NCR SCSI clock frequency
6874  */
6875 static void ncr_selectclock(ncb_p np, u_char scntl3)
6876 {
6877         if (np->multiplier < 2) {
6878                 OUTB(nc_scntl3, scntl3);
6879                 return;
6880         }
6881
6882         if (bootverbose >= 2)
6883                 device_printf(np->dev, "enabling clock multiplier\n");
6884
6885         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
6886         if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
6887                 int i = 20;
6888                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
6889                         DELAY(20);
6890                 if (!i)
6891                         device_printf(np->dev,
6892                             "the chip cannot lock the frequency\n");
6893         } else                  /* Wait 20 micro-seconds for doubler    */
6894                 DELAY(20);
6895         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
6896         OUTB(nc_scntl3, scntl3);
6897         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
6898         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
6899 }
6900
6901 /*
6902  *      calculate NCR SCSI clock frequency (in KHz)
6903  */
6904 static unsigned
6905 ncrgetfreq (ncb_p np, int gen)
6906 {
6907         int ms = 0;
6908         /*
6909          * Measure GEN timer delay in order 
6910          * to calculate SCSI clock frequency
6911          *
6912          * This code will never execute too
6913          * many loop iterations (if DELAY is 
6914          * reasonably correct). It could get
6915          * too low a delay (too high a freq.)
6916          * if the CPU is slow executing the 
6917          * loop for some reason (an NMI, for
6918          * example). For this reason we will
6919          * if multiple measurements are to be 
6920          * performed trust the higher delay 
6921          * (lower frequency returned).
6922          */
6923         OUTB (nc_stest1, 0);    /* make sure clock doubler is OFF           */
6924         OUTW (nc_sien , 0);     /* mask all scsi interrupts                 */
6925         (void) INW (nc_sist);   /* clear pending scsi interrupt             */
6926         OUTB (nc_dien , 0);     /* mask all dma interrupts                  */
6927         (void) INW (nc_sist);   /* another one, just to be sure :)          */
6928         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3            */
6929         OUTB (nc_stime1, 0);    /* disable general purpose timer            */
6930         OUTB (nc_stime1, gen);  /* set to nominal delay of (1<<gen) * 125us */
6931         while (!(INW(nc_sist) & GEN) && ms++ < 1000)
6932                 DELAY(1000);    /* count ms                                 */
6933         OUTB (nc_stime1, 0);    /* disable general purpose timer            */
6934         OUTB (nc_scntl3, 0);
6935         /*
6936          * Set prescaler to divide by whatever "0" means.
6937          * "0" ought to choose divide by 2, but appears
6938          * to set divide by 3.5 mode in my 53c810 ...
6939          */
6940         OUTB (nc_scntl3, 0);
6941
6942         if (bootverbose >= 2)
6943                 printf ("\tDelay (GEN=%d): %u msec\n", gen, ms);
6944         /*
6945          * adjust for prescaler, and convert into KHz 
6946          */
6947         return ms ? ((1 << gen) * 4440) / ms : 0;
6948 }
6949
6950 static void ncr_getclock (ncb_p np, u_char multiplier)
6951 {
6952         unsigned char scntl3;
6953         unsigned char stest1;
6954         scntl3 = INB(nc_scntl3);
6955         stest1 = INB(nc_stest1);
6956           
6957         np->multiplier = 1;
6958
6959         if (multiplier > 1) {
6960                 np->multiplier  = multiplier;
6961                 np->clock_khz   = 40000 * multiplier;
6962         } else {
6963                 if ((scntl3 & 7) == 0) {
6964                         unsigned f1, f2;
6965                         /* throw away first result */
6966                         (void) ncrgetfreq (np, 11);
6967                         f1 = ncrgetfreq (np, 11);
6968                         f2 = ncrgetfreq (np, 11);
6969
6970                         if (bootverbose >= 2)
6971                           printf ("\tNCR clock is %uKHz, %uKHz\n", f1, f2);
6972                         if (f1 > f2) f1 = f2;   /* trust lower result   */
6973                         if (f1 > 45000) {
6974                                 scntl3 = 5;     /* >45Mhz: assume 80MHz */
6975                         } else {
6976                                 scntl3 = 3;     /* <45Mhz: assume 40MHz */
6977                         }
6978                 }
6979                 else if ((scntl3 & 7) == 5)
6980                         np->clock_khz = 80000;  /* Probably a 875 rev. 1 ? */
6981         }
6982 }
6983
6984 /*=========================================================================*/
6985
6986 #ifdef NCR_TEKRAM_EEPROM
6987
6988 struct tekram_eeprom_dev {
6989   u_char        devmode;
6990 #define TKR_PARCHK      0x01
6991 #define TKR_TRYSYNC     0x02
6992 #define TKR_ENDISC      0x04
6993 #define TKR_STARTUNIT   0x08
6994 #define TKR_USETAGS     0x10
6995 #define TKR_TRYWIDE     0x20
6996   u_char        syncparam;      /* max. sync transfer rate (table ?) */
6997   u_char        filler1;
6998   u_char        filler2;
6999 };
7000
7001
7002 struct tekram_eeprom {
7003   struct tekram_eeprom_dev 
7004                 dev[16];
7005   u_char        adaptid;
7006   u_char        adaptmode;
7007 #define TKR_ADPT_GT2DRV 0x01
7008 #define TKR_ADPT_GT1GB  0x02
7009 #define TKR_ADPT_RSTBUS 0x04
7010 #define TKR_ADPT_ACTNEG 0x08
7011 #define TKR_ADPT_NOSEEK 0x10
7012 #define TKR_ADPT_MORLUN 0x20
7013   u_char        delay;          /* unit ? ( table ??? ) */
7014   u_char        tags;           /* use 4 times as many ... */
7015   u_char        filler[60];
7016 };
7017
7018 static void
7019 tekram_write_bit (ncb_p np, int bit)
7020 {
7021         u_char val = 0x10 + ((bit & 1) << 1);
7022
7023         DELAY(10);
7024         OUTB (nc_gpreg, val);
7025         DELAY(10);
7026         OUTB (nc_gpreg, val | 0x04);
7027         DELAY(10);
7028         OUTB (nc_gpreg, val);
7029         DELAY(10);
7030 }
7031
7032 static int
7033 tekram_read_bit (ncb_p np)
7034 {
7035         OUTB (nc_gpreg, 0x10);
7036         DELAY(10);
7037         OUTB (nc_gpreg, 0x14);
7038         DELAY(10);
7039         return INB (nc_gpreg) & 1;
7040 }
7041
7042 static u_short
7043 read_tekram_eeprom_reg (ncb_p np, int reg)
7044 {
7045         int bit;
7046         u_short result = 0;
7047         int cmd = 0x80 | reg;
7048
7049         OUTB (nc_gpreg, 0x10);
7050
7051         tekram_write_bit (np, 1);
7052         for (bit = 7; bit >= 0; bit--)
7053         {
7054                 tekram_write_bit (np, cmd >> bit);
7055         }
7056
7057         for (bit = 0; bit < 16; bit++)
7058         {
7059                 result <<= 1;
7060                 result |= tekram_read_bit (np);
7061         }
7062
7063         OUTB (nc_gpreg, 0x00);
7064         return result;
7065 }
7066
7067 static int 
7068 read_tekram_eeprom(ncb_p np, struct tekram_eeprom *buffer)
7069 {
7070         u_short *p = (u_short *) buffer;
7071         u_short sum = 0;
7072         int i;
7073
7074         if (INB (nc_gpcntl) != 0x09)
7075         {
7076                 return 0;
7077         }
7078         for (i = 0; i < 64; i++)
7079         {
7080                 u_short val;
7081 if((i&0x0f) == 0) printf ("%02x:", i*2);
7082                 val = read_tekram_eeprom_reg (np, i);
7083                 if (p)
7084                         *p++ = val;
7085                 sum += val;
7086 if((i&0x01) == 0x00) printf (" ");
7087                 printf ("%02x%02x", val & 0xff, (val >> 8) & 0xff);
7088 if((i&0x0f) == 0x0f) printf ("\n");
7089         }
7090 printf ("Sum = %04x\n", sum);
7091         return sum == 0x1234;
7092 }
7093 #endif /* NCR_TEKRAM_EEPROM */
7094
7095 static device_method_t ncr_methods[] = {
7096         /* Device interface */
7097         DEVMETHOD(device_probe,         ncr_probe),
7098         DEVMETHOD(device_attach,        ncr_attach),
7099
7100         { 0, 0 }
7101 };
7102
7103 static driver_t ncr_driver = {
7104         "ncr",
7105         ncr_methods,
7106         sizeof(struct ncb),
7107 };
7108
7109 static devclass_t ncr_devclass;
7110
7111 DRIVER_MODULE(ncr, pci, ncr_driver, ncr_devclass, 0, 0);
7112 MODULE_PNP_INFO("W32:vendor/device;U16:#;D:#", pci, ncr, ncr_chip_table,
7113     nitems(ncr_chip_table));
7114 MODULE_DEPEND(ncr, cam, 1, 1, 1);
7115 MODULE_DEPEND(ncr, pci, 1, 1, 1);
7116
7117 /*=========================================================================*/
7118 #endif /* _KERNEL */