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