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