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