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