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