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