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