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