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