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