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