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