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