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