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