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