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