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