]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/dev/ncr/ncr.c
Change improper locking assertion in mge
[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 choosen 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 tranfer 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         unsigned long   device_id;
3173         unsigned short  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(u_long device_id, u_char revision_id)
3229 {
3230         int i, found;
3231         
3232         found = -1;
3233         for (i = 0; i < sizeof(ncr_chip_table)/sizeof(ncr_chip_table[0]); 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 = (4 * div_10M[0] + np->clock_khz - 1) / 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 = (period + 40 - 1) / 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 helpfull.
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
3782         return 0;
3783 }
3784
3785 /*==========================================================
3786 **
3787 **
3788 **      Process pending device interrupts.
3789 **
3790 **
3791 **==========================================================
3792 */
3793
3794 static void
3795 ncr_intr(vnp)
3796         void *vnp;
3797 {
3798         ncb_p np = vnp;
3799
3800         mtx_lock(&np->lock);
3801         ncr_intr_locked(np);
3802         mtx_unlock(&np->lock);
3803 }
3804
3805 static void
3806 ncr_intr_locked(ncb_p np)
3807 {
3808
3809         if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
3810
3811         if (INB(nc_istat) & (INTF|SIP|DIP)) {
3812                 /*
3813                 **      Repeat until no outstanding ints
3814                 */
3815                 do {
3816                         ncr_exception (np);
3817                 } while (INB(nc_istat) & (INTF|SIP|DIP));
3818
3819                 np->ticks = 100;
3820         };
3821
3822         if (DEBUG_FLAGS & DEBUG_TINY) printf ("]\n");
3823 }
3824
3825 /*==========================================================
3826 **
3827 **
3828 **      Start execution of a SCSI command.
3829 **      This is called from the generic SCSI driver.
3830 **
3831 **
3832 **==========================================================
3833 */
3834
3835 static void
3836 ncr_action (struct cam_sim *sim, union ccb *ccb)
3837 {
3838         ncb_p np;
3839
3840         np = (ncb_p) cam_sim_softc(sim);
3841         mtx_assert(&np->lock, MA_OWNED);
3842
3843         switch (ccb->ccb_h.func_code) {
3844         /* Common cases first */
3845         case XPT_SCSI_IO:       /* Execute the requested I/O operation */
3846         {
3847                 nccb_p cp;
3848                 lcb_p lp;
3849                 tcb_p tp;
3850                 struct ccb_scsiio *csio;
3851                 u_int8_t *msgptr;
3852                 u_int msglen;
3853                 u_int msglen2;
3854                 int segments;
3855                 u_int8_t nego;
3856                 u_int8_t idmsg;
3857                 int qidx;
3858                 
3859                 tp = &np->target[ccb->ccb_h.target_id];
3860                 csio = &ccb->csio;
3861
3862                 /*
3863                  * Last time we need to check if this CCB needs to
3864                  * be aborted.
3865                  */
3866                 if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3867                         xpt_done(ccb);
3868                         return;
3869                 }
3870                 ccb->ccb_h.status |= CAM_SIM_QUEUED;
3871
3872                 /*---------------------------------------------------
3873                 **
3874                 **      Assign an nccb / bind ccb
3875                 **
3876                 **----------------------------------------------------
3877                 */
3878                 cp = ncr_get_nccb (np, ccb->ccb_h.target_id,
3879                                    ccb->ccb_h.target_lun);
3880                 if (cp == NULL) {
3881                         /* XXX JGibbs - Freeze SIMQ */
3882                         ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3883                         xpt_done(ccb);
3884                         return;
3885                 };
3886                 
3887                 cp->ccb = ccb;
3888                 
3889                 /*---------------------------------------------------
3890                 **
3891                 **      timestamp
3892                 **
3893                 **----------------------------------------------------
3894                 */
3895                 /*
3896                 ** XXX JGibbs - Isn't this expensive
3897                 **              enough to be conditionalized??
3898                 */
3899
3900                 bzero (&cp->phys.header.stamp, sizeof (struct tstamp));
3901                 cp->phys.header.stamp.start = ticks;
3902
3903                 nego = 0;
3904                 if (tp->nego_cp == NULL) {
3905                         
3906                         if (tp->tinfo.current.width
3907                          != tp->tinfo.goal.width) {
3908                                 tp->nego_cp = cp;
3909                                 nego = NS_WIDE;
3910                         } else if ((tp->tinfo.current.period
3911                                     != tp->tinfo.goal.period)
3912                                 || (tp->tinfo.current.offset
3913                                     != tp->tinfo.goal.offset)) {
3914                                 tp->nego_cp = cp;
3915                                 nego = NS_SYNC;
3916                         };
3917                 };
3918
3919                 /*---------------------------------------------------
3920                 **
3921                 **      choose a new tag ...
3922                 **
3923                 **----------------------------------------------------
3924                 */
3925                 lp = tp->lp[ccb->ccb_h.target_lun];
3926
3927                 if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0
3928                  && (ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
3929                  && (nego == 0)) {
3930                         /*
3931                         **      assign a tag to this nccb
3932                         */
3933                         while (!cp->tag) {
3934                                 nccb_p cp2 = lp->next_nccb;
3935                                 lp->lasttag = lp->lasttag % 255 + 1;
3936                                 while (cp2 && cp2->tag != lp->lasttag)
3937                                         cp2 = cp2->next_nccb;
3938                                 if (cp2) continue;
3939                                 cp->tag=lp->lasttag;
3940                                 if (DEBUG_FLAGS & DEBUG_TAGS) {
3941                                         PRINT_ADDR(ccb);
3942                                         printf ("using tag #%d.\n", cp->tag);
3943                                 };
3944                         };
3945                 } else {
3946                         cp->tag=0;
3947                 };
3948
3949                 /*----------------------------------------------------
3950                 **
3951                 **      Build the identify / tag / sdtr message
3952                 **
3953                 **----------------------------------------------------
3954                 */
3955                 idmsg = MSG_IDENTIFYFLAG | ccb->ccb_h.target_lun;
3956                 if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
3957                         idmsg |= MSG_IDENTIFY_DISCFLAG;
3958
3959                 msgptr = cp->scsi_smsg;
3960                 msglen = 0;
3961                 msgptr[msglen++] = idmsg;
3962
3963                 if (cp->tag) {
3964                         msgptr[msglen++] = ccb->csio.tag_action;
3965                         msgptr[msglen++] = cp->tag;
3966                 }
3967
3968                 switch (nego) {
3969                 case NS_SYNC:
3970                         msgptr[msglen++] = MSG_EXTENDED;
3971                         msgptr[msglen++] = MSG_EXT_SDTR_LEN;
3972                         msgptr[msglen++] = MSG_EXT_SDTR;
3973                         msgptr[msglen++] = tp->tinfo.goal.period;
3974                         msgptr[msglen++] = tp->tinfo.goal.offset;
3975                         if (DEBUG_FLAGS & DEBUG_NEGO) {
3976                                 PRINT_ADDR(ccb);
3977                                 printf ("sync msgout: ");
3978                                 ncr_show_msg (&cp->scsi_smsg [msglen-5]);
3979                                 printf (".\n");
3980                         };
3981                         break;
3982                 case NS_WIDE:
3983                         msgptr[msglen++] = MSG_EXTENDED;
3984                         msgptr[msglen++] = MSG_EXT_WDTR_LEN;
3985                         msgptr[msglen++] = MSG_EXT_WDTR;
3986                         msgptr[msglen++] = tp->tinfo.goal.width;
3987                         if (DEBUG_FLAGS & DEBUG_NEGO) {
3988                                 PRINT_ADDR(ccb);
3989                                 printf ("wide msgout: ");
3990                                 ncr_show_msg (&cp->scsi_smsg [msglen-4]);
3991                                 printf (".\n");
3992                         };
3993                         break;
3994                 };
3995
3996                 /*----------------------------------------------------
3997                 **
3998                 **      Build the identify message for getcc.
3999                 **
4000                 **----------------------------------------------------
4001                 */
4002
4003                 cp->scsi_smsg2 [0] = idmsg;
4004                 msglen2 = 1;
4005
4006                 /*----------------------------------------------------
4007                 **
4008                 **      Build the data descriptors
4009                 **
4010                 **----------------------------------------------------
4011                 */
4012
4013                 /* XXX JGibbs - Handle other types of I/O */
4014                 if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
4015                         segments = ncr_scatter(&cp->phys,
4016                                                (vm_offset_t)csio->data_ptr,
4017                                                (vm_size_t)csio->dxfer_len);
4018
4019                         if (segments < 0) {
4020                                 ccb->ccb_h.status = CAM_REQ_TOO_BIG;
4021                                 ncr_free_nccb(np, cp);
4022                                 xpt_done(ccb);
4023                                 return;
4024                         }
4025                         if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4026                                 cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_in);
4027                                 cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4028                         } else { /* CAM_DIR_OUT */
4029                                 cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_out);
4030                                 cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4031                         }
4032                 } else {
4033                         cp->phys.header.savep = NCB_SCRIPT_PHYS (np, no_data);
4034                         cp->phys.header.goalp = cp->phys.header.savep;
4035                 }
4036
4037                 cp->phys.header.lastp = cp->phys.header.savep;
4038
4039
4040                 /*----------------------------------------------------
4041                 **
4042                 **      fill in nccb
4043                 **
4044                 **----------------------------------------------------
4045                 **
4046                 **
4047                 **      physical -> virtual backlink
4048                 **      Generic SCSI command
4049                 */
4050                 cp->phys.header.cp              = cp;
4051                 /*
4052                 **      Startqueue
4053                 */
4054                 cp->phys.header.launch.l_paddr  = NCB_SCRIPT_PHYS (np, select);
4055                 cp->phys.header.launch.l_cmd    = SCR_JUMP;
4056                 /*
4057                 **      select
4058                 */
4059                 cp->phys.select.sel_id          = ccb->ccb_h.target_id;
4060                 cp->phys.select.sel_scntl3      = tp->tinfo.wval;
4061                 cp->phys.select.sel_sxfer       = tp->tinfo.sval;
4062                 /*
4063                 **      message
4064                 */
4065                 cp->phys.smsg.addr              = CCB_PHYS (cp, scsi_smsg);
4066                 cp->phys.smsg.size              = msglen;
4067         
4068                 cp->phys.smsg2.addr             = CCB_PHYS (cp, scsi_smsg2);
4069                 cp->phys.smsg2.size             = msglen2;
4070                 /*
4071                 **      command
4072                 */
4073                 /* XXX JGibbs - Support other command types */
4074                 cp->phys.cmd.addr               = vtophys (csio->cdb_io.cdb_bytes);
4075                 cp->phys.cmd.size               = csio->cdb_len;
4076                 /*
4077                 **      sense command
4078                 */
4079                 cp->phys.scmd.addr              = CCB_PHYS (cp, sensecmd);
4080                 cp->phys.scmd.size              = 6;
4081                 /*
4082                 **      patch requested size into sense command
4083                 */
4084                 cp->sensecmd[0]                 = 0x03;
4085                 cp->sensecmd[1]                 = ccb->ccb_h.target_lun << 5;
4086                 cp->sensecmd[4]                 = sizeof(struct scsi_sense_data);
4087                 cp->sensecmd[4]                 = csio->sense_len;
4088                 /*
4089                 **      sense data
4090                 */
4091                 cp->phys.sense.addr             = vtophys (&csio->sense_data);
4092                 cp->phys.sense.size             = csio->sense_len;
4093                 /*
4094                 **      status
4095                 */
4096                 cp->actualquirks                = QUIRK_NOMSG;
4097                 cp->host_status                 = nego ? HS_NEGOTIATE : HS_BUSY;
4098                 cp->s_status                    = SCSI_STATUS_ILLEGAL;
4099                 cp->parity_status               = 0;
4100         
4101                 cp->xerr_status                 = XE_OK;
4102                 cp->sync_status                 = tp->tinfo.sval;
4103                 cp->nego_status                 = nego;
4104                 cp->wide_status                 = tp->tinfo.wval;
4105
4106                 /*----------------------------------------------------
4107                 **
4108                 **      Critical region: start this job.
4109                 **
4110                 **----------------------------------------------------
4111                 */
4112
4113                 /*
4114                 **      reselect pattern and activate this job.
4115                 */
4116
4117                 cp->jump_nccb.l_cmd     = (SCR_JUMP ^ IFFALSE (DATA (cp->tag)));
4118                 cp->tlimit              = time_second
4119                                         + ccb->ccb_h.timeout / 1000 + 2;
4120                 cp->magic               = CCB_MAGIC;
4121
4122                 /*
4123                 **      insert into start queue.
4124                 */
4125
4126                 qidx = np->squeueput + 1;
4127                 if (qidx >= MAX_START)
4128                         qidx = 0;
4129                 np->squeue [qidx         ] = NCB_SCRIPT_PHYS (np, idle);
4130                 np->squeue [np->squeueput] = CCB_PHYS (cp, phys);
4131                 np->squeueput = qidx;
4132
4133                 if(DEBUG_FLAGS & DEBUG_QUEUE)
4134                         device_printf(np->dev, "queuepos=%d tryoffset=%d.\n",
4135                                np->squeueput,
4136                                (unsigned)(READSCRIPT(startpos[0]) - 
4137                                (NCB_SCRIPTH_PHYS (np, tryloop))));
4138
4139                 /*
4140                 **      Script processor may be waiting for reselect.
4141                 **      Wake it up.
4142                 */
4143                 OUTB (nc_istat, SIGP);
4144                 break;
4145         }
4146         case XPT_RESET_DEV:     /* Bus Device Reset the specified SCSI device */
4147         case XPT_EN_LUN:                /* Enable LUN as a target */
4148         case XPT_TARGET_IO:             /* Execute target I/O request */
4149         case XPT_ACCEPT_TARGET_IO:      /* Accept Host Target Mode CDB */
4150         case XPT_CONT_TARGET_IO:        /* Continue Host Target I/O Connection*/
4151         case XPT_ABORT:                 /* Abort the specified CCB */
4152                 /* XXX Implement */
4153                 ccb->ccb_h.status = CAM_REQ_INVALID;
4154                 xpt_done(ccb);
4155                 break;
4156         case XPT_SET_TRAN_SETTINGS:
4157         {
4158                 struct  ccb_trans_settings *cts = &ccb->cts;
4159                 tcb_p   tp;
4160                 u_int   update_type;
4161                 struct ccb_trans_settings_scsi *scsi =
4162                     &cts->proto_specific.scsi;
4163                 struct ccb_trans_settings_spi *spi =
4164                     &cts->xport_specific.spi;
4165
4166                 update_type = 0;
4167                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS)
4168                         update_type |= NCR_TRANS_GOAL;
4169                 if (cts->type == CTS_TYPE_USER_SETTINGS)
4170                         update_type |= NCR_TRANS_USER;
4171
4172                 tp = &np->target[ccb->ccb_h.target_id];
4173                 /* Tag and disc enables */
4174                 if ((spi->valid & CTS_SPI_VALID_DISC) != 0) {
4175                         if (update_type & NCR_TRANS_GOAL) {
4176                                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
4177                                         tp->tinfo.disc_tag |= NCR_CUR_DISCENB;
4178                                 else
4179                                         tp->tinfo.disc_tag &= ~NCR_CUR_DISCENB;
4180                         }
4181
4182                         if (update_type & NCR_TRANS_USER) {
4183                                 if ((spi->flags & CTS_SPI_FLAGS_DISC_ENB) != 0)
4184                                         tp->tinfo.disc_tag |= NCR_USR_DISCENB;
4185                                 else
4186                                         tp->tinfo.disc_tag &= ~NCR_USR_DISCENB;
4187                         }
4188
4189                 }
4190
4191                 if ((scsi->valid & CTS_SCSI_VALID_TQ) != 0) {
4192                         if (update_type & NCR_TRANS_GOAL) {
4193                                 if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
4194                                         tp->tinfo.disc_tag |= NCR_CUR_TAGENB;
4195                                 else
4196                                         tp->tinfo.disc_tag &= ~NCR_CUR_TAGENB;
4197                         }
4198
4199                         if (update_type & NCR_TRANS_USER) {
4200                                 if ((scsi->flags & CTS_SCSI_FLAGS_TAG_ENB) != 0)
4201                                         tp->tinfo.disc_tag |= NCR_USR_TAGENB;
4202                                 else
4203                                         tp->tinfo.disc_tag &= ~NCR_USR_TAGENB;
4204                         }       
4205                 }
4206
4207                 /* Filter bus width and sync negotiation settings */
4208                 if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0) {
4209                         if (spi->bus_width > np->maxwide)
4210                                 spi->bus_width = np->maxwide;
4211                 }
4212
4213                 if (((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4214                  || ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)) {
4215                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0) {
4216                                 if (spi->sync_period != 0
4217                                  && (spi->sync_period < np->minsync))
4218                                         spi->sync_period = np->minsync;
4219                         }
4220                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0) {
4221                                 if (spi->sync_offset == 0)
4222                                         spi->sync_period = 0;
4223                                 if (spi->sync_offset > np->maxoffs)
4224                                         spi->sync_offset = np->maxoffs;
4225                         }
4226                 }
4227                 if ((update_type & NCR_TRANS_USER) != 0) {
4228                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4229                                 tp->tinfo.user.period = spi->sync_period;
4230                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)
4231                                 tp->tinfo.user.offset = spi->sync_offset;
4232                         if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
4233                                 tp->tinfo.user.width = spi->bus_width;
4234                 }
4235                 if ((update_type & NCR_TRANS_GOAL) != 0) {
4236                         if ((spi->valid & CTS_SPI_VALID_SYNC_RATE) != 0)
4237                                 tp->tinfo.goal.period = spi->sync_period;
4238
4239                         if ((spi->valid & CTS_SPI_VALID_SYNC_OFFSET) != 0)
4240                                 tp->tinfo.goal.offset = spi->sync_offset;
4241
4242                         if ((spi->valid & CTS_SPI_VALID_BUS_WIDTH) != 0)
4243                                 tp->tinfo.goal.width = spi->bus_width;
4244                 }
4245                 ccb->ccb_h.status = CAM_REQ_CMP;
4246                 xpt_done(ccb);
4247                 break;
4248         }
4249         case XPT_GET_TRAN_SETTINGS:
4250         /* Get default/user set transfer settings for the target */
4251         {
4252                 struct  ccb_trans_settings *cts = &ccb->cts;
4253                 struct  ncr_transinfo *tinfo;
4254                 tcb_p   tp = &np->target[ccb->ccb_h.target_id];
4255                 struct ccb_trans_settings_scsi *scsi =
4256                     &cts->proto_specific.scsi;
4257                 struct ccb_trans_settings_spi *spi =
4258                     &cts->xport_specific.spi;
4259
4260                 cts->protocol = PROTO_SCSI;
4261                 cts->protocol_version = SCSI_REV_2;
4262                 cts->transport = XPORT_SPI;
4263                 cts->transport_version = 2;
4264
4265                 if (cts->type == CTS_TYPE_CURRENT_SETTINGS) {
4266                         tinfo = &tp->tinfo.current;
4267                         if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
4268                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
4269                         else
4270                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
4271
4272                         if (tp->tinfo.disc_tag & NCR_CUR_TAGENB)
4273                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
4274                         else
4275                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
4276                 } else {
4277                         tinfo = &tp->tinfo.user;
4278                         if (tp->tinfo.disc_tag & NCR_USR_DISCENB)
4279                                 spi->flags |= CTS_SPI_FLAGS_DISC_ENB;
4280                         else
4281                                 spi->flags &= ~CTS_SPI_FLAGS_DISC_ENB;
4282
4283                         if (tp->tinfo.disc_tag & NCR_USR_TAGENB)
4284                                 scsi->flags |= CTS_SCSI_FLAGS_TAG_ENB;
4285                         else
4286                                 scsi->flags &= ~CTS_SCSI_FLAGS_TAG_ENB;
4287                 }
4288
4289                 spi->sync_period = tinfo->period;
4290                 spi->sync_offset = tinfo->offset;
4291                 spi->bus_width = tinfo->width;
4292
4293                 spi->valid = CTS_SPI_VALID_SYNC_RATE
4294                            | CTS_SPI_VALID_SYNC_OFFSET
4295                            | CTS_SPI_VALID_BUS_WIDTH
4296                            | CTS_SPI_VALID_DISC;
4297                 scsi->valid = CTS_SCSI_VALID_TQ;
4298
4299                 ccb->ccb_h.status = CAM_REQ_CMP;
4300                 xpt_done(ccb);
4301                 break;
4302         }
4303         case XPT_CALC_GEOMETRY:
4304         {
4305                 /* XXX JGibbs - I'm sure the NCR uses a different strategy,
4306                  *              but it should be able to deal with Adaptec
4307                  *              geometry too.
4308                  */
4309                 cam_calc_geometry(&ccb->ccg, /*extended*/1);
4310                 xpt_done(ccb);
4311                 break;
4312         }
4313         case XPT_RESET_BUS:             /* Reset the specified SCSI bus */
4314         {
4315                 OUTB (nc_scntl1, CRST);
4316                 ccb->ccb_h.status = CAM_REQ_CMP;
4317                 DELAY(10000);   /* Wait until our interrupt handler sees it */ 
4318                 xpt_done(ccb);
4319                 break;
4320         }
4321         case XPT_TERM_IO:               /* Terminate the I/O process */
4322                 /* XXX Implement */
4323                 ccb->ccb_h.status = CAM_REQ_INVALID;
4324                 xpt_done(ccb);
4325                 break;
4326         case XPT_PATH_INQ:              /* Path routing inquiry */
4327         {
4328                 struct ccb_pathinq *cpi = &ccb->cpi;
4329                 
4330                 cpi->version_num = 1; /* XXX??? */
4331                 cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE;
4332                 if ((np->features & FE_WIDE) != 0)
4333                         cpi->hba_inquiry |= PI_WIDE_16;
4334                 cpi->target_sprt = 0;
4335                 cpi->hba_misc = 0;
4336                 cpi->hba_eng_cnt = 0;
4337                 cpi->max_target = (np->features & FE_WIDE) ? 15 : 7;
4338                 cpi->max_lun = MAX_LUN - 1;
4339                 cpi->initiator_id = np->myaddr;
4340                 cpi->bus_id = cam_sim_bus(sim);
4341                 cpi->base_transfer_speed = 3300;
4342                 strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4343                 strncpy(cpi->hba_vid, "Symbios", HBA_IDLEN);
4344                 strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
4345                 cpi->unit_number = cam_sim_unit(sim);
4346                 cpi->transport = XPORT_SPI;
4347                 cpi->transport_version = 2;
4348                 cpi->protocol = PROTO_SCSI;
4349                 cpi->protocol_version = SCSI_REV_2;
4350                 cpi->ccb_h.status = CAM_REQ_CMP;
4351                 xpt_done(ccb);
4352                 break;
4353         }
4354         default:
4355                 ccb->ccb_h.status = CAM_REQ_INVALID;
4356                 xpt_done(ccb);
4357                 break;
4358         }
4359 }
4360
4361 /*==========================================================
4362 **
4363 **
4364 **      Complete execution of a SCSI command.
4365 **      Signal completion to the generic SCSI driver.
4366 **
4367 **
4368 **==========================================================
4369 */
4370
4371 static void
4372 ncr_complete (ncb_p np, nccb_p cp)
4373 {
4374         union ccb *ccb;
4375         tcb_p tp;
4376
4377         /*
4378         **      Sanity check
4379         */
4380
4381         if (!cp || (cp->magic!=CCB_MAGIC) || !cp->ccb) return;
4382         cp->magic = 1;
4383         cp->tlimit= 0;
4384
4385         /*
4386         **      No Reselect anymore.
4387         */
4388         cp->jump_nccb.l_cmd = (SCR_JUMP);
4389
4390         /*
4391         **      No starting.
4392         */
4393         cp->phys.header.launch.l_paddr= NCB_SCRIPT_PHYS (np, idle);
4394
4395         /*
4396         **      timestamp
4397         */
4398         ncb_profile (np, cp);
4399
4400         if (DEBUG_FLAGS & DEBUG_TINY)
4401                 printf ("CCB=%x STAT=%x/%x\n", (int)(intptr_t)cp & 0xfff,
4402                         cp->host_status,cp->s_status);
4403
4404         ccb = cp->ccb;
4405         cp->ccb = NULL;
4406         tp = &np->target[ccb->ccb_h.target_id];
4407
4408         /*
4409         **      We do not queue more than 1 nccb per target 
4410         **      with negotiation at any time. If this nccb was 
4411         **      used for negotiation, clear this info in the tcb.
4412         */
4413
4414         if (cp == tp->nego_cp)
4415                 tp->nego_cp = NULL;
4416
4417         /*
4418         **      Check for parity errors.
4419         */
4420         /* XXX JGibbs - What about reporting them??? */
4421
4422         if (cp->parity_status) {
4423                 PRINT_ADDR(ccb);
4424                 printf ("%d parity error(s), fallback.\n", cp->parity_status);
4425                 /*
4426                 **      fallback to asynch transfer.
4427                 */
4428                 tp->tinfo.goal.period = 0;
4429                 tp->tinfo.goal.offset = 0;
4430         };
4431
4432         /*
4433         **      Check for extended errors.
4434         */
4435
4436         if (cp->xerr_status != XE_OK) {
4437                 PRINT_ADDR(ccb);
4438                 switch (cp->xerr_status) {
4439                 case XE_EXTRA_DATA:
4440                         printf ("extraneous data discarded.\n");
4441                         break;
4442                 case XE_BAD_PHASE:
4443                         printf ("illegal scsi phase (4/5).\n");
4444                         break;
4445                 default:
4446                         printf ("extended error %d.\n", cp->xerr_status);
4447                         break;
4448                 };
4449                 if (cp->host_status==HS_COMPLETE)
4450                         cp->host_status = HS_FAIL;
4451         };
4452
4453         /*
4454         **      Check the status.
4455         */
4456         if (cp->host_status == HS_COMPLETE) {
4457
4458                 if (cp->s_status == SCSI_STATUS_OK) {
4459
4460                         /*
4461                         **      All went well.
4462                         */
4463                         /* XXX JGibbs - Properly calculate residual */
4464
4465                         tp->bytes     += ccb->csio.dxfer_len;
4466                         tp->transfers ++;
4467
4468                         ccb->ccb_h.status = CAM_REQ_CMP;
4469                 } else if ((cp->s_status & SCSI_STATUS_SENSE) != 0) {
4470
4471                         /*
4472                          * XXX Could be TERMIO too.  Should record
4473                          * original status.
4474                          */
4475                         ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
4476                         cp->s_status &= ~SCSI_STATUS_SENSE;
4477                         if (cp->s_status == SCSI_STATUS_OK) {
4478                                 ccb->ccb_h.status =
4479                                     CAM_AUTOSNS_VALID|CAM_SCSI_STATUS_ERROR;
4480                         } else {
4481                                 ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
4482                         }
4483                 } else {
4484                         ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;                      
4485                         ccb->csio.scsi_status = cp->s_status;
4486                 }
4487                 
4488                 
4489         } else if (cp->host_status == HS_SEL_TIMEOUT) {
4490
4491                 /*
4492                 **   Device failed selection
4493                 */
4494                 ccb->ccb_h.status = CAM_SEL_TIMEOUT;
4495
4496         } else if (cp->host_status == HS_TIMEOUT) {
4497
4498                 /*
4499                 **   No response
4500                 */
4501                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4502         } else if (cp->host_status == HS_STALL) {
4503                 ccb->ccb_h.status = CAM_REQUEUE_REQ;
4504         } else {
4505
4506                 /*
4507                 **  Other protocol messes
4508                 */
4509                 PRINT_ADDR(ccb);
4510                 printf ("COMMAND FAILED (%x %x) @%p.\n",
4511                         cp->host_status, cp->s_status, cp);
4512
4513                 ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4514         }
4515
4516         if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4517                 xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
4518                 ccb->ccb_h.status |= CAM_DEV_QFRZN;
4519         }
4520
4521         /*
4522         **      Free this nccb
4523         */
4524         ncr_free_nccb (np, cp);
4525
4526         /*
4527         **      signal completion to generic driver.
4528         */
4529         xpt_done (ccb);
4530 }
4531
4532 /*==========================================================
4533 **
4534 **
4535 **      Signal all (or one) control block done.
4536 **
4537 **
4538 **==========================================================
4539 */
4540
4541 static void
4542 ncr_wakeup (ncb_p np, u_long code)
4543 {
4544         /*
4545         **      Starting at the default nccb and following
4546         **      the links, complete all jobs with a
4547         **      host_status greater than "disconnect".
4548         **
4549         **      If the "code" parameter is not zero,
4550         **      complete all jobs that are not IDLE.
4551         */
4552
4553         nccb_p cp = np->link_nccb;
4554         while (cp) {
4555                 switch (cp->host_status) {
4556
4557                 case HS_IDLE:
4558                         break;
4559
4560                 case HS_DISCONNECT:
4561                         if(DEBUG_FLAGS & DEBUG_TINY) printf ("D");
4562                         /* FALLTHROUGH */
4563
4564                 case HS_BUSY:
4565                 case HS_NEGOTIATE:
4566                         if (!code) break;
4567                         cp->host_status = code;
4568
4569                         /* FALLTHROUGH */
4570
4571                 default:
4572                         ncr_complete (np, cp);
4573                         break;
4574                 };
4575                 cp = cp -> link_nccb;
4576         };
4577 }
4578
4579 static void
4580 ncr_freeze_devq (ncb_p np, struct cam_path *path)
4581 {
4582         nccb_p  cp;
4583         int     i;
4584         int     count;
4585         int     firstskip;
4586         /*
4587         **      Starting at the first nccb and following
4588         **      the links, complete all jobs that match
4589         **      the passed in path and are in the start queue.
4590         */
4591
4592         cp = np->link_nccb;
4593         count = 0;
4594         firstskip = 0;
4595         while (cp) {
4596                 switch (cp->host_status) {
4597
4598                 case HS_BUSY:
4599                 case HS_NEGOTIATE:
4600                         if ((cp->phys.header.launch.l_paddr
4601                             == NCB_SCRIPT_PHYS (np, select))
4602                          && (xpt_path_comp(path, cp->ccb->ccb_h.path) >= 0)) {
4603
4604                                 /* Mark for removal from the start queue */
4605                                 for (i = 1; i < MAX_START; i++) {
4606                                         int idx;
4607
4608                                         idx = np->squeueput - i;
4609                                 
4610                                         if (idx < 0)
4611                                                 idx = MAX_START + idx;
4612                                         if (np->squeue[idx]
4613                                          == CCB_PHYS(cp, phys)) {
4614                                                 np->squeue[idx] =
4615                                                     NCB_SCRIPT_PHYS (np, skip);
4616                                                 if (i > firstskip)
4617                                                         firstskip = i;
4618                                                 break;
4619                                         }
4620                                 }
4621                                 cp->host_status=HS_STALL;
4622                                 ncr_complete (np, cp);
4623                                 count++;
4624                         }
4625                         break;
4626                 default:
4627                         break;
4628                 }
4629                 cp = cp->link_nccb;
4630         }
4631
4632         if (count > 0) {
4633                 int j;
4634                 int bidx;
4635
4636                 /* Compress the start queue */
4637                 j = 0;
4638                 bidx = np->squeueput;
4639                 i = np->squeueput - firstskip;
4640                 if (i < 0)
4641                         i = MAX_START + i;
4642                 for (;;) {
4643
4644                         bidx = i - j;
4645                         if (bidx < 0)
4646                                 bidx = MAX_START + bidx;
4647                         
4648                         if (np->squeue[i] == NCB_SCRIPT_PHYS (np, skip)) {
4649                                 j++;
4650                         } else if (j != 0) {
4651                                 np->squeue[bidx] = np->squeue[i];
4652                                 if (np->squeue[bidx]
4653                                  == NCB_SCRIPT_PHYS(np, idle))
4654                                         break;
4655                         }
4656                         i = (i + 1) % MAX_START;
4657                 }
4658                 np->squeueput = bidx;
4659         }
4660 }
4661
4662 /*==========================================================
4663 **
4664 **
4665 **      Start NCR chip.
4666 **
4667 **
4668 **==========================================================
4669 */
4670
4671 static void
4672 ncr_init(ncb_p np, char * msg, u_long code)
4673 {
4674         int     i;
4675
4676         /*
4677         **      Reset chip.
4678         */
4679
4680         OUTB (nc_istat,  SRST);
4681         DELAY (1000);
4682         OUTB (nc_istat, 0);
4683
4684         /*
4685         **      Message.
4686         */
4687
4688         if (msg)
4689                 device_printf(np->dev, "restart (%s).\n", msg);
4690
4691         /*
4692         **      Clear Start Queue
4693         */
4694
4695         for (i=0;i<MAX_START;i++)
4696                 np -> squeue [i] = NCB_SCRIPT_PHYS (np, idle);
4697
4698         /*
4699         **      Start at first entry.
4700         */
4701
4702         np->squeueput = 0;
4703         WRITESCRIPT(startpos[0], NCB_SCRIPTH_PHYS (np, tryloop));
4704         WRITESCRIPT(start0  [0], SCR_INT ^ IFFALSE (0));
4705
4706         /*
4707         **      Wakeup all pending jobs.
4708         */
4709
4710         ncr_wakeup (np, code);
4711
4712         /*
4713         **      Init chip.
4714         */
4715
4716         OUTB (nc_istat,  0x00   );      /*  Remove Reset, abort ...          */
4717         OUTB (nc_scntl0, 0xca   );      /*  full arb., ena parity, par->ATN  */
4718         OUTB (nc_scntl1, 0x00   );      /*  odd parity, and remove CRST!!    */
4719         ncr_selectclock(np, np->rv_scntl3); /* Select SCSI clock             */
4720         OUTB (nc_scid  , RRE|np->myaddr);/*  host adapter SCSI address       */
4721         OUTW (nc_respid, 1ul<<np->myaddr);/*  id to respond to               */
4722         OUTB (nc_istat , SIGP   );      /*  Signal Process                   */
4723         OUTB (nc_dmode , np->rv_dmode); /* XXX modify burstlen ??? */
4724         OUTB (nc_dcntl , np->rv_dcntl);
4725         OUTB (nc_ctest3, np->rv_ctest3);
4726         OUTB (nc_ctest5, np->rv_ctest5);
4727         OUTB (nc_ctest4, np->rv_ctest4);/*  enable master parity checking    */
4728         OUTB (nc_stest2, np->rv_stest2|EXT); /* Extended Sreq/Sack filtering */
4729         OUTB (nc_stest3, TE     );      /*  TolerANT enable                  */
4730         OUTB (nc_stime0, 0x0b   );      /*  HTH = disabled, STO = 0.1 sec.   */
4731
4732         if (bootverbose >= 2) {
4733                 printf ("\tACTUAL values:SCNTL3:%02x DMODE:%02x  DCNTL:%02x\n",
4734                         np->rv_scntl3, np->rv_dmode, np->rv_dcntl);
4735                 printf ("\t              CTEST3:%02x CTEST4:%02x CTEST5:%02x\n",
4736                         np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4737         }
4738
4739         /*
4740         **    Enable GPIO0 pin for writing if LED support.
4741         */
4742
4743         if (np->features & FE_LED0) {
4744                 OUTOFFB (nc_gpcntl, 0x01);
4745         }
4746
4747         /*
4748         **      Fill in target structure.
4749         */
4750         for (i=0;i<MAX_TARGET;i++) {
4751                 tcb_p tp = &np->target[i];
4752
4753                 tp->tinfo.sval    = 0;
4754                 tp->tinfo.wval    = np->rv_scntl3;
4755
4756                 tp->tinfo.current.period = 0;
4757                 tp->tinfo.current.offset = 0;
4758                 tp->tinfo.current.width = MSG_EXT_WDTR_BUS_8_BIT;
4759         }
4760
4761         /*
4762         **      enable ints
4763         */
4764
4765         OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST);
4766         OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
4767
4768         /*
4769         **    Start script processor.
4770         */
4771
4772         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
4773
4774         /*
4775          * Notify the XPT of the event
4776          */
4777         if (code == HS_RESET)
4778                 xpt_async(AC_BUS_RESET, np->path, NULL);
4779 }
4780
4781 static void
4782 ncr_poll(struct cam_sim *sim)
4783 {       
4784         ncr_intr_locked(cam_sim_softc(sim));  
4785 }
4786
4787
4788 /*==========================================================
4789 **
4790 **      Get clock factor and sync divisor for a given 
4791 **      synchronous factor period.
4792 **      Returns the clock factor (in sxfer) and scntl3 
4793 **      synchronous divisor field.
4794 **
4795 **==========================================================
4796 */
4797
4798 static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
4799 {
4800         u_long  clk = np->clock_khz;    /* SCSI clock frequency in kHz  */
4801         int     div = np->clock_divn;   /* Number of divisors supported */
4802         u_long  fak;                    /* Sync factor in sxfer         */
4803         u_long  per;                    /* Period in tenths of ns       */
4804         u_long  kpc;                    /* (per * clk)                  */
4805
4806         /*
4807         **      Compute the synchronous period in tenths of nano-seconds
4808         */
4809         if      (sfac <= 10)    per = 250;
4810         else if (sfac == 11)    per = 303;
4811         else if (sfac == 12)    per = 500;
4812         else                    per = 40 * sfac;
4813
4814         /*
4815         **      Look for the greatest clock divisor that allows an 
4816         **      input speed faster than the period.
4817         */
4818         kpc = per * clk;
4819         while (--div >= 0)
4820                 if (kpc >= (div_10M[div] * 4)) break;
4821
4822         /*
4823         **      Calculate the lowest clock factor that allows an output 
4824         **      speed not faster than the period.
4825         */
4826         fak = (kpc - 1) / div_10M[div] + 1;
4827
4828 #if 0   /* You can #if 1 if you think this optimization is useful */
4829
4830         per = (fak * div_10M[div]) / clk;
4831
4832         /*
4833         **      Why not to try the immediate lower divisor and to choose 
4834         **      the one that allows the fastest output speed ?
4835         **      We dont want input speed too much greater than output speed.
4836         */
4837         if (div >= 1 && fak < 6) {
4838                 u_long fak2, per2;
4839                 fak2 = (kpc - 1) / div_10M[div-1] + 1;
4840                 per2 = (fak2 * div_10M[div-1]) / clk;
4841                 if (per2 < per && fak2 <= 6) {
4842                         fak = fak2;
4843                         per = per2;
4844                         --div;
4845                 }
4846         }
4847 #endif
4848
4849         if (fak < 4) fak = 4;   /* Should never happen, too bad ... */
4850
4851         /*
4852         **      Compute and return sync parameters for the ncr
4853         */
4854         *fakp           = fak - 4;
4855         *scntl3p        = ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
4856 }
4857
4858 /*==========================================================
4859 **
4860 **      Switch sync mode for current job and its target
4861 **
4862 **==========================================================
4863 */
4864
4865 static void
4866 ncr_setsync(ncb_p np, nccb_p cp, u_char scntl3, u_char sxfer, u_char period)
4867 {
4868         union   ccb *ccb;
4869         struct  ccb_trans_settings neg; 
4870         tcb_p   tp;
4871         int     div;
4872         u_int   target = INB (nc_sdid) & 0x0f;
4873         u_int   period_10ns;
4874
4875         assert (cp);
4876         if (!cp) return;
4877
4878         ccb = cp->ccb;
4879         assert (ccb);
4880         if (!ccb) return;
4881         assert (target == ccb->ccb_h.target_id);
4882
4883         tp = &np->target[target];
4884
4885         if (!scntl3 || !(sxfer & 0x1f))
4886                 scntl3 = np->rv_scntl3;
4887         scntl3 = (scntl3 & 0xf0) | (tp->tinfo.wval & EWS)
4888                | (np->rv_scntl3 & 0x07);
4889
4890         /*
4891         **      Deduce the value of controller sync period from scntl3.
4892         **      period is in tenths of nano-seconds.
4893         */
4894
4895         div = ((scntl3 >> 4) & 0x7);
4896         if ((sxfer & 0x1f) && div)
4897                 period_10ns =
4898                     (((sxfer>>5)+4)*div_10M[div-1])/np->clock_khz;
4899         else
4900                 period_10ns = 0;
4901
4902         tp->tinfo.goal.period = period;
4903         tp->tinfo.goal.offset = sxfer & 0x1f;
4904         tp->tinfo.current.period = period;
4905         tp->tinfo.current.offset = sxfer & 0x1f;
4906
4907         /*
4908         **       Stop there if sync parameters are unchanged
4909         */
4910         if (tp->tinfo.sval == sxfer && tp->tinfo.wval == scntl3) return;
4911         tp->tinfo.sval = sxfer;
4912         tp->tinfo.wval = scntl3;
4913
4914         if (sxfer & 0x1f) {
4915                 /*
4916                 **  Disable extended Sreq/Sack filtering
4917                 */
4918                 if (period_10ns <= 2000) OUTOFFB (nc_stest2, EXT);
4919         }
4920
4921         /*
4922         ** Tell the SCSI layer about the
4923         ** new transfer parameters.
4924         */
4925         memset(&neg, 0, sizeof (neg));
4926         neg.protocol = PROTO_SCSI;
4927         neg.protocol_version = SCSI_REV_2;
4928         neg.transport = XPORT_SPI;
4929         neg.transport_version = 2;
4930         neg.xport_specific.spi.sync_period = period;
4931         neg.xport_specific.spi.sync_offset = sxfer & 0x1f;
4932         neg.xport_specific.spi.valid = CTS_SPI_VALID_SYNC_RATE
4933                 | CTS_SPI_VALID_SYNC_OFFSET;
4934         xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path,
4935                       /*priority*/1);
4936         xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
4937         
4938         /*
4939         **      set actual value and sync_status
4940         */
4941         OUTB (nc_sxfer, sxfer);
4942         np->sync_st = sxfer;
4943         OUTB (nc_scntl3, scntl3);
4944         np->wide_st = scntl3;
4945
4946         /*
4947         **      patch ALL nccbs of this target.
4948         */
4949         for (cp = np->link_nccb; cp; cp = cp->link_nccb) {
4950                 if (!cp->ccb) continue;
4951                 if (cp->ccb->ccb_h.target_id != target) continue;
4952                 cp->sync_status = sxfer;
4953                 cp->wide_status = scntl3;
4954         };
4955 }
4956
4957 /*==========================================================
4958 **
4959 **      Switch wide mode for current job and its target
4960 **      SCSI specs say: a SCSI device that accepts a WDTR 
4961 **      message shall reset the synchronous agreement to 
4962 **      asynchronous mode.
4963 **
4964 **==========================================================
4965 */
4966
4967 static void ncr_setwide (ncb_p np, nccb_p cp, u_char wide, u_char ack)
4968 {
4969         union   ccb *ccb;
4970         struct  ccb_trans_settings neg;         
4971         u_int   target = INB (nc_sdid) & 0x0f;
4972         tcb_p   tp;
4973         u_char  scntl3;
4974         u_char  sxfer;
4975
4976         assert (cp);
4977         if (!cp) return;
4978
4979         ccb = cp->ccb;
4980         assert (ccb);
4981         if (!ccb) return;
4982         assert (target == ccb->ccb_h.target_id);
4983
4984         tp = &np->target[target];
4985         tp->tinfo.current.width = wide;
4986         tp->tinfo.goal.width = wide;
4987         tp->tinfo.current.period = 0;
4988         tp->tinfo.current.offset = 0;
4989
4990         scntl3 = (tp->tinfo.wval & (~EWS)) | (wide ? EWS : 0);
4991
4992         sxfer = ack ? 0 : tp->tinfo.sval;
4993
4994         /*
4995         **       Stop there if sync/wide parameters are unchanged
4996         */
4997         if (tp->tinfo.sval == sxfer && tp->tinfo.wval == scntl3) return;
4998         tp->tinfo.sval = sxfer;
4999         tp->tinfo.wval = scntl3;
5000
5001         /* Tell the SCSI layer about the new transfer params */
5002         memset(&neg, 0, sizeof (neg));
5003         neg.protocol = PROTO_SCSI;
5004         neg.protocol_version = SCSI_REV_2;
5005         neg.transport = XPORT_SPI;
5006         neg.transport_version = 2;
5007         neg.xport_specific.spi.bus_width = (scntl3 & EWS) ?
5008             MSG_EXT_WDTR_BUS_16_BIT : MSG_EXT_WDTR_BUS_8_BIT;
5009         neg.xport_specific.spi.sync_period = 0;
5010         neg.xport_specific.spi.sync_offset = 0;
5011         neg.xport_specific.spi.valid = CTS_SPI_VALID_SYNC_RATE
5012                 | CTS_SPI_VALID_SYNC_OFFSET
5013                 | CTS_SPI_VALID_BUS_WIDTH;
5014         xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path, /*priority*/1);
5015         xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);      
5016
5017         /*
5018         **      set actual value and sync_status
5019         */
5020         OUTB (nc_sxfer, sxfer);
5021         np->sync_st = sxfer;
5022         OUTB (nc_scntl3, scntl3);
5023         np->wide_st = scntl3;
5024
5025         /*
5026         **      patch ALL nccbs of this target.
5027         */
5028         for (cp = np->link_nccb; cp; cp = cp->link_nccb) {
5029                 if (!cp->ccb) continue;
5030                 if (cp->ccb->ccb_h.target_id != target) continue;
5031                 cp->sync_status = sxfer;
5032                 cp->wide_status = scntl3;
5033         };
5034 }
5035
5036 /*==========================================================
5037 **
5038 **
5039 **      ncr timeout handler.
5040 **
5041 **
5042 **==========================================================
5043 **
5044 **      Misused to keep the driver running when
5045 **      interrupts are not configured correctly.
5046 **
5047 **----------------------------------------------------------
5048 */
5049
5050 static void
5051 ncr_timeout (void *arg)
5052 {
5053         ncb_p   np = arg;
5054         time_t  thistime = time_second;
5055         ticks_t step  = np->ticks;
5056         u_long  count = 0;
5057         long signed   t;
5058         nccb_p cp;
5059
5060         mtx_assert(&np->lock, MA_OWNED);
5061         if (np->lasttime != thistime) {
5062                 np->lasttime = thistime;
5063
5064                 /*----------------------------------------------------
5065                 **
5066                 **      handle ncr chip timeouts
5067                 **
5068                 **      Assumption:
5069                 **      We have a chance to arbitrate for the
5070                 **      SCSI bus at least every 10 seconds.
5071                 **
5072                 **----------------------------------------------------
5073                 */
5074
5075                 t = thistime - np->heartbeat;
5076
5077                 if (t<2) np->latetime=0; else np->latetime++;
5078
5079                 if (np->latetime>2) {
5080                         /*
5081                         **      If there are no requests, the script
5082                         **      processor will sleep on SEL_WAIT_RESEL.
5083                         **      But we have to check whether it died.
5084                         **      Let's try to wake it up.
5085                         */
5086                         OUTB (nc_istat, SIGP);
5087                 };
5088
5089                 /*----------------------------------------------------
5090                 **
5091                 **      handle nccb timeouts
5092                 **
5093                 **----------------------------------------------------
5094                 */
5095
5096                 for (cp=np->link_nccb; cp; cp=cp->link_nccb) {
5097                         /*
5098                         **      look for timed out nccbs.
5099                         */
5100                         if (!cp->host_status) continue;
5101                         count++;
5102                         if (cp->tlimit > thistime) continue;
5103
5104                         /*
5105                         **      Disable reselect.
5106                         **      Remove it from startqueue.
5107                         */
5108                         cp->jump_nccb.l_cmd = (SCR_JUMP);
5109                         if (cp->phys.header.launch.l_paddr ==
5110                                 NCB_SCRIPT_PHYS (np, select)) {
5111                                 device_printf(np->dev,
5112                                     "timeout nccb=%p (skip)\n", cp);
5113                                 cp->phys.header.launch.l_paddr
5114                                 = NCB_SCRIPT_PHYS (np, skip);
5115                         };
5116
5117                         switch (cp->host_status) {
5118
5119                         case HS_BUSY:
5120                         case HS_NEGOTIATE:
5121                                 /* FALLTHROUGH */
5122                         case HS_DISCONNECT:
5123                                 cp->host_status=HS_TIMEOUT;
5124                         };
5125                         cp->tag = 0;
5126
5127                         /*
5128                         **      wakeup this nccb.
5129                         */
5130                         ncr_complete (np, cp);
5131                 };
5132         }
5133
5134         callout_reset(&np->timer, step ? step : 1, ncr_timeout, np);
5135
5136         if (INB(nc_istat) & (INTF|SIP|DIP)) {
5137
5138                 /*
5139                 **      Process pending interrupts.
5140                 */
5141
5142                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("{");
5143                 ncr_exception (np);
5144                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("}");
5145         };
5146 }
5147
5148 /*==========================================================
5149 **
5150 **      log message for real hard errors
5151 **
5152 **      "ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
5153 **      "             reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
5154 **
5155 **      exception register:
5156 **              ds:     dstat
5157 **              si:     sist
5158 **
5159 **      SCSI bus lines:
5160 **              so:     control lines as driver by NCR.
5161 **              si:     control lines as seen by NCR.
5162 **              sd:     scsi data lines as seen by NCR.
5163 **
5164 **      wide/fastmode:
5165 **              sxfer:  (see the manual)
5166 **              scntl3: (see the manual)
5167 **
5168 **      current script command:
5169 **              dsp:    script address (relative to start of script).
5170 **              dbc:    first word of script command.
5171 **
5172 **      First 16 register of the chip:
5173 **              r0..rf
5174 **
5175 **==========================================================
5176 */
5177
5178 static void ncr_log_hard_error(ncb_p np, u_short sist, u_char dstat)
5179 {
5180         u_int32_t dsp;
5181         int     script_ofs;
5182         int     script_size;
5183         char    *script_name;
5184         u_char  *script_base;
5185         int     i;
5186
5187         dsp     = INL (nc_dsp);
5188
5189         if (np->p_script < dsp && 
5190             dsp <= np->p_script + sizeof(struct script)) {
5191                 script_ofs      = dsp - np->p_script;
5192                 script_size     = sizeof(struct script);
5193                 script_base     = (u_char *) np->script;
5194                 script_name     = "script";
5195         }
5196         else if (np->p_scripth < dsp && 
5197                  dsp <= np->p_scripth + sizeof(struct scripth)) {
5198                 script_ofs      = dsp - np->p_scripth;
5199                 script_size     = sizeof(struct scripth);
5200                 script_base     = (u_char *) np->scripth;
5201                 script_name     = "scripth";
5202         } else {
5203                 script_ofs      = dsp;
5204                 script_size     = 0;
5205                 script_base     = 0;
5206                 script_name     = "mem";
5207         }
5208
5209         device_printf(np->dev,
5210                 "%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
5211                 (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
5212                 (unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
5213                 (unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
5214                 (unsigned)INL (nc_dbc));
5215
5216         if (((script_ofs & 3) == 0) &&
5217             (unsigned)script_ofs < script_size) {
5218                 device_printf(np->dev, "script cmd = %08x\n",
5219                         (int)READSCRIPT_OFF(script_base, script_ofs));
5220         }
5221
5222         device_printf(np->dev, "regdump:");
5223         for (i=0; i<16;i++)
5224             printf (" %02x", (unsigned)INB_OFF(i));
5225         printf (".\n");
5226 }
5227
5228 /*==========================================================
5229 **
5230 **
5231 **      ncr chip exception handler.
5232 **
5233 **
5234 **==========================================================
5235 */
5236
5237 static void ncr_exception (ncb_p np)
5238 {
5239         u_char  istat, dstat;
5240         u_short sist;
5241
5242         /*
5243         **      interrupt on the fly ?
5244         */
5245         while ((istat = INB (nc_istat)) & INTF) {
5246                 if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
5247                 OUTB (nc_istat, INTF);
5248                 np->profile.num_fly++;
5249                 ncr_wakeup (np, 0);
5250         };
5251         if (!(istat & (SIP|DIP))) {
5252                 return;
5253         }
5254
5255         /*
5256         **      Steinbach's Guideline for Systems Programming:
5257         **      Never test for an error condition you don't know how to handle.
5258         */
5259
5260         sist  = (istat & SIP) ? INW (nc_sist)  : 0;
5261         dstat = (istat & DIP) ? INB (nc_dstat) : 0;
5262         np->profile.num_int++;
5263
5264         if (DEBUG_FLAGS & DEBUG_TINY)
5265                 printf ("<%d|%x:%x|%x:%x>",
5266                         INB(nc_scr0),
5267                         dstat,sist,
5268                         (unsigned)INL(nc_dsp),
5269                         (unsigned)INL(nc_dbc));
5270         if ((dstat==DFE) && (sist==PAR)) return;
5271
5272 /*==========================================================
5273 **
5274 **      First the normal cases.
5275 **
5276 **==========================================================
5277 */
5278         /*-------------------------------------------
5279         **      SCSI reset
5280         **-------------------------------------------
5281         */
5282
5283         if (sist & RST) {
5284                 ncr_init (np, bootverbose ? "scsi reset" : NULL, HS_RESET);
5285                 return;
5286         };
5287
5288         /*-------------------------------------------
5289         **      selection timeout
5290         **
5291         **      IID excluded from dstat mask!
5292         **      (chip bug)
5293         **-------------------------------------------
5294         */
5295
5296         if ((sist  & STO) &&
5297                 !(sist  & (GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5298                 !(dstat & (MDPE|BF|ABRT|SIR))) {
5299                 ncr_int_sto (np);
5300                 return;
5301         };
5302
5303         /*-------------------------------------------
5304         **      Phase mismatch.
5305         **-------------------------------------------
5306         */
5307
5308         if ((sist  & MA) &&
5309                 !(sist  & (STO|GEN|HTH|SGE|UDC|RST|PAR)) &&
5310                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5311                 ncr_int_ma (np, dstat);
5312                 return;
5313         };
5314
5315         /*----------------------------------------
5316         **      move command with length 0
5317         **----------------------------------------
5318         */
5319
5320         if ((dstat & IID) &&
5321                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5322                 !(dstat & (MDPE|BF|ABRT|SIR)) &&
5323                 ((INL(nc_dbc) & 0xf8000000) == SCR_MOVE_TBL)) {
5324                 /*
5325                 **      Target wants more data than available.
5326                 **      The "no_data" script will do it.
5327                 */
5328                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, no_data));
5329                 return;
5330         };
5331
5332         /*-------------------------------------------
5333         **      Programmed interrupt
5334         **-------------------------------------------
5335         */
5336
5337         if ((dstat & SIR) &&
5338                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5339                 !(dstat & (MDPE|BF|ABRT|IID)) &&
5340                 (INB(nc_dsps) <= SIR_MAX)) {
5341                 ncr_int_sir (np);
5342                 return;
5343         };
5344
5345         /*========================================
5346         **      log message for real hard errors
5347         **========================================
5348         */
5349
5350         ncr_log_hard_error(np, sist, dstat);
5351
5352         /*========================================
5353         **      do the register dump
5354         **========================================
5355         */
5356
5357         if (time_second - np->regtime > 10) {
5358                 int i;
5359                 np->regtime = time_second;
5360                 for (i=0; i<sizeof(np->regdump); i++)
5361                         ((volatile char*)&np->regdump)[i] = INB_OFF(i);
5362                 np->regdump.nc_dstat = dstat;
5363                 np->regdump.nc_sist  = sist;
5364         };
5365
5366
5367         /*----------------------------------------
5368         **      clean up the dma fifo
5369         **----------------------------------------
5370         */
5371
5372         if ( (INB(nc_sstat0) & (ILF|ORF|OLF)   ) ||
5373              (INB(nc_sstat1) & (FF3210) ) ||
5374              (INB(nc_sstat2) & (ILF1|ORF1|OLF1)) ||     /* wide .. */
5375              !(dstat & DFE)) {
5376                 device_printf(np->dev, "have to clear fifos.\n");
5377                 OUTB (nc_stest3, TE|CSF);       /* clear scsi fifo */
5378                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);
5379                                                 /* clear dma fifo  */
5380         }
5381
5382         /*----------------------------------------
5383         **      handshake timeout
5384         **----------------------------------------
5385         */
5386
5387         if (sist & HTH) {
5388                 device_printf(np->dev, "handshake timeout\n");
5389                 OUTB (nc_scntl1, CRST);
5390                 DELAY (1000);
5391                 OUTB (nc_scntl1, 0x00);
5392                 OUTB (nc_scr0, HS_FAIL);
5393                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5394                 return;
5395         }
5396
5397         /*----------------------------------------
5398         **      unexpected disconnect
5399         **----------------------------------------
5400         */
5401
5402         if ((sist  & UDC) &&
5403                 !(sist  & (STO|GEN|HTH|MA|SGE|RST|PAR)) &&
5404                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5405                 OUTB (nc_scr0, HS_UNEXPECTED);
5406                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5407                 return;
5408         };
5409
5410         /*----------------------------------------
5411         **      cannot disconnect
5412         **----------------------------------------
5413         */
5414
5415         if ((dstat & IID) &&
5416                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5417                 !(dstat & (MDPE|BF|ABRT|SIR)) &&
5418                 ((INL(nc_dbc) & 0xf8000000) == SCR_WAIT_DISC)) {
5419                 /*
5420                 **      Unexpected data cycle while waiting for disconnect.
5421                 */
5422                 if (INB(nc_sstat2) & LDSC) {
5423                         /*
5424                         **      It's an early reconnect.
5425                         **      Let's continue ...
5426                         */
5427                         OUTB (nc_dcntl, np->rv_dcntl | STD);
5428                         /*
5429                         **      info message
5430                         */
5431                         device_printf(np->dev, "INFO: LDSC while IID.\n");
5432                         return;
5433                 };
5434                 device_printf(np->dev, "target %d doesn't release the bus.\n",
5435                         INB (nc_sdid)&0x0f);
5436                 /*
5437                 **      return without restarting the NCR.
5438                 **      timeout will do the real work.
5439                 */
5440                 return;
5441         };
5442
5443         /*----------------------------------------
5444         **      single step
5445         **----------------------------------------
5446         */
5447
5448         if ((dstat & SSI) &&
5449                 !(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5450                 !(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5451                 OUTB (nc_dcntl, np->rv_dcntl | STD);
5452                 return;
5453         };
5454
5455 /*
5456 **      @RECOVER@ HTH, SGE, ABRT.
5457 **
5458 **      We should try to recover from these interrupts.
5459 **      They may occur if there are problems with synch transfers, or 
5460 **      if targets are switched on or off while the driver is running.
5461 */
5462
5463         if (sist & SGE) {
5464                 /* clear scsi offsets */
5465                 OUTB (nc_ctest3, np->rv_ctest3 | CLF);
5466         }
5467
5468         /*
5469         **      Freeze controller to be able to read the messages.
5470         */
5471
5472         if (DEBUG_FLAGS & DEBUG_FREEZE) {
5473                 int i;
5474                 unsigned char val;
5475                 for (i=0; i<0x60; i++) {
5476                         switch (i%16) {
5477
5478                         case 0:
5479                                 device_printf(np->dev, "reg[%d0]: ", i / 16);
5480                                 break;
5481                         case 4:
5482                         case 8:
5483                         case 12:
5484                                 printf (" ");
5485                                 break;
5486                         };
5487                         val = bus_read_1(np->reg_res, i);
5488                         printf (" %x%x", val/16, val%16);
5489                         if (i%16==15) printf (".\n");
5490                 };
5491
5492                 callout_stop(&np->timer);
5493
5494                 device_printf(np->dev, "halted!\n");
5495                 /*
5496                 **      don't restart controller ...
5497                 */
5498                 OUTB (nc_istat,  SRST);
5499                 return;
5500         };
5501
5502 #ifdef NCR_FREEZE
5503         /*
5504         **      Freeze system to be able to read the messages.
5505         */
5506         printf ("ncr: fatal error: system halted - press reset to reboot ...");
5507         for (;;);
5508 #endif
5509
5510         /*
5511         **      sorry, have to kill ALL jobs ...
5512         */
5513
5514         ncr_init (np, "fatal error", HS_FAIL);
5515 }
5516
5517 /*==========================================================
5518 **
5519 **      ncr chip exception handler for selection timeout
5520 **
5521 **==========================================================
5522 **
5523 **      There seems to be a bug in the 53c810.
5524 **      Although a STO-Interrupt is pending,
5525 **      it continues executing script commands.
5526 **      But it will fail and interrupt (IID) on
5527 **      the next instruction where it's looking
5528 **      for a valid phase.
5529 **
5530 **----------------------------------------------------------
5531 */
5532
5533 static void ncr_int_sto (ncb_p np)
5534 {
5535         u_long dsa, scratcha, diff;
5536         nccb_p cp;
5537         if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
5538
5539         /*
5540         **      look for nccb and set the status.
5541         */
5542
5543         dsa = INL (nc_dsa);
5544         cp = np->link_nccb;
5545         while (cp && (CCB_PHYS (cp, phys) != dsa))
5546                 cp = cp->link_nccb;
5547
5548         if (cp) {
5549                 cp-> host_status = HS_SEL_TIMEOUT;
5550                 ncr_complete (np, cp);
5551         };
5552
5553         /*
5554         **      repair start queue
5555         */
5556
5557         scratcha = INL (nc_scratcha);
5558         diff = scratcha - NCB_SCRIPTH_PHYS (np, tryloop);
5559
5560 /*      assert ((diff <= MAX_START * 20) && !(diff % 20));*/
5561
5562         if ((diff <= MAX_START * 20) && !(diff % 20)) {
5563                 WRITESCRIPT(startpos[0], scratcha);
5564                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
5565                 return;
5566         };
5567         ncr_init (np, "selection timeout", HS_FAIL);
5568 }
5569
5570 /*==========================================================
5571 **
5572 **
5573 **      ncr chip exception handler for phase errors.
5574 **
5575 **
5576 **==========================================================
5577 **
5578 **      We have to construct a new transfer descriptor,
5579 **      to transfer the rest of the current block.
5580 **
5581 **----------------------------------------------------------
5582 */
5583
5584 static void ncr_int_ma (ncb_p np, u_char dstat)
5585 {
5586         u_int32_t       dbc;
5587         u_int32_t       rest;
5588         u_int32_t       dsa;
5589         u_int32_t       dsp;
5590         u_int32_t       nxtdsp;
5591         volatile void   *vdsp_base;
5592         size_t          vdsp_off;
5593         u_int32_t       oadr, olen;
5594         u_int32_t       *tblp, *newcmd;
5595         u_char  cmd, sbcl, ss0, ss2, ctest5;
5596         u_short delta;
5597         nccb_p  cp;
5598
5599         dsp = INL (nc_dsp);
5600         dsa = INL (nc_dsa);
5601         dbc = INL (nc_dbc);
5602         ss0 = INB (nc_sstat0);
5603         ss2 = INB (nc_sstat2);
5604         sbcl= INB (nc_sbcl);
5605
5606         cmd = dbc >> 24;
5607         rest= dbc & 0xffffff;
5608
5609         ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
5610         if (ctest5 & DFS)
5611                 delta=(((ctest5<<8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
5612         else
5613                 delta=(INB (nc_dfifo) - rest) & 0x7f;
5614
5615
5616         /*
5617         **      The data in the dma fifo has not been transfered to
5618         **      the target -> add the amount to the rest
5619         **      and clear the data.
5620         **      Check the sstat2 register in case of wide transfer.
5621         */
5622
5623         if (!(dstat & DFE)) rest += delta;
5624         if (ss0 & OLF) rest++;
5625         if (ss0 & ORF) rest++;
5626         if (INB(nc_scntl3) & EWS) {
5627                 if (ss2 & OLF1) rest++;
5628                 if (ss2 & ORF1) rest++;
5629         };
5630         OUTB (nc_ctest3, np->rv_ctest3 | CLF);  /* clear dma fifo  */
5631         OUTB (nc_stest3, TE|CSF);               /* clear scsi fifo */
5632
5633         /*
5634         **      locate matching cp
5635         */
5636         cp = np->link_nccb;
5637         while (cp && (CCB_PHYS (cp, phys) != dsa))
5638                 cp = cp->link_nccb;
5639
5640         if (!cp) {
5641                 device_printf(np->dev,
5642                     "SCSI phase error fixup: CCB already dequeued (%p)\n", 
5643                     (void *)np->header.cp);
5644                 return;
5645         }
5646         if (cp != np->header.cp) {
5647                 device_printf(np->dev,
5648                     "SCSI phase error fixup: CCB address mismatch "
5649                     "(%p != %p) np->nccb = %p\n", 
5650                     (void *)cp, (void *)np->header.cp,
5651                     (void *)np->link_nccb);
5652 /*          return;*/
5653         }
5654
5655         /*
5656         **      find the interrupted script command,
5657         **      and the address at which to continue.
5658         */
5659
5660         if (dsp == vtophys (&cp->patch[2])) {
5661                 vdsp_base = cp;
5662                 vdsp_off = offsetof(struct nccb, patch[0]);
5663                 nxtdsp = READSCRIPT_OFF(vdsp_base, vdsp_off + 3*4);
5664         } else if (dsp == vtophys (&cp->patch[6])) {
5665                 vdsp_base = cp;
5666                 vdsp_off = offsetof(struct nccb, patch[4]);
5667                 nxtdsp = READSCRIPT_OFF(vdsp_base, vdsp_off + 3*4);
5668         } else if (dsp > np->p_script &&
5669                    dsp <= np->p_script + sizeof(struct script)) {
5670                 vdsp_base = np->script;
5671                 vdsp_off = dsp - np->p_script - 8;
5672                 nxtdsp = dsp;
5673         } else {
5674                 vdsp_base = np->scripth;
5675                 vdsp_off = dsp - np->p_scripth - 8;
5676                 nxtdsp = dsp;
5677         };
5678
5679         /*
5680         **      log the information
5681         */
5682         if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE)) {
5683                 printf ("P%x%x ",cmd&7, sbcl&7);
5684                 printf ("RL=%d D=%d SS0=%x ",
5685                         (unsigned) rest, (unsigned) delta, ss0);
5686         };
5687         if (DEBUG_FLAGS & DEBUG_PHASE) {
5688                 printf ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
5689                         cp, np->header.cp,
5690                         dsp,
5691                         nxtdsp, (volatile char*)vdsp_base+vdsp_off, cmd);
5692         };
5693
5694         /*
5695         **      get old startaddress and old length.
5696         */
5697
5698         oadr = READSCRIPT_OFF(vdsp_base, vdsp_off + 1*4);
5699
5700         if (cmd & 0x10) {       /* Table indirect */
5701                 tblp = (u_int32_t *) ((char*) &cp->phys + oadr);
5702                 olen = tblp[0];
5703                 oadr = tblp[1];
5704         } else {
5705                 tblp = (u_int32_t *) 0;
5706                 olen = READSCRIPT_OFF(vdsp_base, vdsp_off) & 0xffffff;
5707         };
5708
5709         if (DEBUG_FLAGS & DEBUG_PHASE) {
5710                 printf ("OCMD=%x\nTBLP=%p OLEN=%lx OADR=%lx\n",
5711                         (unsigned) (READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24),
5712                         (void *) tblp,
5713                         (u_long) olen,
5714                         (u_long) oadr);
5715         };
5716
5717         /*
5718         **      if old phase not dataphase, leave here.
5719         */
5720
5721         if (cmd != (READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24)) {
5722                 PRINT_ADDR(cp->ccb);
5723                 printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
5724                         (unsigned)cmd,
5725                         (unsigned)READSCRIPT_OFF(vdsp_base, vdsp_off) >> 24);
5726                 
5727                 return;
5728         }
5729         if (cmd & 0x06) {
5730                 PRINT_ADDR(cp->ccb);
5731                 printf ("phase change %x-%x %d@%08x resid=%d.\n",
5732                         cmd&7, sbcl&7, (unsigned)olen,
5733                         (unsigned)oadr, (unsigned)rest);
5734
5735                 OUTB (nc_dcntl, np->rv_dcntl | STD);
5736                 return;
5737         };
5738
5739         /*
5740         **      choose the correct patch area.
5741         **      if savep points to one, choose the other.
5742         */
5743
5744         newcmd = cp->patch;
5745         if (cp->phys.header.savep == vtophys (newcmd)) newcmd+=4;
5746
5747         /*
5748         **      fillin the commands
5749         */
5750
5751         newcmd[0] = ((cmd & 0x0f) << 24) | rest;
5752         newcmd[1] = oadr + olen - rest;
5753         newcmd[2] = SCR_JUMP;
5754         newcmd[3] = nxtdsp;
5755
5756         if (DEBUG_FLAGS & DEBUG_PHASE) {
5757                 PRINT_ADDR(cp->ccb);
5758                 printf ("newcmd[%d] %x %x %x %x.\n",
5759                         (int)(newcmd - cp->patch),
5760                         (unsigned)newcmd[0],
5761                         (unsigned)newcmd[1],
5762                         (unsigned)newcmd[2],
5763                         (unsigned)newcmd[3]);
5764         }
5765         /*
5766         **      fake the return address (to the patch).
5767         **      and restart script processor at dispatcher.
5768         */
5769         np->profile.num_break++;
5770         OUTL (nc_temp, vtophys (newcmd));
5771         if ((cmd & 7) == 0)
5772                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
5773         else
5774                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, checkatn));
5775 }
5776
5777 /*==========================================================
5778 **
5779 **
5780 **      ncr chip exception handler for programmed interrupts.
5781 **
5782 **
5783 **==========================================================
5784 */
5785
5786 static int ncr_show_msg (u_char * msg)
5787 {
5788         u_char i;
5789         printf ("%x",*msg);
5790         if (*msg==MSG_EXTENDED) {
5791                 for (i=1;i<8;i++) {
5792                         if (i-1>msg[1]) break;
5793                         printf ("-%x",msg[i]);
5794                 };
5795                 return (i+1);
5796         } else if ((*msg & 0xf0) == 0x20) {
5797                 printf ("-%x",msg[1]);
5798                 return (2);
5799         };
5800         return (1);
5801 }
5802
5803 static void ncr_int_sir (ncb_p np)
5804 {
5805         u_char scntl3;
5806         u_char chg, ofs, per, fak, wide;
5807         u_char num = INB (nc_dsps);
5808         nccb_p  cp=0;
5809         u_long  dsa;
5810         u_int   target = INB (nc_sdid) & 0x0f;
5811         tcb_p   tp     = &np->target[target];
5812         int     i;
5813         if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
5814
5815         switch (num) {
5816         case SIR_SENSE_RESTART:
5817         case SIR_STALL_RESTART:
5818                 break;
5819
5820         default:
5821                 /*
5822                 **      lookup the nccb
5823                 */
5824                 dsa = INL (nc_dsa);
5825                 cp = np->link_nccb;
5826                 while (cp && (CCB_PHYS (cp, phys) != dsa))
5827                         cp = cp->link_nccb;
5828
5829                 assert (cp);
5830                 if (!cp)
5831                         goto out;
5832                 assert (cp == np->header.cp);
5833                 if (cp != np->header.cp)
5834                         goto out;
5835         }
5836
5837         switch (num) {
5838
5839 /*--------------------------------------------------------------------
5840 **
5841 **      Processing of interrupted getcc selects
5842 **
5843 **--------------------------------------------------------------------
5844 */
5845
5846         case SIR_SENSE_RESTART:
5847                 /*------------------------------------------
5848                 **      Script processor is idle.
5849                 **      Look for interrupted "check cond"
5850                 **------------------------------------------
5851                 */
5852
5853                 if (DEBUG_FLAGS & DEBUG_RESTART)
5854                         device_printf(np->dev, "int#%d", num);
5855                 cp = (nccb_p) 0;
5856                 for (i=0; i<MAX_TARGET; i++) {
5857                         if (DEBUG_FLAGS & DEBUG_RESTART) printf (" t%d", i);
5858                         tp = &np->target[i];
5859                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5860                         cp = tp->hold_cp;
5861                         if (!cp) continue;
5862                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5863                         if ((cp->host_status==HS_BUSY) &&
5864                                 (cp->s_status==SCSI_STATUS_CHECK_COND))
5865                                 break;
5866                         if (DEBUG_FLAGS & DEBUG_RESTART) printf ("- (remove)");
5867                         tp->hold_cp = cp = (nccb_p) 0;
5868                 };
5869
5870                 if (cp) {
5871                         if (DEBUG_FLAGS & DEBUG_RESTART)
5872                                 printf ("+ restart job ..\n");
5873                         OUTL (nc_dsa, CCB_PHYS (cp, phys));
5874                         OUTL (nc_dsp, NCB_SCRIPTH_PHYS (np, getcc));
5875                         return;
5876                 };
5877
5878                 /*
5879                 **      no job, resume normal processing
5880                 */
5881                 if (DEBUG_FLAGS & DEBUG_RESTART) printf (" -- remove trap\n");
5882                 WRITESCRIPT(start0[0], SCR_INT ^ IFFALSE (0));
5883                 break;
5884
5885         case SIR_SENSE_FAILED:
5886                 /*-------------------------------------------
5887                 **      While trying to select for
5888                 **      getting the condition code,
5889                 **      a target reselected us.
5890                 **-------------------------------------------
5891                 */
5892                 if (DEBUG_FLAGS & DEBUG_RESTART) {
5893                         PRINT_ADDR(cp->ccb);
5894                         printf ("in getcc reselect by t%d.\n",
5895                                 INB(nc_ssid) & 0x0f);
5896                 }
5897
5898                 /*
5899                 **      Mark this job
5900                 */
5901                 cp->host_status = HS_BUSY;
5902                 cp->s_status = SCSI_STATUS_CHECK_COND;
5903                 np->target[cp->ccb->ccb_h.target_id].hold_cp = cp;
5904
5905                 /*
5906                 **      And patch code to restart it.
5907                 */
5908                 WRITESCRIPT(start0[0], SCR_INT);
5909                 break;
5910
5911 /*-----------------------------------------------------------------------------
5912 **
5913 **      Was Sie schon immer ueber transfermode negotiation wissen wollten ...
5914 **
5915 **      We try to negotiate sync and wide transfer only after
5916 **      a successfull inquire command. We look at byte 7 of the
5917 **      inquire data to determine the capabilities if the target.
5918 **
5919 **      When we try to negotiate, we append the negotiation message
5920 **      to the identify and (maybe) simple tag message.
5921 **      The host status field is set to HS_NEGOTIATE to mark this
5922 **      situation.
5923 **
5924 **      If the target doesn't answer this message immidiately
5925 **      (as required by the standard), the SIR_NEGO_FAIL interrupt
5926 **      will be raised eventually.
5927 **      The handler removes the HS_NEGOTIATE status, and sets the
5928 **      negotiated value to the default (async / nowide).
5929 **
5930 **      If we receive a matching answer immediately, we check it
5931 **      for validity, and set the values.
5932 **
5933 **      If we receive a Reject message immediately, we assume the
5934 **      negotiation has failed, and fall back to standard values.
5935 **
5936 **      If we receive a negotiation message while not in HS_NEGOTIATE
5937 **      state, it's a target initiated negotiation. We prepare a
5938 **      (hopefully) valid answer, set our parameters, and send back 
5939 **      this answer to the target.
5940 **
5941 **      If the target doesn't fetch the answer (no message out phase),
5942 **      we assume the negotiation has failed, and fall back to default
5943 **      settings.
5944 **
5945 **      When we set the values, we adjust them in all nccbs belonging 
5946 **      to this target, in the controller's register, and in the "phys"
5947 **      field of the controller's struct ncb.
5948 **
5949 **      Possible cases:            hs  sir   msg_in value  send   goto
5950 **      We try try to negotiate:
5951 **      -> target doesnt't msgin   NEG FAIL  noop   defa.  -      dispatch
5952 **      -> target rejected our msg NEG FAIL  reject defa.  -      dispatch
5953 **      -> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
5954 **      -> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
5955 **      -> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
5956 **      -> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
5957 **      -> any other msgin         NEG FAIL  noop   defa.  -      dispatch
5958 **
5959 **      Target tries to negotiate:
5960 **      -> incoming message        --- SYNC  sdtr   set    SDTR   -
5961 **      -> incoming message        --- WIDE  wdtr   set    WDTR   -
5962 **      We sent our answer:
5963 **      -> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
5964 **
5965 **-----------------------------------------------------------------------------
5966 */
5967
5968         case SIR_NEGO_FAILED:
5969                 /*-------------------------------------------------------
5970                 **
5971                 **      Negotiation failed.
5972                 **      Target doesn't send an answer message,
5973                 **      or target rejected our message.
5974                 **
5975                 **      Remove negotiation request.
5976                 **
5977                 **-------------------------------------------------------
5978                 */
5979                 OUTB (HS_PRT, HS_BUSY);
5980
5981                 /* FALLTHROUGH */
5982
5983         case SIR_NEGO_PROTO:
5984                 /*-------------------------------------------------------
5985                 **
5986                 **      Negotiation failed.
5987                 **      Target doesn't fetch the answer message.
5988                 **
5989                 **-------------------------------------------------------
5990                 */
5991
5992                 if (DEBUG_FLAGS & DEBUG_NEGO) {
5993                         PRINT_ADDR(cp->ccb);
5994                         printf ("negotiation failed sir=%x status=%x.\n",
5995                                 num, cp->nego_status);
5996                 };
5997
5998                 /*
5999                 **      any error in negotiation:
6000                 **      fall back to default mode.
6001                 */
6002                 switch (cp->nego_status) {
6003
6004                 case NS_SYNC:
6005                         ncr_setsync (np, cp, 0, 0xe0, 0);
6006                         break;
6007
6008                 case NS_WIDE:
6009                         ncr_setwide (np, cp, 0, 0);
6010                         break;
6011
6012                 };
6013                 np->msgin [0] = MSG_NOOP;
6014                 np->msgout[0] = MSG_NOOP;
6015                 cp->nego_status = 0;
6016                 OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
6017                 break;
6018
6019         case SIR_NEGO_SYNC:
6020                 /*
6021                 **      Synchronous request message received.
6022                 */
6023
6024                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6025                         PRINT_ADDR(cp->ccb);
6026                         printf ("sync msgin: ");
6027                         (void) ncr_show_msg (np->msgin);
6028                         printf (".\n");
6029                 };
6030
6031                 /*
6032                 **      get requested values.
6033                 */
6034
6035                 chg = 0;
6036                 per = np->msgin[3];
6037                 ofs = np->msgin[4];
6038                 if (ofs==0) per=255;
6039
6040                 /*
6041                 **      check values against driver limits.
6042                 */
6043                 if (per < np->minsync)
6044                         {chg = 1; per = np->minsync;}
6045                 if (per < tp->tinfo.user.period)
6046                         {chg = 1; per = tp->tinfo.user.period;}
6047                 if (ofs > tp->tinfo.user.offset)
6048                         {chg = 1; ofs = tp->tinfo.user.offset;}
6049
6050                 /*
6051                 **      Check against controller limits.
6052                 */
6053
6054                 fak     = 7;
6055                 scntl3  = 0;
6056                 if (ofs != 0) {
6057                         ncr_getsync(np, per, &fak, &scntl3);
6058                         if (fak > 7) {
6059                                 chg = 1;
6060                                 ofs = 0;
6061                         }
6062                 }
6063                 if (ofs == 0) {
6064                         fak     = 7;
6065                         per     = 0;
6066                         scntl3  = 0;
6067                 }
6068
6069                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6070                         PRINT_ADDR(cp->ccb);
6071                         printf ("sync: per=%d scntl3=0x%x ofs=%d fak=%d chg=%d.\n",
6072                                 per, scntl3, ofs, fak, chg);
6073                 }
6074
6075                 if (INB (HS_PRT) == HS_NEGOTIATE) {
6076                         OUTB (HS_PRT, HS_BUSY);
6077                         switch (cp->nego_status) {
6078
6079                         case NS_SYNC:
6080                                 /*
6081                                 **      This was an answer message
6082                                 */
6083                                 if (chg) {
6084                                         /*
6085                                         **      Answer wasn't acceptable.
6086                                         */
6087                                         ncr_setsync (np, cp, 0, 0xe0, 0);
6088                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6089                                 } else {
6090                                         /*
6091                                         **      Answer is ok.
6092                                         */
6093                                         ncr_setsync (np,cp,scntl3,(fak<<5)|ofs, per);
6094                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
6095                                 };
6096                                 return;
6097
6098                         case NS_WIDE:
6099                                 ncr_setwide (np, cp, 0, 0);
6100                                 break;
6101                         };
6102                 };
6103
6104                 /*
6105                 **      It was a request. Set value and
6106                 **      prepare an answer message
6107                 */
6108
6109                 ncr_setsync (np, cp, scntl3, (fak<<5)|ofs, per);
6110
6111                 np->msgout[0] = MSG_EXTENDED;
6112                 np->msgout[1] = 3;
6113                 np->msgout[2] = MSG_EXT_SDTR;
6114                 np->msgout[3] = per;
6115                 np->msgout[4] = ofs;
6116
6117                 cp->nego_status = NS_SYNC;
6118
6119                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6120                         PRINT_ADDR(cp->ccb);
6121                         printf ("sync msgout: ");
6122                         (void) ncr_show_msg (np->msgout);
6123                         printf (".\n");
6124                 }
6125
6126                 if (!ofs) {
6127                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6128                         return;
6129                 }
6130                 np->msgin [0] = MSG_NOOP;
6131
6132                 break;
6133
6134         case SIR_NEGO_WIDE:
6135                 /*
6136                 **      Wide request message received.
6137                 */
6138                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6139                         PRINT_ADDR(cp->ccb);
6140                         printf ("wide msgin: ");
6141                         (void) ncr_show_msg (np->msgin);
6142                         printf (".\n");
6143                 };
6144
6145                 /*
6146                 **      get requested values.
6147                 */
6148
6149                 chg  = 0;
6150                 wide = np->msgin[3];
6151
6152                 /*
6153                 **      check values against driver limits.
6154                 */
6155
6156                 if (wide > tp->tinfo.user.width)
6157                         {chg = 1; wide = tp->tinfo.user.width;}
6158
6159                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6160                         PRINT_ADDR(cp->ccb);
6161                         printf ("wide: wide=%d chg=%d.\n", wide, chg);
6162                 }
6163
6164                 if (INB (HS_PRT) == HS_NEGOTIATE) {
6165                         OUTB (HS_PRT, HS_BUSY);
6166                         switch (cp->nego_status) {
6167
6168                         case NS_WIDE:
6169                                 /*
6170                                 **      This was an answer message
6171                                 */
6172                                 if (chg) {
6173                                         /*
6174                                         **      Answer wasn't acceptable.
6175                                         */
6176                                         ncr_setwide (np, cp, 0, 1);
6177                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
6178                                 } else {
6179                                         /*
6180                                         **      Answer is ok.
6181                                         */
6182                                         ncr_setwide (np, cp, wide, 1);
6183                                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
6184                                 };
6185                                 return;
6186
6187                         case NS_SYNC:
6188                                 ncr_setsync (np, cp, 0, 0xe0, 0);
6189                                 break;
6190                         };
6191                 };
6192
6193                 /*
6194                 **      It was a request, set value and
6195                 **      prepare an answer message
6196                 */
6197
6198                 ncr_setwide (np, cp, wide, 1);
6199
6200                 np->msgout[0] = MSG_EXTENDED;
6201                 np->msgout[1] = 2;
6202                 np->msgout[2] = MSG_EXT_WDTR;
6203                 np->msgout[3] = wide;
6204
6205                 np->msgin [0] = MSG_NOOP;
6206
6207                 cp->nego_status = NS_WIDE;
6208
6209                 if (DEBUG_FLAGS & DEBUG_NEGO) {
6210                         PRINT_ADDR(cp->ccb);
6211                         printf ("wide msgout: ");
6212                         (void) ncr_show_msg (np->msgout);
6213                         printf (".\n");
6214                 }
6215                 break;
6216
6217 /*--------------------------------------------------------------------
6218 **
6219 **      Processing of special messages
6220 **
6221 **--------------------------------------------------------------------
6222 */
6223
6224         case SIR_REJECT_RECEIVED:
6225                 /*-----------------------------------------------
6226                 **
6227                 **      We received a MSG_MESSAGE_REJECT message.
6228                 **
6229                 **-----------------------------------------------
6230                 */
6231
6232                 PRINT_ADDR(cp->ccb);
6233                 printf ("MSG_MESSAGE_REJECT received (%x:%x).\n",
6234                         (unsigned)np->lastmsg, np->msgout[0]);
6235                 break;
6236
6237         case SIR_REJECT_SENT:
6238                 /*-----------------------------------------------
6239                 **
6240                 **      We received an unknown message
6241                 **
6242                 **-----------------------------------------------
6243                 */
6244
6245                 PRINT_ADDR(cp->ccb);
6246                 printf ("MSG_MESSAGE_REJECT sent for ");
6247                 (void) ncr_show_msg (np->msgin);
6248                 printf (".\n");
6249                 break;
6250
6251 /*--------------------------------------------------------------------
6252 **
6253 **      Processing of special messages
6254 **
6255 **--------------------------------------------------------------------
6256 */
6257
6258         case SIR_IGN_RESIDUE:
6259                 /*-----------------------------------------------
6260                 **
6261                 **      We received an IGNORE RESIDUE message,
6262                 **      which couldn't be handled by the script.
6263                 **
6264                 **-----------------------------------------------
6265                 */
6266
6267                 PRINT_ADDR(cp->ccb);
6268                 printf ("MSG_IGN_WIDE_RESIDUE received, but not yet implemented.\n");
6269                 break;
6270
6271         case SIR_MISSING_SAVE:
6272                 /*-----------------------------------------------
6273                 **
6274                 **      We received an DISCONNECT message,
6275                 **      but the datapointer wasn't saved before.
6276                 **
6277                 **-----------------------------------------------
6278                 */
6279
6280                 PRINT_ADDR(cp->ccb);
6281                 printf ("MSG_DISCONNECT received, but datapointer not saved:\n"
6282                         "\tdata=%x save=%x goal=%x.\n",
6283                         (unsigned) INL (nc_temp),
6284                         (unsigned) np->header.savep,
6285                         (unsigned) np->header.goalp);
6286                 break;
6287
6288 /*--------------------------------------------------------------------
6289 **
6290 **      Processing of a "SCSI_STATUS_QUEUE_FULL" status.
6291 **
6292 **      XXX JGibbs - We should do the same thing for BUSY status.
6293 **
6294 **      The current command has been rejected,
6295 **      because there are too many in the command queue.
6296 **      We have started too many commands for that target.
6297 **
6298 **--------------------------------------------------------------------
6299 */
6300         case SIR_STALL_QUEUE:
6301                 cp->xerr_status = XE_OK;
6302                 cp->host_status = HS_COMPLETE;
6303                 cp->s_status = SCSI_STATUS_QUEUE_FULL;
6304                 ncr_freeze_devq(np, cp->ccb->ccb_h.path);
6305                 ncr_complete(np, cp);
6306
6307                 /* FALLTHROUGH */
6308
6309         case SIR_STALL_RESTART:
6310                 /*-----------------------------------------------
6311                 **
6312                 **      Enable selecting again,
6313                 **      if NO disconnected jobs.
6314                 **
6315                 **-----------------------------------------------
6316                 */
6317                 /*
6318                 **      Look for a disconnected job.
6319                 */
6320                 cp = np->link_nccb;
6321                 while (cp && cp->host_status != HS_DISCONNECT)
6322                         cp = cp->link_nccb;
6323
6324                 /*
6325                 **      if there is one, ...
6326                 */
6327                 if (cp) {
6328                         /*
6329                         **      wait for reselection
6330                         */
6331                         OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, reselect));
6332                         return;
6333                 };
6334
6335                 /*
6336                 **      else remove the interrupt.
6337                 */
6338
6339                 device_printf(np->dev, "queue empty.\n");
6340                 WRITESCRIPT(start1[0], SCR_INT ^ IFFALSE (0));
6341                 break;
6342         };
6343
6344 out:
6345         OUTB (nc_dcntl, np->rv_dcntl | STD);
6346 }
6347
6348 /*==========================================================
6349 **
6350 **
6351 **      Aquire a control block
6352 **
6353 **
6354 **==========================================================
6355 */
6356
6357 static  nccb_p ncr_get_nccb
6358         (ncb_p np, u_long target, u_long lun)
6359 {
6360         lcb_p lp;
6361         nccb_p cp = NULL;
6362
6363         /*
6364         **      Lun structure available ?
6365         */
6366
6367         lp = np->target[target].lp[lun];
6368         if (lp) {
6369                 cp = lp->next_nccb;
6370
6371                 /*
6372                 **      Look for free CCB
6373                 */
6374
6375                 while (cp && cp->magic) {
6376                         cp = cp->next_nccb;
6377                 }
6378         }
6379
6380         /*
6381         **      if nothing available, create one.
6382         */
6383
6384         if (cp == NULL)
6385                 cp = ncr_alloc_nccb(np, target, lun);
6386
6387         if (cp != NULL) {
6388                 if (cp->magic) {
6389                         device_printf(np->dev, "Bogus free cp found\n");
6390                         return (NULL);
6391                 }
6392                 cp->magic = 1;
6393         }
6394         return (cp);
6395 }
6396
6397 /*==========================================================
6398 **
6399 **
6400 **      Release one control block
6401 **
6402 **
6403 **==========================================================
6404 */
6405
6406 static void ncr_free_nccb (ncb_p np, nccb_p cp)
6407 {
6408         /*
6409         **    sanity
6410         */
6411
6412         assert (cp != NULL);
6413
6414         cp -> host_status = HS_IDLE;
6415         cp -> magic = 0;
6416 }
6417
6418 /*==========================================================
6419 **
6420 **
6421 **      Allocation of resources for Targets/Luns/Tags.
6422 **
6423 **
6424 **==========================================================
6425 */
6426
6427 static nccb_p
6428 ncr_alloc_nccb (ncb_p np, u_long target, u_long lun)
6429 {
6430         tcb_p tp;
6431         lcb_p lp;
6432         nccb_p cp;
6433
6434         assert (np != NULL);
6435
6436         if (target>=MAX_TARGET) return(NULL);
6437         if (lun   >=MAX_LUN   ) return(NULL);
6438
6439         tp=&np->target[target];
6440
6441         if (!tp->jump_tcb.l_cmd) {
6442
6443                 /*
6444                 **      initialize it.
6445                 */
6446                 tp->jump_tcb.l_cmd   = (SCR_JUMP^IFFALSE (DATA (0x80 + target)));
6447                 tp->jump_tcb.l_paddr = np->jump_tcb.l_paddr;
6448
6449                 tp->getscr[0] =
6450                         (np->features & FE_PFEN)? SCR_COPY(1) : SCR_COPY_F(1);
6451                 tp->getscr[1] = vtophys (&tp->tinfo.sval);
6452                 tp->getscr[2] = rman_get_start(np->reg_res) + offsetof (struct ncr_reg, nc_sxfer);
6453                 tp->getscr[3] =
6454                         (np->features & FE_PFEN)? SCR_COPY(1) : SCR_COPY_F(1);
6455                 tp->getscr[4] = vtophys (&tp->tinfo.wval);
6456                 tp->getscr[5] = rman_get_start(np->reg_res) + offsetof (struct ncr_reg, nc_scntl3);
6457
6458                 assert (((offsetof(struct ncr_reg, nc_sxfer) ^
6459                          (offsetof(struct tcb ,tinfo)
6460                         + offsetof(struct ncr_target_tinfo, sval))) & 3) == 0);
6461                 assert (((offsetof(struct ncr_reg, nc_scntl3) ^
6462                          (offsetof(struct tcb, tinfo)
6463                         + offsetof(struct ncr_target_tinfo, wval))) &3) == 0);
6464
6465                 tp->call_lun.l_cmd   = (SCR_CALL);
6466                 tp->call_lun.l_paddr = NCB_SCRIPT_PHYS (np, resel_lun);
6467
6468                 tp->jump_lcb.l_cmd   = (SCR_JUMP);
6469                 tp->jump_lcb.l_paddr = NCB_SCRIPTH_PHYS (np, abort);
6470                 np->jump_tcb.l_paddr = vtophys (&tp->jump_tcb);
6471         }
6472
6473         /*
6474         **      Logic unit control block
6475         */
6476         lp = tp->lp[lun];
6477         if (!lp) {
6478                 /*
6479                 **      Allocate a lcb
6480                 */
6481                 lp = (lcb_p) malloc (sizeof (struct lcb), M_DEVBUF,
6482                         M_NOWAIT | M_ZERO);
6483                 if (!lp) return(NULL);
6484
6485                 /*
6486                 **      Initialize it
6487                 */
6488                 lp->jump_lcb.l_cmd   = (SCR_JUMP ^ IFFALSE (DATA (lun)));
6489                 lp->jump_lcb.l_paddr = tp->jump_lcb.l_paddr;
6490
6491                 lp->call_tag.l_cmd   = (SCR_CALL);
6492                 lp->call_tag.l_paddr = NCB_SCRIPT_PHYS (np, resel_tag);
6493
6494                 lp->jump_nccb.l_cmd   = (SCR_JUMP);
6495                 lp->jump_nccb.l_paddr = NCB_SCRIPTH_PHYS (np, aborttag);
6496
6497                 lp->actlink = 1;
6498
6499                 /*
6500                 **   Chain into LUN list
6501                 */
6502                 tp->jump_lcb.l_paddr = vtophys (&lp->jump_lcb);
6503                 tp->lp[lun] = lp;
6504
6505         }
6506
6507         /*
6508         **      Allocate a nccb
6509         */
6510         cp = (nccb_p) malloc (sizeof (struct nccb), M_DEVBUF, M_NOWAIT|M_ZERO);
6511
6512         if (!cp)
6513                 return (NULL);
6514
6515         if (DEBUG_FLAGS & DEBUG_ALLOC) { 
6516                 printf ("new nccb @%p.\n", cp);
6517         }
6518
6519         /*
6520         **      Fill in physical addresses
6521         */
6522
6523         cp->p_nccb           = vtophys (cp);
6524
6525         /*
6526         **      Chain into reselect list
6527         */
6528         cp->jump_nccb.l_cmd   = SCR_JUMP;
6529         cp->jump_nccb.l_paddr = lp->jump_nccb.l_paddr;
6530         lp->jump_nccb.l_paddr = CCB_PHYS (cp, jump_nccb);
6531         cp->call_tmp.l_cmd   = SCR_CALL;
6532         cp->call_tmp.l_paddr = NCB_SCRIPT_PHYS (np, resel_tmp);
6533
6534         /*
6535         **      Chain into wakeup list
6536         */
6537         cp->link_nccb      = np->link_nccb;
6538         np->link_nccb      = cp;
6539
6540         /*
6541         **      Chain into CCB list
6542         */
6543         cp->next_nccb   = lp->next_nccb;
6544         lp->next_nccb   = cp;
6545
6546         return (cp);
6547 }
6548
6549 /*==========================================================
6550 **
6551 **
6552 **      Build Scatter Gather Block
6553 **
6554 **
6555 **==========================================================
6556 **
6557 **      The transfer area may be scattered among
6558 **      several non adjacent physical pages.
6559 **
6560 **      We may use MAX_SCATTER blocks.
6561 **
6562 **----------------------------------------------------------
6563 */
6564
6565 static  int     ncr_scatter
6566         (struct dsb* phys, vm_offset_t vaddr, vm_size_t datalen)
6567 {
6568         u_long  paddr, pnext;
6569
6570         u_short segment  = 0;
6571         u_long  segsize, segaddr;
6572         u_long  size, csize    = 0;
6573         u_long  chunk = MAX_SIZE;
6574         int     free;
6575
6576         bzero (&phys->data, sizeof (phys->data));
6577         if (!datalen) return (0);
6578
6579         paddr = vtophys (vaddr);
6580
6581         /*
6582         **      insert extra break points at a distance of chunk.
6583         **      We try to reduce the number of interrupts caused
6584         **      by unexpected phase changes due to disconnects.
6585         **      A typical harddisk may disconnect before ANY block.
6586         **      If we wanted to avoid unexpected phase changes at all
6587         **      we had to use a break point every 512 bytes.
6588         **      Of course the number of scatter/gather blocks is
6589         **      limited.
6590         */
6591
6592         free = MAX_SCATTER - 1;
6593
6594         if (vaddr & PAGE_MASK) free -= datalen / PAGE_SIZE;
6595
6596         if (free>1)
6597                 while ((chunk * free >= 2 * datalen) && (chunk>=1024))
6598                         chunk /= 2;
6599
6600         if(DEBUG_FLAGS & DEBUG_SCATTER)
6601                 printf("ncr?:\tscattering virtual=%p size=%d chunk=%d.\n",
6602                        (void *) vaddr, (unsigned) datalen, (unsigned) chunk);
6603
6604         /*
6605         **   Build data descriptors.
6606         */
6607         while (datalen && (segment < MAX_SCATTER)) {
6608
6609                 /*
6610                 **      this segment is empty
6611                 */
6612                 segsize = 0;
6613                 segaddr = paddr;
6614                 pnext   = paddr;
6615
6616                 if (!csize) csize = chunk;
6617
6618                 while ((datalen) && (paddr == pnext) && (csize)) {
6619
6620                         /*
6621                         **      continue this segment
6622                         */
6623                         pnext = (paddr & (~PAGE_MASK)) + PAGE_SIZE;
6624
6625                         /*
6626                         **      Compute max size
6627                         */
6628
6629                         size = pnext - paddr;           /* page size */
6630                         if (size > datalen) size = datalen;  /* data size */
6631                         if (size > csize  ) size = csize  ;  /* chunksize */
6632
6633                         segsize += size;
6634                         vaddr   += size;
6635                         csize   -= size;
6636                         datalen -= size;
6637                         paddr    = vtophys (vaddr);
6638                 };
6639
6640                 if(DEBUG_FLAGS & DEBUG_SCATTER)
6641                         printf ("\tseg #%d  addr=%x  size=%d  (rest=%d).\n",
6642                         segment,
6643                         (unsigned) segaddr,
6644                         (unsigned) segsize,
6645                         (unsigned) datalen);
6646
6647                 phys->data[segment].addr = segaddr;
6648                 phys->data[segment].size = segsize;
6649                 segment++;
6650         }
6651
6652         if (datalen) {
6653                 printf("ncr?: scatter/gather failed (residue=%d).\n",
6654                         (unsigned) datalen);
6655                 return (-1);
6656         };
6657
6658         return (segment);
6659 }
6660
6661 /*==========================================================
6662 **
6663 **
6664 **      Test the pci bus snoop logic :-(
6665 **
6666 **      Has to be called with interrupts disabled.
6667 **
6668 **
6669 **==========================================================
6670 */
6671
6672 #ifndef NCR_IOMAPPED
6673 static int ncr_regtest (struct ncb* np)
6674 {
6675         register volatile u_int32_t data;
6676         /*
6677         **      ncr registers may NOT be cached.
6678         **      write 0xffffffff to a read only register area,
6679         **      and try to read it back.
6680         */
6681         data = 0xffffffff;
6682         OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
6683         data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
6684 #if 1
6685         if (data == 0xffffffff) {
6686 #else
6687         if ((data & 0xe2f0fffd) != 0x02000080) {
6688 #endif
6689                 printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
6690                         (unsigned) data);
6691                 return (0x10);
6692         };
6693         return (0);
6694 }
6695 #endif
6696
6697 static int ncr_snooptest (struct ncb* np)
6698 {
6699         u_int32_t ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
6700         int     i, err=0;
6701 #ifndef NCR_IOMAPPED
6702         err |= ncr_regtest (np);
6703         if (err) return (err);
6704 #endif
6705         /*
6706         **      init
6707         */
6708         pc  = NCB_SCRIPTH_PHYS (np, snooptest);
6709         host_wr = 1;
6710         ncr_wr  = 2;
6711         /*
6712         **      Set memory and register.
6713         */
6714         ncr_cache = host_wr;
6715         OUTL (nc_temp, ncr_wr);
6716         /*
6717         **      Start script (exchange values)
6718         */
6719         OUTL (nc_dsp, pc);
6720         /*
6721         **      Wait 'til done (with timeout)
6722         */
6723         for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
6724                 if (INB(nc_istat) & (INTF|SIP|DIP))
6725                         break;
6726         /*
6727         **      Save termination position.
6728         */
6729         pc = INL (nc_dsp);
6730         /*
6731         **      Read memory and register.
6732         */
6733         host_rd = ncr_cache;
6734         ncr_rd  = INL (nc_scratcha);
6735         ncr_bk  = INL (nc_temp);
6736         /*
6737         **      Reset ncr chip
6738         */
6739         OUTB (nc_istat,  SRST);
6740         DELAY (1000);
6741         OUTB (nc_istat,  0   );
6742         /*
6743         **      check for timeout
6744         */
6745         if (i>=NCR_SNOOP_TIMEOUT) {
6746                 printf ("CACHE TEST FAILED: timeout.\n");
6747                 return (0x20);
6748         };
6749         /*
6750         **      Check termination position.
6751         */
6752         if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
6753                 printf ("CACHE TEST FAILED: script execution failed.\n");
6754                 printf ("start=%08lx, pc=%08lx, end=%08lx\n", 
6755                         (u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
6756                         (u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
6757                 return (0x40);
6758         };
6759         /*
6760         **      Show results.
6761         */
6762         if (host_wr != ncr_rd) {
6763                 printf ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
6764                         (int) host_wr, (int) ncr_rd);
6765                 err |= 1;
6766         };
6767         if (host_rd != ncr_wr) {
6768                 printf ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
6769                         (int) ncr_wr, (int) host_rd);
6770                 err |= 2;
6771         };
6772         if (ncr_bk != ncr_wr) {
6773                 printf ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
6774                         (int) ncr_wr, (int) ncr_bk);
6775                 err |= 4;
6776         };
6777         return (err);
6778 }
6779
6780 /*==========================================================
6781 **
6782 **
6783 **      Profiling the drivers and targets performance.
6784 **
6785 **
6786 **==========================================================
6787 */
6788
6789 /*
6790 **      Compute the difference in milliseconds.
6791 **/
6792
6793 static  int ncr_delta (int *from, int *to)
6794 {
6795         if (!from) return (-1);
6796         if (!to)   return (-2);
6797         return ((to - from) * 1000 / hz);
6798 }
6799
6800 #define PROFILE  cp->phys.header.stamp
6801 static  void ncb_profile (ncb_p np, nccb_p cp)
6802 {
6803         int co, da, st, en, di, se, post,work,disc;
6804         u_long diff;
6805
6806         PROFILE.end = ticks;
6807
6808         st = ncr_delta (&PROFILE.start,&PROFILE.status);
6809         if (st<0) return;       /* status  not reached  */
6810
6811         da = ncr_delta (&PROFILE.start,&PROFILE.data);
6812         if (da<0) return;       /* No data transfer phase */
6813
6814         co = ncr_delta (&PROFILE.start,&PROFILE.command);
6815         if (co<0) return;       /* command not executed */
6816
6817         en = ncr_delta (&PROFILE.start,&PROFILE.end),
6818         di = ncr_delta (&PROFILE.start,&PROFILE.disconnect),
6819         se = ncr_delta (&PROFILE.start,&PROFILE.select);
6820         post = en - st;
6821
6822         /*
6823         **      @PROFILE@  Disconnect time invalid if multiple disconnects
6824         */
6825
6826         if (di>=0) disc = se-di; else  disc = 0;
6827
6828         work = (st - co) - disc;
6829
6830         diff = (np->disc_phys - np->disc_ref) & 0xff;
6831         np->disc_ref += diff;
6832
6833         np->profile.num_trans   += 1;
6834         if (cp->ccb)
6835                 np->profile.num_bytes   += cp->ccb->csio.dxfer_len;
6836         np->profile.num_disc    += diff;
6837         np->profile.ms_setup    += co;
6838         np->profile.ms_data     += work;
6839         np->profile.ms_disc     += disc;
6840         np->profile.ms_post     += post;
6841 }
6842 #undef PROFILE
6843
6844 /*==========================================================
6845 **
6846 **      Determine the ncr's clock frequency.
6847 **      This is essential for the negotiation
6848 **      of the synchronous transfer rate.
6849 **
6850 **==========================================================
6851 **
6852 **      Note: we have to return the correct value.
6853 **      THERE IS NO SAVE DEFAULT VALUE.
6854 **
6855 **      Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
6856 **      53C860 and 53C875 rev. 1 support fast20 transfers but 
6857 **      do not have a clock doubler and so are provided with a 
6858 **      80 MHz clock. All other fast20 boards incorporate a doubler 
6859 **      and so should be delivered with a 40 MHz clock.
6860 **      The future fast40 chips (895/895) use a 40 Mhz base clock 
6861 **      and provide a clock quadrupler (160 Mhz). The code below 
6862 **      tries to deal as cleverly as possible with all this stuff.
6863 **
6864 **----------------------------------------------------------
6865 */
6866
6867 /*
6868  *      Select NCR SCSI clock frequency
6869  */
6870 static void ncr_selectclock(ncb_p np, u_char scntl3)
6871 {
6872         if (np->multiplier < 2) {
6873                 OUTB(nc_scntl3, scntl3);
6874                 return;
6875         }
6876
6877         if (bootverbose >= 2)
6878                 device_printf(np->dev, "enabling clock multiplier\n");
6879
6880         OUTB(nc_stest1, DBLEN);    /* Enable clock multiplier             */
6881         if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
6882                 int i = 20;
6883                 while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
6884                         DELAY(20);
6885                 if (!i)
6886                         device_printf(np->dev,
6887                             "the chip cannot lock the frequency\n");
6888         } else                  /* Wait 20 micro-seconds for doubler    */
6889                 DELAY(20);
6890         OUTB(nc_stest3, HSC);           /* Halt the scsi clock          */
6891         OUTB(nc_scntl3, scntl3);
6892         OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier      */
6893         OUTB(nc_stest3, 0x00);          /* Restart scsi clock           */
6894 }
6895
6896 /*
6897  *      calculate NCR SCSI clock frequency (in KHz)
6898  */
6899 static unsigned
6900 ncrgetfreq (ncb_p np, int gen)
6901 {
6902         int ms = 0;
6903         /*
6904          * Measure GEN timer delay in order 
6905          * to calculate SCSI clock frequency
6906          *
6907          * This code will never execute too
6908          * many loop iterations (if DELAY is 
6909          * reasonably correct). It could get
6910          * too low a delay (too high a freq.)
6911          * if the CPU is slow executing the 
6912          * loop for some reason (an NMI, for
6913          * example). For this reason we will
6914          * if multiple measurements are to be 
6915          * performed trust the higher delay 
6916          * (lower frequency returned).
6917          */
6918         OUTB (nc_stest1, 0);    /* make sure clock doubler is OFF           */
6919         OUTW (nc_sien , 0);     /* mask all scsi interrupts                 */
6920         (void) INW (nc_sist);   /* clear pending scsi interrupt             */
6921         OUTB (nc_dien , 0);     /* mask all dma interrupts                  */
6922         (void) INW (nc_sist);   /* another one, just to be sure :)          */
6923         OUTB (nc_scntl3, 4);    /* set pre-scaler to divide by 3            */
6924         OUTB (nc_stime1, 0);    /* disable general purpose timer            */
6925         OUTB (nc_stime1, gen);  /* set to nominal delay of (1<<gen) * 125us */
6926         while (!(INW(nc_sist) & GEN) && ms++ < 1000)
6927                 DELAY(1000);    /* count ms                                 */
6928         OUTB (nc_stime1, 0);    /* disable general purpose timer            */
6929         OUTB (nc_scntl3, 0);
6930         /*
6931          * Set prescaler to divide by whatever "0" means.
6932          * "0" ought to choose divide by 2, but appears
6933          * to set divide by 3.5 mode in my 53c810 ...
6934          */
6935         OUTB (nc_scntl3, 0);
6936
6937         if (bootverbose >= 2)
6938                 printf ("\tDelay (GEN=%d): %u msec\n", gen, ms);
6939         /*
6940          * adjust for prescaler, and convert into KHz 
6941          */
6942         return ms ? ((1 << gen) * 4440) / ms : 0;
6943 }
6944
6945 static void ncr_getclock (ncb_p np, u_char multiplier)
6946 {
6947         unsigned char scntl3;
6948         unsigned char stest1;
6949         scntl3 = INB(nc_scntl3);
6950         stest1 = INB(nc_stest1);
6951           
6952         np->multiplier = 1;
6953
6954         if (multiplier > 1) {
6955                 np->multiplier  = multiplier;
6956                 np->clock_khz   = 40000 * multiplier;
6957         } else {
6958                 if ((scntl3 & 7) == 0) {
6959                         unsigned f1, f2;
6960                         /* throw away first result */
6961                         (void) ncrgetfreq (np, 11);
6962                         f1 = ncrgetfreq (np, 11);
6963                         f2 = ncrgetfreq (np, 11);
6964
6965                         if (bootverbose >= 2)
6966                           printf ("\tNCR clock is %uKHz, %uKHz\n", f1, f2);
6967                         if (f1 > f2) f1 = f2;   /* trust lower result   */
6968                         if (f1 > 45000) {
6969                                 scntl3 = 5;     /* >45Mhz: assume 80MHz */
6970                         } else {
6971                                 scntl3 = 3;     /* <45Mhz: assume 40MHz */
6972                         }
6973                 }
6974                 else if ((scntl3 & 7) == 5)
6975                         np->clock_khz = 80000;  /* Probably a 875 rev. 1 ? */
6976         }
6977 }
6978
6979 /*=========================================================================*/
6980
6981 #ifdef NCR_TEKRAM_EEPROM
6982
6983 struct tekram_eeprom_dev {
6984   u_char        devmode;
6985 #define TKR_PARCHK      0x01
6986 #define TKR_TRYSYNC     0x02
6987 #define TKR_ENDISC      0x04
6988 #define TKR_STARTUNIT   0x08
6989 #define TKR_USETAGS     0x10
6990 #define TKR_TRYWIDE     0x20
6991   u_char        syncparam;      /* max. sync transfer rate (table ?) */
6992   u_char        filler1;
6993   u_char        filler2;
6994 };
6995
6996
6997 struct tekram_eeprom {
6998   struct tekram_eeprom_dev 
6999                 dev[16];
7000   u_char        adaptid;
7001   u_char        adaptmode;
7002 #define TKR_ADPT_GT2DRV 0x01
7003 #define TKR_ADPT_GT1GB  0x02
7004 #define TKR_ADPT_RSTBUS 0x04
7005 #define TKR_ADPT_ACTNEG 0x08
7006 #define TKR_ADPT_NOSEEK 0x10
7007 #define TKR_ADPT_MORLUN 0x20
7008   u_char        delay;          /* unit ? ( table ??? ) */
7009   u_char        tags;           /* use 4 times as many ... */
7010   u_char        filler[60];
7011 };
7012
7013 static void
7014 tekram_write_bit (ncb_p np, int bit)
7015 {
7016         u_char val = 0x10 + ((bit & 1) << 1);
7017
7018         DELAY(10);
7019         OUTB (nc_gpreg, val);
7020         DELAY(10);
7021         OUTB (nc_gpreg, val | 0x04);
7022         DELAY(10);
7023         OUTB (nc_gpreg, val);
7024         DELAY(10);
7025 }
7026
7027 static int
7028 tekram_read_bit (ncb_p np)
7029 {
7030         OUTB (nc_gpreg, 0x10);
7031         DELAY(10);
7032         OUTB (nc_gpreg, 0x14);
7033         DELAY(10);
7034         return INB (nc_gpreg) & 1;
7035 }
7036
7037 static u_short
7038 read_tekram_eeprom_reg (ncb_p np, int reg)
7039 {
7040         int bit;
7041         u_short result = 0;
7042         int cmd = 0x80 | reg;
7043
7044         OUTB (nc_gpreg, 0x10);
7045
7046         tekram_write_bit (np, 1);
7047         for (bit = 7; bit >= 0; bit--)
7048         {
7049                 tekram_write_bit (np, cmd >> bit);
7050         }
7051
7052         for (bit = 0; bit < 16; bit++)
7053         {
7054                 result <<= 1;
7055                 result |= tekram_read_bit (np);
7056         }
7057
7058         OUTB (nc_gpreg, 0x00);
7059         return result;
7060 }
7061
7062 static int 
7063 read_tekram_eeprom(ncb_p np, struct tekram_eeprom *buffer)
7064 {
7065         u_short *p = (u_short *) buffer;
7066         u_short sum = 0;
7067         int i;
7068
7069         if (INB (nc_gpcntl) != 0x09)
7070         {
7071                 return 0;
7072         }
7073         for (i = 0; i < 64; i++)
7074         {
7075                 u_short val;
7076 if((i&0x0f) == 0) printf ("%02x:", i*2);
7077                 val = read_tekram_eeprom_reg (np, i);
7078                 if (p)
7079                         *p++ = val;
7080                 sum += val;
7081 if((i&0x01) == 0x00) printf (" ");
7082                 printf ("%02x%02x", val & 0xff, (val >> 8) & 0xff);
7083 if((i&0x0f) == 0x0f) printf ("\n");
7084         }
7085 printf ("Sum = %04x\n", sum);
7086         return sum == 0x1234;
7087 }
7088 #endif /* NCR_TEKRAM_EEPROM */
7089
7090 static device_method_t ncr_methods[] = {
7091         /* Device interface */
7092         DEVMETHOD(device_probe,         ncr_probe),
7093         DEVMETHOD(device_attach,        ncr_attach),
7094
7095         { 0, 0 }
7096 };
7097
7098 static driver_t ncr_driver = {
7099         "ncr",
7100         ncr_methods,
7101         sizeof(struct ncb),
7102 };
7103
7104 static devclass_t ncr_devclass;
7105
7106 DRIVER_MODULE(ncr, pci, ncr_driver, ncr_devclass, 0, 0);
7107 MODULE_DEPEND(ncr, cam, 1, 1, 1);
7108 MODULE_DEPEND(ncr, pci, 1, 1, 1);
7109
7110 /*=========================================================================*/
7111 #endif /* _KERNEL */