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