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