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