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