ncr.c revision 41766
1/**************************************************************************
2**
3**  $Id: ncr.c,v 1.139 1998/12/07 21:58:47 archie 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_setwide	(ncb_p np, nccb_p cp, u_char wide, u_char ack);
1337static	int	ncr_show_msg	(u_char * msg);
1338static	int	ncr_snooptest	(ncb_p np);
1339static	void	ncr_action	(struct cam_sim *sim, union ccb *ccb);
1340static	void	ncr_timeout	(void *arg);
1341static  void    ncr_wakeup	(ncb_p np, u_long code);
1342
1343static  const char*	ncr_probe	(pcici_t tag, pcidi_t type);
1344static	void	ncr_attach	(pcici_t tag, int unit);
1345
1346#endif /* KERNEL */
1347
1348/*==========================================================
1349**
1350**
1351**      Global static data.
1352**
1353**
1354**==========================================================
1355*/
1356
1357
1358#if !defined(lint)
1359static const char ident[] =
1360	"\n$Id: ncr.c,v 1.139 1998/12/07 21:58:47 archie Exp $\n";
1361#endif
1362
1363static const u_long	ncr_version = NCR_VERSION	* 11
1364	+ (u_long) sizeof (struct ncb)	*  7
1365	+ (u_long) sizeof (struct nccb)	*  5
1366	+ (u_long) sizeof (struct lcb)	*  3
1367	+ (u_long) sizeof (struct tcb)	*  2;
1368
1369#ifdef KERNEL
1370static const int nncr=MAX_UNITS;	/* XXX to be replaced by SYSCTL */
1371static ncb_p ncrp [MAX_UNITS];		/* XXX to be replaced by SYSCTL */
1372
1373static int ncr_debug = SCSI_NCR_DEBUG;
1374SYSCTL_INT(_debug, OID_AUTO, ncr_debug, CTLFLAG_RW, &ncr_debug, 0, "");
1375
1376static int ncr_cache; /* to be aligned _NOT_ static */
1377
1378/*==========================================================
1379**
1380**
1381**      Global static data:	auto configure
1382**
1383**
1384**==========================================================
1385*/
1386
1387#define	NCR_810_ID	(0x00011000ul)
1388#define	NCR_815_ID	(0x00041000ul)
1389#define	NCR_820_ID	(0x00021000ul)
1390#define	NCR_825_ID	(0x00031000ul)
1391#define	NCR_860_ID	(0x00061000ul)
1392#define	NCR_875_ID	(0x000f1000ul)
1393#define	NCR_875_ID2	(0x008f1000ul)
1394#define	NCR_885_ID	(0x000d1000ul)
1395#define	NCR_895_ID	(0x000c1000ul)
1396#define	NCR_896_ID	(0x000b1000ul)
1397
1398
1399static u_long ncr_count;
1400
1401static struct	pci_device ncr_device = {
1402	"ncr",
1403	ncr_probe,
1404	ncr_attach,
1405	&ncr_count,
1406	NULL
1407};
1408
1409DATA_SET (pcidevice_set, ncr_device);
1410
1411static char *ncr_name (ncb_p np)
1412{
1413	static char name[10];
1414	snprintf(name, sizeof(name), "ncr%d", np->unit);
1415	return (name);
1416}
1417
1418/*==========================================================
1419**
1420**
1421**      Scripts for NCR-Processor.
1422**
1423**      Use ncr_script_bind for binding to physical addresses.
1424**
1425**
1426**==========================================================
1427**
1428**	NADDR generates a reference to a field of the controller data.
1429**	PADDR generates a reference to another part of the script.
1430**	RADDR generates a reference to a script processor register.
1431**	FADDR generates a reference to a script processor register
1432**		with offset.
1433**
1434**----------------------------------------------------------
1435*/
1436
1437#define	RELOC_SOFTC	0x40000000
1438#define	RELOC_LABEL	0x50000000
1439#define	RELOC_REGISTER	0x60000000
1440#define	RELOC_KVAR	0x70000000
1441#define	RELOC_LABELH	0x80000000
1442#define	RELOC_MASK	0xf0000000
1443
1444#define	NADDR(label)	(RELOC_SOFTC | offsetof(struct ncb, label))
1445#define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1446#define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
1447#define	RADDR(label)	(RELOC_REGISTER | REG(label))
1448#define	FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1449#define	KVAR(which)	(RELOC_KVAR | (which))
1450
1451#define KVAR_SECOND			(0)
1452#define KVAR_TICKS			(1)
1453#define KVAR_NCR_CACHE			(2)
1454
1455#define	SCRIPT_KVAR_FIRST		(0)
1456#define	SCRIPT_KVAR_LAST		(3)
1457
1458/*
1459 * Kernel variables referenced in the scripts.
1460 * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
1461 */
1462static void *script_kvars[] =
1463	{ &time_second, &ticks, &ncr_cache };
1464
1465static	struct script script0 = {
1466/*--------------------------< START >-----------------------*/ {
1467	/*
1468	**	Claim to be still alive ...
1469	*/
1470	SCR_COPY (sizeof (((struct ncb *)0)->heartbeat)),
1471		KVAR (KVAR_SECOND),
1472		NADDR (heartbeat),
1473	/*
1474	**      Make data structure address invalid.
1475	**      clear SIGP.
1476	*/
1477	SCR_LOAD_REG (dsa, 0xff),
1478		0,
1479	SCR_FROM_REG (ctest2),
1480		0,
1481}/*-------------------------< START0 >----------------------*/,{
1482	/*
1483	**	Hook for interrupted GetConditionCode.
1484	**	Will be patched to ... IFTRUE by
1485	**	the interrupt handler.
1486	*/
1487	SCR_INT ^ IFFALSE (0),
1488		SIR_SENSE_RESTART,
1489
1490}/*-------------------------< START1 >----------------------*/,{
1491	/*
1492	**	Hook for stalled start queue.
1493	**	Will be patched to IFTRUE by the interrupt handler.
1494	*/
1495	SCR_INT ^ IFFALSE (0),
1496		SIR_STALL_RESTART,
1497	/*
1498	**	Then jump to a certain point in tryloop.
1499	**	Due to the lack of indirect addressing the code
1500	**	is self modifying here.
1501	*/
1502	SCR_JUMP,
1503}/*-------------------------< STARTPOS >--------------------*/,{
1504		PADDRH(tryloop),
1505
1506}/*-------------------------< TRYSEL >----------------------*/,{
1507	/*
1508	**	Now:
1509	**	DSA: Address of a Data Structure
1510	**	or   Address of the IDLE-Label.
1511	**
1512	**	TEMP:	Address of a script, which tries to
1513	**		start the NEXT entry.
1514	**
1515	**	Save the TEMP register into the SCRATCHA register.
1516	**	Then copy the DSA to TEMP and RETURN.
1517	**	This is kind of an indirect jump.
1518	**	(The script processor has NO stack, so the
1519	**	CALL is actually a jump and link, and the
1520	**	RETURN is an indirect jump.)
1521	**
1522	**	If the slot was empty, DSA contains the address
1523	**	of the IDLE part of this script. The processor
1524	**	jumps to IDLE and waits for a reselect.
1525	**	It will wake up and try the same slot again
1526	**	after the SIGP bit becomes set by the host.
1527	**
1528	**	If the slot was not empty, DSA contains
1529	**	the address of the phys-part of a nccb.
1530	**	The processor jumps to this address.
1531	**	phys starts with head,
1532	**	head starts with launch,
1533	**	so actually the processor jumps to
1534	**	the lauch part.
1535	**	If the entry is scheduled for execution,
1536	**	then launch contains a jump to SELECT.
1537	**	If it's not scheduled, it contains a jump to IDLE.
1538	*/
1539	SCR_COPY (4),
1540		RADDR (temp),
1541		RADDR (scratcha),
1542	SCR_COPY (4),
1543		RADDR (dsa),
1544		RADDR (temp),
1545	SCR_RETURN,
1546		0
1547
1548}/*-------------------------< SKIP >------------------------*/,{
1549	/*
1550	**	This entry has been canceled.
1551	**	Next time use the next slot.
1552	*/
1553	SCR_COPY (4),
1554		RADDR (scratcha),
1555		PADDR (startpos),
1556	/*
1557	**	patch the launch field.
1558	**	should look like an idle process.
1559	*/
1560	SCR_COPY_F (4),
1561		RADDR (dsa),
1562		PADDR (skip2),
1563	SCR_COPY (8),
1564		PADDR (idle),
1565}/*-------------------------< SKIP2 >-----------------------*/,{
1566		0,
1567	SCR_JUMP,
1568		PADDR(start),
1569}/*-------------------------< IDLE >------------------------*/,{
1570	/*
1571	**	Nothing to do?
1572	**	Wait for reselect.
1573	*/
1574	SCR_JUMP,
1575		PADDR(reselect),
1576
1577}/*-------------------------< SELECT >----------------------*/,{
1578	/*
1579	**	DSA	contains the address of a scheduled
1580	**		data structure.
1581	**
1582	**	SCRATCHA contains the address of the script,
1583	**		which starts the next entry.
1584	**
1585	**	Set Initiator mode.
1586	**
1587	**	(Target mode is left as an exercise for the reader)
1588	*/
1589
1590	SCR_CLR (SCR_TRG),
1591		0,
1592	SCR_LOAD_REG (HS_REG, 0xff),
1593		0,
1594
1595	/*
1596	**      And try to select this target.
1597	*/
1598	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1599		PADDR (reselect),
1600
1601	/*
1602	**	Now there are 4 possibilities:
1603	**
1604	**	(1) The ncr looses arbitration.
1605	**	This is ok, because it will try again,
1606	**	when the bus becomes idle.
1607	**	(But beware of the timeout function!)
1608	**
1609	**	(2) The ncr is reselected.
1610	**	Then the script processor takes the jump
1611	**	to the RESELECT label.
1612	**
1613	**	(3) The ncr completes the selection.
1614	**	Then it will execute the next statement.
1615	**
1616	**	(4) There is a selection timeout.
1617	**	Then the ncr should interrupt the host and stop.
1618	**	Unfortunately, it seems to continue execution
1619	**	of the script. But it will fail with an
1620	**	IID-interrupt on the next WHEN.
1621	*/
1622
1623	SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_IN)),
1624		0,
1625
1626	/*
1627	**	Save target id to ctest0 register
1628	*/
1629
1630	SCR_FROM_REG (sdid),
1631		0,
1632	SCR_TO_REG (ctest0),
1633		0,
1634	/*
1635	**	Send the IDENTIFY and SIMPLE_TAG messages
1636	**	(and the MSG_EXT_SDTR message)
1637	*/
1638	SCR_MOVE_TBL ^ SCR_MSG_OUT,
1639		offsetof (struct dsb, smsg),
1640#ifdef undef /* XXX better fail than try to deal with this ... */
1641	SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1642		-16,
1643#endif
1644	SCR_CLR (SCR_ATN),
1645		0,
1646	SCR_COPY (1),
1647		RADDR (sfbr),
1648		NADDR (lastmsg),
1649	/*
1650	**	Selection complete.
1651	**	Next time use the next slot.
1652	*/
1653	SCR_COPY (4),
1654		RADDR (scratcha),
1655		PADDR (startpos),
1656}/*-------------------------< PREPARE >----------------------*/,{
1657	/*
1658	**      The ncr doesn't have an indirect load
1659	**	or store command. So we have to
1660	**	copy part of the control block to a
1661	**	fixed place, where we can access it.
1662	**
1663	**	We patch the address part of a
1664	**	COPY command with the DSA-register.
1665	*/
1666	SCR_COPY_F (4),
1667		RADDR (dsa),
1668		PADDR (loadpos),
1669	/*
1670	**	then we do the actual copy.
1671	*/
1672	SCR_COPY (sizeof (struct head)),
1673	/*
1674	**	continued after the next label ...
1675	*/
1676
1677}/*-------------------------< LOADPOS >---------------------*/,{
1678		0,
1679		NADDR (header),
1680	/*
1681	**      Mark this nccb as not scheduled.
1682	*/
1683	SCR_COPY (8),
1684		PADDR (idle),
1685		NADDR (header.launch),
1686	/*
1687	**      Set a time stamp for this selection
1688	*/
1689	SCR_COPY (sizeof (ticks)),
1690		KVAR (KVAR_TICKS),
1691		NADDR (header.stamp.select),
1692	/*
1693	**      load the savep (saved pointer) into
1694	**      the TEMP register (actual pointer)
1695	*/
1696	SCR_COPY (4),
1697		NADDR (header.savep),
1698		RADDR (temp),
1699	/*
1700	**      Initialize the status registers
1701	*/
1702	SCR_COPY (4),
1703		NADDR (header.status),
1704		RADDR (scr0),
1705
1706}/*-------------------------< PREPARE2 >---------------------*/,{
1707	/*
1708	**      Load the synchronous mode register
1709	*/
1710	SCR_COPY (1),
1711		NADDR (sync_st),
1712		RADDR (sxfer),
1713	/*
1714	**      Load the wide mode and timing register
1715	*/
1716	SCR_COPY (1),
1717		NADDR (wide_st),
1718		RADDR (scntl3),
1719	/*
1720	**	Initialize the msgout buffer with a NOOP message.
1721	*/
1722	SCR_LOAD_REG (scratcha, MSG_NOOP),
1723		0,
1724	SCR_COPY (1),
1725		RADDR (scratcha),
1726		NADDR (msgout),
1727	SCR_COPY (1),
1728		RADDR (scratcha),
1729		NADDR (msgin),
1730	/*
1731	**	Message in phase ?
1732	*/
1733	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
1734		PADDR (dispatch),
1735	/*
1736	**	Extended or reject message ?
1737	*/
1738	SCR_FROM_REG (sbdl),
1739		0,
1740	SCR_JUMP ^ IFTRUE (DATA (MSG_EXTENDED)),
1741		PADDR (msg_in),
1742	SCR_JUMP ^ IFTRUE (DATA (MSG_MESSAGE_REJECT)),
1743		PADDRH (msg_reject),
1744	/*
1745	**	normal processing
1746	*/
1747	SCR_JUMP,
1748		PADDR (dispatch),
1749}/*-------------------------< SETMSG >----------------------*/,{
1750	SCR_COPY (1),
1751		RADDR (scratcha),
1752		NADDR (msgout),
1753	SCR_SET (SCR_ATN),
1754		0,
1755}/*-------------------------< CLRACK >----------------------*/,{
1756	/*
1757	**	Terminate possible pending message phase.
1758	*/
1759	SCR_CLR (SCR_ACK),
1760		0,
1761
1762}/*-----------------------< DISPATCH >----------------------*/,{
1763	SCR_FROM_REG (HS_REG),
1764		0,
1765	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
1766		SIR_NEGO_FAILED,
1767	/*
1768	**	remove bogus output signals
1769	*/
1770	SCR_REG_REG (socl, SCR_AND, CACK|CATN),
1771		0,
1772	SCR_RETURN ^ IFTRUE (WHEN (SCR_DATA_OUT)),
1773		0,
1774	SCR_RETURN ^ IFTRUE (IF (SCR_DATA_IN)),
1775		0,
1776	SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
1777		PADDR (msg_out),
1778	SCR_JUMP ^ IFTRUE (IF (SCR_MSG_IN)),
1779		PADDR (msg_in),
1780	SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
1781		PADDR (command),
1782	SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
1783		PADDR (status),
1784	/*
1785	**      Discard one illegal phase byte, if required.
1786	*/
1787	SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
1788		0,
1789	SCR_COPY (1),
1790		RADDR (scratcha),
1791		NADDR (xerr_st),
1792	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
1793		8,
1794	SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
1795		NADDR (scratch),
1796	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
1797		8,
1798	SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
1799		NADDR (scratch),
1800	SCR_JUMP,
1801		PADDR (dispatch),
1802
1803}/*-------------------------< NO_DATA >--------------------*/,{
1804	/*
1805	**	The target wants to tranfer too much data
1806	**	or in the wrong direction.
1807	**      Remember that in extended error.
1808	*/
1809	SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
1810		0,
1811	SCR_COPY (1),
1812		RADDR (scratcha),
1813		NADDR (xerr_st),
1814	/*
1815	**      Discard one data byte, if required.
1816	*/
1817	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
1818		8,
1819	SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
1820		NADDR (scratch),
1821	SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
1822		8,
1823	SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
1824		NADDR (scratch),
1825	/*
1826	**      .. and repeat as required.
1827	*/
1828	SCR_CALL,
1829		PADDR (dispatch),
1830	SCR_JUMP,
1831		PADDR (no_data),
1832}/*-------------------------< CHECKATN >--------------------*/,{
1833	/*
1834	**	If AAP (bit 1 of scntl0 register) is set
1835	**	and a parity error is detected,
1836	**	the script processor asserts ATN.
1837	**
1838	**	The target should switch to a MSG_OUT phase
1839	**	to get the message.
1840	*/
1841	SCR_FROM_REG (socl),
1842		0,
1843	SCR_JUMP ^ IFFALSE (MASK (CATN, CATN)),
1844		PADDR (dispatch),
1845	/*
1846	**	count it
1847	*/
1848	SCR_REG_REG (PS_REG, SCR_ADD, 1),
1849		0,
1850	/*
1851	**	Prepare a MSG_INITIATOR_DET_ERR message
1852	**	(initiator detected error).
1853	**	The target should retry the transfer.
1854	*/
1855	SCR_LOAD_REG (scratcha, MSG_INITIATOR_DET_ERR),
1856		0,
1857	SCR_JUMP,
1858		PADDR (setmsg),
1859
1860}/*-------------------------< COMMAND >--------------------*/,{
1861	/*
1862	**	If this is not a GETCC transfer ...
1863	*/
1864	SCR_FROM_REG (SS_REG),
1865		0,
1866/*<<<*/	SCR_JUMPR ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
1867		28,
1868	/*
1869	**	... set a timestamp ...
1870	*/
1871	SCR_COPY (sizeof (ticks)),
1872		KVAR (KVAR_TICKS),
1873		NADDR (header.stamp.command),
1874	/*
1875	**	... and send the command
1876	*/
1877	SCR_MOVE_TBL ^ SCR_COMMAND,
1878		offsetof (struct dsb, cmd),
1879	SCR_JUMP,
1880		PADDR (dispatch),
1881	/*
1882	**	Send the GETCC command
1883	*/
1884/*>>>*/	SCR_MOVE_TBL ^ SCR_COMMAND,
1885		offsetof (struct dsb, scmd),
1886	SCR_JUMP,
1887		PADDR (dispatch),
1888
1889}/*-------------------------< STATUS >--------------------*/,{
1890	/*
1891	**	set the timestamp.
1892	*/
1893	SCR_COPY (sizeof (ticks)),
1894		KVAR (KVAR_TICKS),
1895		NADDR (header.stamp.status),
1896	/*
1897	**	If this is a GETCC transfer,
1898	*/
1899	SCR_FROM_REG (SS_REG),
1900		0,
1901/*<<<*/	SCR_JUMPR ^ IFFALSE (DATA (SCSI_STATUS_CHECK_COND)),
1902		40,
1903	/*
1904	**	get the status
1905	*/
1906	SCR_MOVE_ABS (1) ^ SCR_STATUS,
1907		NADDR (scratch),
1908	/*
1909	**	Save status to scsi_status.
1910	**	Mark as complete.
1911	**	And wait for disconnect.
1912	*/
1913	SCR_TO_REG (SS_REG),
1914		0,
1915	SCR_REG_REG (SS_REG, SCR_OR, SCSI_STATUS_SENSE),
1916		0,
1917	SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1918		0,
1919	SCR_JUMP,
1920		PADDR (checkatn),
1921	/*
1922	**	If it was no GETCC transfer,
1923	**	save the status to scsi_status.
1924	*/
1925/*>>>*/	SCR_MOVE_ABS (1) ^ SCR_STATUS,
1926		NADDR (scratch),
1927	SCR_TO_REG (SS_REG),
1928		0,
1929	/*
1930	**	if it was no check condition ...
1931	*/
1932	SCR_JUMP ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
1933		PADDR (checkatn),
1934	/*
1935	**	... mark as complete.
1936	*/
1937	SCR_LOAD_REG (HS_REG, HS_COMPLETE),
1938		0,
1939	SCR_JUMP,
1940		PADDR (checkatn),
1941
1942}/*-------------------------< MSG_IN >--------------------*/,{
1943	/*
1944	**	Get the first byte of the message
1945	**	and save it to SCRATCHA.
1946	**
1947	**	The script processor doesn't negate the
1948	**	ACK signal after this transfer.
1949	*/
1950	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
1951		NADDR (msgin[0]),
1952	/*
1953	**	Check for message parity error.
1954	*/
1955	SCR_TO_REG (scratcha),
1956		0,
1957	SCR_FROM_REG (socl),
1958		0,
1959	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
1960		PADDRH (msg_parity),
1961	SCR_FROM_REG (scratcha),
1962		0,
1963	/*
1964	**	Parity was ok, handle this message.
1965	*/
1966	SCR_JUMP ^ IFTRUE (DATA (MSG_CMDCOMPLETE)),
1967		PADDR (complete),
1968	SCR_JUMP ^ IFTRUE (DATA (MSG_SAVEDATAPOINTER)),
1969		PADDR (save_dp),
1970	SCR_JUMP ^ IFTRUE (DATA (MSG_RESTOREPOINTERS)),
1971		PADDR (restore_dp),
1972	SCR_JUMP ^ IFTRUE (DATA (MSG_DISCONNECT)),
1973		PADDR (disconnect),
1974	SCR_JUMP ^ IFTRUE (DATA (MSG_EXTENDED)),
1975		PADDRH (msg_extended),
1976	SCR_JUMP ^ IFTRUE (DATA (MSG_NOOP)),
1977		PADDR (clrack),
1978	SCR_JUMP ^ IFTRUE (DATA (MSG_MESSAGE_REJECT)),
1979		PADDRH (msg_reject),
1980	SCR_JUMP ^ IFTRUE (DATA (MSG_IGN_WIDE_RESIDUE)),
1981		PADDRH (msg_ign_residue),
1982	/*
1983	**	Rest of the messages left as
1984	**	an exercise ...
1985	**
1986	**	Unimplemented messages:
1987	**	fall through to MSG_BAD.
1988	*/
1989}/*-------------------------< MSG_BAD >------------------*/,{
1990	/*
1991	**	unimplemented message - reject it.
1992	*/
1993	SCR_INT,
1994		SIR_REJECT_SENT,
1995	SCR_LOAD_REG (scratcha, MSG_MESSAGE_REJECT),
1996		0,
1997	SCR_JUMP,
1998		PADDR (setmsg),
1999
2000}/*-------------------------< COMPLETE >-----------------*/,{
2001	/*
2002	**	Complete message.
2003	**
2004	**	If it's not the get condition code,
2005	**	copy TEMP register to LASTP in header.
2006	*/
2007	SCR_FROM_REG (SS_REG),
2008		0,
2009/*<<<*/	SCR_JUMPR ^ IFTRUE (MASK (SCSI_STATUS_SENSE, SCSI_STATUS_SENSE)),
2010		12,
2011	SCR_COPY (4),
2012		RADDR (temp),
2013		NADDR (header.lastp),
2014/*>>>*/	/*
2015	**	When we terminate the cycle by clearing ACK,
2016	**	the target may disconnect immediately.
2017	**
2018	**	We don't want to be told of an
2019	**	"unexpected disconnect",
2020	**	so we disable this feature.
2021	*/
2022	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2023		0,
2024	/*
2025	**	Terminate cycle ...
2026	*/
2027	SCR_CLR (SCR_ACK|SCR_ATN),
2028		0,
2029	/*
2030	**	... and wait for the disconnect.
2031	*/
2032	SCR_WAIT_DISC,
2033		0,
2034}/*-------------------------< CLEANUP >-------------------*/,{
2035	/*
2036	**      dsa:    Pointer to nccb
2037	**	      or xxxxxxFF (no nccb)
2038	**
2039	**      HS_REG:   Host-Status (<>0!)
2040	*/
2041	SCR_FROM_REG (dsa),
2042		0,
2043	SCR_JUMP ^ IFTRUE (DATA (0xff)),
2044		PADDR (signal),
2045	/*
2046	**      dsa is valid.
2047	**	save the status registers
2048	*/
2049	SCR_COPY (4),
2050		RADDR (scr0),
2051		NADDR (header.status),
2052	/*
2053	**	and copy back the header to the nccb.
2054	*/
2055	SCR_COPY_F (4),
2056		RADDR (dsa),
2057		PADDR (cleanup0),
2058	SCR_COPY (sizeof (struct head)),
2059		NADDR (header),
2060}/*-------------------------< CLEANUP0 >--------------------*/,{
2061		0,
2062
2063	/*
2064	**	If command resulted in "check condition"
2065	**	status and is not yet completed,
2066	**	try to get the condition code.
2067	*/
2068	SCR_FROM_REG (HS_REG),
2069		0,
2070/*<<<*/	SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2071		16,
2072	SCR_FROM_REG (SS_REG),
2073		0,
2074	SCR_JUMP ^ IFTRUE (DATA (SCSI_STATUS_CHECK_COND)),
2075		PADDRH(getcc2),
2076}/*-------------------------< SIGNAL >----------------------*/,{
2077	/*
2078	**	if status = queue full,
2079	**	reinsert in startqueue and stall queue.
2080	*/
2081/*>>>*/	SCR_FROM_REG (SS_REG),
2082		0,
2083	SCR_INT ^ IFTRUE (DATA (SCSI_STATUS_QUEUE_FULL)),
2084		SIR_STALL_QUEUE,
2085  	/*
2086	**	And make the DSA register invalid.
2087	*/
2088	SCR_LOAD_REG (dsa, 0xff), /* invalid */
2089		0,
2090	/*
2091	**	if job completed ...
2092	*/
2093	SCR_FROM_REG (HS_REG),
2094		0,
2095	/*
2096	**	... signal completion to the host
2097	*/
2098	SCR_INT_FLY ^ IFFALSE (MASK (0, HS_DONEMASK)),
2099		0,
2100	/*
2101	**	Auf zu neuen Schandtaten!
2102	*/
2103	SCR_JUMP,
2104		PADDR(start),
2105
2106}/*-------------------------< SAVE_DP >------------------*/,{
2107	/*
2108	**	SAVE_DP message:
2109	**	Copy TEMP register to SAVEP in header.
2110	*/
2111	SCR_COPY (4),
2112		RADDR (temp),
2113		NADDR (header.savep),
2114	SCR_JUMP,
2115		PADDR (clrack),
2116}/*-------------------------< RESTORE_DP >---------------*/,{
2117	/*
2118	**	RESTORE_DP message:
2119	**	Copy SAVEP in header to TEMP register.
2120	*/
2121	SCR_COPY (4),
2122		NADDR (header.savep),
2123		RADDR (temp),
2124	SCR_JUMP,
2125		PADDR (clrack),
2126
2127}/*-------------------------< DISCONNECT >---------------*/,{
2128	/*
2129	**	If QUIRK_AUTOSAVE is set,
2130	**	do an "save pointer" operation.
2131	*/
2132	SCR_FROM_REG (QU_REG),
2133		0,
2134/*<<<*/	SCR_JUMPR ^ IFFALSE (MASK (QUIRK_AUTOSAVE, QUIRK_AUTOSAVE)),
2135		12,
2136	/*
2137	**	like SAVE_DP message:
2138	**	Copy TEMP register to SAVEP in header.
2139	*/
2140	SCR_COPY (4),
2141		RADDR (temp),
2142		NADDR (header.savep),
2143/*>>>*/	/*
2144	**	Check if temp==savep or temp==goalp:
2145	**	if not, log a missing save pointer message.
2146	**	In fact, it's a comparison mod 256.
2147	**
2148	**	Hmmm, I hadn't thought that I would be urged to
2149	**	write this kind of ugly self modifying code.
2150	**
2151	**	It's unbelievable, but the ncr53c8xx isn't able
2152	**	to subtract one register from another.
2153	*/
2154	SCR_FROM_REG (temp),
2155		0,
2156	/*
2157	**	You are not expected to understand this ..
2158	**
2159	**	CAUTION: only little endian architectures supported! XXX
2160	*/
2161	SCR_COPY_F (1),
2162		NADDR (header.savep),
2163		PADDR (disconnect0),
2164}/*-------------------------< DISCONNECT0 >--------------*/,{
2165/*<<<*/	SCR_JUMPR ^ IFTRUE (DATA (1)),
2166		20,
2167	/*
2168	**	neither this
2169	*/
2170	SCR_COPY_F (1),
2171		NADDR (header.goalp),
2172		PADDR (disconnect1),
2173}/*-------------------------< DISCONNECT1 >--------------*/,{
2174	SCR_INT ^ IFFALSE (DATA (1)),
2175		SIR_MISSING_SAVE,
2176/*>>>*/
2177
2178	/*
2179	**	DISCONNECTing  ...
2180	**
2181	**	disable the "unexpected disconnect" feature,
2182	**	and remove the ACK signal.
2183	*/
2184	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2185		0,
2186	SCR_CLR (SCR_ACK|SCR_ATN),
2187		0,
2188	/*
2189	**	Wait for the disconnect.
2190	*/
2191	SCR_WAIT_DISC,
2192		0,
2193	/*
2194	**	Profiling:
2195	**	Set a time stamp,
2196	**	and count the disconnects.
2197	*/
2198	SCR_COPY (sizeof (ticks)),
2199		KVAR (KVAR_TICKS),
2200		NADDR (header.stamp.disconnect),
2201	SCR_COPY (4),
2202		NADDR (disc_phys),
2203		RADDR (temp),
2204	SCR_REG_REG (temp, SCR_ADD, 0x01),
2205		0,
2206	SCR_COPY (4),
2207		RADDR (temp),
2208		NADDR (disc_phys),
2209	/*
2210	**	Status is: DISCONNECTED.
2211	*/
2212	SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2213		0,
2214	SCR_JUMP,
2215		PADDR (cleanup),
2216
2217}/*-------------------------< MSG_OUT >-------------------*/,{
2218	/*
2219	**	The target requests a message.
2220	*/
2221	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2222		NADDR (msgout),
2223	SCR_COPY (1),
2224		RADDR (sfbr),
2225		NADDR (lastmsg),
2226	/*
2227	**	If it was no ABORT message ...
2228	*/
2229	SCR_JUMP ^ IFTRUE (DATA (MSG_ABORT)),
2230		PADDRH (msg_out_abort),
2231	/*
2232	**	... wait for the next phase
2233	**	if it's a message out, send it again, ...
2234	*/
2235	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2236		PADDR (msg_out),
2237}/*-------------------------< MSG_OUT_DONE >--------------*/,{
2238	/*
2239	**	... else clear the message ...
2240	*/
2241	SCR_LOAD_REG (scratcha, MSG_NOOP),
2242		0,
2243	SCR_COPY (4),
2244		RADDR (scratcha),
2245		NADDR (msgout),
2246	/*
2247	**	... and process the next phase
2248	*/
2249	SCR_JUMP,
2250		PADDR (dispatch),
2251
2252}/*------------------------< BADGETCC >---------------------*/,{
2253	/*
2254	**	If SIGP was set, clear it and try again.
2255	*/
2256	SCR_FROM_REG (ctest2),
2257		0,
2258	SCR_JUMP ^ IFTRUE (MASK (CSIGP,CSIGP)),
2259		PADDRH (getcc2),
2260	SCR_INT,
2261		SIR_SENSE_FAILED,
2262}/*-------------------------< RESELECT >--------------------*/,{
2263	/*
2264	**	This NOP will be patched with LED OFF
2265	**	SCR_REG_REG (gpreg, SCR_OR, 0x01)
2266	*/
2267	SCR_NO_OP,
2268		0,
2269
2270	/*
2271	**	make the DSA invalid.
2272	*/
2273	SCR_LOAD_REG (dsa, 0xff),
2274		0,
2275	SCR_CLR (SCR_TRG),
2276		0,
2277	/*
2278	**	Sleep waiting for a reselection.
2279	**	If SIGP is set, special treatment.
2280	**
2281	**	Zu allem bereit ..
2282	*/
2283	SCR_WAIT_RESEL,
2284		PADDR(reselect2),
2285}/*-------------------------< RESELECT1 >--------------------*/,{
2286	/*
2287	**	This NOP will be patched with LED ON
2288	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2289	*/
2290	SCR_NO_OP,
2291		0,
2292	/*
2293	**	... zu nichts zu gebrauchen ?
2294	**
2295	**      load the target id into the SFBR
2296	**	and jump to the control block.
2297	**
2298	**	Look at the declarations of
2299	**	- struct ncb
2300	**	- struct tcb
2301	**	- struct lcb
2302	**	- struct nccb
2303	**	to understand what's going on.
2304	*/
2305	SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2306		0,
2307	SCR_TO_REG (ctest0),
2308		0,
2309	SCR_JUMP,
2310		NADDR (jump_tcb),
2311}/*-------------------------< RESELECT2 >-------------------*/,{
2312	/*
2313	**	This NOP will be patched with LED ON
2314	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2315	*/
2316	SCR_NO_OP,
2317		0,
2318	/*
2319	**	If it's not connected :(
2320	**	-> interrupted by SIGP bit.
2321	**	Jump to start.
2322	*/
2323	SCR_FROM_REG (ctest2),
2324		0,
2325	SCR_JUMP ^ IFTRUE (MASK (CSIGP,CSIGP)),
2326		PADDR (start),
2327	SCR_JUMP,
2328		PADDR (reselect),
2329
2330}/*-------------------------< RESEL_TMP >-------------------*/,{
2331	/*
2332	**	The return address in TEMP
2333	**	is in fact the data structure address,
2334	**	so copy it to the DSA register.
2335	*/
2336	SCR_COPY (4),
2337		RADDR (temp),
2338		RADDR (dsa),
2339	SCR_JUMP,
2340		PADDR (prepare),
2341
2342}/*-------------------------< RESEL_LUN >-------------------*/,{
2343	/*
2344	**	come back to this point
2345	**	to get an IDENTIFY message
2346	**	Wait for a msg_in phase.
2347	*/
2348/*<<<*/	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2349		48,
2350	/*
2351	**	message phase
2352	**	It's not a sony, it's a trick:
2353	**	read the data without acknowledging it.
2354	*/
2355	SCR_FROM_REG (sbdl),
2356		0,
2357/*<<<*/	SCR_JUMPR ^ IFFALSE (MASK (MSG_IDENTIFYFLAG, 0x98)),
2358		32,
2359	/*
2360	**	It WAS an Identify message.
2361	**	get it and ack it!
2362	*/
2363	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2364		NADDR (msgin),
2365	SCR_CLR (SCR_ACK),
2366		0,
2367	/*
2368	**	Mask out the lun.
2369	*/
2370	SCR_REG_REG (sfbr, SCR_AND, 0x07),
2371		0,
2372	SCR_RETURN,
2373		0,
2374	/*
2375	**	No message phase or no IDENTIFY message:
2376	**	return 0.
2377	*/
2378/*>>>*/	SCR_LOAD_SFBR (0),
2379		0,
2380	SCR_RETURN,
2381		0,
2382
2383}/*-------------------------< RESEL_TAG >-------------------*/,{
2384	/*
2385	**	come back to this point
2386	**	to get a SIMPLE_TAG message
2387	**	Wait for a MSG_IN phase.
2388	*/
2389/*<<<*/	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2390		64,
2391	/*
2392	**	message phase
2393	**	It's a trick - read the data
2394	**	without acknowledging it.
2395	*/
2396	SCR_FROM_REG (sbdl),
2397		0,
2398/*<<<*/	SCR_JUMPR ^ IFFALSE (DATA (MSG_SIMPLE_Q_TAG)),
2399		48,
2400	/*
2401	**	It WAS a SIMPLE_TAG message.
2402	**	get it and ack it!
2403	*/
2404	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2405		NADDR (msgin),
2406	SCR_CLR (SCR_ACK),
2407		0,
2408	/*
2409	**	Wait for the second byte (the tag)
2410	*/
2411/*<<<*/	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2412		24,
2413	/*
2414	**	Get it and ack it!
2415	*/
2416	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2417		NADDR (msgin),
2418	SCR_CLR (SCR_ACK|SCR_CARRY),
2419		0,
2420	SCR_RETURN,
2421		0,
2422	/*
2423	**	No message phase or no SIMPLE_TAG message
2424	**	or no second byte: return 0.
2425	*/
2426/*>>>*/	SCR_LOAD_SFBR (0),
2427		0,
2428	SCR_SET (SCR_CARRY),
2429		0,
2430	SCR_RETURN,
2431		0,
2432
2433}/*-------------------------< DATA_IN >--------------------*/,{
2434/*
2435**	Because the size depends on the
2436**	#define MAX_SCATTER parameter,
2437**	it is filled in at runtime.
2438**
2439**	SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2440**		PADDR (no_data),
2441**	SCR_COPY (sizeof (ticks)),
2442**		KVAR (KVAR_TICKS),
2443**		NADDR (header.stamp.data),
2444**	SCR_MOVE_TBL ^ SCR_DATA_IN,
2445**		offsetof (struct dsb, data[ 0]),
2446**
2447**  ##===========< i=1; i<MAX_SCATTER >=========
2448**  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2449**  ||		PADDR (checkatn),
2450**  ||	SCR_MOVE_TBL ^ SCR_DATA_IN,
2451**  ||		offsetof (struct dsb, data[ i]),
2452**  ##==========================================
2453**
2454**	SCR_CALL,
2455**		PADDR (checkatn),
2456**	SCR_JUMP,
2457**		PADDR (no_data),
2458*/
24590
2460}/*-------------------------< DATA_OUT >-------------------*/,{
2461/*
2462**	Because the size depends on the
2463**	#define MAX_SCATTER parameter,
2464**	it is filled in at runtime.
2465**
2466**	SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2467**		PADDR (no_data),
2468**	SCR_COPY (sizeof (ticks)),
2469**		KVAR (KVAR_TICKS),
2470**		NADDR (header.stamp.data),
2471**	SCR_MOVE_TBL ^ SCR_DATA_OUT,
2472**		offsetof (struct dsb, data[ 0]),
2473**
2474**  ##===========< i=1; i<MAX_SCATTER >=========
2475**  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2476**  ||		PADDR (dispatch),
2477**  ||	SCR_MOVE_TBL ^ SCR_DATA_OUT,
2478**  ||		offsetof (struct dsb, data[ i]),
2479**  ##==========================================
2480**
2481**	SCR_CALL,
2482**		PADDR (dispatch),
2483**	SCR_JUMP,
2484**		PADDR (no_data),
2485**
2486**---------------------------------------------------------
2487*/
2488(u_long)0
2489
2490}/*--------------------------------------------------------*/
2491};
2492
2493
2494static	struct scripth scripth0 = {
2495/*-------------------------< TRYLOOP >---------------------*/{
2496/*
2497**	Load an entry of the start queue into dsa
2498**	and try to start it by jumping to TRYSEL.
2499**
2500**	Because the size depends on the
2501**	#define MAX_START parameter, it is filled
2502**	in at runtime.
2503**
2504**-----------------------------------------------------------
2505**
2506**  ##===========< I=0; i<MAX_START >===========
2507**  ||	SCR_COPY (4),
2508**  ||		NADDR (squeue[i]),
2509**  ||		RADDR (dsa),
2510**  ||	SCR_CALL,
2511**  ||		PADDR (trysel),
2512**  ##==========================================
2513**
2514**	SCR_JUMP,
2515**		PADDRH(tryloop),
2516**
2517**-----------------------------------------------------------
2518*/
25190
2520}/*-------------------------< MSG_PARITY >---------------*/,{
2521	/*
2522	**	count it
2523	*/
2524	SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2525		0,
2526	/*
2527	**	send a "message parity error" message.
2528	*/
2529	SCR_LOAD_REG (scratcha, MSG_PARITY_ERROR),
2530		0,
2531	SCR_JUMP,
2532		PADDR (setmsg),
2533}/*-------------------------< MSG_MESSAGE_REJECT >---------------*/,{
2534	/*
2535	**	If a negotiation was in progress,
2536	**	negotiation failed.
2537	*/
2538	SCR_FROM_REG (HS_REG),
2539		0,
2540	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2541		SIR_NEGO_FAILED,
2542	/*
2543	**	else make host log this message
2544	*/
2545	SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2546		SIR_REJECT_RECEIVED,
2547	SCR_JUMP,
2548		PADDR (clrack),
2549
2550}/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2551	/*
2552	**	Terminate cycle
2553	*/
2554	SCR_CLR (SCR_ACK),
2555		0,
2556	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2557		PADDR (dispatch),
2558	/*
2559	**	get residue size.
2560	*/
2561	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2562		NADDR (msgin[1]),
2563	/*
2564	**	Check for message parity error.
2565	*/
2566	SCR_TO_REG (scratcha),
2567		0,
2568	SCR_FROM_REG (socl),
2569		0,
2570	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2571		PADDRH (msg_parity),
2572	SCR_FROM_REG (scratcha),
2573		0,
2574	/*
2575	**	Size is 0 .. ignore message.
2576	*/
2577	SCR_JUMP ^ IFTRUE (DATA (0)),
2578		PADDR (clrack),
2579	/*
2580	**	Size is not 1 .. have to interrupt.
2581	*/
2582/*<<<*/	SCR_JUMPR ^ IFFALSE (DATA (1)),
2583		40,
2584	/*
2585	**	Check for residue byte in swide register
2586	*/
2587	SCR_FROM_REG (scntl2),
2588		0,
2589/*<<<*/	SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2590		16,
2591	/*
2592	**	There IS data in the swide register.
2593	**	Discard it.
2594	*/
2595	SCR_REG_REG (scntl2, SCR_OR, WSR),
2596		0,
2597	SCR_JUMP,
2598		PADDR (clrack),
2599	/*
2600	**	Load again the size to the sfbr register.
2601	*/
2602/*>>>*/	SCR_FROM_REG (scratcha),
2603		0,
2604/*>>>*/	SCR_INT,
2605		SIR_IGN_RESIDUE,
2606	SCR_JUMP,
2607		PADDR (clrack),
2608
2609}/*-------------------------< MSG_EXTENDED >-------------*/,{
2610	/*
2611	**	Terminate cycle
2612	*/
2613	SCR_CLR (SCR_ACK),
2614		0,
2615	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2616		PADDR (dispatch),
2617	/*
2618	**	get length.
2619	*/
2620	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2621		NADDR (msgin[1]),
2622	/*
2623	**	Check for message parity error.
2624	*/
2625	SCR_TO_REG (scratcha),
2626		0,
2627	SCR_FROM_REG (socl),
2628		0,
2629	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2630		PADDRH (msg_parity),
2631	SCR_FROM_REG (scratcha),
2632		0,
2633	/*
2634	*/
2635	SCR_JUMP ^ IFTRUE (DATA (3)),
2636		PADDRH (msg_ext_3),
2637	SCR_JUMP ^ IFFALSE (DATA (2)),
2638		PADDR (msg_bad),
2639}/*-------------------------< MSG_EXT_2 >----------------*/,{
2640	SCR_CLR (SCR_ACK),
2641		0,
2642	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2643		PADDR (dispatch),
2644	/*
2645	**	get extended message code.
2646	*/
2647	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2648		NADDR (msgin[2]),
2649	/*
2650	**	Check for message parity error.
2651	*/
2652	SCR_TO_REG (scratcha),
2653		0,
2654	SCR_FROM_REG (socl),
2655		0,
2656	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2657		PADDRH (msg_parity),
2658	SCR_FROM_REG (scratcha),
2659		0,
2660	SCR_JUMP ^ IFTRUE (DATA (MSG_EXT_WDTR)),
2661		PADDRH (msg_wdtr),
2662	/*
2663	**	unknown extended message
2664	*/
2665	SCR_JUMP,
2666		PADDR (msg_bad)
2667}/*-------------------------< MSG_WDTR >-----------------*/,{
2668	SCR_CLR (SCR_ACK),
2669		0,
2670	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2671		PADDR (dispatch),
2672	/*
2673	**	get data bus width
2674	*/
2675	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2676		NADDR (msgin[3]),
2677	SCR_FROM_REG (socl),
2678		0,
2679	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2680		PADDRH (msg_parity),
2681	/*
2682	**	let the host do the real work.
2683	*/
2684	SCR_INT,
2685		SIR_NEGO_WIDE,
2686	/*
2687	**	let the target fetch our answer.
2688	*/
2689	SCR_SET (SCR_ATN),
2690		0,
2691	SCR_CLR (SCR_ACK),
2692		0,
2693
2694	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2695		SIR_NEGO_PROTO,
2696	/*
2697	**	Send the MSG_EXT_WDTR
2698	*/
2699	SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
2700		NADDR (msgout),
2701	SCR_CLR (SCR_ATN),
2702		0,
2703	SCR_COPY (1),
2704		RADDR (sfbr),
2705		NADDR (lastmsg),
2706	SCR_JUMP,
2707		PADDR (msg_out_done),
2708
2709}/*-------------------------< MSG_EXT_3 >----------------*/,{
2710	SCR_CLR (SCR_ACK),
2711		0,
2712	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2713		PADDR (dispatch),
2714	/*
2715	**	get extended message code.
2716	*/
2717	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2718		NADDR (msgin[2]),
2719	/*
2720	**	Check for message parity error.
2721	*/
2722	SCR_TO_REG (scratcha),
2723		0,
2724	SCR_FROM_REG (socl),
2725		0,
2726	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2727		PADDRH (msg_parity),
2728	SCR_FROM_REG (scratcha),
2729		0,
2730	SCR_JUMP ^ IFTRUE (DATA (MSG_EXT_SDTR)),
2731		PADDRH (msg_sdtr),
2732	/*
2733	**	unknown extended message
2734	*/
2735	SCR_JUMP,
2736		PADDR (msg_bad)
2737
2738}/*-------------------------< MSG_SDTR >-----------------*/,{
2739	SCR_CLR (SCR_ACK),
2740		0,
2741	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2742		PADDR (dispatch),
2743	/*
2744	**	get period and offset
2745	*/
2746	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2747		NADDR (msgin[3]),
2748	SCR_FROM_REG (socl),
2749		0,
2750	SCR_JUMP ^ IFTRUE (MASK (CATN, CATN)),
2751		PADDRH (msg_parity),
2752	/*
2753	**	let the host do the real work.
2754	*/
2755	SCR_INT,
2756		SIR_NEGO_SYNC,
2757	/*
2758	**	let the target fetch our answer.
2759	*/
2760	SCR_SET (SCR_ATN),
2761		0,
2762	SCR_CLR (SCR_ACK),
2763		0,
2764
2765	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2766		SIR_NEGO_PROTO,
2767	/*
2768	**	Send the MSG_EXT_SDTR
2769	*/
2770	SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
2771		NADDR (msgout),
2772	SCR_CLR (SCR_ATN),
2773		0,
2774	SCR_COPY (1),
2775		RADDR (sfbr),
2776		NADDR (lastmsg),
2777	SCR_JUMP,
2778		PADDR (msg_out_done),
2779
2780}/*-------------------------< MSG_OUT_ABORT >-------------*/,{
2781	/*
2782	**	After ABORT message,
2783	**
2784	**	expect an immediate disconnect, ...
2785	*/
2786	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2787		0,
2788	SCR_CLR (SCR_ACK|SCR_ATN),
2789		0,
2790	SCR_WAIT_DISC,
2791		0,
2792	/*
2793	**	... and set the status to "ABORTED"
2794	*/
2795	SCR_LOAD_REG (HS_REG, HS_ABORTED),
2796		0,
2797	SCR_JUMP,
2798		PADDR (cleanup),
2799
2800}/*-------------------------< GETCC >-----------------------*/,{
2801	/*
2802	**	The ncr doesn't have an indirect load
2803	**	or store command. So we have to
2804	**	copy part of the control block to a
2805	**	fixed place, where we can modify it.
2806	**
2807	**	We patch the address part of a COPY command
2808	**	with the address of the dsa register ...
2809	*/
2810	SCR_COPY_F (4),
2811		RADDR (dsa),
2812		PADDRH (getcc1),
2813	/*
2814	**	... then we do the actual copy.
2815	*/
2816	SCR_COPY (sizeof (struct head)),
2817}/*-------------------------< GETCC1 >----------------------*/,{
2818		0,
2819		NADDR (header),
2820	/*
2821	**	Initialize the status registers
2822	*/
2823	SCR_COPY (4),
2824		NADDR (header.status),
2825		RADDR (scr0),
2826}/*-------------------------< GETCC2 >----------------------*/,{
2827	/*
2828	**	Get the condition code from a target.
2829	**
2830	**	DSA points to a data structure.
2831	**	Set TEMP to the script location
2832	**	that receives the condition code.
2833	**
2834	**	Because there is no script command
2835	**	to load a longword into a register,
2836	**	we use a CALL command.
2837	*/
2838/*<<<*/	SCR_CALLR,
2839		24,
2840	/*
2841	**	Get the condition code.
2842	*/
2843	SCR_MOVE_TBL ^ SCR_DATA_IN,
2844		offsetof (struct dsb, sense),
2845	/*
2846	**	No data phase may follow!
2847	*/
2848	SCR_CALL,
2849		PADDR (checkatn),
2850	SCR_JUMP,
2851		PADDR (no_data),
2852/*>>>*/
2853
2854	/*
2855	**	The CALL jumps to this point.
2856	**	Prepare for a RESTORE_POINTER message.
2857	**	Save the TEMP register into the saved pointer.
2858	*/
2859	SCR_COPY (4),
2860		RADDR (temp),
2861		NADDR (header.savep),
2862	/*
2863	**	Load scratcha, because in case of a selection timeout,
2864	**	the host will expect a new value for startpos in
2865	**	the scratcha register.
2866	*/
2867	SCR_COPY (4),
2868		PADDR (startpos),
2869		RADDR (scratcha),
2870#ifdef NCR_GETCC_WITHMSG
2871	/*
2872	**	If QUIRK_NOMSG is set, select without ATN.
2873	**	and don't send a message.
2874	*/
2875	SCR_FROM_REG (QU_REG),
2876		0,
2877	SCR_JUMP ^ IFTRUE (MASK (QUIRK_NOMSG, QUIRK_NOMSG)),
2878		PADDRH(getcc3),
2879	/*
2880	**	Then try to connect to the target.
2881	**	If we are reselected, special treatment
2882	**	of the current job is required before
2883	**	accepting the reselection.
2884	*/
2885	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2886		PADDR(badgetcc),
2887	/*
2888	**	save target id.
2889	*/
2890	SCR_FROM_REG (sdid),
2891		0,
2892	SCR_TO_REG (ctest0),
2893		0,
2894	/*
2895	**	Send the IDENTIFY message.
2896	**	In case of short transfer, remove ATN.
2897	*/
2898	SCR_MOVE_TBL ^ SCR_MSG_OUT,
2899		offsetof (struct dsb, smsg2),
2900	SCR_CLR (SCR_ATN),
2901		0,
2902	/*
2903	**	save the first byte of the message.
2904	*/
2905	SCR_COPY (1),
2906		RADDR (sfbr),
2907		NADDR (lastmsg),
2908	SCR_JUMP,
2909		PADDR (prepare2),
2910
2911#endif
2912}/*-------------------------< GETCC3 >----------------------*/,{
2913	/*
2914	**	Try to connect to the target.
2915	**	If we are reselected, special treatment
2916	**	of the current job is required before
2917	**	accepting the reselection.
2918	**
2919	**	Silly target won't accept a message.
2920	**	Select without ATN.
2921	*/
2922	SCR_SEL_TBL ^ offsetof (struct dsb, select),
2923		PADDR(badgetcc),
2924	/*
2925	**	save target id.
2926	*/
2927	SCR_FROM_REG (sdid),
2928		0,
2929	SCR_TO_REG (ctest0),
2930		0,
2931	/*
2932	**	Force error if selection timeout
2933	*/
2934	SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_IN)),
2935		0,
2936	/*
2937	**	don't negotiate.
2938	*/
2939	SCR_JUMP,
2940		PADDR (prepare2),
2941}/*-------------------------< ABORTTAG >-------------------*/,{
2942	/*
2943	**      Abort a bad reselection.
2944	**	Set the message to ABORT vs. ABORT_TAG
2945	*/
2946	SCR_LOAD_REG (scratcha, MSG_ABORT_TAG),
2947		0,
2948	SCR_JUMPR ^ IFFALSE (CARRYSET),
2949		8,
2950}/*-------------------------< ABORT >----------------------*/,{
2951	SCR_LOAD_REG (scratcha, MSG_ABORT),
2952		0,
2953	SCR_COPY (1),
2954		RADDR (scratcha),
2955		NADDR (msgout),
2956	SCR_SET (SCR_ATN),
2957		0,
2958	SCR_CLR (SCR_ACK),
2959		0,
2960	/*
2961	**	and send it.
2962	**	we expect an immediate disconnect
2963	*/
2964	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2965		0,
2966	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2967		NADDR (msgout),
2968	SCR_COPY (1),
2969		RADDR (sfbr),
2970		NADDR (lastmsg),
2971	SCR_CLR (SCR_ACK|SCR_ATN),
2972		0,
2973	SCR_WAIT_DISC,
2974		0,
2975	SCR_JUMP,
2976		PADDR (start),
2977}/*-------------------------< SNOOPTEST >-------------------*/,{
2978	/*
2979	**	Read the variable.
2980	*/
2981	SCR_COPY (4),
2982		KVAR (KVAR_NCR_CACHE),
2983		RADDR (scratcha),
2984	/*
2985	**	Write the variable.
2986	*/
2987	SCR_COPY (4),
2988		RADDR (temp),
2989		KVAR (KVAR_NCR_CACHE),
2990	/*
2991	**	Read back the variable.
2992	*/
2993	SCR_COPY (4),
2994		KVAR (KVAR_NCR_CACHE),
2995		RADDR (temp),
2996}/*-------------------------< SNOOPEND >-------------------*/,{
2997	/*
2998	**	And stop.
2999	*/
3000	SCR_INT,
3001		99,
3002}/*--------------------------------------------------------*/
3003};
3004
3005
3006/*==========================================================
3007**
3008**
3009**	Fill in #define dependent parts of the script
3010**
3011**
3012**==========================================================
3013*/
3014
3015void ncr_script_fill (struct script * scr, struct scripth * scrh)
3016{
3017	int	i;
3018	ncrcmd	*p;
3019
3020	p = scrh->tryloop;
3021	for (i=0; i<MAX_START; i++) {
3022		*p++ =SCR_COPY (4);
3023		*p++ =NADDR (squeue[i]);
3024		*p++ =RADDR (dsa);
3025		*p++ =SCR_CALL;
3026		*p++ =PADDR (trysel);
3027	};
3028	*p++ =SCR_JUMP;
3029	*p++ =PADDRH(tryloop);
3030
3031	assert ((char *)p == (char *)&scrh->tryloop + sizeof (scrh->tryloop));
3032
3033	p = scr->data_in;
3034
3035	*p++ =SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN));
3036	*p++ =PADDR (no_data);
3037	*p++ =SCR_COPY (sizeof (ticks));
3038	*p++ =(ncrcmd) KVAR (KVAR_TICKS);
3039	*p++ =NADDR (header.stamp.data);
3040	*p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3041	*p++ =offsetof (struct dsb, data[ 0]);
3042
3043	for (i=1; i<MAX_SCATTER; i++) {
3044		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3045		*p++ =PADDR (checkatn);
3046		*p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3047		*p++ =offsetof (struct dsb, data[i]);
3048	};
3049
3050	*p++ =SCR_CALL;
3051	*p++ =PADDR (checkatn);
3052	*p++ =SCR_JUMP;
3053	*p++ =PADDR (no_data);
3054
3055	assert ((char *)p == (char *)&scr->data_in + sizeof (scr->data_in));
3056
3057	p = scr->data_out;
3058
3059	*p++ =SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_OUT));
3060	*p++ =PADDR (no_data);
3061	*p++ =SCR_COPY (sizeof (ticks));
3062	*p++ =(ncrcmd) KVAR (KVAR_TICKS);
3063	*p++ =NADDR (header.stamp.data);
3064	*p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3065	*p++ =offsetof (struct dsb, data[ 0]);
3066
3067	for (i=1; i<MAX_SCATTER; i++) {
3068		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3069		*p++ =PADDR (dispatch);
3070		*p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3071		*p++ =offsetof (struct dsb, data[i]);
3072	};
3073
3074	*p++ =SCR_CALL;
3075	*p++ =PADDR (dispatch);
3076	*p++ =SCR_JUMP;
3077	*p++ =PADDR (no_data);
3078
3079	assert ((char *)p == (char *)&scr->data_out + sizeof (scr->data_out));
3080}
3081
3082/*==========================================================
3083**
3084**
3085**	Copy and rebind a script.
3086**
3087**
3088**==========================================================
3089*/
3090
3091static void ncr_script_copy_and_bind (ncb_p np, ncrcmd *src, ncrcmd *dst, int len)
3092{
3093	ncrcmd  opcode, new, old, tmp1, tmp2;
3094	ncrcmd	*start, *end;
3095	int relocs, offset;
3096
3097	start = src;
3098	end = src + len/4;
3099	offset = 0;
3100
3101	while (src < end) {
3102
3103		opcode = *src++;
3104		WRITESCRIPT_OFF(dst, offset, opcode);
3105		offset += 4;
3106
3107		/*
3108		**	If we forget to change the length
3109		**	in struct script, a field will be
3110		**	padded with 0. This is an illegal
3111		**	command.
3112		*/
3113
3114		if (opcode == 0) {
3115			printf ("%s: ERROR0 IN SCRIPT at %d.\n",
3116				ncr_name(np), (int) (src-start-1));
3117			DELAY (1000000);
3118		};
3119
3120		if (DEBUG_FLAGS & DEBUG_SCRIPT)
3121			printf ("%p:  <%x>\n",
3122				(src-1), (unsigned)opcode);
3123
3124		/*
3125		**	We don't have to decode ALL commands
3126		*/
3127		switch (opcode >> 28) {
3128
3129		case 0xc:
3130			/*
3131			**	COPY has TWO arguments.
3132			*/
3133			relocs = 2;
3134			tmp1 = src[0];
3135			if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3136				tmp1 = 0;
3137			tmp2 = src[1];
3138			if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3139				tmp2 = 0;
3140			if ((tmp1 ^ tmp2) & 3) {
3141				printf ("%s: ERROR1 IN SCRIPT at %d.\n",
3142					ncr_name(np), (int) (src-start-1));
3143				DELAY (1000000);
3144			}
3145			/*
3146			**	If PREFETCH feature not enabled, remove
3147			**	the NO FLUSH bit if present.
3148			*/
3149			if ((opcode & SCR_NO_FLUSH) && !(np->features&FE_PFEN))
3150				WRITESCRIPT_OFF(dst, offset - 4,
3151				    (opcode & ~SCR_NO_FLUSH));
3152			break;
3153
3154		case 0x0:
3155			/*
3156			**	MOVE (absolute address)
3157			*/
3158			relocs = 1;
3159			break;
3160
3161		case 0x8:
3162			/*
3163			**	JUMP / CALL
3164			**	dont't relocate if relative :-)
3165			*/
3166			if (opcode & 0x00800000)
3167				relocs = 0;
3168			else
3169				relocs = 1;
3170			break;
3171
3172		case 0x4:
3173		case 0x5:
3174		case 0x6:
3175		case 0x7:
3176			relocs = 1;
3177			break;
3178
3179		default:
3180			relocs = 0;
3181			break;
3182		};
3183
3184		if (relocs) {
3185			while (relocs--) {
3186				old = *src++;
3187
3188				switch (old & RELOC_MASK) {
3189				case RELOC_REGISTER:
3190					new = (old & ~RELOC_MASK) + np->paddr;
3191					break;
3192				case RELOC_LABEL:
3193					new = (old & ~RELOC_MASK) + np->p_script;
3194					break;
3195				case RELOC_LABELH:
3196					new = (old & ~RELOC_MASK) + np->p_scripth;
3197					break;
3198				case RELOC_SOFTC:
3199					new = (old & ~RELOC_MASK) + vtophys(np);
3200					break;
3201				case RELOC_KVAR:
3202					if (((old & ~RELOC_MASK) <
3203					     SCRIPT_KVAR_FIRST) ||
3204					    ((old & ~RELOC_MASK) >
3205					     SCRIPT_KVAR_LAST))
3206						panic("ncr KVAR out of range");
3207					new = vtophys(script_kvars[old &
3208					    ~RELOC_MASK]);
3209					break;
3210				case 0:
3211					/* Don't relocate a 0 address. */
3212					if (old == 0) {
3213						new = old;
3214						break;
3215					}
3216					/* fall through */
3217				default:
3218					panic("ncr_script_copy_and_bind: weird relocation %x @ %d\n", old, (int)(src - start));
3219					break;
3220				}
3221
3222				WRITESCRIPT_OFF(dst, offset, new);
3223				offset += 4;
3224			}
3225		} else {
3226			WRITESCRIPT_OFF(dst, offset, *src++);
3227			offset += 4;
3228		}
3229
3230	};
3231}
3232
3233/*==========================================================
3234**
3235**
3236**      Auto configuration.
3237**
3238**
3239**==========================================================
3240*/
3241
3242/*----------------------------------------------------------
3243**
3244**	Reduce the transfer length to the max value
3245**	we can transfer safely.
3246**
3247**      Reading a block greater then MAX_SIZE from the
3248**	raw (character) device exercises a memory leak
3249**	in the vm subsystem. This is common to ALL devices.
3250**	We have submitted a description of this bug to
3251**	<FreeBSD-bugs@freefall.cdrom.com>.
3252**	It should be fixed in the current release.
3253**
3254**----------------------------------------------------------
3255*/
3256
3257void ncr_min_phys (struct  buf *bp)
3258{
3259	if ((unsigned long)bp->b_bcount > MAX_SIZE) bp->b_bcount = MAX_SIZE;
3260}
3261
3262/*----------------------------------------------------------
3263**
3264**	Maximal number of outstanding requests per target.
3265**
3266**----------------------------------------------------------
3267*/
3268
3269u_int32_t ncr_info (int unit)
3270{
3271	return (1);   /* may be changed later */
3272}
3273
3274/*----------------------------------------------------------
3275**
3276**	NCR chip devices table and chip look up function.
3277**	Features bit are defined in ncrreg.h. Is it the
3278**	right place?
3279**
3280**----------------------------------------------------------
3281*/
3282typedef struct {
3283	unsigned long	device_id;
3284	unsigned short	minrevid;
3285	char	       *name;
3286	unsigned char	maxburst;
3287	unsigned char	maxoffs;
3288	unsigned char	clock_divn;
3289	unsigned int	features;
3290} ncr_chip;
3291
3292static ncr_chip ncr_chip_table[] = {
3293 {NCR_810_ID, 0x00,	"ncr 53c810 fast10 scsi",		4,  8, 4,
3294 FE_ERL}
3295 ,
3296 {NCR_810_ID, 0x10,	"ncr 53c810a fast10 scsi",		4,  8, 4,
3297 FE_ERL|FE_LDSTR|FE_PFEN|FE_BOF}
3298 ,
3299 {NCR_815_ID, 0x00,	"ncr 53c815 fast10 scsi", 		4,  8, 4,
3300 FE_ERL|FE_BOF}
3301 ,
3302 {NCR_820_ID, 0x00,	"ncr 53c820 fast10 wide scsi", 		4,  8, 4,
3303 FE_WIDE|FE_ERL}
3304 ,
3305 {NCR_825_ID, 0x00,	"ncr 53c825 fast10 wide scsi",		4,  8, 4,
3306 FE_WIDE|FE_ERL|FE_BOF}
3307 ,
3308 {NCR_825_ID, 0x10,	"ncr 53c825a fast10 wide scsi",		7,  8, 4,
3309 FE_WIDE|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3310 ,
3311 {NCR_860_ID, 0x00,	"ncr 53c860 fast20 scsi",		4,  8, 5,
3312 FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_LDSTR|FE_PFEN}
3313 ,
3314 {NCR_875_ID, 0x00,	"ncr 53c875 fast20 wide scsi",		7, 16, 5,
3315 FE_WIDE|FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3316 ,
3317 {NCR_875_ID, 0x02,	"ncr 53c875 fast20 wide scsi",		7, 16, 5,
3318 FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3319 ,
3320 {NCR_875_ID2, 0x00,	"ncr 53c875j fast20 wide scsi",		7, 16, 5,
3321 FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3322 ,
3323 {NCR_885_ID, 0x00,	"ncr 53c885 fast20 wide scsi",		7, 16, 5,
3324 FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3325 ,
3326 {NCR_895_ID, 0x00,	"ncr 53c895 fast40 wide scsi",		7, 31, 7,
3327 FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3328 ,
3329 {NCR_896_ID, 0x00,	"ncr 53c896 fast40 wide scsi",		7, 31, 7,
3330 FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM}
3331};
3332
3333static int ncr_chip_lookup(u_long device_id, u_char revision_id)
3334{
3335	int i, found;
3336
3337	found = -1;
3338	for (i = 0; i < sizeof(ncr_chip_table)/sizeof(ncr_chip_table[0]); i++) {
3339		if (device_id	== ncr_chip_table[i].device_id &&
3340		    ncr_chip_table[i].minrevid <= revision_id) {
3341			if (found < 0 ||
3342			    ncr_chip_table[found].minrevid
3343			      < ncr_chip_table[i].minrevid) {
3344				found = i;
3345			}
3346		}
3347	}
3348	return found;
3349}
3350
3351/*----------------------------------------------------------
3352**
3353**	Probe the hostadapter.
3354**
3355**----------------------------------------------------------
3356*/
3357
3358
3359
3360static	const char* ncr_probe (pcici_t tag, pcidi_t type)
3361{
3362	u_char rev = pci_conf_read (tag, PCI_CLASS_REG) & 0xff;
3363	int i;
3364
3365	i = ncr_chip_lookup(type, rev);
3366	if (i >= 0)
3367		return ncr_chip_table[i].name;
3368
3369	return (NULL);
3370}
3371
3372
3373
3374/*==========================================================
3375**
3376**	NCR chip clock divisor table.
3377**	Divisors are multiplied by 10,000,000 in order to make
3378**	calculations more simple.
3379**
3380**==========================================================
3381*/
3382
3383#define _5M 5000000
3384static u_long div_10M[] =
3385	{2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3386
3387/*===============================================================
3388**
3389**	NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128
3390**	transfers. 32,64,128 are only supported by 875 and 895 chips.
3391**	We use log base 2 (burst length) as internal code, with
3392**	value 0 meaning "burst disabled".
3393**
3394**===============================================================
3395*/
3396
3397/*
3398 *	Burst length from burst code.
3399 */
3400#define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3401
3402/*
3403 *	Burst code from io register bits.
3404 */
3405#define burst_code(dmode, ctest4, ctest5) \
3406	(ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
3407
3408/*
3409 *	Set initial io register bits from burst code.
3410 */
3411static void
3412ncr_init_burst(ncb_p np, u_char bc)
3413{
3414	np->rv_ctest4	&= ~0x80;
3415	np->rv_dmode	&= ~(0x3 << 6);
3416	np->rv_ctest5	&= ~0x4;
3417
3418	if (!bc) {
3419		np->rv_ctest4	|= 0x80;
3420	}
3421	else {
3422		--bc;
3423		np->rv_dmode	|= ((bc & 0x3) << 6);
3424		np->rv_ctest5	|= (bc & 0x4);
3425	}
3426}
3427
3428/*==========================================================
3429**
3430**
3431**      Auto configuration:  attach and init a host adapter.
3432**
3433**
3434**==========================================================
3435*/
3436
3437
3438static void
3439ncr_attach (pcici_t config_id, int unit)
3440{
3441	ncb_p np = (struct ncb*) 0;
3442	u_char	 rev = 0;
3443	u_long	 period;
3444	int	 i;
3445	u_int8_t usrsync;
3446	u_int8_t usrwide;
3447	struct cam_devq *devq;
3448
3449	/*
3450	**	allocate and initialize structures.
3451	*/
3452
3453	np = (ncb_p) malloc (sizeof (struct ncb), M_DEVBUF, M_NOWAIT);
3454	if (!np) return;
3455	ncrp[unit]=np;
3456	bzero (np, sizeof (*np));
3457
3458	np->unit = unit;
3459
3460	/*
3461	**	Try to map the controller chip to
3462	**	virtual and physical memory.
3463	*/
3464
3465	if (!pci_map_mem (config_id, 0x14, &np->vaddr, &np->paddr))
3466		return;
3467
3468	/*
3469	**	Make the controller's registers available.
3470	**	Now the INB INW INL OUTB OUTW OUTL macros
3471	**	can be used safely.
3472	*/
3473
3474#ifdef __i386__
3475	np->reg = (struct ncr_reg*) np->vaddr;
3476#endif
3477
3478#ifdef NCR_IOMAPPED
3479	/*
3480	**	Try to map the controller chip into iospace.
3481	*/
3482
3483	if (!pci_map_port (config_id, 0x10, &np->port))
3484		return;
3485#endif
3486
3487
3488	/*
3489	**	Save some controller register default values
3490	*/
3491
3492	np->rv_scntl3	= INB(nc_scntl3) & 0x77;
3493	np->rv_dmode	= INB(nc_dmode)  & 0xce;
3494	np->rv_dcntl	= INB(nc_dcntl)  & 0xa9;
3495	np->rv_ctest3	= INB(nc_ctest3) & 0x01;
3496	np->rv_ctest4	= INB(nc_ctest4) & 0x88;
3497	np->rv_ctest5	= INB(nc_ctest5) & 0x24;
3498	np->rv_gpcntl	= INB(nc_gpcntl);
3499	np->rv_stest2	= INB(nc_stest2) & 0x20;
3500
3501	if (bootverbose >= 2) {
3502		printf ("\tBIOS values:  SCNTL3:%02x DMODE:%02x  DCNTL:%02x\n",
3503			np->rv_scntl3, np->rv_dmode, np->rv_dcntl);
3504		printf ("\t              CTEST3:%02x CTEST4:%02x CTEST5:%02x\n",
3505			np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
3506	}
3507
3508	np->rv_dcntl  |= NOCOM;
3509
3510	/*
3511	**	Do chip dependent initialization.
3512	*/
3513
3514	rev = pci_conf_read (config_id, PCI_CLASS_REG) & 0xff;
3515
3516	/*
3517	**	Get chip features from chips table.
3518	*/
3519	i = ncr_chip_lookup(pci_conf_read(config_id, PCI_ID_REG), rev);
3520
3521	if (i >= 0) {
3522		np->maxburst	= ncr_chip_table[i].maxburst;
3523		np->maxoffs	= ncr_chip_table[i].maxoffs;
3524		np->clock_divn	= ncr_chip_table[i].clock_divn;
3525		np->features	= ncr_chip_table[i].features;
3526	} else {	/* Should'nt happen if probe() is ok */
3527		np->maxburst	= 4;
3528		np->maxoffs	= 8;
3529		np->clock_divn	= 4;
3530		np->features	= FE_ERL;
3531	}
3532
3533	np->maxwide	= np->features & FE_WIDE ? 1 : 0;
3534	np->clock_khz	= np->features & FE_CLK80 ? 80000 : 40000;
3535	if	(np->features & FE_QUAD)	np->multiplier = 4;
3536	else if	(np->features & FE_DBLR)	np->multiplier = 2;
3537	else					np->multiplier = 1;
3538
3539	/*
3540	**	Get the frequency of the chip's clock.
3541	**	Find the right value for scntl3.
3542	*/
3543	if (np->features & (FE_ULTRA|FE_ULTRA2))
3544		ncr_getclock(np, np->multiplier);
3545
3546#ifdef NCR_TEKRAM_EEPROM
3547	if (bootverbose) {
3548		printf ("%s: Tekram EEPROM read %s\n",
3549			ncr_name(np),
3550			read_tekram_eeprom (np, NULL) ?
3551			"succeeded" : "failed");
3552	}
3553#endif /* NCR_TEKRAM_EEPROM */
3554
3555	/*
3556	 *	If scntl3 != 0, we assume BIOS is present.
3557	 */
3558	if (np->rv_scntl3)
3559		np->features |= FE_BIOS;
3560
3561	/*
3562	 * Divisor to be used for async (timer pre-scaler).
3563	 */
3564	i = np->clock_divn - 1;
3565	while (i >= 0) {
3566		--i;
3567		if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3568			++i;
3569			break;
3570		}
3571	}
3572	np->rv_scntl3 = i+1;
3573
3574	/*
3575	 * Minimum synchronous period factor supported by the chip.
3576	 * Btw, 'period' is in tenths of nanoseconds.
3577	 */
3578
3579	period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3580	if	(period <= 250)		np->minsync = 10;
3581	else if	(period <= 303)		np->minsync = 11;
3582	else if	(period <= 500)		np->minsync = 12;
3583	else				np->minsync = (period + 40 - 1) / 40;
3584
3585	/*
3586	 * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3587	 */
3588
3589	if	(np->minsync < 25 && !(np->features & (FE_ULTRA|FE_ULTRA2)))
3590		np->minsync = 25;
3591	else if	(np->minsync < 12 && !(np->features & FE_ULTRA2))
3592		np->minsync = 12;
3593
3594	/*
3595	 * Maximum synchronous period factor supported by the chip.
3596	 */
3597
3598	period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3599	np->maxsync = period > 2540 ? 254 : period / 10;
3600
3601	/*
3602	 * Now, some features available with Symbios compatible boards.
3603	 * LED support through GPIO0 and DIFF support.
3604	 */
3605
3606#ifdef	SCSI_NCR_SYMBIOS_COMPAT
3607	if (!(np->rv_gpcntl & 0x01))
3608		np->features |= FE_LED0;
3609#if 0	/* Not safe enough without NVRAM support or user settable option */
3610	if (!(INB(nc_gpreg) & 0x08))
3611		np->features |= FE_DIFF;
3612#endif
3613#endif	/* SCSI_NCR_SYMBIOS_COMPAT */
3614
3615	/*
3616	 * Prepare initial IO registers settings.
3617	 * Trust BIOS only if we believe we have one and if we want to.
3618	 */
3619#ifdef	SCSI_NCR_TRUST_BIOS
3620	if (!(np->features & FE_BIOS)) {
3621#else
3622	if (1) {
3623#endif
3624		np->rv_dmode = 0;
3625		np->rv_dcntl = NOCOM;
3626		np->rv_ctest3 = 0;
3627		np->rv_ctest4 = MPEE;
3628		np->rv_ctest5 = 0;
3629		np->rv_stest2 = 0;
3630
3631		if (np->features & FE_ERL)
3632			np->rv_dmode 	|= ERL;	  /* Enable Read Line */
3633		if (np->features & FE_BOF)
3634			np->rv_dmode 	|= BOF;	  /* Burst Opcode Fetch */
3635		if (np->features & FE_ERMP)
3636			np->rv_dmode	|= ERMP;  /* Enable Read Multiple */
3637		if (np->features & FE_CLSE)
3638			np->rv_dcntl	|= CLSE;  /* Cache Line Size Enable */
3639		if (np->features & FE_WRIE)
3640			np->rv_ctest3	|= WRIE;  /* Write and Invalidate */
3641		if (np->features & FE_PFEN)
3642			np->rv_dcntl	|= PFEN;  /* Prefetch Enable */
3643		if (np->features & FE_DFS)
3644			np->rv_ctest5	|= DFS;	  /* Dma Fifo Size */
3645		if (np->features & FE_DIFF)
3646			np->rv_stest2	|= 0x20;  /* Differential mode */
3647		ncr_init_burst(np, np->maxburst); /* Max dwords burst length */
3648	} else {
3649		np->maxburst =
3650			burst_code(np->rv_dmode, np->rv_ctest4, np->rv_ctest5);
3651	}
3652
3653#ifndef NCR_IOMAPPED
3654	/*
3655	**	Get on-chip SRAM address, if supported
3656	*/
3657	if ((np->features & FE_RAM) && sizeof(struct script) <= 4096)
3658		(void)(!pci_map_mem (config_id,0x18, &np->vaddr2, &np->paddr2));
3659#endif	/* !NCR_IOMAPPED */
3660
3661	/*
3662	**	Allocate structure for script relocation.
3663	*/
3664	if (np->vaddr2 != NULL) {
3665#ifdef __alpha__
3666		np->script = NULL;
3667#else
3668		np->script = (struct script *) np->vaddr2;
3669#endif
3670		np->p_script = np->paddr2;
3671	} else if (sizeof (struct script) > PAGE_SIZE) {
3672		np->script  = (struct script*) vm_page_alloc_contig
3673			(round_page(sizeof (struct script)),
3674			 0x100000, 0xffffffff, PAGE_SIZE);
3675	} else {
3676		np->script  = (struct script *)
3677			malloc (sizeof (struct script), M_DEVBUF, M_WAITOK);
3678	}
3679
3680	/* XXX JGibbs - Use contigmalloc */
3681	if (sizeof (struct scripth) > PAGE_SIZE) {
3682		np->scripth = (struct scripth*) vm_page_alloc_contig
3683			(round_page(sizeof (struct scripth)),
3684			 0x100000, 0xffffffff, PAGE_SIZE);
3685	} else
3686		{
3687		np->scripth = (struct scripth *)
3688			malloc (sizeof (struct scripth), M_DEVBUF, M_WAITOK);
3689	}
3690
3691#ifdef SCSI_NCR_PCI_CONFIG_FIXUP
3692	/*
3693	**	If cache line size is enabled, check PCI config space and
3694	**	try to fix it up if necessary.
3695	*/
3696#ifdef PCIR_CACHELNSZ	/* To be sure that new PCI stuff is present */
3697	{
3698		u_char cachelnsz = pci_cfgread(config_id, PCIR_CACHELNSZ, 1);
3699		u_short command  = pci_cfgread(config_id, PCIR_COMMAND, 2);
3700
3701		if (!cachelnsz) {
3702			cachelnsz = 8;
3703			printf("%s: setting PCI cache line size register to %d.\n",
3704				ncr_name(np), (int)cachelnsz);
3705			pci_cfgwrite(config_id, PCIR_CACHELNSZ, cachelnsz, 1);
3706		}
3707
3708		if (!(command & (1<<4))) {
3709			command |= (1<<4);
3710			printf("%s: setting PCI command write and invalidate.\n",
3711				ncr_name(np));
3712			pci_cfgwrite(config_id, PCIR_COMMAND, command, 2);
3713		}
3714	}
3715#endif /* PCIR_CACHELNSZ */
3716
3717#endif /* SCSI_NCR_PCI_CONFIG_FIXUP */
3718
3719	/* Initialize per-target user settings */
3720	usrsync = 0;
3721	if (SCSI_NCR_DFLT_SYNC) {
3722		usrsync = SCSI_NCR_DFLT_SYNC;
3723		if (usrsync > np->maxsync)
3724			usrsync = np->maxsync;
3725		if (usrsync < np->minsync)
3726			usrsync = np->minsync;
3727	};
3728
3729	usrwide = (SCSI_NCR_MAX_WIDE);
3730	if (usrwide > np->maxwide) usrwide=np->maxwide;
3731
3732	for (i=0;i<MAX_TARGET;i++) {
3733		tcb_p tp = &np->target[i];
3734
3735		tp->tinfo.user.period = usrsync;
3736		tp->tinfo.user.offset = usrsync != 0 ? np->maxoffs : 0;
3737		tp->tinfo.user.width = usrwide;
3738		tp->tinfo.disc_tag = NCR_CUR_DISCENB
3739				   | NCR_CUR_TAGENB
3740				   | NCR_USR_DISCENB
3741				   | NCR_USR_TAGENB;
3742	}
3743
3744	/*
3745	**	Bells and whistles   ;-)
3746	*/
3747	if (bootverbose)
3748		printf("%s: minsync=%d, maxsync=%d, maxoffs=%d, %d dwords burst, %s dma fifo\n",
3749		ncr_name(np), np->minsync, np->maxsync, np->maxoffs,
3750		burst_length(np->maxburst),
3751		(np->rv_ctest5 & DFS) ? "large" : "normal");
3752
3753	/*
3754	**	Print some complementary information that can be helpfull.
3755	*/
3756	if (bootverbose)
3757		printf("%s: %s, %s IRQ driver%s\n",
3758			ncr_name(np),
3759			np->rv_stest2 & 0x20 ? "differential" : "single-ended",
3760			np->rv_dcntl & IRQM ? "totem pole" : "open drain",
3761			np->vaddr2 ? ", using on-chip SRAM" : "");
3762
3763	/*
3764	**	Patch scripts to physical addresses
3765	*/
3766	ncr_script_fill (&script0, &scripth0);
3767
3768	if (np->script)
3769		np->p_script	= vtophys(np->script);
3770	np->p_scripth	= vtophys(np->scripth);
3771
3772	ncr_script_copy_and_bind (np, (ncrcmd *) &script0,
3773			(ncrcmd *) np->script, sizeof(struct script));
3774
3775	ncr_script_copy_and_bind (np, (ncrcmd *) &scripth0,
3776		(ncrcmd *) np->scripth, sizeof(struct scripth));
3777
3778	/*
3779	**    Patch the script for LED support.
3780	*/
3781
3782	if (np->features & FE_LED0) {
3783		WRITESCRIPT(reselect[0],  SCR_REG_REG(gpreg, SCR_OR,  0x01));
3784		WRITESCRIPT(reselect1[0], SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3785		WRITESCRIPT(reselect2[0], SCR_REG_REG(gpreg, SCR_AND, 0xfe));
3786	}
3787
3788	/*
3789	**	init data structure
3790	*/
3791
3792	np->jump_tcb.l_cmd	= SCR_JUMP;
3793	np->jump_tcb.l_paddr	= NCB_SCRIPTH_PHYS (np, abort);
3794
3795	/*
3796	**  Get SCSI addr of host adapter (set by bios?).
3797	*/
3798
3799	np->myaddr = INB(nc_scid) & 0x07;
3800	if (!np->myaddr) np->myaddr = SCSI_NCR_MYADDR;
3801
3802#ifdef NCR_DUMP_REG
3803	/*
3804	**	Log the initial register contents
3805	*/
3806	{
3807		int reg;
3808		for (reg=0; reg<256; reg+=4) {
3809			if (reg%16==0) printf ("reg[%2x]", reg);
3810			printf (" %08x", (int)pci_conf_read (config_id, reg));
3811			if (reg%16==12) printf ("\n");
3812		}
3813	}
3814#endif /* NCR_DUMP_REG */
3815
3816	/*
3817	**	Reset chip.
3818	*/
3819
3820	OUTB (nc_istat,  SRST);
3821	DELAY (1000);
3822	OUTB (nc_istat,  0   );
3823
3824
3825	/*
3826	**	Now check the cache handling of the pci chipset.
3827	*/
3828
3829	if (ncr_snooptest (np)) {
3830		printf ("CACHE INCORRECTLY CONFIGURED.\n");
3831		return;
3832	};
3833
3834	/*
3835	**	Install the interrupt handler.
3836	*/
3837
3838	if (!pci_map_int (config_id, ncr_intr, np, &cam_imask))
3839		printf ("\tinterruptless mode: reduced performance.\n");
3840
3841	/*
3842	** Create the device queue.  We only allow MAX_START-1 concurrent
3843	** transactions so we can be sure to have one element free in our
3844	** start queue to reset to the idle loop.
3845	*/
3846	devq = cam_simq_alloc(MAX_START - 1);
3847	if (devq == NULL)
3848		return;
3849
3850	/*
3851	**	Now tell the generic SCSI layer
3852	**	about our bus.
3853	*/
3854	np->sim = cam_sim_alloc(ncr_action, ncr_poll, "ncr", np, np->unit,
3855				1, MAX_TAGS, devq);
3856	if (np->sim == NULL) {
3857		cam_simq_free(devq);
3858		return;
3859	}
3860
3861
3862	if (xpt_bus_register(np->sim, 0) != CAM_SUCCESS) {
3863		free(np->sim, M_DEVBUF);
3864		return;
3865	}
3866
3867#ifdef __alpha__
3868	alpha_register_pci_scsi(config_id->bus, config_id->slot, np->sim);
3869#endif
3870
3871	if (xpt_create_path(&np->path, /*periph*/NULL,
3872			    cam_sim_path(np->sim), CAM_TARGET_WILDCARD,
3873			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
3874		xpt_bus_deregister(cam_sim_path(np->sim));
3875		cam_sim_free(np->sim, /*free_simq*/TRUE);
3876		free(np->sim, M_DEVBUF);
3877		return;
3878	}
3879
3880	/*
3881	**	start the timeout daemon
3882	*/
3883	ncr_timeout (np);
3884	np->lasttime=0;
3885
3886	return;
3887}
3888
3889/*==========================================================
3890**
3891**
3892**	Process pending device interrupts.
3893**
3894**
3895**==========================================================
3896*/
3897
3898static void
3899ncr_intr(vnp)
3900	void *vnp;
3901{
3902	ncb_p np = vnp;
3903	int oldspl = splcam();
3904
3905	if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
3906
3907	if (INB(nc_istat) & (INTF|SIP|DIP)) {
3908		/*
3909		**	Repeat until no outstanding ints
3910		*/
3911		do {
3912			ncr_exception (np);
3913		} while (INB(nc_istat) & (INTF|SIP|DIP));
3914
3915		np->ticks = 100;
3916	};
3917
3918	if (DEBUG_FLAGS & DEBUG_TINY) printf ("]\n");
3919
3920	splx (oldspl);
3921}
3922
3923/*==========================================================
3924**
3925**
3926**	Start execution of a SCSI command.
3927**	This is called from the generic SCSI driver.
3928**
3929**
3930**==========================================================
3931*/
3932
3933static void
3934ncr_action (struct cam_sim *sim, union ccb *ccb)
3935{
3936	ncb_p np;
3937
3938	np = (ncb_p) cam_sim_softc(sim);
3939
3940	switch (ccb->ccb_h.func_code) {
3941	/* Common cases first */
3942	case XPT_SCSI_IO:	/* Execute the requested I/O operation */
3943	{
3944		nccb_p cp;
3945		lcb_p lp;
3946		tcb_p tp;
3947		int oldspl;
3948		struct ccb_scsiio *csio;
3949		u_int8_t *msgptr;
3950		u_int msglen;
3951		u_int msglen2;
3952		int segments;
3953		u_int8_t nego;
3954		u_int8_t idmsg;
3955		u_int8_t qidx;
3956
3957		tp = &np->target[ccb->ccb_h.target_id];
3958		csio = &ccb->csio;
3959
3960		oldspl = splcam();
3961
3962		/*
3963		 * Last time we need to check if this CCB needs to
3964		 * be aborted.
3965		 */
3966		if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
3967			xpt_done(ccb);
3968			splx(oldspl);
3969			return;
3970		}
3971		ccb->ccb_h.status |= CAM_SIM_QUEUED;
3972
3973		/*---------------------------------------------------
3974		**
3975		**	Assign an nccb / bind ccb
3976		**
3977		**----------------------------------------------------
3978		*/
3979		cp = ncr_get_nccb (np, ccb->ccb_h.target_id,
3980				   ccb->ccb_h.target_lun);
3981		if (cp == NULL) {
3982			/* XXX JGibbs - Freeze SIMQ */
3983			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
3984			xpt_done(ccb);
3985			return;
3986		};
3987
3988		cp->ccb = ccb;
3989
3990		/*---------------------------------------------------
3991		**
3992		**	timestamp
3993		**
3994		**----------------------------------------------------
3995		*/
3996		/*
3997		** XXX JGibbs - Isn't this expensive
3998		**		enough to be conditionalized??
3999		*/
4000
4001		bzero (&cp->phys.header.stamp, sizeof (struct tstamp));
4002		cp->phys.header.stamp.start = ticks;
4003
4004		nego = 0;
4005		if (tp->nego_cp == NULL) {
4006
4007			if (tp->tinfo.current.width
4008			 != tp->tinfo.goal.width) {
4009				tp->nego_cp = cp;
4010				nego = NS_WIDE;
4011			} else if (tp->tinfo.current.period
4012				!= tp->tinfo.goal.period) {
4013				tp->nego_cp = cp;
4014				nego = NS_SYNC;
4015			};
4016		};
4017
4018		/*---------------------------------------------------
4019		**
4020		**	choose a new tag ...
4021		**
4022		**----------------------------------------------------
4023		*/
4024		lp = tp->lp[ccb->ccb_h.target_lun];
4025
4026		if ((ccb->ccb_h.flags & CAM_TAG_ACTION_VALID) != 0
4027		 && (ccb->csio.tag_action != CAM_TAG_ACTION_NONE)
4028		 && (nego == 0)) {
4029			/*
4030			**	assign a tag to this nccb
4031			*/
4032			while (!cp->tag) {
4033				nccb_p cp2 = lp->next_nccb;
4034				lp->lasttag = lp->lasttag % 255 + 1;
4035				while (cp2 && cp2->tag != lp->lasttag)
4036					cp2 = cp2->next_nccb;
4037				if (cp2) continue;
4038				cp->tag=lp->lasttag;
4039				if (DEBUG_FLAGS & DEBUG_TAGS) {
4040					PRINT_ADDR(ccb);
4041					printf ("using tag #%d.\n", cp->tag);
4042				};
4043			};
4044		} else {
4045			cp->tag=0;
4046		};
4047
4048		/*----------------------------------------------------
4049		**
4050		**	Build the identify / tag / sdtr message
4051		**
4052		**----------------------------------------------------
4053		*/
4054		idmsg = MSG_IDENTIFYFLAG | ccb->ccb_h.target_lun;
4055		if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
4056			idmsg |= MSG_IDENTIFY_DISCFLAG;
4057
4058		msgptr = cp->scsi_smsg;
4059		msglen = 0;
4060		msgptr[msglen++] = idmsg;
4061
4062		if (cp->tag) {
4063	    		msgptr[msglen++] = ccb->csio.tag_action;
4064			msgptr[msglen++] = cp->tag;
4065		}
4066
4067		switch (nego) {
4068		case NS_SYNC:
4069			msgptr[msglen++] = MSG_EXTENDED;
4070			msgptr[msglen++] = MSG_EXT_SDTR_LEN;
4071			msgptr[msglen++] = MSG_EXT_SDTR;
4072			msgptr[msglen++] = tp->tinfo.goal.period;
4073			msgptr[msglen++] = tp->tinfo.goal.offset;;
4074			if (DEBUG_FLAGS & DEBUG_NEGO) {
4075				PRINT_ADDR(ccb);
4076				printf ("sync msgout: ");
4077				ncr_show_msg (&cp->scsi_smsg [msglen-5]);
4078				printf (".\n");
4079			};
4080			break;
4081		case NS_WIDE:
4082			msgptr[msglen++] = MSG_EXTENDED;
4083			msgptr[msglen++] = MSG_EXT_WDTR_LEN;
4084			msgptr[msglen++] = MSG_EXT_WDTR;
4085			msgptr[msglen++] = tp->tinfo.goal.width;
4086			if (DEBUG_FLAGS & DEBUG_NEGO) {
4087				PRINT_ADDR(ccb);
4088				printf ("wide msgout: ");
4089				ncr_show_msg (&cp->scsi_smsg [msglen-4]);
4090				printf (".\n");
4091			};
4092			break;
4093		};
4094
4095		/*----------------------------------------------------
4096		**
4097		**	Build the identify message for getcc.
4098		**
4099		**----------------------------------------------------
4100		*/
4101
4102		cp->scsi_smsg2 [0] = idmsg;
4103		msglen2 = 1;
4104
4105		/*----------------------------------------------------
4106		**
4107		**	Build the data descriptors
4108		**
4109		**----------------------------------------------------
4110		*/
4111
4112		/* XXX JGibbs - Handle other types of I/O */
4113		if ((ccb->ccb_h.flags & CAM_DIR_MASK) != CAM_DIR_NONE) {
4114			segments = ncr_scatter(&cp->phys,
4115					       (vm_offset_t)csio->data_ptr,
4116					       (vm_size_t)csio->dxfer_len);
4117
4118			if (segments < 0) {
4119				ccb->ccb_h.status = CAM_REQ_TOO_BIG;
4120				ncr_free_nccb(np, cp);
4121				splx(oldspl);
4122				xpt_done(ccb);
4123				return;
4124			}
4125			if ((ccb->ccb_h.flags & CAM_DIR_MASK) == CAM_DIR_IN) {
4126				cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_in);
4127				cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4128			} else { /* CAM_DIR_OUT */
4129				cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_out);
4130				cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
4131			}
4132		} else {
4133			cp->phys.header.savep = NCB_SCRIPT_PHYS (np, no_data);
4134			cp->phys.header.goalp = cp->phys.header.savep;
4135		}
4136
4137		cp->phys.header.lastp = cp->phys.header.savep;
4138
4139
4140		/*----------------------------------------------------
4141		**
4142		**	fill in nccb
4143		**
4144		**----------------------------------------------------
4145		**
4146		**
4147		**	physical -> virtual backlink
4148		**	Generic SCSI command
4149		*/
4150		cp->phys.header.cp		= cp;
4151		/*
4152		**	Startqueue
4153		*/
4154		cp->phys.header.launch.l_paddr	= NCB_SCRIPT_PHYS (np, select);
4155		cp->phys.header.launch.l_cmd	= SCR_JUMP;
4156		/*
4157		**	select
4158		*/
4159		cp->phys.select.sel_id		= ccb->ccb_h.target_id;
4160		cp->phys.select.sel_scntl3	= tp->tinfo.wval;
4161		cp->phys.select.sel_sxfer	= tp->tinfo.sval;
4162		/*
4163		**	message
4164		*/
4165		cp->phys.smsg.addr		= CCB_PHYS (cp, scsi_smsg);
4166		cp->phys.smsg.size		= msglen;
4167
4168		cp->phys.smsg2.addr		= CCB_PHYS (cp, scsi_smsg2);
4169		cp->phys.smsg2.size		= msglen2;
4170		/*
4171		**	command
4172		*/
4173		/* XXX JGibbs - Support other command types */
4174		cp->phys.cmd.addr		= vtophys (csio->cdb_io.cdb_bytes);
4175		cp->phys.cmd.size		= csio->cdb_len;
4176		/*
4177		**	sense command
4178		*/
4179		cp->phys.scmd.addr		= CCB_PHYS (cp, sensecmd);
4180		cp->phys.scmd.size		= 6;
4181		/*
4182		**	patch requested size into sense command
4183		*/
4184		cp->sensecmd[0]			= 0x03;
4185		cp->sensecmd[1]			= ccb->ccb_h.target_lun << 5;
4186		cp->sensecmd[4]			= sizeof(struct scsi_sense_data);
4187		cp->sensecmd[4]			= csio->sense_len;
4188		/*
4189		**	sense data
4190		*/
4191		cp->phys.sense.addr		= vtophys (&csio->sense_data);
4192		cp->phys.sense.size		= csio->sense_len;
4193		/*
4194		**	status
4195		*/
4196		cp->actualquirks		= QUIRK_NOMSG;
4197		cp->host_status			= nego ? HS_NEGOTIATE : HS_BUSY;
4198		cp->s_status			= SCSI_STATUS_ILLEGAL;
4199		cp->parity_status		= 0;
4200
4201		cp->xerr_status			= XE_OK;
4202		cp->sync_status			= tp->tinfo.sval;
4203		cp->nego_status			= nego;
4204		cp->wide_status			= tp->tinfo.wval;
4205
4206		/*----------------------------------------------------
4207		**
4208		**	Critical region: start this job.
4209		**
4210		**----------------------------------------------------
4211		*/
4212
4213		/*
4214		**	reselect pattern and activate this job.
4215		*/
4216
4217		cp->jump_nccb.l_cmd	= (SCR_JUMP ^ IFFALSE (DATA (cp->tag)));
4218		cp->tlimit		= time_second
4219					+ ccb->ccb_h.timeout / 1000 + 2;
4220		cp->magic		= CCB_MAGIC;
4221
4222		/*
4223		**	insert into start queue.
4224		*/
4225
4226		qidx = np->squeueput + 1;
4227		if (qidx >= MAX_START) qidx=0;
4228		np->squeue [qidx	 ] = NCB_SCRIPT_PHYS (np, idle);
4229		np->squeue [np->squeueput] = CCB_PHYS (cp, phys);
4230		np->squeueput = qidx;
4231
4232		if(DEBUG_FLAGS & DEBUG_QUEUE)
4233			printf("%s: queuepos=%d tryoffset=%d.\n",
4234			       ncr_name (np), np->squeueput,
4235			       (unsigned)(READSCRIPT(startpos[0]) -
4236			       (NCB_SCRIPTH_PHYS (np, tryloop))));
4237
4238		/*
4239		**	Script processor may be waiting for reselect.
4240		**	Wake it up.
4241		*/
4242		OUTB (nc_istat, SIGP);
4243
4244		/*
4245		**	and reenable interrupts
4246		*/
4247		splx (oldspl);
4248		break;
4249	}
4250	case XPT_RESET_DEV:	/* Bus Device Reset the specified SCSI device */
4251	case XPT_EN_LUN:		/* Enable LUN as a target */
4252	case XPT_TARGET_IO:		/* Execute target I/O request */
4253	case XPT_ACCEPT_TARGET_IO:	/* Accept Host Target Mode CDB */
4254	case XPT_CONT_TARGET_IO:	/* Continue Host Target I/O Connection*/
4255	case XPT_ABORT:			/* Abort the specified CCB */
4256		/* XXX Implement */
4257		ccb->ccb_h.status = CAM_REQ_INVALID;
4258		xpt_done(ccb);
4259		break;
4260	case XPT_SET_TRAN_SETTINGS:
4261	{
4262		struct	ccb_trans_settings *cts;
4263		tcb_p	tp;
4264		u_int	update_type;
4265		int	s;
4266
4267		cts = &ccb->cts;
4268		update_type = 0;
4269		if ((cts->flags & CCB_TRANS_CURRENT_SETTINGS) != 0)
4270			update_type |= NCR_TRANS_GOAL;
4271		if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0)
4272			update_type |= NCR_TRANS_USER;
4273
4274		s = splcam();
4275		tp = &np->target[ccb->ccb_h.target_id];
4276		/* Tag and disc enables */
4277		if ((cts->valid & CCB_TRANS_DISC_VALID) != 0) {
4278			if (update_type & NCR_TRANS_GOAL) {
4279				if ((cts->flags & CCB_TRANS_DISC_ENB) != 0)
4280					tp->tinfo.disc_tag |= NCR_CUR_DISCENB;
4281				else
4282					tp->tinfo.disc_tag &= ~NCR_CUR_DISCENB;
4283			}
4284
4285			if (update_type & NCR_TRANS_USER) {
4286				if ((cts->flags & CCB_TRANS_DISC_ENB) != 0)
4287					tp->tinfo.disc_tag |= NCR_USR_DISCENB;
4288				else
4289					tp->tinfo.disc_tag &= ~NCR_USR_DISCENB;
4290			}
4291
4292		}
4293
4294		if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
4295			if (update_type & NCR_TRANS_GOAL) {
4296				if ((cts->flags & CCB_TRANS_TAG_ENB) != 0)
4297					tp->tinfo.disc_tag |= NCR_CUR_TAGENB;
4298				else
4299					tp->tinfo.disc_tag &= ~NCR_CUR_TAGENB;
4300			}
4301
4302			if (update_type & NCR_TRANS_USER) {
4303				if ((cts->flags & CCB_TRANS_TAG_ENB) != 0)
4304					tp->tinfo.disc_tag |= NCR_USR_TAGENB;
4305				else
4306					tp->tinfo.disc_tag &= ~NCR_USR_TAGENB;
4307			}
4308		}
4309
4310		/* Filter bus width and sync negotiation settings */
4311		if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) != 0) {
4312			if (cts->bus_width > np->maxwide)
4313				cts->bus_width = np->maxwide;
4314		}
4315
4316		if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) != 0) {
4317			if (cts->sync_period != 0
4318			 && (cts->sync_period < np->minsync))
4319				cts->sync_period = np->minsync;
4320			if ((cts->valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0) {
4321				if (cts->sync_offset == 0)
4322					cts->sync_period = 0;
4323				if (cts->sync_offset > np->maxoffs)
4324					cts->sync_offset = np->maxoffs;
4325			}
4326		}
4327		if ((update_type & NCR_TRANS_USER) != 0) {
4328			tp->tinfo.user.period = cts->sync_period;
4329			tp->tinfo.user.offset = cts->sync_offset;
4330			tp->tinfo.user.width = cts->bus_width;
4331		}
4332		if ((update_type & NCR_TRANS_GOAL) != 0) {
4333			tp->tinfo.goal.period = cts->sync_period;
4334			tp->tinfo.goal.offset = cts->sync_offset;
4335			tp->tinfo.goal.width = cts->bus_width;
4336		}
4337		splx(s);
4338		ccb->ccb_h.status = CAM_REQ_CMP;
4339		xpt_done(ccb);
4340		break;
4341	}
4342	case XPT_GET_TRAN_SETTINGS:
4343	/* Get default/user set transfer settings for the target */
4344	{
4345		struct	ccb_trans_settings *cts;
4346		struct	ncr_transinfo *tinfo;
4347		tcb_p	tp;
4348		int	s;
4349
4350		cts = &ccb->cts;
4351		tp = &np->target[ccb->ccb_h.target_id];
4352
4353		s = splcam();
4354		if ((cts->flags & CCB_TRANS_CURRENT_SETTINGS) != 0) {
4355			tinfo = &tp->tinfo.current;
4356			if (tp->tinfo.disc_tag & NCR_CUR_DISCENB)
4357				cts->flags = CCB_TRANS_DISC_ENB;
4358			else
4359				cts->flags = 0;
4360
4361			if (tp->tinfo.disc_tag & NCR_CUR_TAGENB)
4362				cts->flags |= CCB_TRANS_TAG_ENB;
4363		} else {
4364			tinfo = &tp->tinfo.user;
4365			if (tp->tinfo.disc_tag & NCR_USR_DISCENB)
4366				cts->flags = CCB_TRANS_DISC_ENB;
4367			else
4368				cts->flags = 0;
4369
4370			if (tp->tinfo.disc_tag & NCR_USR_TAGENB)
4371				cts->flags |= CCB_TRANS_TAG_ENB;
4372		}
4373
4374		cts->sync_period = tinfo->period;
4375		cts->sync_offset = tinfo->offset;
4376		cts->bus_width = tinfo->width;
4377
4378		splx(s);
4379
4380		cts->valid = CCB_TRANS_SYNC_RATE_VALID
4381			   | CCB_TRANS_SYNC_OFFSET_VALID
4382			   | CCB_TRANS_BUS_WIDTH_VALID
4383			   | CCB_TRANS_DISC_VALID
4384			   | CCB_TRANS_TQ_VALID;
4385
4386		ccb->ccb_h.status = CAM_REQ_CMP;
4387		xpt_done(ccb);
4388		break;
4389	}
4390	case XPT_CALC_GEOMETRY:
4391	{
4392		struct	  ccb_calc_geometry *ccg;
4393		u_int32_t size_mb;
4394		u_int32_t secs_per_cylinder;
4395		int	  extended;
4396
4397		/* XXX JGibbs - I'm sure the NCR uses a different strategy,
4398		 *		but it should be able to deal with Adaptec
4399		 *		geometry too.
4400		 */
4401		extended = 1;
4402		ccg = &ccb->ccg;
4403		size_mb = ccg->volume_size
4404			/ ((1024L * 1024L) / ccg->block_size);
4405
4406		if (size_mb > 1024 && extended) {
4407			ccg->heads = 255;
4408			ccg->secs_per_track = 63;
4409		} else {
4410			ccg->heads = 64;
4411			ccg->secs_per_track = 32;
4412		}
4413		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
4414		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
4415		ccb->ccb_h.status = CAM_REQ_CMP;
4416		xpt_done(ccb);
4417		break;
4418	}
4419	case XPT_RESET_BUS:		/* Reset the specified SCSI bus */
4420	{
4421		OUTB (nc_scntl1, CRST);
4422		ccb->ccb_h.status = CAM_REQ_CMP;
4423		DELAY(10000);	/* Wait until our interrupt handler sees it */
4424		xpt_done(ccb);
4425		break;
4426	}
4427	case XPT_TERM_IO:		/* Terminate the I/O process */
4428		/* XXX Implement */
4429		ccb->ccb_h.status = CAM_REQ_INVALID;
4430		xpt_done(ccb);
4431		break;
4432	case XPT_PATH_INQ:		/* Path routing inquiry */
4433	{
4434		struct ccb_pathinq *cpi = &ccb->cpi;
4435
4436		cpi->version_num = 1; /* XXX??? */
4437		cpi->hba_inquiry = PI_SDTR_ABLE|PI_TAG_ABLE;
4438		if ((np->features & FE_WIDE) != 0)
4439			cpi->hba_inquiry |= PI_WIDE_16;
4440		cpi->target_sprt = 0;
4441		cpi->hba_misc = 0;
4442		cpi->hba_eng_cnt = 0;
4443		cpi->max_target = (np->features & FE_WIDE) ? 15 : 7;
4444		cpi->max_lun = MAX_LUN - 1;
4445		cpi->initiator_id = np->myaddr;
4446		cpi->bus_id = cam_sim_bus(sim);
4447		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
4448		strncpy(cpi->hba_vid, "Symbios", HBA_IDLEN);
4449		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
4450		cpi->unit_number = cam_sim_unit(sim);
4451		cpi->ccb_h.status = CAM_REQ_CMP;
4452		xpt_done(ccb);
4453		break;
4454	}
4455	default:
4456		ccb->ccb_h.status = CAM_REQ_INVALID;
4457		xpt_done(ccb);
4458		break;
4459	}
4460}
4461
4462/*==========================================================
4463**
4464**
4465**	Complete execution of a SCSI command.
4466**	Signal completion to the generic SCSI driver.
4467**
4468**
4469**==========================================================
4470*/
4471
4472void
4473ncr_complete (ncb_p np, nccb_p cp)
4474{
4475	union ccb *ccb;
4476	tcb_p tp;
4477	lcb_p lp;
4478
4479	/*
4480	**	Sanity check
4481	*/
4482
4483	if (!cp || (cp->magic!=CCB_MAGIC) || !cp->ccb) return;
4484	cp->magic = 1;
4485	cp->tlimit= 0;
4486
4487	/*
4488	**	No Reselect anymore.
4489	*/
4490	cp->jump_nccb.l_cmd = (SCR_JUMP);
4491
4492	/*
4493	**	No starting.
4494	*/
4495	cp->phys.header.launch.l_paddr= NCB_SCRIPT_PHYS (np, idle);
4496
4497	/*
4498	**	timestamp
4499	*/
4500	ncb_profile (np, cp);
4501
4502	if (DEBUG_FLAGS & DEBUG_TINY)
4503		printf ("CCB=%x STAT=%x/%x\n", (int)(intptr_t)cp & 0xfff,
4504			cp->host_status,cp->s_status);
4505
4506	ccb = cp->ccb;
4507	cp->ccb = NULL;
4508	tp = &np->target[ccb->ccb_h.target_id];
4509	lp = tp->lp[ccb->ccb_h.target_lun];
4510
4511	/*
4512	**	We do not queue more than 1 nccb per target
4513	**	with negotiation at any time. If this nccb was
4514	**	used for negotiation, clear this info in the tcb.
4515	*/
4516
4517	if (cp == tp->nego_cp)
4518		tp->nego_cp = NULL;
4519
4520	/*
4521	**	Check for parity errors.
4522	*/
4523	/* XXX JGibbs - What about reporting them??? */
4524
4525	if (cp->parity_status) {
4526		PRINT_ADDR(ccb);
4527		printf ("%d parity error(s), fallback.\n", cp->parity_status);
4528		/*
4529		**	fallback to asynch transfer.
4530		*/
4531		tp->tinfo.goal.period = 0;
4532		tp->tinfo.goal.offset = 0;
4533	};
4534
4535	/*
4536	**	Check for extended errors.
4537	*/
4538
4539	if (cp->xerr_status != XE_OK) {
4540		PRINT_ADDR(ccb);
4541		switch (cp->xerr_status) {
4542		case XE_EXTRA_DATA:
4543			printf ("extraneous data discarded.\n");
4544			break;
4545		case XE_BAD_PHASE:
4546			printf ("illegal scsi phase (4/5).\n");
4547			break;
4548		default:
4549			printf ("extended error %d.\n", cp->xerr_status);
4550			break;
4551		};
4552		if (cp->host_status==HS_COMPLETE)
4553			cp->host_status = HS_FAIL;
4554	};
4555
4556	/*
4557	**	Check the status.
4558	*/
4559	if (cp->host_status == HS_COMPLETE) {
4560
4561		if (cp->s_status == SCSI_STATUS_OK) {
4562
4563			/*
4564			**	All went well.
4565			*/
4566			/* XXX JGibbs - Properly calculate residual */
4567
4568			tp->bytes     += ccb->csio.dxfer_len;
4569			tp->transfers ++;
4570
4571			ccb->ccb_h.status = CAM_REQ_CMP;
4572		} else if ((cp->s_status & SCSI_STATUS_SENSE) != 0) {
4573
4574			/*
4575			 * XXX Could be TERMIO too.  Should record
4576			 * original status.
4577			 */
4578			ccb->csio.scsi_status = SCSI_STATUS_CHECK_COND;
4579			cp->s_status &= ~SCSI_STATUS_SENSE;
4580			if (cp->s_status == SCSI_STATUS_OK) {
4581				ccb->ccb_h.status =
4582				    CAM_AUTOSNS_VALID|CAM_SCSI_STATUS_ERROR;
4583			} else {
4584				ccb->ccb_h.status = CAM_AUTOSENSE_FAIL;
4585			}
4586		} else {
4587			ccb->ccb_h.status = CAM_SCSI_STATUS_ERROR;
4588			ccb->csio.scsi_status = cp->s_status;
4589		}
4590
4591
4592	} else if (cp->host_status == HS_SEL_TIMEOUT) {
4593
4594		/*
4595		**   Device failed selection
4596		*/
4597		ccb->ccb_h.status = CAM_SEL_TIMEOUT;
4598
4599	} else if (cp->host_status == HS_TIMEOUT) {
4600
4601		/*
4602		**   No response
4603		*/
4604		ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4605	} else if (cp->host_status == HS_STALL) {
4606		ccb->ccb_h.status = CAM_REQUEUE_REQ;
4607	} else {
4608
4609		/*
4610		**  Other protocol messes
4611		*/
4612		PRINT_ADDR(ccb);
4613		printf ("COMMAND FAILED (%x %x) @%p.\n",
4614			cp->host_status, cp->s_status, cp);
4615
4616		ccb->ccb_h.status = CAM_CMD_TIMEOUT;
4617	}
4618
4619	if ((ccb->ccb_h.status & CAM_STATUS_MASK) != CAM_REQ_CMP) {
4620		xpt_freeze_devq(ccb->ccb_h.path, /*count*/1);
4621		ccb->ccb_h.status |= CAM_DEV_QFRZN;
4622	}
4623
4624	/*
4625	**	Free this nccb
4626	*/
4627	ncr_free_nccb (np, cp);
4628
4629	/*
4630	**	signal completion to generic driver.
4631	*/
4632	xpt_done (ccb);
4633}
4634
4635/*==========================================================
4636**
4637**
4638**	Signal all (or one) control block done.
4639**
4640**
4641**==========================================================
4642*/
4643
4644void
4645ncr_wakeup (ncb_p np, u_long code)
4646{
4647	/*
4648	**	Starting at the default nccb and following
4649	**	the links, complete all jobs with a
4650	**	host_status greater than "disconnect".
4651	**
4652	**	If the "code" parameter is not zero,
4653	**	complete all jobs that are not IDLE.
4654	*/
4655
4656	nccb_p cp = np->link_nccb;
4657	while (cp) {
4658		switch (cp->host_status) {
4659
4660		case HS_IDLE:
4661			break;
4662
4663		case HS_DISCONNECT:
4664			if(DEBUG_FLAGS & DEBUG_TINY) printf ("D");
4665			/* fall through */
4666
4667		case HS_BUSY:
4668		case HS_NEGOTIATE:
4669			if (!code) break;
4670			cp->host_status = code;
4671
4672			/* fall through */
4673
4674		default:
4675			ncr_complete (np, cp);
4676			break;
4677		};
4678		cp = cp -> link_nccb;
4679	};
4680}
4681
4682static void
4683ncr_freeze_devq (ncb_p np, struct cam_path *path)
4684{
4685	nccb_p	cp;
4686	int	i;
4687	int	count;
4688	int	firstskip;
4689	/*
4690	**	Starting at the first nccb and following
4691	**	the links, complete all jobs that match
4692	**	the passed in path and are in the start queue.
4693	*/
4694
4695	cp = np->link_nccb;
4696	count = 0;
4697	firstskip = 0;
4698	while (cp) {
4699		switch (cp->host_status) {
4700
4701		case HS_BUSY:
4702		case HS_NEGOTIATE:
4703			if ((cp->phys.header.launch.l_paddr
4704			    == NCB_SCRIPT_PHYS (np, select))
4705			 && (xpt_path_comp(path, cp->ccb->ccb_h.path) >= 0)) {
4706
4707				/* Mark for removal from the start queue */
4708				for (i = 1; i < MAX_START; i++) {
4709					int idx;
4710
4711					idx = np->squeueput - i;
4712
4713					if (idx < 0)
4714						idx = MAX_START + idx;
4715					if (np->squeue[idx]
4716					 == CCB_PHYS(cp, phys)) {
4717						np->squeue[idx] =
4718						    NCB_SCRIPT_PHYS (np, skip);
4719						if (i > firstskip)
4720							firstskip = i;
4721						break;
4722					}
4723				}
4724				cp->host_status=HS_STALL;
4725				ncr_complete (np, cp);
4726				count++;
4727			}
4728			break;
4729		default:
4730			break;
4731		}
4732		cp = cp->link_nccb;
4733	}
4734
4735	if (count > 0) {
4736		int j;
4737		int bidx;
4738
4739		/* Compress the start queue */
4740		j = 0;
4741		bidx = np->squeueput;
4742		i = np->squeueput - firstskip;
4743		if (i < 0)
4744			i = MAX_START + i;
4745		for (;;) {
4746
4747			bidx = i - j;
4748			if (bidx < 0)
4749				bidx = MAX_START + bidx;
4750
4751			if (np->squeue[i] == NCB_SCRIPT_PHYS (np, skip)) {
4752				j++;
4753			} else if (j != 0) {
4754				np->squeue[bidx] = np->squeue[i];
4755				if (np->squeue[bidx]
4756				 == NCB_SCRIPT_PHYS(np, idle))
4757					break;
4758			}
4759			i = (i + 1) % MAX_START;
4760		}
4761		np->squeueput = bidx;
4762	}
4763}
4764
4765/*==========================================================
4766**
4767**
4768**	Start NCR chip.
4769**
4770**
4771**==========================================================
4772*/
4773
4774void ncr_init
4775(ncb_p np, char * msg, u_long code)
4776{
4777	int	i;
4778
4779	/*
4780	**	Reset chip.
4781	*/
4782
4783	OUTB (nc_istat,  SRST);
4784	DELAY (1000);
4785	OUTB (nc_istat, 0);
4786
4787	/*
4788	**	Message.
4789	*/
4790
4791	if (msg) printf ("%s: restart (%s).\n", ncr_name (np), msg);
4792
4793	/*
4794	**	Clear Start Queue
4795	*/
4796
4797	for (i=0;i<MAX_START;i++)
4798		np -> squeue [i] = NCB_SCRIPT_PHYS (np, idle);
4799
4800	/*
4801	**	Start at first entry.
4802	*/
4803
4804	np->squeueput = 0;
4805	WRITESCRIPT(startpos[0], NCB_SCRIPTH_PHYS (np, tryloop));
4806	WRITESCRIPT(start0  [0], SCR_INT ^ IFFALSE (0));
4807
4808	/*
4809	**	Wakeup all pending jobs.
4810	*/
4811
4812	ncr_wakeup (np, code);
4813
4814	/*
4815	**	Init chip.
4816	*/
4817
4818	OUTB (nc_istat,  0x00   );      /*  Remove Reset, abort ...	     */
4819	OUTB (nc_scntl0, 0xca   );      /*  full arb., ena parity, par->ATN  */
4820	OUTB (nc_scntl1, 0x00	);	/*  odd parity, and remove CRST!!    */
4821	ncr_selectclock(np, np->rv_scntl3); /* Select SCSI clock             */
4822	OUTB (nc_scid  , RRE|np->myaddr);/*  host adapter SCSI address       */
4823	OUTW (nc_respid, 1ul<<np->myaddr);/*  id to respond to		     */
4824	OUTB (nc_istat , SIGP	);	/*  Signal Process		     */
4825	OUTB (nc_dmode , np->rv_dmode);	/* XXX modify burstlen ??? */
4826	OUTB (nc_dcntl , np->rv_dcntl);
4827	OUTB (nc_ctest3, np->rv_ctest3);
4828	OUTB (nc_ctest5, np->rv_ctest5);
4829	OUTB (nc_ctest4, np->rv_ctest4);/*  enable master parity checking    */
4830	OUTB (nc_stest2, np->rv_stest2|EXT); /* Extended Sreq/Sack filtering */
4831	OUTB (nc_stest3, TE     );	/*  TolerANT enable		     */
4832	OUTB (nc_stime0, 0x0b	);	/*  HTH = disabled, STO = 0.1 sec.   */
4833
4834	if (bootverbose >= 2) {
4835		printf ("\tACTUAL values:SCNTL3:%02x DMODE:%02x  DCNTL:%02x\n",
4836			np->rv_scntl3, np->rv_dmode, np->rv_dcntl);
4837		printf ("\t              CTEST3:%02x CTEST4:%02x CTEST5:%02x\n",
4838			np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4839	}
4840
4841	/*
4842	**    Enable GPIO0 pin for writing if LED support.
4843	*/
4844
4845	if (np->features & FE_LED0) {
4846		OUTOFFB (nc_gpcntl, 0x01);
4847	}
4848
4849	/*
4850	**	Fill in target structure.
4851	*/
4852	for (i=0;i<MAX_TARGET;i++) {
4853		tcb_p tp = &np->target[i];
4854
4855		tp->tinfo.sval    = 0;
4856		tp->tinfo.wval    = np->rv_scntl3;
4857
4858		tp->tinfo.current.period = 0;
4859		tp->tinfo.current.offset = 0;
4860		tp->tinfo.current.width = MSG_EXT_WDTR_BUS_8_BIT;
4861	}
4862
4863	/*
4864	**      enable ints
4865	*/
4866
4867	OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST);
4868	OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
4869
4870	/*
4871	**    Start script processor.
4872	*/
4873
4874	OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
4875
4876	/*
4877	 * Notify the XPT of the event
4878	 */
4879	if (code == HS_RESET)
4880		xpt_async(AC_BUS_RESET, np->path, NULL);
4881}
4882
4883static void
4884ncr_poll(struct cam_sim *sim)
4885{
4886	ncr_intr(cam_sim_softc(sim));
4887}
4888
4889
4890/*==========================================================
4891**
4892**	Get clock factor and sync divisor for a given
4893**	synchronous factor period.
4894**	Returns the clock factor (in sxfer) and scntl3
4895**	synchronous divisor field.
4896**
4897**==========================================================
4898*/
4899
4900static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
4901{
4902	u_long	clk = np->clock_khz;	/* SCSI clock frequency in kHz	*/
4903	int	div = np->clock_divn;	/* Number of divisors supported	*/
4904	u_long	fak;			/* Sync factor in sxfer		*/
4905	u_long	per;			/* Period in tenths of ns	*/
4906	u_long	kpc;			/* (per * clk)			*/
4907
4908	/*
4909	**	Compute the synchronous period in tenths of nano-seconds
4910	*/
4911	if	(sfac <= 10)	per = 250;
4912	else if	(sfac == 11)	per = 303;
4913	else if	(sfac == 12)	per = 500;
4914	else			per = 40 * sfac;
4915
4916	/*
4917	**	Look for the greatest clock divisor that allows an
4918	**	input speed faster than the period.
4919	*/
4920	kpc = per * clk;
4921	while (--div >= 0)
4922		if (kpc >= (div_10M[div] * 4)) break;
4923
4924	/*
4925	**	Calculate the lowest clock factor that allows an output
4926	**	speed not faster than the period.
4927	*/
4928	fak = (kpc - 1) / div_10M[div] + 1;
4929
4930#if 0	/* You can #if 1 if you think this optimization is usefull */
4931
4932	per = (fak * div_10M[div]) / clk;
4933
4934	/*
4935	**	Why not to try the immediate lower divisor and to choose
4936	**	the one that allows the fastest output speed ?
4937	**	We dont want input speed too much greater than output speed.
4938	*/
4939	if (div >= 1 && fak < 6) {
4940		u_long fak2, per2;
4941		fak2 = (kpc - 1) / div_10M[div-1] + 1;
4942		per2 = (fak2 * div_10M[div-1]) / clk;
4943		if (per2 < per && fak2 <= 6) {
4944			fak = fak2;
4945			per = per2;
4946			--div;
4947		}
4948	}
4949#endif
4950
4951	if (fak < 4) fak = 4;	/* Should never happen, too bad ... */
4952
4953	/*
4954	**	Compute and return sync parameters for the ncr
4955	*/
4956	*fakp		= fak - 4;
4957	*scntl3p	= ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
4958}
4959
4960/*==========================================================
4961**
4962**	Switch sync mode for current job and its target
4963**
4964**==========================================================
4965*/
4966
4967static void
4968ncr_setsync(ncb_p np, nccb_p cp, u_char scntl3, u_char sxfer, u_char period)
4969{
4970	union	ccb *ccb;
4971	struct	ccb_trans_settings neg;
4972	tcb_p	tp;
4973	int	div;
4974	u_int	target = INB (nc_ctest0) & 0x0f;
4975	u_int	period_10ns;
4976
4977	assert (cp);
4978	if (!cp) return;
4979
4980	ccb = cp->ccb;
4981	assert (ccb);
4982	if (!ccb) return;
4983	assert (target == ccb->ccb_h.target_id);
4984
4985	tp = &np->target[target];
4986
4987	if (!scntl3 || !(sxfer & 0x1f))
4988		scntl3 = np->rv_scntl3;
4989	scntl3 = (scntl3 & 0xf0) | (tp->tinfo.wval & EWS)
4990	       | (np->rv_scntl3 & 0x07);
4991
4992	/*
4993	**	Deduce the value of controller sync period from scntl3.
4994	**	period is in tenths of nano-seconds.
4995	*/
4996
4997	div = ((scntl3 >> 4) & 0x7);
4998	if ((sxfer & 0x1f) && div)
4999		period_10ns =
5000		    (((sxfer>>5)+4)*div_10M[div-1])/np->clock_khz;
5001	else
5002		period_10ns = 0;
5003
5004	tp->tinfo.goal.period = period;
5005	tp->tinfo.goal.offset = sxfer & 0x1f;
5006	tp->tinfo.current.period = period;
5007	tp->tinfo.current.offset = sxfer & 0x1f;
5008
5009	/*
5010	**	 Stop there if sync parameters are unchanged
5011	*/
5012	if (tp->tinfo.sval == sxfer && tp->tinfo.wval == scntl3) return;
5013	tp->tinfo.sval = sxfer;
5014	tp->tinfo.wval = scntl3;
5015
5016	if (sxfer & 0x1f) {
5017		/*
5018		**  Disable extended Sreq/Sack filtering
5019		*/
5020		if (period_10ns <= 2000) OUTOFFB (nc_stest2, EXT);
5021	}
5022
5023	/*
5024	** Tell the SCSI layer about the
5025	** new transfer parameters.
5026	*/
5027	neg.sync_period = period;
5028	neg.sync_offset = sxfer & 0x1f;
5029	neg.valid = CCB_TRANS_SYNC_RATE_VALID
5030		| CCB_TRANS_SYNC_OFFSET_VALID;
5031	xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path,
5032		      /*priority*/1);
5033	xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
5034
5035	/*
5036	**	set actual value and sync_status
5037	*/
5038	OUTB (nc_sxfer, sxfer);
5039	np->sync_st = sxfer;
5040	OUTB (nc_scntl3, scntl3);
5041	np->wide_st = scntl3;
5042
5043	/*
5044	**	patch ALL nccbs of this target.
5045	*/
5046	for (cp = np->link_nccb; cp; cp = cp->link_nccb) {
5047		if (!cp->ccb) continue;
5048		if (cp->ccb->ccb_h.target_id != target) continue;
5049		cp->sync_status = sxfer;
5050		cp->wide_status = scntl3;
5051	};
5052}
5053
5054/*==========================================================
5055**
5056**	Switch wide mode for current job and its target
5057**	SCSI specs say: a SCSI device that accepts a WDTR
5058**	message shall reset the synchronous agreement to
5059**	asynchronous mode.
5060**
5061**==========================================================
5062*/
5063
5064static void ncr_setwide (ncb_p np, nccb_p cp, u_char wide, u_char ack)
5065{
5066	union	ccb *ccb;
5067	struct	ccb_trans_settings neg;
5068	u_int	target = INB (nc_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