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