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