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