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