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