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