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