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