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