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