ncr.c revision 12879
1/**************************************************************************
2**
3**  $Id: ncr.c,v 1.51 1995/12/14 09:54:04 phk Exp $
4**
5**  Device driver for the   NCR 53C810   PCI-SCSI-Controller.
6**
7**  FreeBSD / NetBSD
8**
9**-------------------------------------------------------------------------
10**
11**  Written for 386bsd and FreeBSD by
12**	Wolfgang Stanglmeier	<wolf@cologne.de>
13**	Stefan Esser		<se@mi.Uni-Koeln.de>
14**
15**  Ported to NetBSD by
16**	Charles M. Hannum	<mycroft@gnu.ai.mit.edu>
17**
18**-------------------------------------------------------------------------
19**
20** Copyright (c) 1994 Wolfgang Stanglmeier.  All rights reserved.
21**
22** Redistribution and use in source and binary forms, with or without
23** modification, are permitted provided that the following conditions
24** are met:
25** 1. Redistributions of source code must retain the above copyright
26**    notice, this list of conditions and the following disclaimer.
27** 2. Redistributions in binary form must reproduce the above copyright
28**    notice, this list of conditions and the following disclaimer in the
29**    documentation and/or other materials provided with the distribution.
30** 3. The name of the author may not be used to endorse or promote products
31**    derived from this software without specific prior written permission.
32**
33** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
34** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
35** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
36** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
37** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
38** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
39** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
40** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
41** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
42** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
43**
44***************************************************************************
45*/
46
47#define NCR_DATE "pl23 95/09/07"
48
49#define NCR_VERSION	(2)
50#define	MAX_UNITS	(16)
51
52#define NCR_GETCC_WITHMSG
53
54/*==========================================================
55**
56**	Configuration and Debugging
57**
58**	May be overwritten in <arch/conf/xxxx>
59**
60**==========================================================
61*/
62
63/*
64**    SCSI address of this device.
65**    The boot routines should have set it.
66**    If not, use this.
67*/
68
69#ifndef SCSI_NCR_MYADDR
70#define SCSI_NCR_MYADDR      (7)
71#endif /* SCSI_NCR_MYADDR */
72
73/*
74**    The maximal synchronous frequency in kHz.
75**    (0=asynchronous)
76*/
77
78#ifndef SCSI_NCR_MAX_SYNC
79#define SCSI_NCR_MAX_SYNC   (10000)
80#endif /* SCSI_NCR_MAX_SYNC */
81
82/*
83**    The maximal bus with (in log2 byte)
84**    (0=8 bit, 1=16 bit)
85*/
86
87#ifndef SCSI_NCR_MAX_WIDE
88#define SCSI_NCR_MAX_WIDE   (1)
89#endif /* SCSI_NCR_MAX_WIDE */
90
91/*
92**    The maximum number of tags per logic unit.
93**    Used only for disk devices that support tags.
94*/
95
96#ifndef SCSI_NCR_MAX_TAGS
97#define SCSI_NCR_MAX_TAGS    (4)
98#endif /* SCSI_NCR_MAX_TAGS */
99
100/*==========================================================
101**
102**      Configuration and Debugging
103**
104**==========================================================
105*/
106
107/*
108**    Number of targets supported by the driver.
109**    n permits target numbers 0..n-1.
110**    Default is 7, meaning targets #0..#6.
111**    #7 .. is myself.
112*/
113
114#define MAX_TARGET  (16)
115
116/*
117**    Number of logic units supported by the driver.
118**    n enables logic unit numbers 0..n-1.
119**    The common SCSI devices require only
120**    one lun, so take 1 as the default.
121*/
122
123#define MAX_LUN     (1)
124
125/*
126**    The maximum number of jobs scheduled for starting.
127**    There should be one slot per target, and one slot
128**    for each tag of each target in use.
129**    The calculation below is actually quite silly ...
130*/
131
132#define MAX_START   (MAX_TARGET + 7 * SCSI_NCR_MAX_TAGS)
133
134/*
135**    The maximum number of segments a transfer is split into.
136*/
137
138#define MAX_SCATTER (33)
139
140/*
141**    The maximum transfer length (should be >= 64k).
142**    MUST NOT be greater than (MAX_SCATTER-1) * NBPG.
143*/
144
145#define MAX_SIZE  ((MAX_SCATTER-1) * (long) NBPG)
146
147/*
148**	other
149*/
150
151#define NCR_SNOOP_TIMEOUT (1000000)
152
153/*==========================================================
154**
155**      Include files
156**
157**==========================================================
158*/
159
160#ifdef __NetBSD__
161#ifdef _KERNEL
162#define KERNEL
163#endif
164#endif
165#include <stddef.h>
166
167#include <sys/types.h>
168#include <sys/param.h>
169#include <sys/time.h>
170#include <sys/proc.h>
171
172#ifdef KERNEL
173#include <sys/systm.h>
174#include <sys/malloc.h>
175#include <sys/buf.h>
176#include <sys/kernel.h>
177#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		[ 24];
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.51 1995/12/14 09:54:04 phk 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
1261
1262#ifndef __NetBSD__
1263static ncb_p		ncrp [MAX_UNITS];
1264#endif /* !__NetBSD__ */
1265
1266static int ncr_debug = SCSI_DEBUG_FLAGS;
1267SYSCTL_INT(_debug, OID_AUTO, ncr_debug, CTLFLAG_RW, &ncr_debug, 0, "");
1268
1269static int ncr_cache; /* to be aligned _NOT_ static */
1270
1271/*==========================================================
1272**
1273**
1274**      Global static data:	auto configure
1275**
1276**
1277**==========================================================
1278*/
1279
1280#define	NCR_810_ID	(0x00011000ul)
1281#define	NCR_810AP_ID	(0x00051000ul)
1282#define	NCR_815_ID	(0x00041000ul)
1283#define	NCR_825_ID	(0x00031000ul)
1284#define	NCR_860_ID	(0x00061000ul)
1285#define	NCR_875_ID	(0x000f1000ul)
1286
1287#ifdef __NetBSD__
1288
1289struct	cfdriver ncrcd = {
1290	NULL, "ncr", ncr_probe, ncr_attach, DV_DISK, sizeof(struct ncb)
1291};
1292
1293#else /* !__NetBSD__ */
1294
1295static u_long ncr_count;
1296
1297static struct	pci_device ncr_device = {
1298	"ncr",
1299	ncr_probe,
1300	ncr_attach,
1301	&ncr_count,
1302	NULL
1303};
1304
1305DATA_SET (pcidevice_set, ncr_device);
1306
1307#endif /* !__NetBSD__ */
1308
1309static struct scsi_adapter ncr_switch =
1310{
1311	ncr_start,
1312	ncr_min_phys,
1313	0,
1314	0,
1315#ifndef __NetBSD__
1316	ncr_info,
1317	"ncr",
1318#endif /* !__NetBSD__ */
1319};
1320
1321static struct scsi_device ncr_dev =
1322{
1323	NULL,			/* Use default error handler */
1324	NULL,			/* have a queue, served by this */
1325	NULL,			/* have no async handler */
1326	NULL,			/* Use default 'done' routine */
1327#ifndef __NetBSD__
1328	"ncr",
1329#endif /* !__NetBSD__ */
1330};
1331
1332#ifdef __NetBSD__
1333
1334#define	ncr_name(np)	(np->sc_dev.dv_xname)
1335
1336#else /* !__NetBSD__ */
1337
1338static char *ncr_name (ncb_p np)
1339{
1340	static char name[10];
1341	sprintf(name, "ncr%d", np->unit);
1342	return (name);
1343}
1344#endif
1345
1346/*==========================================================
1347**
1348**
1349**      Scripts for NCR-Processor.
1350**
1351**      Use ncr_script_bind for binding to physical addresses.
1352**
1353**
1354**==========================================================
1355**
1356**	NADDR generates a reference to a field of the controller data.
1357**	PADDR generates a reference to another part of the script.
1358**	RADDR generates a reference to a script processor register.
1359**	FADDR generates a reference to a script processor register
1360**		with offset.
1361**
1362**----------------------------------------------------------
1363*/
1364
1365#define	RELOC_SOFTC	0x40000000
1366#define	RELOC_LABEL	0x50000000
1367#define	RELOC_REGISTER	0x60000000
1368#define	RELOC_MASK	0xf0000000
1369
1370#define	NADDR(label)	(RELOC_SOFTC | offsetof(struct ncb, label))
1371#define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1372#define	RADDR(label)	(RELOC_REGISTER | REG(label))
1373#define	FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1374
1375static	struct script script0 = {
1376/*--------------------------< START >-----------------------*/ {
1377	/*
1378	**	Claim to be still alive ...
1379	*/
1380	SCR_COPY (sizeof (((struct ncb *)0)->heartbeat)),
1381		(ncrcmd) &time.tv_sec,
1382		NADDR (heartbeat),
1383	/*
1384	**      Make data structure address invalid.
1385	**      clear SIGP.
1386	*/
1387	SCR_LOAD_REG (dsa, 0xff),
1388		0,
1389	SCR_FROM_REG (ctest2),
1390		0,
1391}/*-------------------------< START0 >----------------------*/,{
1392	/*
1393	**	Hook for interrupted GetConditionCode.
1394	**	Will be patched to ... IFTRUE by
1395	**	the interrupt handler.
1396	*/
1397	SCR_INT ^ IFFALSE (0),
1398		SIR_SENSE_RESTART,
1399
1400}/*-------------------------< START1 >----------------------*/,{
1401	/*
1402	**	Hook for stalled start queue.
1403	**	Will be patched to IFTRUE by the interrupt handler.
1404	*/
1405	SCR_INT ^ IFFALSE (0),
1406		SIR_STALL_RESTART,
1407	/*
1408	**	Then jump to a certain point in tryloop.
1409	**	Due to the lack of indirect addressing the code
1410	**	is self modifying here.
1411	*/
1412	SCR_JUMP,
1413}/*-------------------------< STARTPOS >--------------------*/,{
1414		PADDR(tryloop),
1415}/*-------------------------< TRYLOOP >---------------------*/,{
1416/*
1417**	Load an entry of the start queue into dsa
1418**	and try to start it by jumping to TRYSEL.
1419**
1420**	Because the size depends on the
1421**	#define MAX_START parameter, it is filled
1422**	in at runtime.
1423**
1424**-----------------------------------------------------------
1425**
1426**  ##===========< I=0; i<MAX_START >===========
1427**  ||	SCR_COPY (4),
1428**  ||		NADDR (squeue[i]),
1429**  ||		RADDR (dsa),
1430**  ||	SCR_CALL,
1431**  ||		PADDR (trysel),
1432**  ##==========================================
1433**
1434**	SCR_JUMP,
1435**		PADDR(tryloop),
1436**
1437**-----------------------------------------------------------
1438*/
14390
1440
1441}/*-------------------------< TRYSEL >----------------------*/,{
1442	/*
1443	**	Now:
1444	**	DSA: Address of a Data Structure
1445	**	or   Address of the IDLE-Label.
1446	**
1447	**	TEMP:	Address of a script, which tries to
1448	**		start the NEXT entry.
1449	**
1450	**	Save the TEMP register into the SCRATCHA register.
1451	**	Then copy the DSA to TEMP and RETURN.
1452	**	This is kind of an indirect jump.
1453	**	(The script processor has NO stack, so the
1454	**	CALL is actually a jump and link, and the
1455	**	RETURN is an indirect jump.)
1456	**
1457	**	If the slot was empty, DSA contains the address
1458	**	of the IDLE part of this script. The processor
1459	**	jumps to IDLE and waits for a reselect.
1460	**	It will wake up and try the same slot again
1461	**	after the SIGP bit becomes set by the host.
1462	**
1463	**	If the slot was not empty, DSA contains
1464	**	the address of the phys-part of a ccb.
1465	**	The processor jumps to this address.
1466	**	phys starts with head,
1467	**	head starts with launch,
1468	**	so actually the processor jumps to
1469	**	the lauch part.
1470	**	If the entry is scheduled for execution,
1471	**	then launch contains a jump to SELECT.
1472	**	If it's not scheduled, it contains a jump to IDLE.
1473	*/
1474	SCR_COPY (4),
1475		RADDR (temp),
1476		RADDR (scratcha),
1477	SCR_COPY (4),
1478		RADDR (dsa),
1479		RADDR (temp),
1480	SCR_RETURN,
1481		0
1482
1483}/*-------------------------< SKIP >------------------------*/,{
1484	/*
1485	**	This entry has been canceled.
1486	**	Next time use the next slot.
1487	*/
1488	SCR_COPY (4),
1489		RADDR (scratcha),
1490		PADDR (startpos),
1491	/*
1492	**	patch the launch field.
1493	**	should look like an idle process.
1494	*/
1495	SCR_COPY (4),
1496		RADDR (dsa),
1497		PADDR (skip2),
1498	SCR_COPY (8),
1499		PADDR (idle),
1500}/*-------------------------< SKIP2 >-----------------------*/,{
1501		0,
1502	SCR_JUMP,
1503		PADDR(start),
1504}/*-------------------------< IDLE >------------------------*/,{
1505	/*
1506	**	Nothing to do?
1507	**	Wait for reselect.
1508	*/
1509	SCR_JUMP,
1510		PADDR(reselect),
1511
1512}/*-------------------------< SELECT >----------------------*/,{
1513	/*
1514	**	DSA	contains the address of a scheduled
1515	**		data structure.
1516	**
1517	**	SCRATCHA contains the address of the script,
1518	**		which starts the next entry.
1519	**
1520	**	Set Initiator mode.
1521	**
1522	**	(Target mode is left as an exercise for the reader)
1523	*/
1524
1525	SCR_CLR (SCR_TRG),
1526		0,
1527	SCR_LOAD_REG (HS_REG, 0xff),
1528		0,
1529
1530	/*
1531	**      And try to select this target.
1532	*/
1533	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1534		PADDR (reselect),
1535
1536	/*
1537	**	Now there are 4 possibilities:
1538	**
1539	**	(1) The ncr looses arbitration.
1540	**	This is ok, because it will try again,
1541	**	when the bus becomes idle.
1542	**	(But beware of the timeout function!)
1543	**
1544	**	(2) The ncr is reselected.
1545	**	Then the script processor takes the jump
1546	**	to the RESELECT label.
1547	**
1548	**	(3) The ncr completes the selection.
1549	**	Then it will execute the next statement.
1550	**
1551	**	(4) There is a selection timeout.
1552	**	Then the ncr should interrupt the host and stop.
1553	**	Unfortunately, it seems to continue execution
1554	**	of the script. But it will fail with an
1555	**	IID-interrupt on the next WHEN.
1556	*/
1557
1558	SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_IN)),
1559		0,
1560
1561	/*
1562	**	Save target id to ctest0 register
1563	*/
1564
1565	SCR_FROM_REG (sdid),
1566		0,
1567	SCR_TO_REG (ctest0),
1568		0,
1569	/*
1570	**	Send the IDENTIFY and SIMPLE_TAG messages
1571	**	(and the M_X_SYNC_REQ message)
1572	*/
1573	SCR_MOVE_TBL ^ SCR_MSG_OUT,
1574		offsetof (struct dsb, smsg),
1575	SCR_JUMPR ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1576		-16,
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_targ = np->myaddr;
3435	np->sc_link.fordriver	 = 0;
3436#endif /* !__NetBSD__ */
3437	np->sc_link.adapter      = &ncr_switch;
3438	np->sc_link.device       = &ncr_dev;
3439	np->sc_link.flags	 = 0;
3440
3441#ifdef __NetBSD__
3442	config_found(self, &np->sc_link, ncr_print);
3443#else /* !__NetBSD__ */
3444#if (__FreeBSD__ >= 2)
3445	scbus = scsi_alloc_bus();
3446	if(!scbus)
3447		return;
3448	scbus->adapter_link = &np->sc_link;
3449
3450	if(np->maxwide)
3451		scbus->maxtarg = 15;
3452
3453	if (bootverbose) {
3454		unsigned t_from = 0;
3455		unsigned t_to   = scbus->maxtarg;
3456		unsigned myaddr = np->myaddr;
3457
3458		char *txt_and = "";
3459		printf ("%s scanning for targets ", ncr_name (np));
3460		if (t_from < myaddr) {
3461			printf ("%d..%d ", t_from, myaddr -1);
3462			txt_and = "and ";
3463		}
3464		if (myaddr < t_to)
3465			printf ("%s%d..%d ", txt_and, myaddr +1, t_to);
3466		printf ("(V%d " NCR_DATE ")\n", NCR_VERSION);
3467	}
3468
3469	scsi_attachdevs (scbus);
3470	scbus = NULL;   /* Upper-level SCSI code owns this now */
3471#else
3472	scsi_attachdevs (&np->sc_link);
3473#endif /* !__FreeBSD__ >= 2 */
3474#endif /* !__NetBSD__ */
3475
3476	/*
3477	**	start the timeout daemon
3478	*/
3479	ncr_timeout (np);
3480	np->lasttime=0;
3481
3482	/*
3483	**  Done.
3484	*/
3485
3486	return;
3487}
3488
3489/*==========================================================
3490**
3491**
3492**	Process pending device interrupts.
3493**
3494**
3495**==========================================================
3496*/
3497
3498static int
3499ncr_intr(vnp)
3500	void *vnp;
3501{
3502	ncb_p np = vnp;
3503	int n = 0;
3504	int oldspl = splbio();
3505
3506	if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
3507
3508	if (INB(nc_istat) & (INTF|SIP|DIP)) {
3509		/*
3510		**	Repeat until no outstanding ints
3511		*/
3512		do {
3513			ncr_exception (np);
3514		} while (INB(nc_istat) & (INTF|SIP|DIP));
3515
3516		n=1;
3517		np->ticks = 100;
3518	};
3519
3520	if (DEBUG_FLAGS & DEBUG_TINY) printf ("]\n");
3521
3522	splx (oldspl);
3523	return (n);
3524}
3525
3526/*==========================================================
3527**
3528**
3529**	Start execution of a SCSI command.
3530**	This is called from the generic SCSI driver.
3531**
3532**
3533**==========================================================
3534*/
3535
3536static INT32 ncr_start (struct scsi_xfer * xp)
3537{
3538#ifdef __NetBSD__
3539	ncb_p np  = xp->sc_link->adapter_softc;
3540#else /*__NetBSD__*/
3541	ncb_p np  = ncrp[xp->sc_link->adapter_unit];
3542#endif/*__NetBSD__*/
3543
3544	struct scsi_generic * cmd = xp->cmd;
3545	ccb_p cp;
3546	lcb_p lp;
3547	tcb_p tp = &np->target[xp->sc_link->target];
3548
3549	int	i, oldspl, segments, flags = xp->flags;
3550	u_char	ptr, nego, idmsg;
3551	u_long  msglen, msglen2;
3552
3553
3554
3555	/*---------------------------------------------
3556	**
3557	**   Reset SCSI bus
3558	**
3559	**	Interrupt handler does the real work.
3560	**
3561	**---------------------------------------------
3562	*/
3563
3564	if (flags & SCSI_RESET) {
3565		OUTB (nc_scntl1, CRST);
3566		DELAY (1000);
3567		return(COMPLETE);
3568	};
3569
3570	/*---------------------------------------------
3571	**
3572	**      Some shortcuts ...
3573	**
3574	**---------------------------------------------
3575	*/
3576
3577	if ((xp->sc_link->target == np->myaddr	  ) ||
3578		(xp->sc_link->target >= MAX_TARGET) ||
3579		(xp->sc_link->lun    >= MAX_LUN   ) ||
3580		(flags    & SCSI_DATA_UIO)) {
3581		xp->error = XS_DRIVER_STUFFUP;
3582		return(COMPLETE);
3583	};
3584
3585	/*---------------------------------------------
3586	**
3587	**      Diskaccess to partial blocks?
3588	**
3589	**---------------------------------------------
3590	*/
3591
3592	if ((xp->datalen & 0x1ff) && !(tp->inqdata[0] & 0x1f)) {
3593		switch (cmd->opcode) {
3594		case 0x28:  /* READ_BIG  (10) */
3595		case 0xa8:  /* READ_HUGE (12) */
3596		case 0x2a:  /* WRITE_BIG (10) */
3597		case 0xaa:  /* WRITE_HUGE(12) */
3598			PRINT_ADDR(xp);
3599			printf ("access to partial disk block refused.\n");
3600			xp->error = XS_DRIVER_STUFFUP;
3601			return(COMPLETE);
3602		};
3603	};
3604
3605	if (DEBUG_FLAGS & DEBUG_TINY) {
3606		PRINT_ADDR(xp);
3607		printf ("CMD=%x F=%x L=%x ", cmd->opcode,
3608			(unsigned)xp->flags, (unsigned) xp->datalen);
3609	}
3610
3611	/*--------------------------------------------
3612	**
3613	**   Sanity checks ...
3614	**	copied from Elischer's Adaptec driver.
3615	**
3616	**--------------------------------------------
3617	*/
3618
3619	flags = xp->flags;
3620	if (!(flags & INUSE)) {
3621		printf("%s: ?INUSE?\n", ncr_name (np));
3622		xp->flags |= INUSE;
3623	};
3624
3625	if(flags & ITSDONE) {
3626		printf("%s: ?ITSDONE?\n", ncr_name (np));
3627		xp->flags &= ~ITSDONE;
3628	};
3629
3630	if (xp->bp)
3631		flags |= (SCSI_NOSLEEP); /* just to be sure */
3632
3633	/*---------------------------------------------------
3634	**
3635	**	Assign a ccb / bind xp
3636	**
3637	**----------------------------------------------------
3638	*/
3639
3640	oldspl = splbio();
3641
3642	if (!(cp=ncr_get_ccb (np, flags, xp->sc_link->target, xp->sc_link->lun))) {
3643		printf ("%s: no ccb.\n", ncr_name (np));
3644		xp->error = XS_DRIVER_STUFFUP;
3645		splx(oldspl);
3646		return(TRY_AGAIN_LATER);
3647	};
3648	cp->xfer = xp;
3649
3650	/*---------------------------------------------------
3651	**
3652	**	timestamp
3653	**
3654	**----------------------------------------------------
3655	*/
3656
3657	bzero (&cp->phys.header.stamp, sizeof (struct tstamp));
3658	cp->phys.header.stamp.start = time;
3659
3660	/*----------------------------------------------------
3661	**
3662	**	Get device quirks from a speciality table.
3663	**
3664	**	@GENSCSI@
3665	**	This should be a part of the device table
3666	**	in "scsi_conf.c".
3667	**
3668	**----------------------------------------------------
3669	*/
3670
3671	if (tp->quirks & QUIRK_UPDATE) {
3672#ifdef NEW_SCSICONF
3673		tp->quirks = xp->sc_link->quirks;
3674#else
3675		tp->quirks = ncr_lookup ((char*) &tp->inqdata[0]);
3676#endif
3677#ifndef NCR_GETCC_WITHMSG
3678		if (tp->quirks) {
3679			PRINT_ADDR(xp);
3680			printf ("quirks=%x.\n", tp->quirks);
3681		};
3682#endif
3683	};
3684
3685	/*---------------------------------------------------
3686	**
3687	**	negotiation required?
3688	**
3689	**----------------------------------------------------
3690	*/
3691
3692	nego = 0;
3693
3694	if (tp->inqdata[7]) {
3695		/*
3696		**	negotiate synchronous transfers?
3697		*/
3698
3699		if (!tp->period) {
3700			if (SCSI_NCR_MAX_SYNC
3701#if defined (CDROM_ASYNC) || defined (GENERIC)
3702			    && ((tp->inqdata[0] & 0x1f) != 5)
3703#endif
3704			    && (tp->inqdata[7] & INQ7_SYNC)) {
3705				nego = NS_SYNC;
3706			} else {
3707				tp->period  =0xffff;
3708				tp->sval = 0xe0;
3709				PRINT_ADDR(xp);
3710				printf ("asynchronous.\n");
3711			};
3712		};
3713
3714		/*
3715		**	negotiate wide transfers ?
3716		*/
3717
3718		if (!tp->widedone) {
3719			if (tp->inqdata[7] & INQ7_WIDE16) {
3720				if (!nego) nego = NS_WIDE;
3721			} else
3722				tp->widedone=1;
3723		};
3724	};
3725
3726	/*---------------------------------------------------
3727	**
3728	**	choose a new tag ...
3729	**
3730	**----------------------------------------------------
3731	*/
3732
3733	if ((lp = tp->lp[xp->sc_link->lun]) && (lp->usetags)) {
3734		/*
3735		**	assign a tag to this ccb!
3736		*/
3737		while (!cp->tag) {
3738			ccb_p cp2 = lp->next_ccb;
3739			lp->lasttag = lp->lasttag % 255 + 1;
3740			while (cp2 && cp2->tag != lp->lasttag)
3741				cp2 = cp2->next_ccb;
3742			if (cp2) continue;
3743			cp->tag=lp->lasttag;
3744			if (DEBUG_FLAGS & DEBUG_TAGS) {
3745				PRINT_ADDR(xp);
3746				printf ("using tag #%d.\n", cp->tag);
3747			};
3748		};
3749	} else {
3750		cp->tag=0;
3751	};
3752
3753	/*----------------------------------------------------
3754	**
3755	**	Build the identify / tag / sdtr message
3756	**
3757	**----------------------------------------------------
3758	*/
3759
3760	idmsg = M_IDENTIFY | xp->sc_link->lun;
3761#ifndef NCR_NO_DISCONNECT
3762	/*---------------------------------------------------------------------
3763	** Some users have problems with this driver.
3764	** I assume that the current problems relate to a conflict between
3765	** a disconnect and an immediately following reconnect operation.
3766	** With this option one can prevent the driver from using disconnects.
3767	** Without disconnects the performance will be severely degraded.
3768	** But it may help to trace down the core problem.
3769	**---------------------------------------------------------------------
3770	*/
3771	if ((cp!=&np->ccb) && (np->disc))
3772		idmsg |= 0x40;
3773#endif
3774
3775	cp -> scsi_smsg [0] = idmsg;
3776	msglen=1;
3777
3778	if (cp->tag) {
3779
3780		/*
3781		**	Ordered write ops, unordered read ops.
3782		*/
3783		switch (cmd->opcode) {
3784		case 0x08:  /* READ_SMALL (6) */
3785		case 0x28:  /* READ_BIG  (10) */
3786		case 0xa8:  /* READ_HUGE (12) */
3787			cp -> scsi_smsg [msglen] = M_SIMPLE_TAG;
3788			break;
3789		default:
3790			cp -> scsi_smsg [msglen] = M_ORDERED_TAG;
3791		}
3792
3793		/*
3794		**	can be overwritten by ncrcontrol
3795		*/
3796		switch (np->order) {
3797		case M_SIMPLE_TAG:
3798		case M_ORDERED_TAG:
3799			cp -> scsi_smsg [msglen] = np->order;
3800		};
3801		msglen++;
3802		cp -> scsi_smsg [msglen++] = cp -> tag;
3803	}
3804
3805	switch (nego) {
3806	case NS_SYNC:
3807		cp -> scsi_smsg [msglen++] = M_EXTENDED;
3808		cp -> scsi_smsg [msglen++] = 3;
3809		cp -> scsi_smsg [msglen++] = M_X_SYNC_REQ;
3810		cp -> scsi_smsg [msglen++] = tp->minsync;
3811		cp -> scsi_smsg [msglen++] = tp->maxoffs;
3812		if (DEBUG_FLAGS & DEBUG_NEGO) {
3813			PRINT_ADDR(cp->xfer);
3814			printf ("sync msgout: ");
3815			ncr_show_msg (&cp->scsi_smsg [msglen-5]);
3816			printf (".\n");
3817		};
3818		break;
3819	case NS_WIDE:
3820		cp -> scsi_smsg [msglen++] = M_EXTENDED;
3821		cp -> scsi_smsg [msglen++] = 2;
3822		cp -> scsi_smsg [msglen++] = M_X_WIDE_REQ;
3823		cp -> scsi_smsg [msglen++] = tp->usrwide;
3824		if (DEBUG_FLAGS & DEBUG_NEGO) {
3825			PRINT_ADDR(cp->xfer);
3826			printf ("wide msgout: ");
3827			ncr_show_msg (&cp->scsi_smsg [msglen-4]);
3828			printf (".\n");
3829		};
3830		break;
3831	};
3832
3833	/*----------------------------------------------------
3834	**
3835	**	Build the identify message for getcc.
3836	**
3837	**----------------------------------------------------
3838	*/
3839
3840	cp -> scsi_smsg2 [0] = idmsg;
3841	msglen2 = 1;
3842
3843	/*----------------------------------------------------
3844	**
3845	**	Build the data descriptors
3846	**
3847	**----------------------------------------------------
3848	*/
3849
3850	segments = ncr_scatter (&cp->phys, (vm_offset_t) xp->data,
3851					(vm_size_t) xp->datalen);
3852
3853	if (segments < 0) {
3854		xp->error = XS_DRIVER_STUFFUP;
3855		ncr_free_ccb(np, cp, flags);
3856		splx(oldspl);
3857		return(COMPLETE);
3858	};
3859
3860	/*----------------------------------------------------
3861	**
3862	**	Set the SAVED_POINTER.
3863	**
3864	**----------------------------------------------------
3865	*/
3866
3867	if (flags & SCSI_DATA_IN) {
3868		cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_in);
3869		cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
3870	} else if (flags & SCSI_DATA_OUT) {
3871		cp->phys.header.savep = NCB_SCRIPT_PHYS (np, data_out);
3872		cp->phys.header.goalp = cp->phys.header.savep +20 +segments*16;
3873	} else {
3874		cp->phys.header.savep = NCB_SCRIPT_PHYS (np, no_data);
3875		cp->phys.header.goalp = cp->phys.header.savep;
3876	};
3877	cp->phys.header.lastp = cp->phys.header.savep;
3878
3879
3880	/*----------------------------------------------------
3881	**
3882	**	fill in ccb
3883	**
3884	**----------------------------------------------------
3885	**
3886	**
3887	**	physical -> virtual backlink
3888	**	Generic SCSI command
3889	*/
3890	cp->phys.header.cp		= cp;
3891	/*
3892	**	Startqueue
3893	*/
3894	cp->phys.header.launch.l_paddr	= NCB_SCRIPT_PHYS (np, select);
3895	cp->phys.header.launch.l_cmd	= SCR_JUMP;
3896	/*
3897	**	select
3898	*/
3899	cp->phys.select.sel_id		= xp->sc_link->target;
3900	cp->phys.select.sel_scntl3	= tp->wval;
3901	cp->phys.select.sel_sxfer	= tp->sval;
3902	/*
3903	**	message
3904	*/
3905/*	cp->phys.smsg.addr		= cp->p_scsi_smsg;*/
3906	cp->phys.smsg.addr		= CCB_PHYS (cp, scsi_smsg);
3907	cp->phys.smsg.size		= msglen;
3908
3909/*	cp->phys.smsg2.addr		= cp->p_scsi_smsg2;*/
3910	cp->phys.smsg2.addr		= CCB_PHYS (cp, scsi_smsg2);
3911	cp->phys.smsg2.size		= msglen2;
3912	/*
3913	**	command
3914	*/
3915	cp->phys.cmd.addr		= vtophys (cmd);
3916	cp->phys.cmd.size		= xp->cmdlen;
3917	/*
3918	**	sense command
3919	*/
3920/*	cp->phys.scmd.addr		= cp->p_sensecmd;*/
3921	cp->phys.scmd.addr		= CCB_PHYS (cp, sensecmd);
3922	cp->phys.scmd.size		= 6;
3923	/*
3924	**	patch requested size into sense command
3925	*/
3926	cp->sensecmd[0]			= 0x03;
3927	cp->sensecmd[1]			= xp->sc_link->lun << 5;
3928	cp->sensecmd[4]			= sizeof(struct scsi_sense_data);
3929	if (xp->req_sense_length)
3930		cp->sensecmd[4]		= xp->req_sense_length;
3931	/*
3932	**	sense data
3933	*/
3934	cp->phys.sense.addr		= vtophys (&cp->xfer->sense);
3935	cp->phys.sense.size		= sizeof(struct scsi_sense_data);
3936	/*
3937	**	status
3938	*/
3939	cp->actualquirks		= tp->quirks;
3940	cp->host_status			= nego ? HS_NEGOTIATE : HS_BUSY;
3941	cp->scsi_status			= S_ILLEGAL;
3942	cp->parity_status		= 0;
3943
3944	cp->xerr_status			= XE_OK;
3945	cp->sync_status			= tp->sval;
3946	cp->nego_status			= nego;
3947	cp->wide_status			= tp->wval;
3948
3949	/*----------------------------------------------------
3950	**
3951	**	Critical region: start this job.
3952	**
3953	**----------------------------------------------------
3954	*/
3955
3956	/*
3957	**	reselect pattern and activate this job.
3958	*/
3959
3960	cp->jump_ccb.l_cmd	= (SCR_JUMP ^ IFFALSE (DATA (cp->tag)));
3961	cp->tlimit		= time.tv_sec + xp->timeout / 1000 + 2;
3962	cp->magic		= CCB_MAGIC;
3963
3964	/*
3965	**	insert into start queue.
3966	*/
3967
3968	ptr = np->squeueput + 1;
3969	if (ptr >= MAX_START) ptr=0;
3970	np->squeue [ptr	  ] = NCB_SCRIPT_PHYS (np, idle);
3971	np->squeue [np->squeueput] = CCB_PHYS (cp, phys);
3972	np->squeueput = ptr;
3973
3974	if(DEBUG_FLAGS & DEBUG_QUEUE)
3975		printf ("%s: queuepos=%d tryoffset=%d.\n", ncr_name (np),
3976		np->squeueput,
3977		(unsigned)(np->script->startpos[0]-
3978			   (NCB_SCRIPT_PHYS (np, tryloop))));
3979
3980	/*
3981	**	Script processor may be waiting for reselect.
3982	**	Wake it up.
3983	*/
3984	OUTB (nc_istat, SIGP);
3985
3986	/*
3987	**	and reenable interrupts
3988	*/
3989	splx (oldspl);
3990
3991	/*
3992	**	If interrupts are enabled, return now.
3993	**	Command is successfully queued.
3994	*/
3995
3996#ifdef __NetBSD__
3997        if (!(flags & SCSI_POLL)) {
3998#else /* !__NetBSD__ */
3999	if (!(flags & SCSI_NOMASK)) {
4000#endif /* __NetBSD__ */
4001		if (np->lasttime) {
4002			if(DEBUG_FLAGS & DEBUG_TINY) printf ("Q");
4003			return(SUCCESSFULLY_QUEUED);
4004		};
4005	};
4006
4007	/*----------------------------------------------------
4008	**
4009	**	Interrupts not yet enabled - have to poll.
4010	**
4011	**----------------------------------------------------
4012	*/
4013
4014	if (DEBUG_FLAGS & DEBUG_POLL) printf("P");
4015
4016	for (i=xp->timeout; i && !(xp->flags & ITSDONE);i--) {
4017		if ((DEBUG_FLAGS & DEBUG_POLL) && (cp->host_status))
4018			printf ("%c", (cp->host_status & 0xf) + '0');
4019		DELAY (1000);
4020		ncr_exception (np);
4021	};
4022
4023	/*
4024	**	Abort if command not done.
4025	*/
4026	if (!(xp->flags & ITSDONE)) {
4027		printf ("%s: aborting job ...\n", ncr_name (np));
4028		OUTB (nc_istat, CABRT);
4029		DELAY (100000);
4030		OUTB (nc_istat, SIGP);
4031		ncr_exception (np);
4032	};
4033
4034	if (!(xp->flags & ITSDONE)) {
4035		printf ("%s: abortion failed at %x.\n",
4036			ncr_name (np), (unsigned) INL(nc_dsp));
4037		ncr_init (np, "timeout", HS_TIMEOUT);
4038	};
4039
4040	if (!(xp->flags & ITSDONE)) {
4041		cp-> host_status = HS_SEL_TIMEOUT;
4042		ncr_complete (np, cp);
4043	};
4044
4045	if (DEBUG_FLAGS & DEBUG_RESULT) {
4046		printf ("%s: result: %x %x.\n",
4047			ncr_name (np), cp->host_status, cp->scsi_status);
4048	};
4049#ifdef __NetBSD__
4050        if (!(flags & SCSI_POLL))
4051#else /* !__NetBSD__ */
4052	if (!(flags & SCSI_NOMASK))
4053#endif /* __NetBSD__ */
4054		return (SUCCESSFULLY_QUEUED);
4055	switch (xp->error) {
4056	case  0     : return (COMPLETE);
4057	case XS_BUSY: return (TRY_AGAIN_LATER);
4058	};
4059	return (COMPLETE);
4060}
4061
4062/*==========================================================
4063**
4064**
4065**	Complete execution of a SCSI command.
4066**	Signal completion to the generic SCSI driver.
4067**
4068**
4069**==========================================================
4070*/
4071
4072void ncr_complete (ncb_p np, ccb_p cp)
4073{
4074	struct scsi_xfer * xp;
4075	tcb_p tp;
4076	lcb_p lp;
4077
4078	/*
4079	**	Sanity check
4080	*/
4081
4082	if (!cp || (cp->magic!=CCB_MAGIC) || !cp->xfer) return;
4083	cp->magic = 1;
4084	cp->tlimit= 0;
4085
4086	/*
4087	**	No Reselect anymore.
4088	*/
4089	cp->jump_ccb.l_cmd = (SCR_JUMP);
4090
4091	/*
4092	**	No starting.
4093	*/
4094	cp->phys.header.launch.l_paddr= NCB_SCRIPT_PHYS (np, idle);
4095
4096	/*
4097	**	timestamp
4098	*/
4099	ncb_profile (np, cp);
4100
4101	if (DEBUG_FLAGS & DEBUG_TINY)
4102		printf ("CCB=%x STAT=%x/%x\n", (unsigned)cp & 0xfff,
4103			cp->host_status,cp->scsi_status);
4104
4105	xp = cp->xfer;
4106	cp->xfer = NULL;
4107	tp = &np->target[xp->sc_link->target];
4108	lp = tp->lp[xp->sc_link->lun];
4109
4110	/*
4111	**	Check for parity errors.
4112	*/
4113
4114	if (cp->parity_status) {
4115		PRINT_ADDR(xp);
4116		printf ("%d parity error(s), fallback.\n", cp->parity_status);
4117		/*
4118		**	fallback to asynch transfer.
4119		*/
4120		tp->usrsync=255;
4121		tp->period =  0;
4122	};
4123
4124	/*
4125	**	Check for extended errors.
4126	*/
4127
4128	if (cp->xerr_status != XE_OK) {
4129		PRINT_ADDR(xp);
4130		switch (cp->xerr_status) {
4131		case XE_EXTRA_DATA:
4132			printf ("extraneous data discarded.\n");
4133			break;
4134		case XE_BAD_PHASE:
4135			printf ("illegal scsi phase (4/5).\n");
4136			break;
4137		default:
4138			printf ("extended error %d.\n", cp->xerr_status);
4139			break;
4140		};
4141		if (cp->host_status==HS_COMPLETE)
4142			cp->host_status = HS_FAIL;
4143	};
4144
4145	/*
4146	**	Check the status.
4147	*/
4148#ifdef __NetBSD__
4149	if (xp->error != XS_NOERROR) {
4150
4151                /*
4152                **      Don't override the error value.
4153                */
4154	} else
4155#endif /* __NetBSD__ */
4156	if (   (cp->host_status == HS_COMPLETE)
4157		&& (cp->scsi_status == S_GOOD)) {
4158
4159		/*
4160		**	All went well.
4161		*/
4162
4163		xp->resid = 0;
4164
4165		/*
4166		** if (cp->phys.header.lastp != cp->phys.header.goalp)...
4167		**
4168		**	@RESID@
4169		**	Could dig out the correct value for resid,
4170		**	but it would be quite complicated.
4171		**
4172		**	The ah1542.c driver sets it to 0 too ...
4173		*/
4174
4175		/*
4176		**	Try to assign a ccb to this nexus
4177		*/
4178		ncr_alloc_ccb (np, xp);
4179
4180		/*
4181		**	On inquire cmd (0x12) save some data.
4182		*/
4183		if (xp->cmd->opcode == 0x12) {
4184			bcopy (	xp->data,
4185				&tp->inqdata,
4186				sizeof (tp->inqdata));
4187
4188			/*
4189			**	set number of tags
4190			*/
4191			ncr_setmaxtags (tp, tp->usrtags);
4192
4193			/*
4194			**	prepare negotiation of synch and wide.
4195			*/
4196			ncr_negotiate (np, tp);
4197
4198			/*
4199			**	force quirks update before next command start
4200			*/
4201			tp->quirks |= QUIRK_UPDATE;
4202		};
4203
4204		/*
4205		**	Announce changes to the generic driver
4206		*/
4207		if (lp) {
4208			ncr_settags (tp, lp);
4209			if (lp->reqlink != lp->actlink)
4210				ncr_opennings (np, lp, xp);
4211		};
4212
4213		tp->bytes     += xp->datalen;
4214		tp->transfers ++;
4215#ifndef __NetBSD__
4216	} else if (xp->flags & SCSI_ERR_OK) {
4217
4218		/*
4219		**   Not correct, but errors expected.
4220		*/
4221		xp->resid = 0;
4222#endif /* !__NetBSD__ */
4223	} else if ((cp->host_status == HS_COMPLETE)
4224		&& (cp->scsi_status == (S_SENSE|S_GOOD))) {
4225
4226		/*
4227		**   Check condition code
4228		*/
4229		xp->error = XS_SENSE;
4230
4231		if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4232			u_char * p = (u_char*) & xp->sense;
4233			int i;
4234			printf ("\n%s: sense data:", ncr_name (np));
4235			for (i=0; i<14; i++) printf (" %x", *p++);
4236			printf (".\n");
4237		};
4238
4239	} else if ((cp->host_status == HS_COMPLETE)
4240		&& (cp->scsi_status == S_BUSY)) {
4241
4242		/*
4243		**   Target is busy.
4244		*/
4245		xp->error = XS_BUSY;
4246
4247	} else if ((cp->host_status == HS_SEL_TIMEOUT)
4248		|| (cp->host_status == HS_TIMEOUT)) {
4249
4250		/*
4251		**   No response
4252		*/
4253		xp->error = XS_TIMEOUT;
4254
4255	} else {
4256
4257		/*
4258		**  Other protocol messes
4259		*/
4260		PRINT_ADDR(xp);
4261		printf ("COMMAND FAILED (%x %x) @%x.\n",
4262			cp->host_status, cp->scsi_status, (unsigned)cp);
4263
4264		xp->error = XS_TIMEOUT;
4265	}
4266
4267	xp->flags |= ITSDONE;
4268
4269	/*
4270	**	trace output
4271	*/
4272
4273	if (tp->usrflag & UF_TRACE) {
4274		u_char * p;
4275		int i;
4276		PRINT_ADDR(xp);
4277		printf (" CMD:");
4278		p = (u_char*) &xp->cmd->opcode;
4279		for (i=0; i<xp->cmdlen; i++) printf (" %x", *p++);
4280
4281		if (cp->host_status==HS_COMPLETE) {
4282			switch (cp->scsi_status) {
4283			case S_GOOD:
4284				printf ("  GOOD");
4285				break;
4286			case S_CHECK_COND:
4287				printf ("  SENSE:");
4288				p = (u_char*) &xp->sense;
4289				for (i=0; i<xp->req_sense_length; i++)
4290					printf (" %x", *p++);
4291				break;
4292			default:
4293				printf ("  STAT: %x\n", cp->scsi_status);
4294				break;
4295			};
4296		} else printf ("  HOSTERROR: %x", cp->host_status);
4297		printf ("\n");
4298	};
4299
4300	/*
4301	**	Free this ccb
4302	*/
4303	ncr_free_ccb (np, cp, xp->flags);
4304
4305	/*
4306	**	signal completion to generic driver.
4307	*/
4308	scsi_done (xp);
4309}
4310
4311/*==========================================================
4312**
4313**
4314**	Signal all (or one) control block done.
4315**
4316**
4317**==========================================================
4318*/
4319
4320void ncr_wakeup (ncb_p np, u_long code)
4321{
4322	/*
4323	**	Starting at the default ccb and following
4324	**	the links, complete all jobs with a
4325	**	host_status greater than "disconnect".
4326	**
4327	**	If the "code" parameter is not zero,
4328	**	complete all jobs that are not IDLE.
4329	*/
4330
4331	ccb_p cp = &np->ccb;
4332	while (cp) {
4333		switch (cp->host_status) {
4334
4335		case HS_IDLE:
4336			break;
4337
4338		case HS_DISCONNECT:
4339			if(DEBUG_FLAGS & DEBUG_TINY) printf ("D");
4340			/* fall through */
4341
4342		case HS_BUSY:
4343		case HS_NEGOTIATE:
4344			if (!code) break;
4345			cp->host_status = code;
4346
4347			/* fall through */
4348
4349		default:
4350			ncr_complete (np, cp);
4351			break;
4352		};
4353		cp = cp -> link_ccb;
4354	};
4355}
4356
4357/*==========================================================
4358**
4359**
4360**	Start NCR chip.
4361**
4362**
4363**==========================================================
4364*/
4365
4366void ncr_init (ncb_p np, char * msg, u_long code)
4367{
4368	int	i;
4369	u_long	usrsync;
4370	u_char	usrwide;
4371	u_char	burstlen;
4372
4373	/*
4374	**	Reset chip.
4375	*/
4376
4377	OUTB (nc_istat,  SRST);
4378	DELAY (1000);
4379
4380	/*
4381	**	Message.
4382	*/
4383
4384	if (msg) printf ("%s: restart (%s).\n", ncr_name (np), msg);
4385
4386	/*
4387	**	Clear Start Queue
4388	*/
4389
4390	for (i=0;i<MAX_START;i++)
4391		np -> squeue [i] = NCB_SCRIPT_PHYS (np, idle);
4392
4393	/*
4394	**	Start at first entry.
4395	*/
4396
4397	np->squeueput = 0;
4398	np->script->startpos[0] = NCB_SCRIPT_PHYS (np, tryloop);
4399	np->script->start0  [0] = SCR_INT ^ IFFALSE (0);
4400
4401	/*
4402	**	Wakeup all pending jobs.
4403	*/
4404
4405	ncr_wakeup (np, code);
4406
4407	/*
4408	**	Init chip.
4409	*/
4410
4411#ifndef __NetBSD__
4412	if (pci_max_burst_len < 4) {
4413		static u_char tbl[4]={0,0,0x40,0x80};
4414		burstlen = tbl[pci_max_burst_len];
4415	} else burstlen = 0xc0;
4416#else /* !__NetBSD__ */
4417	burstlen = 0xc0;
4418#endif /* __NetBSD__ */
4419
4420	OUTB (nc_istat,  0      );      /*  Remove Reset, abort ...	     */
4421	OUTB (nc_scntl0, 0xca   );      /*  full arb., ena parity, par->ATN  */
4422	OUTB (nc_scntl1, 0x00	);	/*  odd parity, and remove CRST!!    */
4423	OUTB (nc_scntl3, np->rv_scntl3);/*  timing prescaler		     */
4424	OUTB (nc_scid  , RRE|np->myaddr);/*  host adapter SCSI address       */
4425	OUTW (nc_respid, 1ul<<np->myaddr);/*  id to respond to		     */
4426	OUTB (nc_istat , SIGP	);	/*  Signal Process		     */
4427	OUTB (nc_dmode , burstlen);	/*  Burst length = 2 .. 16 transfers */
4428	OUTB (nc_dcntl , NOCOM  );      /*  no single step mode, protect SFBR*/
4429	OUTB (nc_ctest4, 0x08	);	/*  enable master parity checking    */
4430	OUTB (nc_stest2, EXT    );	/*  Extended Sreq/Sack filtering     */
4431	OUTB (nc_stest3, TE     );	/*  TolerANT enable		     */
4432	OUTB (nc_stime0, 0xfb	);	/*  HTH = 1.6sec  STO = 0.1 sec.     */
4433
4434	/*
4435	**	Reinitialize usrsync.
4436	**	Have to renegotiate synch mode.
4437	*/
4438
4439	usrsync = 255;
4440	if (SCSI_NCR_MAX_SYNC) {
4441		u_long period;
4442		period =1000000/SCSI_NCR_MAX_SYNC; /* ns = 10e6 / kHz */
4443		if (period <= 11 * np->ns_sync) {
4444			if (period < 4 * np->ns_sync)
4445				usrsync = np->ns_sync;
4446			else
4447				usrsync = period / 4;
4448		};
4449	};
4450
4451	/*
4452	**	Reinitialize usrwide.
4453	**	Have to renegotiate wide mode.
4454	*/
4455
4456	usrwide = (SCSI_NCR_MAX_WIDE);
4457	if (usrwide > np->maxwide) usrwide=np->maxwide;
4458
4459	/*
4460	**	Disable disconnects.
4461	*/
4462
4463	np->disc = 0;
4464
4465	/*
4466	**	Fill in target structure.
4467	*/
4468
4469	for (i=0;i<MAX_TARGET;i++) {
4470		tcb_p tp = &np->target[i];
4471
4472		tp->sval    = 0;
4473		tp->wval    = np->rv_scntl3;
4474
4475		tp->usrsync = usrsync;
4476		tp->usrwide = usrwide;
4477
4478		ncr_negotiate (np, tp);
4479	}
4480
4481	/*
4482	**      enable ints
4483	*/
4484
4485	OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST);
4486	OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
4487
4488	/*
4489	**    Start script processor.
4490	*/
4491
4492	OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
4493}
4494
4495/*==========================================================
4496**
4497**	Prepare the negotiation values for wide and
4498**	synchronous transfers.
4499**
4500**==========================================================
4501*/
4502
4503static void ncr_negotiate (struct ncb* np, struct tcb* tp)
4504{
4505	/*
4506	**	minsync unit is 4ns !
4507	*/
4508
4509	u_long minsync = tp->usrsync;
4510
4511	if (minsync < 25) minsync=25;
4512
4513	/*
4514	**	if not scsi 2
4515	**	don't believe FAST!
4516	*/
4517
4518	if ((minsync < 50) && (tp->inqdata[2] & 0x0f) < 2)
4519		minsync=50;
4520
4521	/*
4522	**	our limit ..
4523	*/
4524
4525	if (minsync < np->ns_sync)
4526		minsync = np->ns_sync;
4527
4528	/*
4529	**	divider limit
4530	*/
4531
4532	if (minsync > (np->ns_sync * 11) / 4)
4533		minsync = 255;
4534
4535	tp->minsync = minsync;
4536	tp->maxoffs = (minsync<255 ? 8 : 0);
4537
4538	/*
4539	**	period=0: has to negotiate sync transfer
4540	*/
4541
4542	tp->period=0;
4543
4544	/*
4545	**	widedone=0: has to negotiate wide transfer
4546	*/
4547	tp->widedone=0;
4548}
4549
4550/*==========================================================
4551**
4552**	Switch sync mode for current job and it's target
4553**
4554**==========================================================
4555*/
4556
4557static void ncr_setsync (ncb_p np, ccb_p cp, u_char sxfer)
4558{
4559	struct scsi_xfer *xp;
4560	tcb_p tp;
4561	u_char target = INB (nc_ctest0)&7;
4562
4563	assert (cp);
4564	if (!cp) return;
4565
4566	xp = cp->xfer;
4567	assert (xp);
4568	if (!xp) return;
4569	assert (target == xp->sc_link->target & 7);
4570
4571	tp = &np->target[target];
4572	tp->period= sxfer&0xf ? ((sxfer>>5)+4) * np->ns_sync : 0xffff;
4573
4574	if (tp->sval == sxfer) return;
4575	tp->sval = sxfer;
4576
4577	/*
4578	**	Bells and whistles   ;-)
4579	*/
4580	PRINT_ADDR(xp);
4581	if (sxfer & 0x0f) {
4582		/*
4583		**  Disable extended Sreq/Sack filtering
4584		*/
4585		if (tp->period <= 200) OUTB (nc_stest2, 0);
4586		printf ("%s%dns (%d Mb/sec) offset %d.\n",
4587			tp->period<200 ? "FAST SCSI-2 ":"",
4588			tp->period, (1000+tp->period/2)/tp->period,
4589			sxfer & 0x0f);
4590	} else  printf ("asynchronous.\n");
4591
4592	/*
4593	**	set actual value and sync_status
4594	*/
4595	OUTB (nc_sxfer, sxfer);
4596	np->sync_st = sxfer;
4597
4598	/*
4599	**	patch ALL ccbs of this target.
4600	*/
4601	for (cp = &np->ccb; cp; cp = cp->link_ccb) {
4602		if (!cp->xfer) continue;
4603		if (cp->xfer->sc_link->target != target) continue;
4604		cp->sync_status = sxfer;
4605	};
4606}
4607
4608/*==========================================================
4609**
4610**	Switch wide mode for current job and it's target
4611**
4612**==========================================================
4613*/
4614
4615static void ncr_setwide (ncb_p np, ccb_p cp, u_char wide)
4616{
4617	struct scsi_xfer *xp;
4618	u_short target = INB (nc_ctest0)&7;
4619	tcb_p tp;
4620	u_char	scntl3 = np->rv_scntl3 | (wide ? EWS : 0);
4621
4622	assert (cp);
4623	if (!cp) return;
4624
4625	xp = cp->xfer;
4626	assert (xp);
4627	if (!xp) return;
4628	assert (target == xp->sc_link->target & 7);
4629
4630	tp = &np->target[target];
4631	tp->widedone  =  wide+1;
4632	if (tp->wval == scntl3) return;
4633	tp->wval = scntl3;
4634
4635	/*
4636	**	Bells and whistles   ;-)
4637	*/
4638	PRINT_ADDR(xp);
4639	if (scntl3 & EWS)
4640		printf ("WIDE SCSI (16 bit) enabled.\n");
4641	else
4642		printf ("WIDE SCSI disabled.\n");
4643
4644	/*
4645	**	set actual value and sync_status
4646	*/
4647	OUTB (nc_scntl3, scntl3);
4648	np->wide_st = scntl3;
4649
4650	/*
4651	**	patch ALL ccbs of this target.
4652	*/
4653	for (cp = &np->ccb; cp; cp = cp->link_ccb) {
4654		if (!cp->xfer) continue;
4655		if (cp->xfer->sc_link->target != target) continue;
4656		cp->wide_status = scntl3;
4657	};
4658}
4659
4660/*==========================================================
4661**
4662**	Switch tagged mode for a target.
4663**
4664**==========================================================
4665*/
4666
4667static void ncr_setmaxtags (tcb_p tp, u_long usrtags)
4668{
4669	int l;
4670	tp->usrtags = usrtags;
4671	for (l=0; l<MAX_LUN; l++) {
4672		lcb_p lp;
4673		if (!tp) break;
4674		lp=tp->lp[l];
4675		if (!lp) continue;
4676		ncr_settags (tp, lp);
4677	};
4678}
4679
4680static void ncr_settags (tcb_p tp, lcb_p lp)
4681{
4682	u_char reqtags, tmp;
4683
4684	if ((!tp) || (!lp)) return;
4685
4686	/*
4687	**	only devices capable of tagges commands
4688	**	only disk devices
4689	**	only if enabled by user ..
4690	*/
4691	if ((  tp->inqdata[7] & INQ7_QUEUE) && ((tp->inqdata[0] & 0x1f)==0x00)
4692		&& tp->usrtags) {
4693		reqtags = tp->usrtags;
4694		if (lp->actlink <= 1)
4695			lp->usetags=reqtags;
4696	} else {
4697		reqtags = 1;
4698		if (lp->actlink <= 1)
4699			lp->usetags=0;
4700	};
4701
4702	/*
4703	**	don't announce more than available.
4704	*/
4705	tmp = lp->actccbs;
4706	if (tmp > reqtags) tmp = reqtags;
4707	lp->reqlink = tmp;
4708
4709	/*
4710	**	don't discard if announced.
4711	*/
4712	tmp = lp->actlink;
4713	if (tmp < reqtags) tmp = reqtags;
4714	lp->reqccbs = tmp;
4715}
4716
4717/*----------------------------------------------------
4718**
4719**	handle user commands
4720**
4721**----------------------------------------------------
4722*/
4723
4724static void ncr_usercmd (ncb_p np)
4725{
4726	u_char t;
4727	tcb_p tp;
4728
4729	switch (np->user.cmd) {
4730
4731	case 0: return;
4732
4733	case UC_SETSYNC:
4734		for (t=0; t<MAX_TARGET; t++) {
4735			if (!((np->user.target>>t)&1)) continue;
4736			tp = &np->target[t];
4737			tp->usrsync = np->user.data;
4738			ncr_negotiate (np, tp);
4739		};
4740		break;
4741
4742	case UC_SETTAGS:
4743		if (np->user.data > MAX_TAGS)
4744			break;
4745		for (t=0; t<MAX_TARGET; t++) {
4746			if (!((np->user.target>>t)&1)) continue;
4747			ncr_setmaxtags (&np->target[t], np->user.data);
4748		};
4749		break;
4750
4751	case UC_SETDEBUG:
4752		ncr_debug = np->user.data;
4753		break;
4754
4755	case UC_SETORDER:
4756		np->order = np->user.data;
4757		break;
4758
4759	case UC_SETWIDE:
4760		for (t=0; t<MAX_TARGET; t++) {
4761			u_long size;
4762			if (!((np->user.target>>t)&1)) continue;
4763			tp = &np->target[t];
4764			size = np->user.data;
4765			if (size > np->maxwide) size=np->maxwide;
4766			tp->usrwide = size;
4767			ncr_negotiate (np, tp);
4768		};
4769		break;
4770
4771	case UC_SETFLAG:
4772		for (t=0; t<MAX_TARGET; t++) {
4773			if (!((np->user.target>>t)&1)) continue;
4774			tp = &np->target[t];
4775			tp->usrflag = np->user.data;
4776		};
4777		break;
4778	}
4779	np->user.cmd=0;
4780}
4781
4782
4783
4784
4785/*==========================================================
4786**
4787**
4788**	ncr timeout handler.
4789**
4790**
4791**==========================================================
4792**
4793**	Misused to keep the driver running when
4794**	interrupts are not configured correctly.
4795**
4796**----------------------------------------------------------
4797*/
4798
4799static void ncr_timeout (ncb_p np)
4800{
4801	u_long	thistime = time.tv_sec;
4802	u_long	step  = np->ticks;
4803	u_long	count = 0;
4804	long signed   t;
4805	ccb_p cp;
4806
4807	if (np->lasttime != thistime) {
4808		/*
4809		**	block ncr interrupts
4810		*/
4811		int oldspl = splbio();
4812		np->lasttime = thistime;
4813
4814		ncr_usercmd (np);
4815
4816		/*----------------------------------------------------
4817		**
4818		**	handle ncr chip timeouts
4819		**
4820		**	Assumption:
4821		**	We have a chance to arbitrate for the
4822		**	SCSI bus at least every 10 seconds.
4823		**
4824		**----------------------------------------------------
4825		*/
4826
4827		t = thistime - np->heartbeat;
4828
4829		if (t<2) np->latetime=0; else np->latetime++;
4830
4831		if (np->latetime>2) {
4832			/*
4833			**      If there are no requests, the script
4834			**      processor will sleep on SEL_WAIT_RESEL.
4835			**      But we have to check whether it died.
4836			**      Let's wake it up.
4837			*/
4838			OUTB (nc_istat, SIGP);
4839		};
4840
4841		if (np->latetime>4) {
4842			/*
4843			**	Although we tried to wake it up,
4844			**	the script processor didn't respond.
4845			**
4846			**	May be a target is hanging,
4847			**	or another initator lets a tape device
4848			**	rewind with disconnect disabled :-(
4849			**
4850			**	We won't accept that.
4851			*/
4852			if (INB (nc_sbcl) & CBSY)
4853				OUTB (nc_scntl1, CRST);
4854			DELAY (1000);
4855			ncr_init (np, "ncr dead ?", HS_TIMEOUT);
4856			np->heartbeat = thistime;
4857		};
4858
4859		/*----------------------------------------------------
4860		**
4861		**	handle ccb timeouts
4862		**
4863		**----------------------------------------------------
4864		*/
4865
4866		for (cp=&np->ccb; cp; cp=cp->link_ccb) {
4867			/*
4868			**	look for timed out ccbs.
4869			*/
4870			if (!cp->host_status) continue;
4871			count++;
4872			if (cp->tlimit > thistime) continue;
4873
4874			/*
4875			**	Disable reselect.
4876			**      Remove it from startqueue.
4877			*/
4878			cp->jump_ccb.l_cmd = (SCR_JUMP);
4879			if (cp->phys.header.launch.l_paddr ==
4880				NCB_SCRIPT_PHYS (np, select)) {
4881				printf ("%s: timeout ccb=%x (skip)\n",
4882					ncr_name (np), (unsigned)cp);
4883				cp->phys.header.launch.l_paddr
4884				= NCB_SCRIPT_PHYS (np, skip);
4885			};
4886
4887			switch (cp->host_status) {
4888
4889			case HS_BUSY:
4890			case HS_NEGOTIATE:
4891				/*
4892				** still in start queue ?
4893				*/
4894				if (cp->phys.header.launch.l_paddr ==
4895					NCB_SCRIPT_PHYS (np, skip))
4896					continue;
4897
4898				/* fall through */
4899			case HS_DISCONNECT:
4900				cp->host_status=HS_TIMEOUT;
4901			};
4902			cp->tag = 0;
4903
4904			/*
4905			**	wakeup this ccb.
4906			*/
4907			ncr_complete (np, cp);
4908		};
4909		splx (oldspl);
4910	}
4911
4912	timeout (TIMEOUT ncr_timeout, (caddr_t) np, step ? step : 1);
4913
4914	if (INB(nc_istat) & (INTF|SIP|DIP)) {
4915
4916		/*
4917		**	Process pending interrupts.
4918		*/
4919
4920		int	oldspl	= splbio ();
4921		if (DEBUG_FLAGS & DEBUG_TINY) printf ("{");
4922		ncr_exception (np);
4923		if (DEBUG_FLAGS & DEBUG_TINY) printf ("}");
4924		splx (oldspl);
4925	};
4926}
4927
4928/*==========================================================
4929**
4930**
4931**	ncr chip exception handler.
4932**
4933**
4934**==========================================================
4935*/
4936
4937void ncr_exception (ncb_p np)
4938{
4939	u_char	istat, dstat;
4940	u_short	sist;
4941	u_long	dsp, dsa;
4942	int	i, script_ofs;
4943
4944	/*
4945	**	interrupt on the fly ?
4946	*/
4947	while ((istat = INB (nc_istat)) & INTF) {
4948		if (DEBUG_FLAGS & DEBUG_TINY) printf ("F");
4949		OUTB (nc_istat, INTF);
4950		np->profile.num_fly++;
4951		ncr_wakeup (np, 0);
4952	};
4953
4954	if (!(istat & (SIP|DIP))) return;
4955
4956	/*
4957	**	Steinbach's Guideline for Systems Programming:
4958	**	Never test for an error condition you don't know how to handle.
4959	*/
4960
4961	dstat = INB (nc_dstat);
4962	sist  = INW (nc_sist) ;
4963	np->profile.num_int++;
4964
4965	if (DEBUG_FLAGS & DEBUG_TINY)
4966		printf ("<%d|%x:%x|%x:%x>",
4967			INB(nc_scr0),
4968			dstat,sist,
4969			(unsigned)INL(nc_dsp),
4970			(unsigned)INL(nc_dbc));
4971	if ((dstat==DFE) && (sist==PAR)) return;
4972
4973/*==========================================================
4974**
4975**	First the normal cases.
4976**
4977**==========================================================
4978*/
4979	/*-------------------------------------------
4980	**	SCSI reset
4981	**-------------------------------------------
4982	*/
4983
4984	if (sist & RST) {
4985		ncr_init (np, bootverbose ? "scsi reset" : NULL, HS_RESET);
4986		return;
4987	};
4988
4989	/*-------------------------------------------
4990	**	selection timeout
4991	**
4992	**	IID excluded from dstat mask!
4993	**	(chip bug)
4994	**-------------------------------------------
4995	*/
4996
4997	if ((sist  & STO) &&
4998		!(sist  & (GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
4999		!(dstat & (MDPE|BF|ABRT|SIR))) {
5000		ncr_int_sto (np);
5001		return;
5002	};
5003
5004	/*-------------------------------------------
5005	**      Phase mismatch.
5006	**-------------------------------------------
5007	*/
5008
5009	if ((sist  & MA) &&
5010		!(sist  & (STO|GEN|HTH|SGE|UDC|RST|PAR)) &&
5011		!(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5012		ncr_int_ma (np);
5013		return;
5014	};
5015
5016	/*----------------------------------------
5017	**	move command with length 0
5018	**----------------------------------------
5019	*/
5020
5021	if ((dstat & IID) &&
5022		!(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5023		!(dstat & (MDPE|BF|ABRT|SIR)) &&
5024		((INL(nc_dbc) & 0xf8000000) == SCR_MOVE_TBL)) {
5025		/*
5026		**      Target wants more data than available.
5027		**	The "no_data" script will do it.
5028		*/
5029		OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, no_data));
5030		return;
5031	};
5032
5033	/*-------------------------------------------
5034	**	Programmed interrupt
5035	**-------------------------------------------
5036	*/
5037
5038	if ((dstat & SIR) &&
5039		!(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5040		!(dstat & (MDPE|BF|ABRT|IID)) &&
5041		(INB(nc_dsps) <= SIR_MAX)) {
5042		ncr_int_sir (np);
5043		return;
5044	};
5045
5046	/*========================================
5047	**	do the register dump
5048	**========================================
5049	*/
5050
5051	if (time.tv_sec - np->regtime.tv_sec>10) {
5052		int i;
5053		np->regtime = time;
5054		for (i=0; i<sizeof(np->regdump); i++)
5055			((char*)&np->regdump)[i] = ((char*)np->reg)[i];
5056		np->regdump.nc_dstat = dstat;
5057		np->regdump.nc_sist  = sist;
5058	};
5059
5060	/*=========================================
5061	**	log message for real hard errors
5062	**=========================================
5063
5064	"ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ (dsp:dbc)."
5065	"	      reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
5066
5067	exception register:
5068		ds:	dstat
5069		si:	sist
5070
5071	SCSI bus lines:
5072		so:	control lines as driver by NCR.
5073		si:	control lines as seen by NCR.
5074		sd:	scsi data lines as seen by NCR.
5075
5076	wide/fastmode:
5077		sxfer:	(see the manual)
5078		scntl3:	(see the manual)
5079
5080	current script command:
5081		dsp:	script adress (relative to start of script).
5082		dbc:	first word of script command.
5083
5084	First 16 register of the chip:
5085		r0..rf
5086
5087	=============================================
5088	*/
5089
5090	dsp = (unsigned) INL (nc_dsp);
5091	dsa = (unsigned) INL (nc_dsa);
5092
5093	script_ofs = dsp - np->p_script;
5094
5095	printf ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%x:%08x).\n",
5096		ncr_name (np), INB (nc_ctest0)&0x0f, dstat, sist,
5097		INB (nc_socl), INB (nc_sbcl), INB (nc_sbdl),
5098		INB (nc_sxfer),INB (nc_scntl3), script_ofs,
5099		(unsigned) INL (nc_dbc));
5100
5101	if (((script_ofs & 3) == 0) &&
5102	    (unsigned)script_ofs < sizeof(struct script)) {
5103		printf ("\tscript cmd = %08x\n",
5104			*(ncrcmd *)((char*)np->script +script_ofs));
5105	}
5106
5107	printf ("\treg:\t");
5108	for (i=0; i<16;i++)
5109		printf (" %02x", ((u_char*)np->reg)[i]);
5110	printf (".\n");
5111
5112	/*----------------------------------------
5113	**	clean up the dma fifo
5114	**----------------------------------------
5115	*/
5116
5117	if ( (INB(nc_sstat0) & (ILF|ORF|OLF)   ) ||
5118	     (INB(nc_sstat1) & (FF3210)	) ||
5119	     (INB(nc_sstat2) & (ILF1|ORF1|OLF1)) ||	/* wide .. */
5120	     !(dstat & DFE)) {
5121		printf ("%s: have to clear fifos.\n", ncr_name (np));
5122		OUTB (nc_stest3, TE|CSF);	/* clear scsi fifo */
5123		OUTB (nc_ctest3, CLF);		/* clear dma fifo  */
5124	}
5125
5126	/*----------------------------------------
5127	**	handshake timeout
5128	**----------------------------------------
5129	*/
5130
5131	if (sist & HTH) {
5132		printf ("%s: handshake timeout\n", ncr_name(np));
5133		OUTB (nc_scntl1, CRST);
5134		DELAY (1000);
5135		OUTB (nc_scntl1, 0x00);
5136		OUTB (nc_scr0, HS_FAIL);
5137		OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5138		return;
5139	}
5140
5141	/*----------------------------------------
5142	**	unexpected disconnect
5143	**----------------------------------------
5144	*/
5145
5146	if ((sist  & UDC) &&
5147		!(sist  & (STO|GEN|HTH|MA|SGE|RST|PAR)) &&
5148		!(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5149		OUTB (nc_scr0, HS_UNEXPECTED);
5150		OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, cleanup));
5151		return;
5152	};
5153
5154	/*----------------------------------------
5155	**	cannot disconnect
5156	**----------------------------------------
5157	*/
5158
5159	if ((dstat & IID) &&
5160		!(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5161		!(dstat & (MDPE|BF|ABRT|SIR)) &&
5162		((INL(nc_dbc) & 0xf8000000) == SCR_WAIT_DISC)) {
5163		/*
5164		**      Unexpected data cycle while waiting for disconnect.
5165		*/
5166		if (INB(nc_sstat2) & LDSC) {
5167			/*
5168			**	It's an early reconnect.
5169			**	Let's continue ...
5170			*/
5171			OUTB (nc_dcntl, (STD|NOCOM));
5172			/*
5173			**	info message
5174			*/
5175			printf ("%s: INFO: LDSC while IID.\n",
5176				ncr_name (np));
5177			return;
5178		};
5179		printf ("%s: target %d doesn't release the bus.\n",
5180			ncr_name (np), INB (nc_ctest0)&0x0f);
5181		/*
5182		**	return without restarting the NCR.
5183		**	timeout will do the real work.
5184		*/
5185		return;
5186	};
5187
5188	/*----------------------------------------
5189	**	single step
5190	**----------------------------------------
5191	*/
5192
5193	if ((dstat & SSI) &&
5194		!(sist  & (STO|GEN|HTH|MA|SGE|UDC|RST|PAR)) &&
5195		!(dstat & (MDPE|BF|ABRT|SIR|IID))) {
5196		OUTB (nc_dcntl, (STD|NOCOM));
5197		return;
5198	};
5199
5200/*
5201**	@RECOVER@ HTH, SGE, ABRT.
5202**
5203**	We should try to recover from these interrupts.
5204**	They may occur if there are problems with synch transfers, or
5205**	if targets are switched on or off while the driver is running.
5206*/
5207
5208	if (sist & SGE) {
5209		OUTB (nc_ctest3, CLF);		/* clear scsi offsets */
5210	}
5211
5212	/*
5213	**	Freeze controller to be able to read the messages.
5214	*/
5215
5216	if (DEBUG_FLAGS & DEBUG_FREEZE) {
5217		int i;
5218		unsigned char val;
5219		for (i=0; i<0x60; i++) {
5220			switch (i%16) {
5221
5222			case 0:
5223				printf ("%s: reg[%d0]: ",
5224					ncr_name(np),i/16);
5225				break;
5226			case 4:
5227			case 8:
5228			case 12:
5229				printf (" ");
5230				break;
5231			};
5232			val = ((unsigned char*) np->vaddr) [i];
5233			printf (" %x%x", val/16, val%16);
5234			if (i%16==15) printf (".\n");
5235		};
5236
5237		untimeout (TIMEOUT ncr_timeout, (caddr_t) np);
5238
5239		printf ("%s: halted!\n", ncr_name(np));
5240		/*
5241		**	don't restart controller ...
5242		*/
5243		OUTB (nc_istat,  SRST);
5244		return;
5245	};
5246
5247#ifdef NCR_FREEZE
5248	/*
5249	**	Freeze system to be able to read the messages.
5250	*/
5251	printf ("ncr: fatal error: system halted - press reset to reboot ...");
5252	(void) splhigh();
5253	for (;;);
5254#endif
5255
5256	/*
5257	**	sorry, have to kill ALL jobs ...
5258	*/
5259
5260	ncr_init (np, "fatal error", HS_FAIL);
5261}
5262
5263/*==========================================================
5264**
5265**	ncr chip exception handler for selection timeout
5266**
5267**==========================================================
5268**
5269**	There seems to be a bug in the 53c810.
5270**	Although a STO-Interrupt is pending,
5271**	it continues executing script commands.
5272**	But it will fail and interrupt (IID) on
5273**	the next instruction where it's looking
5274**	for a valid phase.
5275**
5276**----------------------------------------------------------
5277*/
5278
5279void ncr_int_sto (ncb_p np)
5280{
5281	u_long dsa, scratcha, diff;
5282	ccb_p cp;
5283	if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
5284
5285	/*
5286	**	look for ccb and set the status.
5287	*/
5288
5289	dsa = INL (nc_dsa);
5290	cp = &np->ccb;
5291	while (cp && (CCB_PHYS (cp, phys) != dsa))
5292		cp = cp->link_ccb;
5293
5294	if (cp) {
5295		cp-> host_status = HS_SEL_TIMEOUT;
5296		ncr_complete (np, cp);
5297	};
5298
5299	/*
5300	**	repair start queue
5301	*/
5302
5303	scratcha = INL (nc_scratcha);
5304	diff = scratcha - NCB_SCRIPT_PHYS (np, tryloop);
5305
5306/*	assert ((diff <= MAX_START * 20) && !(diff % 20));*/
5307
5308	if ((diff <= MAX_START * 20) && !(diff % 20)) {
5309		np->script->startpos[0] = scratcha;
5310		OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, start));
5311		return;
5312	};
5313	ncr_init (np, "selection timeout", HS_FAIL);
5314}
5315
5316/*==========================================================
5317**
5318**
5319**	ncr chip exception handler for phase errors.
5320**
5321**
5322**==========================================================
5323**
5324**	We have to construct a new transfer descriptor,
5325**	to transfer the rest of the current block.
5326**
5327**----------------------------------------------------------
5328*/
5329
5330static void ncr_int_ma (ncb_p np)
5331{
5332	u_long	dbc;
5333	u_long	rest;
5334	u_long	dsa;
5335	u_long	dsp;
5336	u_long	nxtdsp;
5337	u_long	*vdsp;
5338	u_long	oadr, olen;
5339	u_long	*tblp, *newcmd;
5340	u_char	cmd, sbcl, delta, ss0, ss2;
5341	ccb_p	cp;
5342
5343	dsp = INL (nc_dsp);
5344	dsa = INL (nc_dsa);
5345	dbc = INL (nc_dbc);
5346	ss0 = INB (nc_sstat0);
5347	ss2 = INB (nc_sstat2);
5348	sbcl= INB (nc_sbcl);
5349
5350	cmd = dbc >> 24;
5351	rest= dbc & 0xffffff;
5352	delta=(INB (nc_dfifo) - rest) & 0x7f;
5353
5354	/*
5355	**	The data in the dma fifo has not been transfered to
5356	**	the target -> add the amount to the rest
5357	**	and clear the data.
5358	**	Check the sstat2 register in case of wide transfer.
5359	*/
5360
5361	if (! (INB(nc_dstat) & DFE)) rest += delta;
5362	if (ss0 & OLF) rest++;
5363	if (ss0 & ORF) rest++;
5364	if (INB(nc_scntl3) & EWS) {
5365		if (ss2 & OLF1) rest++;
5366		if (ss2 & ORF1) rest++;
5367	};
5368	OUTB (nc_ctest3, CLF   );	/* clear dma fifo  */
5369	OUTB (nc_stest3, TE|CSF);	/* clear scsi fifo */
5370
5371	/*
5372	**	locate matching cp
5373	*/
5374	dsa = INL (nc_dsa);
5375	cp = &np->ccb;
5376	while (cp && (CCB_PHYS (cp, phys) != dsa))
5377		cp = cp->link_ccb;
5378
5379	if (!cp) {
5380	    printf ("%s: SCSI phase error fixup: CCB already dequeued (0x%08lx)\n",
5381		    ncr_name (np), (u_long) np->header.cp);
5382	    return;
5383	}
5384	if (cp != np->header.cp) {
5385	    printf ("%s: SCSI phase error fixup: CCB address mismatch (0x%08lx != 0x%08lx)\n",
5386		    ncr_name (np), (u_long) cp, (u_long) np->header.cp);
5387	    return;
5388	}
5389
5390	/*
5391	**	find the interrupted script command,
5392	**	and the address at which to continue.
5393	*/
5394
5395	if (dsp == vtophys (&cp->patch[2])) {
5396		vdsp = &cp->patch[0];
5397		nxtdsp = vdsp[3];
5398	} else if (dsp == vtophys (&cp->patch[6])) {
5399		vdsp = &cp->patch[4];
5400		nxtdsp = vdsp[3];
5401	} else {
5402		vdsp = (u_long*) ((char*)np->script - np->p_script + dsp -8);
5403		nxtdsp = dsp;
5404	};
5405
5406	/*
5407	**	log the information
5408	*/
5409	if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE)) {
5410		printf ("P%x%x ",cmd&7, sbcl&7);
5411		printf ("RL=%d D=%d SS0=%x ",
5412			(unsigned) rest, (unsigned) delta, ss0);
5413	};
5414	if (DEBUG_FLAGS & DEBUG_PHASE) {
5415		printf ("\nCP=%x CP2=%x DSP=%x NXT=%x VDSP=%x CMD=%x ",
5416			(unsigned)cp, (unsigned)np->header.cp,
5417			(unsigned)dsp,
5418			(unsigned)nxtdsp, (unsigned)vdsp, cmd);
5419	};
5420
5421	/*
5422	**	get old startaddress and old length.
5423	*/
5424
5425	oadr = vdsp[1];
5426
5427	if (cmd & 0x10) {	/* Table indirect */
5428		tblp = (u_long*) ((char*) &cp->phys + oadr);
5429		olen = tblp[0];
5430		oadr = tblp[1];
5431	} else {
5432		tblp = (u_long*) 0;
5433		olen = vdsp[0] & 0xffffff;
5434	};
5435
5436	if (DEBUG_FLAGS & DEBUG_PHASE) {
5437		printf ("OCMD=%x\nTBLP=%x OLEN=%x OADR=%x\n",
5438			(unsigned) (vdsp[0] >> 24),
5439			(unsigned) tblp,
5440			(unsigned) olen,
5441			(unsigned) oadr);
5442	};
5443
5444	/*
5445	**	if old phase not dataphase, leave here.
5446	*/
5447
5448	if (cmd != (vdsp[0] >> 24)) {
5449		PRINT_ADDR(cp->xfer);
5450		printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
5451			(unsigned)cmd, (unsigned)vdsp[0] >> 24);
5452
5453		return;
5454	}
5455	if (cmd & 0x06) {
5456		PRINT_ADDR(cp->xfer);
5457		printf ("phase change %x-%x %d@%08x resid=%d.\n",
5458			cmd&7, sbcl&7, (unsigned)olen,
5459			(unsigned)oadr, (unsigned)rest);
5460
5461		OUTB (nc_dcntl, (STD|NOCOM));
5462		return;
5463	};
5464
5465	/*
5466	**	choose the correct patch area.
5467	**	if savep points to one, choose the other.
5468	*/
5469
5470	newcmd = cp->patch;
5471	if (cp->phys.header.savep == vtophys (newcmd)) newcmd+=4;
5472
5473	/*
5474	**	fillin the commands
5475	*/
5476
5477	newcmd[0] = ((cmd & 0x0f) << 24) | rest;
5478	newcmd[1] = oadr + olen - rest;
5479	newcmd[2] = SCR_JUMP;
5480	newcmd[3] = nxtdsp;
5481
5482	if (DEBUG_FLAGS & DEBUG_PHASE) {
5483		PRINT_ADDR(cp->xfer);
5484		printf ("newcmd[%d] %x %x %x %x.\n",
5485			newcmd - cp->patch,
5486			(unsigned)newcmd[0],
5487			(unsigned)newcmd[1],
5488			(unsigned)newcmd[2],
5489			(unsigned)newcmd[3]);
5490	}
5491	/*
5492	**	fake the return address (to the patch).
5493	**	and restart script processor at dispatcher.
5494	*/
5495	np->profile.num_break++;
5496	OUTL (nc_temp, vtophys (newcmd));
5497	OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
5498}
5499
5500/*==========================================================
5501**
5502**
5503**      ncr chip exception handler for programmed interrupts.
5504**
5505**
5506**==========================================================
5507*/
5508
5509static int ncr_show_msg (u_char * msg)
5510{
5511	u_char i;
5512	printf ("%x",*msg);
5513	if (*msg==M_EXTENDED) {
5514		for (i=1;i<8;i++) {
5515			if (i-1>msg[1]) break;
5516			printf ("-%x",msg[i]);
5517		};
5518		return (i+1);
5519	} else if ((*msg & 0xf0) == 0x20) {
5520		printf ("-%x",msg[1]);
5521		return (2);
5522	};
5523	return (1);
5524}
5525
5526void ncr_int_sir (ncb_p np)
5527{
5528	u_char chg, ofs, per, fak, wide;
5529	u_char num = INB (nc_dsps);
5530	ccb_p	cp=0;
5531	u_long	dsa;
5532	u_char	target = INB (nc_ctest0) & 7;
5533	tcb_p	tp     = &np->target[target];
5534	int     i;
5535	if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
5536
5537	switch (num) {
5538	case SIR_SENSE_RESTART:
5539	case SIR_STALL_RESTART:
5540		break;
5541
5542	default:
5543		/*
5544		**	lookup the ccb
5545		*/
5546		dsa = INL (nc_dsa);
5547		cp = &np->ccb;
5548		while (cp && (CCB_PHYS (cp, phys) != dsa))
5549			cp = cp->link_ccb;
5550
5551		assert (cp);
5552		if (!cp)
5553			goto out;
5554		assert (cp == np->header.cp);
5555		if (cp != np->header.cp)
5556			goto out;
5557	}
5558
5559	switch (num) {
5560
5561/*--------------------------------------------------------------------
5562**
5563**	Processing of interrupted getcc selects
5564**
5565**--------------------------------------------------------------------
5566*/
5567
5568	case SIR_SENSE_RESTART:
5569		/*------------------------------------------
5570		**	Script processor is idle.
5571		**	Look for interrupted "check cond"
5572		**------------------------------------------
5573		*/
5574
5575		if (DEBUG_FLAGS & DEBUG_RESTART)
5576			printf ("%s: int#%d",ncr_name (np),num);
5577		cp = (ccb_p) 0;
5578		for (i=0; i<MAX_TARGET; i++) {
5579			if (DEBUG_FLAGS & DEBUG_RESTART) printf (" t%d", i);
5580			tp = &np->target[i];
5581			if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5582			cp = tp->hold_cp;
5583			if (!cp) continue;
5584			if (DEBUG_FLAGS & DEBUG_RESTART) printf ("+");
5585			if ((cp->host_status==HS_BUSY) &&
5586				(cp->scsi_status==S_CHECK_COND))
5587				break;
5588			if (DEBUG_FLAGS & DEBUG_RESTART) printf ("- (remove)");
5589			tp->hold_cp = cp = (ccb_p) 0;
5590		};
5591
5592		if (cp) {
5593			if (DEBUG_FLAGS & DEBUG_RESTART)
5594				printf ("+ restart job ..\n");
5595			OUTL (nc_dsa, CCB_PHYS (cp, phys));
5596			OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, getcc));
5597			return;
5598		};
5599
5600		/*
5601		**	no job, resume normal processing
5602		*/
5603		if (DEBUG_FLAGS & DEBUG_RESTART) printf (" -- remove trap\n");
5604		np->script->start0[0] =  SCR_INT ^ IFFALSE (0);
5605		break;
5606
5607	case SIR_SENSE_FAILED:
5608		/*-------------------------------------------
5609		**	While trying to select for
5610		**	getting the condition code,
5611		**	a target reselected us.
5612		**-------------------------------------------
5613		*/
5614		if (DEBUG_FLAGS & DEBUG_RESTART) {
5615			PRINT_ADDR(cp->xfer);
5616			printf ("in getcc reselect by t%d.\n",
5617				INB(nc_ssid) & 0x0f);
5618		}
5619
5620		/*
5621		**	Mark this job
5622		*/
5623		cp->host_status = HS_BUSY;
5624		cp->scsi_status = S_CHECK_COND;
5625		np->target[cp->xfer->sc_link->target].hold_cp = cp;
5626
5627		/*
5628		**	And patch code to restart it.
5629		*/
5630		np->script->start0[0] =  SCR_INT;
5631		break;
5632
5633/*-----------------------------------------------------------------------------
5634**
5635**	Was Sie schon immer ueber transfermode negotiation wissen wollten ...
5636**
5637**	We try to negotiate sync and wide transfer only after
5638**	a successfull inquire command. We look at byte 7 of the
5639**	inquire data to determine the capabilities if the target.
5640**
5641**	When we try to negotiate, we append the negotiation message
5642**	to the identify and (maybe) simple tag message.
5643**	The host status field is set to HS_NEGOTIATE to mark this
5644**	situation.
5645**
5646**	If the target doesn't answer this message immidiately
5647**	(as required by the standard), the SIR_NEGO_FAIL interrupt
5648**	will be raised eventually.
5649**	The handler removes the HS_NEGOTIATE status, and sets the
5650**	negotiated value to the default (async / nowide).
5651**
5652**	If we receive a matching answer immediately, we check it
5653**	for validity, and set the values.
5654**
5655**	If we receive a Reject message immediately, we assume the
5656**	negotiation has failed, and fall back to standard values.
5657**
5658**	If we receive a negotiation message while not in HS_NEGOTIATE
5659**	state, it's a target initiated negotiation. We prepare a
5660**	(hopefully) valid answer, set our parameters, and send back
5661**	this answer to the target.
5662**
5663**	If the target doesn't fetch the answer (no message out phase),
5664**	we assume the negotiation has failed, and fall back to default
5665**	settings.
5666**
5667**	When we set the values, we adjust them in all ccbs belonging
5668**	to this target, in the controller's register, and in the "phys"
5669**	field of the controller's struct ncb.
5670**
5671**	Possible cases:		   hs  sir   msg_in value  send   goto
5672**	We try try to negotiate:
5673**	-> target doesnt't msgin   NEG FAIL  noop   defa.  -      dispatch
5674**	-> target rejected our msg NEG FAIL  reject defa.  -      dispatch
5675**	-> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
5676**	-> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
5677**	-> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
5678**	-> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
5679**	-> any other msgin	   NEG FAIL  noop   defa.  -      dispatch
5680**
5681**	Target tries to negotiate:
5682**	-> incoming message	   --- SYNC  sdtr   set    SDTR   -
5683**	-> incoming message	   --- WIDE  wdtr   set    WDTR   -
5684**      We sent our answer:
5685**	-> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
5686**
5687**-----------------------------------------------------------------------------
5688*/
5689
5690	case SIR_NEGO_FAILED:
5691		/*-------------------------------------------------------
5692		**
5693		**	Negotiation failed.
5694		**	Target doesn't send an answer message,
5695		**	or target rejected our message.
5696		**
5697		**      Remove negotiation request.
5698		**
5699		**-------------------------------------------------------
5700		*/
5701		OUTB (HS_PRT, HS_BUSY);
5702
5703		/* fall through */
5704
5705	case SIR_NEGO_PROTO:
5706		/*-------------------------------------------------------
5707		**
5708		**	Negotiation failed.
5709		**	Target doesn't fetch the answer message.
5710		**
5711		**-------------------------------------------------------
5712		*/
5713
5714		if (DEBUG_FLAGS & DEBUG_NEGO) {
5715			PRINT_ADDR(cp->xfer);
5716			printf ("negotiation failed sir=%x status=%x.\n",
5717				num, cp->nego_status);
5718		};
5719
5720		/*
5721		**	any error in negotiation:
5722		**	fall back to default mode.
5723		*/
5724		switch (cp->nego_status) {
5725
5726		case NS_SYNC:
5727			ncr_setsync (np, cp, 0xe0);
5728			break;
5729
5730		case NS_WIDE:
5731			ncr_setwide (np, cp, 0);
5732			break;
5733
5734		};
5735		np->msgin [0] = M_NOOP;
5736		np->msgout[0] = M_NOOP;
5737		cp->nego_status = 0;
5738		OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, dispatch));
5739		break;
5740
5741	case SIR_NEGO_SYNC:
5742		/*
5743		**	Synchronous request message received.
5744		*/
5745
5746		if (DEBUG_FLAGS & DEBUG_NEGO) {
5747			PRINT_ADDR(cp->xfer);
5748			printf ("sync msgin: ");
5749			(void) ncr_show_msg (np->msgin);
5750			printf (".\n");
5751		};
5752
5753		/*
5754		**	get requested values.
5755		*/
5756
5757		chg = 0;
5758		per = np->msgin[3];
5759		ofs = np->msgin[4];
5760		if (ofs==0) per=255;
5761
5762		/*
5763		**      if target sends SDTR message,
5764		**	      it CAN transfer synch.
5765		*/
5766
5767		if (ofs)
5768			tp->inqdata[7] |= INQ7_SYNC;
5769
5770		/*
5771		**	check values against driver limits.
5772		*/
5773
5774		if (per < np->ns_sync)
5775			{chg = 1; per = np->ns_sync;}
5776		if (per < tp->minsync)
5777			{chg = 1; per = tp->minsync;}
5778		if (ofs > tp->maxoffs)
5779			{chg = 1; ofs = tp->maxoffs;}
5780
5781		/*
5782		**	Check against controller limits.
5783		*/
5784		fak = (4ul * per - 1) / np->ns_sync - 3;
5785		if (ofs && (fak>7))   {chg = 1; ofs = 0;}
5786		if (!ofs) fak=7;
5787
5788		if (DEBUG_FLAGS & DEBUG_NEGO) {
5789			PRINT_ADDR(cp->xfer);
5790			printf ("sync: per=%d ofs=%d fak=%d chg=%d.\n",
5791				per, ofs, fak, chg);
5792		}
5793
5794		if (INB (HS_PRT) == HS_NEGOTIATE) {
5795			OUTB (HS_PRT, HS_BUSY);
5796			switch (cp->nego_status) {
5797
5798			case NS_SYNC:
5799				/*
5800				**      This was an answer message
5801				*/
5802				if (chg) {
5803					/*
5804					**	Answer wasn't acceptable.
5805					*/
5806					ncr_setsync (np, cp, 0xe0);
5807					OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
5808				} else {
5809					/*
5810					**	Answer is ok.
5811					*/
5812					ncr_setsync (np, cp, (fak<<5)|ofs);
5813					OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
5814				};
5815				return;
5816
5817			case NS_WIDE:
5818				ncr_setwide (np, cp, 0);
5819				break;
5820			};
5821		};
5822
5823		/*
5824		**	It was a request. Set value and
5825		**      prepare an answer message
5826		*/
5827
5828		ncr_setsync (np, cp, (fak<<5)|ofs);
5829
5830		np->msgout[0] = M_EXTENDED;
5831		np->msgout[1] = 3;
5832		np->msgout[2] = M_X_SYNC_REQ;
5833		np->msgout[3] = per;
5834		np->msgout[4] = ofs;
5835
5836		cp->nego_status = NS_SYNC;
5837
5838		if (DEBUG_FLAGS & DEBUG_NEGO) {
5839			PRINT_ADDR(cp->xfer);
5840			printf ("sync msgout: ");
5841			(void) ncr_show_msg (np->msgin);
5842			printf (".\n");
5843		}
5844
5845		if (!ofs) {
5846			OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
5847			return;
5848		}
5849		np->msgin [0] = M_NOOP;
5850
5851		break;
5852
5853	case SIR_NEGO_WIDE:
5854		/*
5855		**	Wide request message received.
5856		*/
5857		if (DEBUG_FLAGS & DEBUG_NEGO) {
5858			PRINT_ADDR(cp->xfer);
5859			printf ("wide msgin: ");
5860			(void) ncr_show_msg (np->msgin);
5861			printf (".\n");
5862		};
5863
5864		/*
5865		**	get requested values.
5866		*/
5867
5868		chg  = 0;
5869		wide = np->msgin[3];
5870
5871		/*
5872		**      if target sends WDTR message,
5873		**	      it CAN transfer wide.
5874		*/
5875
5876		if (wide)
5877			tp->inqdata[7] |= INQ7_WIDE16;
5878
5879		/*
5880		**	check values against driver limits.
5881		*/
5882
5883		if (wide > tp->usrwide)
5884			{chg = 1; wide = tp->usrwide;}
5885
5886		if (DEBUG_FLAGS & DEBUG_NEGO) {
5887			PRINT_ADDR(cp->xfer);
5888			printf ("wide: wide=%d chg=%d.\n", wide, chg);
5889		}
5890
5891		if (INB (HS_PRT) == HS_NEGOTIATE) {
5892			OUTB (HS_PRT, HS_BUSY);
5893			switch (cp->nego_status) {
5894
5895			case NS_WIDE:
5896				/*
5897				**      This was an answer message
5898				*/
5899				if (chg) {
5900					/*
5901					**	Answer wasn't acceptable.
5902					*/
5903					ncr_setwide (np, cp, 0);
5904					OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, msg_bad));
5905				} else {
5906					/*
5907					**	Answer is ok.
5908					*/
5909					ncr_setwide (np, cp, wide);
5910					OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, clrack));
5911				};
5912				return;
5913
5914			case NS_SYNC:
5915				ncr_setsync (np, cp, 0xe0);
5916				break;
5917			};
5918		};
5919
5920		/*
5921		**	It was a request, set value and
5922		**      prepare an answer message
5923		*/
5924
5925		ncr_setwide (np, cp, wide);
5926
5927		np->msgout[0] = M_EXTENDED;
5928		np->msgout[1] = 2;
5929		np->msgout[2] = M_X_WIDE_REQ;
5930		np->msgout[3] = wide;
5931
5932		np->msgin [0] = M_NOOP;
5933
5934		cp->nego_status = NS_WIDE;
5935
5936		if (DEBUG_FLAGS & DEBUG_NEGO) {
5937			PRINT_ADDR(cp->xfer);
5938			printf ("wide msgout: ");
5939			(void) ncr_show_msg (np->msgin);
5940			printf (".\n");
5941		}
5942		break;
5943
5944/*--------------------------------------------------------------------
5945**
5946**	Processing of special messages
5947**
5948**--------------------------------------------------------------------
5949*/
5950
5951	case SIR_REJECT_RECEIVED:
5952		/*-----------------------------------------------
5953		**
5954		**	We received a M_REJECT message.
5955		**
5956		**-----------------------------------------------
5957		*/
5958
5959		PRINT_ADDR(cp->xfer);
5960		printf ("M_REJECT received (%x:%x).\n",
5961			(unsigned)np->lastmsg, np->msgout[0]);
5962		break;
5963
5964	case SIR_REJECT_SENT:
5965		/*-----------------------------------------------
5966		**
5967		**	We received an unknown message
5968		**
5969		**-----------------------------------------------
5970		*/
5971
5972		PRINT_ADDR(cp->xfer);
5973		printf ("M_REJECT sent for ");
5974		(void) ncr_show_msg (np->msgin);
5975		printf (".\n");
5976		break;
5977
5978/*--------------------------------------------------------------------
5979**
5980**	Processing of special messages
5981**
5982**--------------------------------------------------------------------
5983*/
5984
5985	case SIR_IGN_RESIDUE:
5986		/*-----------------------------------------------
5987		**
5988		**	We received an IGNORE RESIDUE message,
5989		**	which couldn't be handled by the script.
5990		**
5991		**-----------------------------------------------
5992		*/
5993
5994		PRINT_ADDR(cp->xfer);
5995		printf ("M_IGN_RESIDUE received, but not yet implemented.\n");
5996		break;
5997
5998	case SIR_MISSING_SAVE:
5999		/*-----------------------------------------------
6000		**
6001		**	We received an DISCONNECT message,
6002		**	but the datapointer wasn't saved before.
6003		**
6004		**-----------------------------------------------
6005		*/
6006
6007		PRINT_ADDR(cp->xfer);
6008		printf ("M_DISCONNECT received, but datapointer not saved:\n"
6009			"\tdata=%x save=%x goal=%x.\n",
6010			(unsigned) INL (nc_temp),
6011			(unsigned) np->header.savep,
6012			(unsigned) np->header.goalp);
6013		break;
6014
6015/*--------------------------------------------------------------------
6016**
6017**	Processing of a "S_QUEUE_FULL" status.
6018**
6019**	The current command has been rejected,
6020**	because there are too many in the command queue.
6021**	We have started too many commands for that target.
6022**
6023**	If possible, reinsert at head of queue.
6024**	Stall queue until there are no disconnected jobs
6025**	(ncr is REALLY idle). Then restart processing.
6026**
6027**	We should restart the current job after the controller
6028**	has become idle. But this is not yet implemented.
6029**
6030**--------------------------------------------------------------------
6031*/
6032	case SIR_STALL_QUEUE:
6033		/*-----------------------------------------------
6034		**
6035		**	Stall the start queue.
6036		**
6037		**-----------------------------------------------
6038		*/
6039		PRINT_ADDR(cp->xfer);
6040		printf ("queue full.\n");
6041
6042		np->script->start1[0] =  SCR_INT;
6043
6044		/*
6045		**	Try to disable tagged transfers.
6046		*/
6047		ncr_setmaxtags (&np->target[target], 0);
6048
6049		/*
6050		** @QUEUE@
6051		**
6052		**	Should update the launch field of the
6053		**	current job to be able to restart it.
6054		**	Then prepend it to the start queue.
6055		*/
6056
6057		/* fall through */
6058
6059	case SIR_STALL_RESTART:
6060		/*-----------------------------------------------
6061		**
6062		**	Enable selecting again,
6063		**	if NO disconnected jobs.
6064		**
6065		**-----------------------------------------------
6066		*/
6067		/*
6068		**	Look for a disconnected job.
6069		*/
6070		cp = &np->ccb;
6071		while (cp && cp->host_status != HS_DISCONNECT)
6072			cp = cp->link_ccb;
6073
6074		/*
6075		**	if there is one, ...
6076		*/
6077		if (cp) {
6078			/*
6079			**	wait for reselection
6080			*/
6081			OUTL (nc_dsp, NCB_SCRIPT_PHYS (np, reselect));
6082			return;
6083		};
6084
6085		/*
6086		**	else remove the interrupt.
6087		*/
6088
6089		printf ("%s: queue empty.\n", ncr_name (np));
6090		np->script->start1[0] =  SCR_INT ^ IFFALSE (0);
6091		break;
6092	};
6093
6094out:
6095	OUTB (nc_dcntl, (STD|NOCOM));
6096}
6097
6098/*==========================================================
6099**
6100**
6101**	Aquire a control block
6102**
6103**
6104**==========================================================
6105*/
6106
6107static	ccb_p ncr_get_ccb
6108	(ncb_p np, u_long flags, u_long target, u_long lun)
6109{
6110	lcb_p lp;
6111	ccb_p cp = (ccb_p) 0;
6112
6113	/*
6114	**	Lun structure available ?
6115	*/
6116
6117	lp = np->target[target].lp[lun];
6118	if (lp) {
6119		cp = lp->next_ccb;
6120
6121		/*
6122		**	Look for free CCB
6123		*/
6124
6125		while (cp && cp->magic) cp = cp->next_ccb;
6126	}
6127
6128	/*
6129	**	if nothing available, take the default.
6130	*/
6131
6132	if (!cp) cp = &np->ccb;
6133
6134	/*
6135	**	Wait until available.
6136	*/
6137
6138	while (cp->magic) {
6139		if (flags & SCSI_NOSLEEP) break;
6140		if (tsleep ((caddr_t)cp, PRIBIO|PCATCH, "ncr", 0))
6141			break;
6142	};
6143
6144	if (cp->magic)
6145		return ((ccb_p) 0);
6146
6147	cp->magic = 1;
6148	return (cp);
6149}
6150
6151/*==========================================================
6152**
6153**
6154**	Release one control block
6155**
6156**
6157**==========================================================
6158*/
6159
6160void ncr_free_ccb (ncb_p np, ccb_p cp, int flags)
6161{
6162	/*
6163	**    sanity
6164	*/
6165
6166	assert (cp != NULL);
6167
6168	cp -> host_status = HS_IDLE;
6169	cp -> magic = 0;
6170	if (cp == &np->ccb)
6171		wakeup ((caddr_t) cp);
6172}
6173
6174/*==========================================================
6175**
6176**
6177**      Allocation of resources for Targets/Luns/Tags.
6178**
6179**
6180**==========================================================
6181*/
6182
6183static	void ncr_alloc_ccb (ncb_p np, struct scsi_xfer * xp)
6184{
6185	tcb_p tp;
6186	lcb_p lp;
6187	ccb_p cp;
6188
6189	u_long	target;
6190	u_long	lun;
6191
6192	assert (np != NULL);
6193	assert (xp != NULL);
6194
6195	target = xp->sc_link->target;
6196	lun    = xp->sc_link->lun;
6197
6198	if (target>=MAX_TARGET) return;
6199	if (lun   >=MAX_LUN   ) return;
6200
6201	tp=&np->target[target];
6202
6203	if (!tp->jump_tcb.l_cmd) {
6204
6205		/*
6206		**	initialize it.
6207		*/
6208		tp->jump_tcb.l_cmd   = (SCR_JUMP^IFFALSE (DATA (0x80 + target)));
6209		tp->jump_tcb.l_paddr = np->jump_tcb.l_paddr;
6210
6211		tp->getscr[0] = SCR_COPY (1);
6212		tp->getscr[1] = vtophys (&tp->sval);
6213		tp->getscr[2] = np->paddr + offsetof (struct ncr_reg, nc_sxfer);
6214		tp->getscr[3] = SCR_COPY (1);
6215		tp->getscr[4] = vtophys (&tp->wval);
6216		tp->getscr[5] = np->paddr + offsetof (struct ncr_reg, nc_scntl3);
6217
6218		assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
6219			offsetof(struct tcb    , sval    )) &3) == 0);
6220		assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
6221			offsetof(struct tcb    , wval    )) &3) == 0);
6222
6223		tp->call_lun.l_cmd   = (SCR_CALL);
6224		tp->call_lun.l_paddr = NCB_SCRIPT_PHYS (np, resel_lun);
6225
6226		tp->jump_lcb.l_cmd   = (SCR_JUMP);
6227		tp->jump_lcb.l_paddr = NCB_SCRIPT_PHYS (np, abort);
6228		np->jump_tcb.l_paddr = vtophys (&tp->jump_tcb);
6229
6230		ncr_setmaxtags (tp, SCSI_NCR_MAX_TAGS);
6231	}
6232
6233	/*
6234	**	Logic unit control block
6235	*/
6236	lp = tp->lp[lun];
6237	if (!lp) {
6238		/*
6239		**	Allocate a lcb
6240		*/
6241		lp = (lcb_p) malloc (sizeof (struct lcb), M_DEVBUF, M_NOWAIT);
6242		if (!lp) return;
6243
6244		/*
6245		**	Initialize it
6246		*/
6247		bzero (lp, sizeof (*lp));
6248		lp->jump_lcb.l_cmd   = (SCR_JUMP ^ IFFALSE (DATA (lun)));
6249		lp->jump_lcb.l_paddr = tp->jump_lcb.l_paddr;
6250
6251		lp->call_tag.l_cmd   = (SCR_CALL);
6252		lp->call_tag.l_paddr = NCB_SCRIPT_PHYS (np, resel_tag);
6253
6254		lp->jump_ccb.l_cmd   = (SCR_JUMP);
6255		lp->jump_ccb.l_paddr = NCB_SCRIPT_PHYS (np, aborttag);
6256
6257		lp->actlink = 1;
6258
6259		/*
6260		**   Chain into LUN list
6261		*/
6262		tp->jump_lcb.l_paddr = vtophys (&lp->jump_lcb);
6263		tp->lp[lun] = lp;
6264
6265	}
6266
6267	/*
6268	**	Limit possible number of ccbs.
6269	**
6270	**	If tagged command queueing is enabled,
6271	**	can use more than one ccb.
6272	*/
6273
6274	if (np->actccbs >= MAX_START-2) return;
6275	if (lp->actccbs && (lp->actccbs >= lp->reqccbs))
6276		return;
6277
6278	/*
6279	**	Allocate a ccb
6280	*/
6281	cp = (ccb_p) malloc (sizeof (struct ccb), M_DEVBUF, M_NOWAIT);
6282
6283	if (!cp)
6284		return;
6285
6286	if (DEBUG_FLAGS & DEBUG_ALLOC) {
6287		PRINT_ADDR(xp);
6288		printf ("new ccb @%x.\n", (unsigned) cp);
6289	}
6290
6291	/*
6292	**	Count it
6293	*/
6294	lp->actccbs++;
6295	np->actccbs++;
6296
6297	/*
6298	**	Initialize it
6299	*/
6300	bzero (cp, sizeof (*cp));
6301
6302	/*
6303	**	Fill in physical addresses
6304	*/
6305
6306	cp->p_ccb	     = vtophys (cp);
6307
6308	/*
6309	**	Chain into reselect list
6310	*/
6311	cp->jump_ccb.l_cmd   = SCR_JUMP;
6312	cp->jump_ccb.l_paddr = lp->jump_ccb.l_paddr;
6313	lp->jump_ccb.l_paddr = CCB_PHYS (cp, jump_ccb);
6314	cp->call_tmp.l_cmd   = SCR_CALL;
6315	cp->call_tmp.l_paddr = NCB_SCRIPT_PHYS (np, resel_tmp);
6316
6317	/*
6318	**	Chain into wakeup list
6319	*/
6320	cp->link_ccb      = np->ccb.link_ccb;
6321	np->ccb.link_ccb  = cp;
6322
6323	/*
6324	**	Chain into CCB list
6325	*/
6326	cp->next_ccb	= lp->next_ccb;
6327	lp->next_ccb	= cp;
6328}
6329
6330/*==========================================================
6331**
6332**
6333**	Announce the number of ccbs/tags to the scsi driver.
6334**
6335**
6336**==========================================================
6337*/
6338
6339static void ncr_opennings (ncb_p np, lcb_p lp, struct scsi_xfer * xp)
6340{
6341	/*
6342	**	want to reduce the number ...
6343	*/
6344	if (lp->actlink > lp->reqlink) {
6345
6346		/*
6347		**	Try to  reduce the count.
6348		**	We assume to run at splbio ..
6349		*/
6350		u_char diff = lp->actlink - lp->reqlink;
6351
6352		if (!diff) return;
6353
6354#ifdef __NetBSD__
6355		if (diff > xp->sc_link->openings)
6356			diff = xp->sc_link->openings;
6357
6358		xp->sc_link->openings	-= diff;
6359#else /* !__NetBSD__ */
6360		if (diff > xp->sc_link->opennings)
6361			diff = xp->sc_link->opennings;
6362
6363		xp->sc_link->opennings	-= diff;
6364#endif /* __NetBSD__ */
6365		lp->actlink		-= diff;
6366		if (DEBUG_FLAGS & DEBUG_TAGS)
6367			printf ("%s: actlink: diff=%d, new=%d, req=%d\n",
6368				ncr_name(np), diff, lp->actlink, lp->reqlink);
6369		return;
6370	};
6371
6372	/*
6373	**	want to increase the number ?
6374	*/
6375	if (lp->reqlink > lp->actlink) {
6376		u_char diff = lp->reqlink - lp->actlink;
6377
6378#ifdef __NetBSD__
6379		xp->sc_link->openings	+= diff;
6380#else /* !__NetBSD__ */
6381		xp->sc_link->opennings	+= diff;
6382#endif /* __NetBSD__ */
6383		lp->actlink		+= diff;
6384		wakeup ((caddr_t) xp->sc_link);
6385		if (DEBUG_FLAGS & DEBUG_TAGS)
6386			printf ("%s: actlink: diff=%d, new=%d, req=%d\n",
6387				ncr_name(np), diff, lp->actlink, lp->reqlink);
6388	};
6389}
6390
6391/*==========================================================
6392**
6393**
6394**	Build Scatter Gather Block
6395**
6396**
6397**==========================================================
6398**
6399**	The transfer area may be scattered among
6400**	several non adjacent physical pages.
6401**
6402**	We may use MAX_SCATTER blocks.
6403**
6404**----------------------------------------------------------
6405*/
6406
6407static	int	ncr_scatter
6408	(struct dsb* phys, vm_offset_t vaddr, vm_size_t datalen)
6409{
6410	u_long	paddr, pnext;
6411
6412	u_short	segment  = 0;
6413	u_long	segsize, segaddr;
6414	u_long	size, csize    = 0;
6415	u_long	chunk = MAX_SIZE;
6416	int	free;
6417
6418	bzero (&phys->data, sizeof (phys->data));
6419	if (!datalen) return (0);
6420
6421	paddr = vtophys (vaddr);
6422
6423	/*
6424	**	insert extra break points at a distance of chunk.
6425	**	We try to reduce the number of interrupts caused
6426	**	by unexpected phase changes due to disconnects.
6427	**	A typical harddisk may disconnect before ANY block.
6428	**	If we wanted to avoid unexpected phase changes at all
6429	**	we had to use a break point every 512 bytes.
6430	**	Of course the number of scatter/gather blocks is
6431	**	limited.
6432	*/
6433
6434	free = MAX_SCATTER - 1;
6435
6436	if (vaddr & (NBPG-1)) free -= datalen / NBPG;
6437
6438	if (free>1)
6439		while ((chunk * free >= 2 * datalen) && (chunk>=1024))
6440			chunk /= 2;
6441
6442	if(DEBUG_FLAGS & DEBUG_SCATTER)
6443		printf("ncr?:\tscattering virtual=0x%x size=%d chunk=%d.\n",
6444			(unsigned) vaddr, (unsigned) datalen, (unsigned) chunk);
6445
6446	/*
6447	**   Build data descriptors.
6448	*/
6449	while (datalen && (segment < MAX_SCATTER)) {
6450
6451		/*
6452		**	this segment is empty
6453		*/
6454		segsize = 0;
6455		segaddr = paddr;
6456		pnext   = paddr;
6457
6458		if (!csize) csize = chunk;
6459
6460		while ((datalen) && (paddr == pnext) && (csize)) {
6461
6462			/*
6463			**	continue this segment
6464			*/
6465			pnext = (paddr & (~(NBPG - 1))) + NBPG;
6466
6467			/*
6468			**	Compute max size
6469			*/
6470
6471			size = pnext - paddr;		/* page size */
6472			if (size > datalen) size = datalen;  /* data size */
6473			if (size > csize  ) size = csize  ;  /* chunksize */
6474
6475			segsize += size;
6476			vaddr   += size;
6477			csize   -= size;
6478			datalen -= size;
6479			paddr    = vtophys (vaddr);
6480		};
6481
6482		if(DEBUG_FLAGS & DEBUG_SCATTER)
6483			printf ("\tseg #%d  addr=%x  size=%d  (rest=%d).\n",
6484			segment,
6485			(unsigned) segaddr,
6486			(unsigned) segsize,
6487			(unsigned) datalen);
6488
6489		phys->data[segment].addr = segaddr;
6490		phys->data[segment].size = segsize;
6491		segment++;
6492	}
6493
6494	if (datalen) {
6495		printf("ncr?: scatter/gather failed (residue=%d).\n",
6496			(unsigned) datalen);
6497		return (-1);
6498	};
6499
6500	return (segment);
6501}
6502
6503/*==========================================================
6504**
6505**
6506**	Test the pci bus snoop logic :-(
6507**
6508**	Has to be called with interrupts disabled.
6509**
6510**
6511**==========================================================
6512*/
6513
6514#ifndef NCR_IOMAPPED
6515static int ncr_regtest (struct ncb* np)
6516{
6517	register volatile u_long data, *addr;
6518	/*
6519	**	ncr registers may NOT be cached.
6520	**	write 0xffffffff to a read only register area,
6521	**	and try to read it back.
6522	*/
6523	addr = (u_long*) &np->reg->nc_dstat;
6524	data = 0xffffffff;
6525	*addr= data;
6526	data = *addr;
6527#if 1
6528	if (data == 0xffffffff) {
6529#else
6530	if ((data & 0xe2f0fffd) != 0x02000080) {
6531#endif
6532		printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
6533			(unsigned) data);
6534		return (0x10);
6535	};
6536	return (0);
6537}
6538#endif
6539
6540static int ncr_snooptest (struct ncb* np)
6541{
6542	u_long	ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc, err=0;
6543	int	i;
6544#ifndef NCR_IOMAPPED
6545	err |= ncr_regtest (np);
6546	if (err) return (err);
6547#endif
6548	/*
6549	**	init
6550	*/
6551	pc  = NCB_SCRIPT_PHYS (np, snooptest);
6552	host_wr = 1;
6553	ncr_wr  = 2;
6554	/*
6555	**	Set memory and register.
6556	*/
6557	ncr_cache = host_wr;
6558	OUTL (nc_temp, ncr_wr);
6559	/*
6560	**	Start script (exchange values)
6561	*/
6562	OUTL (nc_dsp, pc);
6563	/*
6564	**	Wait 'til done (with timeout)
6565	*/
6566	for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
6567		if (INB(nc_istat) & (INTF|SIP|DIP))
6568			break;
6569	/*
6570	**	Save termination position.
6571	*/
6572	pc = INL (nc_dsp);
6573	/*
6574	**	Read memory and register.
6575	*/
6576	host_rd = ncr_cache;
6577	ncr_rd  = INL (nc_scratcha);
6578	ncr_bk  = INL (nc_temp);
6579	/*
6580	**	Reset ncr chip
6581	*/
6582	OUTB (nc_istat,  SRST);
6583	DELAY (1000);
6584	OUTB (nc_istat,  0   );
6585	/*
6586	**	check for timeout
6587	*/
6588	if (i>=NCR_SNOOP_TIMEOUT) {
6589		printf ("CACHE TEST FAILED: timeout.\n");
6590		return (0x20);
6591	};
6592	/*
6593	**	Check termination position.
6594	*/
6595	if (pc != NCB_SCRIPT_PHYS (np, snoopend)+8) {
6596		printf ("CACHE TEST FAILED: script execution failed.\n");
6597		return (0x40);
6598	};
6599	/*
6600	**	Show results.
6601	*/
6602	if (host_wr != ncr_rd) {
6603		printf ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
6604			(int) host_wr, (int) ncr_rd);
6605		err |= 1;
6606	};
6607	if (host_rd != ncr_wr) {
6608		printf ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
6609			(int) ncr_wr, (int) host_rd);
6610		err |= 2;
6611	};
6612	if (ncr_bk != ncr_wr) {
6613		printf ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
6614			(int) ncr_wr, (int) ncr_bk);
6615		err |= 4;
6616	};
6617	return (err);
6618}
6619
6620/*==========================================================
6621**
6622**
6623**	Profiling the drivers and targets performance.
6624**
6625**
6626**==========================================================
6627*/
6628
6629/*
6630**	Compute the difference in milliseconds.
6631**/
6632
6633static	int ncr_delta (struct timeval * from, struct timeval * to)
6634{
6635	if (!from->tv_sec) return (-1);
6636	if (!to  ->tv_sec) return (-2);
6637	return ( (to->tv_sec  - from->tv_sec  -       2)*1000+
6638		+(to->tv_usec - from->tv_usec + 2000000)/1000);
6639}
6640
6641#define PROFILE  cp->phys.header.stamp
6642static	void ncb_profile (ncb_p np, ccb_p cp)
6643{
6644	int co, da, st, en, di, se, post,work,disc;
6645	u_long diff;
6646
6647	PROFILE.end = time;
6648
6649	st = ncr_delta (&PROFILE.start,&PROFILE.status);
6650	if (st<0) return;	/* status  not reached  */
6651
6652	da = ncr_delta (&PROFILE.start,&PROFILE.data);
6653	if (da<0) return;	/* No data transfer phase */
6654
6655	co = ncr_delta (&PROFILE.start,&PROFILE.command);
6656	if (co<0) return;	/* command not executed */
6657
6658	en = ncr_delta (&PROFILE.start,&PROFILE.end),
6659	di = ncr_delta (&PROFILE.start,&PROFILE.disconnect),
6660	se = ncr_delta (&PROFILE.start,&PROFILE.select);
6661	post = en - st;
6662
6663	/*
6664	**	@PROFILE@  Disconnect time invalid if multiple disconnects
6665	*/
6666
6667	if (di>=0) disc = se-di; else  disc = 0;
6668
6669	work = (st - co) - disc;
6670
6671	diff = (np->disc_phys - np->disc_ref) & 0xff;
6672	np->disc_ref += diff;
6673
6674	np->profile.num_trans	+= 1;
6675	if (cp->xfer)
6676	np->profile.num_bytes	+= cp->xfer->datalen;
6677	np->profile.num_disc	+= diff;
6678	np->profile.ms_setup	+= co;
6679	np->profile.ms_data	+= work;
6680	np->profile.ms_disc	+= disc;
6681	np->profile.ms_post	+= post;
6682}
6683#undef PROFILE
6684
6685/*==========================================================
6686**
6687**
6688**	Device lookup.
6689**
6690**	@GENSCSI@ should be integrated to scsiconf.c
6691**
6692**
6693**==========================================================
6694*/
6695
6696#ifndef NEW_SCSICONF
6697
6698struct table_entry {
6699	char *	manufacturer;
6700	char *	model;
6701	char *	version;
6702	u_long	info;
6703};
6704
6705static struct table_entry device_tab[] =
6706{
6707#ifdef NCR_GETCC_WITHMSG
6708	{"", "", "", QUIRK_NOMSG},
6709	{"SONY", "SDT-5000", "3.17", QUIRK_NOMSG},
6710	{"WangDAT", "Model 2600", "01.7", QUIRK_NOMSG},
6711	{"WangDAT", "Model 3200", "02.2", QUIRK_NOMSG},
6712	{"WangDAT", "Model 1300", "02.4", QUIRK_NOMSG},
6713#endif
6714	{"", "", "", 0} /* catch all: must be last entry. */
6715};
6716
6717static u_long ncr_lookup(char * id)
6718{
6719	struct table_entry * p = device_tab;
6720	char *d, *r, c;
6721
6722	for (;;p++) {
6723
6724		d = id+8;
6725		r = p->manufacturer;
6726		while ((c=*r++)) if (c!=*d++) break;
6727		if (c) continue;
6728
6729		d = id+16;
6730		r = p->model;
6731		while ((c=*r++)) if (c!=*d++) break;
6732		if (c) continue;
6733
6734		d = id+32;
6735		r = p->version;
6736		while ((c=*r++)) if (c!=*d++) break;
6737		if (c) continue;
6738
6739		return (p->info);
6740	}
6741}
6742#endif
6743
6744/*==========================================================
6745**
6746**	Determine the ncr's clock frequency.
6747**	This is important for the negotiation
6748**	of the synchronous transfer rate.
6749**
6750**==========================================================
6751**
6752**	Note: we have to return the correct value.
6753**	THERE IS NO SAVE DEFAULT VALUE.
6754**
6755**	We assume that all NCR based boards are delivered
6756**	with a 40Mhz clock. Because we have to divide
6757**	by an integer value greater than 3, only clock
6758**	frequencies of 40Mhz (/4) or 50MHz (/5) permit
6759**	the FAST-SCSI rate of 10MHz.
6760**
6761**----------------------------------------------------------
6762*/
6763
6764#ifndef NCR_CLOCK
6765#	define NCR_CLOCK 40
6766#endif /* NCR_CLOCK */
6767
6768
6769static void ncr_getclock (ncb_p np)
6770{
6771	u_char	tbl[5] = {6,2,3,4,6};
6772	u_char	f;
6773	u_char	ns_clock = (1000/NCR_CLOCK);
6774
6775	/*
6776	**	Compute the best value for scntl3.
6777	*/
6778
6779	f = (2 * MIN_SYNC_PD - 1) / ns_clock;
6780	if (!f ) f=1;
6781	if (f>4) f=4;
6782	np -> ns_sync = (ns_clock * tbl[f]) / 2;
6783	np -> rv_scntl3 = f<<4;
6784
6785	f = (2 * MIN_ASYNC_PD - 1) / ns_clock;
6786	if (!f ) f=1;
6787	if (f>4) f=4;
6788	np -> ns_async = (ns_clock * tbl[f]) / 2;
6789	np -> rv_scntl3 |= f;
6790	if (DEBUG_FLAGS & DEBUG_TIMING)
6791		printf ("%s: sclk=%d async=%d sync=%d (ns) scntl3=0x%x\n",
6792		ncr_name (np), ns_clock, np->ns_async, np->ns_sync, np->rv_scntl3);
6793}
6794
6795/*=========================================================================*/
6796#endif /* KERNEL */
6797
6798
6799