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