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