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