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