xref: /freebsd/sys/dev/sym/sym_hipd.c (revision c807777a43ef2b59786fa8a1a35c1f154fd069e5)
1 /*
2  *  Device driver optimized for the Symbios/LSI 53C896/53C895A/53C1010
3  *  PCI-SCSI controllers.
4  *
5  *  Copyright (C) 1999-2000  Gerard Roudier <groudier@club-internet.fr>
6  *
7  *  This driver also supports the following Symbios/LSI PCI-SCSI chips:
8  *	53C810A, 53C825A, 53C860, 53C875, 53C876, 53C885, 53C895.
9  *
10  *  but does not support earlier chips as the following ones:
11  *	53C810, 53C815, 53C825.
12  *
13  *  This driver for FreeBSD-CAM is derived from the Linux sym53c8xx driver.
14  *  Copyright (C) 1998-1999  Gerard Roudier
15  *
16  *  The sym53c8xx driver is derived from the ncr53c8xx driver that had been
17  *  a port of the FreeBSD ncr driver to Linux-1.2.13.
18  *
19  *  The original ncr driver has been written for 386bsd and FreeBSD by
20  *          Wolfgang Stanglmeier        <wolf@cologne.de>
21  *          Stefan Esser                <se@mi.Uni-Koeln.de>
22  *  Copyright (C) 1994  Wolfgang Stanglmeier
23  *
24  *  The initialisation code, and part of the code that addresses
25  *  FreeBSD-CAM services is based on the aic7xxx driver for FreeBSD-CAM
26  *  written by Justin T. Gibbs.
27  *
28  *  Other major contributions:
29  *
30  *  NVRAM detection and reading.
31  *  Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
32  *
33  *-----------------------------------------------------------------------------
34  *
35  * Redistribution and use in source and binary forms, with or without
36  * modification, are permitted provided that the following conditions
37  * are met:
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. The name of the author may not be used to endorse or promote products
44  *    derived from this software without specific prior written permission.
45  *
46  * THIS SOFTWARE IS PROVIDED BY THE AUTHORS AND CONTRIBUTORS ``AS IS'' AND
47  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
48  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
49  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE FOR
50  * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
51  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
52  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
53  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
54  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
55  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
56  * SUCH DAMAGE.
57  */
58 
59 /* $FreeBSD$ */
60 
61 #define SYM_DRIVER_NAME	"sym-1.2.0-20000108"
62 
63 #include <pci.h>
64 #include <stddef.h>	/* For offsetof */
65 
66 #include <sys/param.h>
67 /*
68  *  Only use the BUS stuff for PCI under FreeBSD 4 and later versions.
69  *  Note that the old BUS stuff also works for FreeBSD 4 and spares
70  *  about 1.5KB for the driver objet file.
71  */
72 #if 	__FreeBSD_version >= 400000
73 #define	FreeBSD_4_Bus
74 #endif
75 
76 #include <sys/systm.h>
77 #include <sys/malloc.h>
78 #include <sys/kernel.h>
79 #ifdef FreeBSD_4_Bus
80 #include <sys/module.h>
81 #include <sys/bus.h>
82 #endif
83 
84 #include <sys/buf.h>
85 #include <sys/proc.h>
86 
87 #include <pci/pcireg.h>
88 #include <pci/pcivar.h>
89 
90 #include <machine/bus_memio.h>
91 #include <machine/bus_pio.h>
92 #include <machine/bus.h>
93 #ifdef FreeBSD_4_Bus
94 #include <machine/resource.h>
95 #include <sys/rman.h>
96 #endif
97 #include <machine/clock.h>
98 
99 #include <cam/cam.h>
100 #include <cam/cam_ccb.h>
101 #include <cam/cam_sim.h>
102 #include <cam/cam_xpt_sim.h>
103 #include <cam/cam_debug.h>
104 
105 #include <cam/scsi/scsi_all.h>
106 #include <cam/scsi/scsi_message.h>
107 
108 #include <vm/vm.h>
109 #include <vm/vm_param.h>
110 #include <vm/pmap.h>
111 
112 #if 0
113 #include <sys/kernel.h>
114 #include <sys/sysctl.h>
115 #include <vm/vm_extern.h>
116 #endif
117 
118 /* Short and quite clear integer types */
119 typedef int8_t    s8;
120 typedef int16_t   s16;
121 typedef	int32_t   s32;
122 typedef u_int8_t  u8;
123 typedef u_int16_t u16;
124 typedef	u_int32_t u32;
125 
126 /* Driver configuration and definitions */
127 #include "opt_sym.h"
128 #include <dev/sym/sym_conf.h>
129 #include <dev/sym/sym_defs.h>
130 
131 /*
132  *  On x86 architecture, write buffers management does not
133  *  reorder writes to memory. So, preventing compiler from
134  *  optimizing the code is enough to guarantee some ordering
135  *  when the CPU is writing data accessed by the PCI chip.
136  *  On Alpha architecture, explicit barriers are to be used.
137  *  By the way, the *BSD semantic associates the barrier
138  *  with some window on the BUS and the corresponding verbs
139  *  are for now unused. What a strangeness. The driver must
140  *  ensure that accesses from the CPU to the start and done
141  *  queues are not reordered by either the compiler or the
142  *  CPU and uses 'volatile' for this purpose.
143  */
144 
145 #ifdef	__alpha__
146 #define MEMORY_BARRIER()	alpha_mb()
147 #else /*__i386__*/
148 #define MEMORY_BARRIER()	do { ; } while(0)
149 #endif
150 
151 /*
152  *  A la VMS/CAM-3 queue management.
153  */
154 
155 typedef struct sym_quehead {
156 	struct sym_quehead *flink;	/* Forward  pointer */
157 	struct sym_quehead *blink;	/* Backward pointer */
158 } SYM_QUEHEAD;
159 
160 #define sym_que_init(ptr) do { \
161 	(ptr)->flink = (ptr); (ptr)->blink = (ptr); \
162 } while (0)
163 
164 static __inline struct sym_quehead *sym_que_first(struct sym_quehead *head)
165 {
166 	return (head->flink == head) ? 0 : head->flink;
167 }
168 
169 static __inline struct sym_quehead *sym_que_last(struct sym_quehead *head)
170 {
171 	return (head->blink == head) ? 0 : head->blink;
172 }
173 
174 static __inline void __sym_que_add(struct sym_quehead * new,
175 	struct sym_quehead * blink,
176 	struct sym_quehead * flink)
177 {
178 	flink->blink	= new;
179 	new->flink	= flink;
180 	new->blink	= blink;
181 	blink->flink	= new;
182 }
183 
184 static __inline void __sym_que_del(struct sym_quehead * blink,
185 	struct sym_quehead * flink)
186 {
187 	flink->blink = blink;
188 	blink->flink = flink;
189 }
190 
191 static __inline int sym_que_empty(struct sym_quehead *head)
192 {
193 	return head->flink == head;
194 }
195 
196 static __inline void sym_que_splice(struct sym_quehead *list,
197 	struct sym_quehead *head)
198 {
199 	struct sym_quehead *first = list->flink;
200 
201 	if (first != list) {
202 		struct sym_quehead *last = list->blink;
203 		struct sym_quehead *at   = head->flink;
204 
205 		first->blink = head;
206 		head->flink  = first;
207 
208 		last->flink = at;
209 		at->blink   = last;
210 	}
211 }
212 
213 #define sym_que_entry(ptr, type, member) \
214 	((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
215 
216 
217 #define sym_insque(new, pos)		__sym_que_add(new, pos, (pos)->flink)
218 
219 #define sym_remque(el)			__sym_que_del((el)->blink, (el)->flink)
220 
221 #define sym_insque_head(new, head)	__sym_que_add(new, head, (head)->flink)
222 
223 static __inline struct sym_quehead *sym_remque_head(struct sym_quehead *head)
224 {
225 	struct sym_quehead *elem = head->flink;
226 
227 	if (elem != head)
228 		__sym_que_del(head, elem->flink);
229 	else
230 		elem = 0;
231 	return elem;
232 }
233 
234 #define sym_insque_tail(new, head)	__sym_que_add(new, (head)->blink, head)
235 
236 static __inline struct sym_quehead *sym_remque_tail(struct sym_quehead *head)
237 {
238 	struct sym_quehead *elem = head->blink;
239 
240 	if (elem != head)
241 		__sym_que_del(elem->blink, head);
242 	else
243 		elem = 0;
244 	return elem;
245 }
246 
247 /*
248  *  This one may be usefull.
249  */
250 #define FOR_EACH_QUEUED_ELEMENT(head, qp) \
251 	for (qp = (head)->flink; qp != (head); qp = qp->flink)
252 /*
253  *  FreeBSD does not offer our kind of queue in the CAM CCB.
254  *  So, we have to cast.
255  */
256 #define sym_qptr(p)	((struct sym_quehead *) (p))
257 
258 /*
259  *  Simple bitmap operations.
260  */
261 #define sym_set_bit(p, n)	(((u32 *)(p))[(n)>>5] |=  (1<<((n)&0x1f)))
262 #define sym_clr_bit(p, n)	(((u32 *)(p))[(n)>>5] &= ~(1<<((n)&0x1f)))
263 #define sym_is_bit(p, n)	(((u32 *)(p))[(n)>>5] &   (1<<((n)&0x1f)))
264 
265 /*
266  *  Number of tasks per device we want to handle.
267  */
268 #if	SYM_CONF_MAX_TAG_ORDER > 8
269 #error	"more than 256 tags per logical unit not allowed."
270 #endif
271 #define	SYM_CONF_MAX_TASK	(1<<SYM_CONF_MAX_TAG_ORDER)
272 
273 /*
274  *  Donnot use more tasks that we can handle.
275  */
276 #ifndef	SYM_CONF_MAX_TAG
277 #define	SYM_CONF_MAX_TAG	SYM_CONF_MAX_TASK
278 #endif
279 #if	SYM_CONF_MAX_TAG > SYM_CONF_MAX_TASK
280 #undef	SYM_CONF_MAX_TAG
281 #define	SYM_CONF_MAX_TAG	SYM_CONF_MAX_TASK
282 #endif
283 
284 /*
285  *    This one means 'NO TAG for this job'
286  */
287 #define NO_TAG	(256)
288 
289 /*
290  *  Number of SCSI targets.
291  */
292 #if	SYM_CONF_MAX_TARGET > 16
293 #error	"more than 16 targets not allowed."
294 #endif
295 
296 /*
297  *  Number of logical units per target.
298  */
299 #if	SYM_CONF_MAX_LUN > 64
300 #error	"more than 64 logical units per target not allowed."
301 #endif
302 
303 /*
304  *    Asynchronous pre-scaler (ns). Shall be 40 for
305  *    the SCSI timings to be compliant.
306  */
307 #define	SYM_CONF_MIN_ASYNC (40)
308 
309 /*
310  *  Number of entries in the START and DONE queues.
311  *
312  *  We limit to 1 PAGE in order to succeed allocation of
313  *  these queues. Each entry is 8 bytes long (2 DWORDS).
314  */
315 #ifdef	SYM_CONF_MAX_START
316 #define	SYM_CONF_MAX_QUEUE (SYM_CONF_MAX_START+2)
317 #else
318 #define	SYM_CONF_MAX_QUEUE (7*SYM_CONF_MAX_TASK+2)
319 #define	SYM_CONF_MAX_START (SYM_CONF_MAX_QUEUE-2)
320 #endif
321 
322 #if	SYM_CONF_MAX_QUEUE > PAGE_SIZE/8
323 #undef	SYM_CONF_MAX_QUEUE
324 #define	SYM_CONF_MAX_QUEUE   PAGE_SIZE/8
325 #undef	SYM_CONF_MAX_START
326 #define	SYM_CONF_MAX_START (SYM_CONF_MAX_QUEUE-2)
327 #endif
328 
329 /*
330  *  For this one, we want a short name :-)
331  */
332 #define MAX_QUEUE	SYM_CONF_MAX_QUEUE
333 
334 /*
335  *  This one should have been already defined.
336  */
337 #ifndef offsetof
338 #define offsetof(t, m)	((size_t) (&((t *)0)->m))
339 #endif
340 
341 /*
342  *  Active debugging tags and verbosity.
343  */
344 #define DEBUG_ALLOC	(0x0001)
345 #define DEBUG_PHASE	(0x0002)
346 #define DEBUG_POLL	(0x0004)
347 #define DEBUG_QUEUE	(0x0008)
348 #define DEBUG_RESULT	(0x0010)
349 #define DEBUG_SCATTER	(0x0020)
350 #define DEBUG_SCRIPT	(0x0040)
351 #define DEBUG_TINY	(0x0080)
352 #define DEBUG_TIMING	(0x0100)
353 #define DEBUG_NEGO	(0x0200)
354 #define DEBUG_TAGS	(0x0400)
355 #define DEBUG_POINTER	(0x0800)
356 
357 #if 0
358 static int sym_debug = 0;
359 	#define DEBUG_FLAGS sym_debug
360 #else
361 /*	#define DEBUG_FLAGS (0x0631) */
362 	#define DEBUG_FLAGS (0x0000)
363 #endif
364 #define sym_verbose	(np->verbose)
365 
366 /*
367  *  Virtual to bus address translation.
368  */
369 #ifdef	__alpha__
370 #define	vtobus(p)	alpha_XXX_dmamap((vm_offset_t)(p))
371 #else /*__i386__*/
372 #define vtobus(p)	vtophys(p)
373 #endif
374 
375 /*
376  *  Copy from main memory to PCI memory space.
377  */
378 #ifdef	__alpha__
379 #define memcpy_to_pci(d, s, n)	memcpy_toio((u32)(d), (void *)(s), (n))
380 #else /*__i386__*/
381 #define memcpy_to_pci(d, s, n)	bcopy((s), (void *)(d), (n))
382 #endif
383 
384 /*
385  *  Insert a delay in micro-seconds and milli-seconds.
386  */
387 static void UDELAY(long us) { DELAY(us); }
388 static void MDELAY(long ms) { while (ms--) UDELAY(1000); }
389 
390 /*
391  *  Memory allocation/allocator.
392  *  We assume allocations are naturally aligned and if it is
393  *  not guaranteed, we may use our internal allocator.
394  */
395 #ifdef	SYM_CONF_USE_INTERNAL_ALLOCATOR
396 /*
397  *  Simple power of two buddy-like allocator.
398  *
399  *  This simple code is not intended to be fast, but to
400  *  provide power of 2 aligned memory allocations.
401  *  Since the SCRIPTS processor only supplies 8 bit arithmetic,
402  *  this allocator allows simple and fast address calculations
403  *  from the SCRIPTS code. In addition, cache line alignment
404  *  is guaranteed for power of 2 cache line size.
405  *
406  *  This allocator has been developped for the Linux sym53c8xx
407  *  driver, since this O/S does not provide naturally aligned
408  *  allocations.
409  *  It has the vertue to allow the driver to use private pages
410  *  of memory that will be useful if we ever need to deal with
411  *  IO MMU for PCI.
412  */
413 
414 #define MEMO_SHIFT	4	/* 16 bytes minimum memory chunk */
415 #define MEMO_PAGE_ORDER	0	/* 1 PAGE maximum (for now (ever?) */
416 typedef unsigned long addr;	/* Enough bits to bit-hack addresses */
417 
418 #if 0
419 #define MEMO_FREE_UNUSED	/* Free unused pages immediately */
420 #endif
421 
422 struct m_link {
423 	struct m_link *next;	/* Simple links are enough */
424 };
425 
426 #ifndef M_DMA_32BIT
427 #define M_DMA_32BIT	0	/* Will this flag ever exist */
428 #endif
429 
430 #define get_pages() \
431 	malloc(PAGE_SIZE<<MEMO_PAGE_ORDER, M_DEVBUF, M_NOWAIT)
432 #define free_pages(p) \
433 	free((p), M_DEVBUF)
434 
435 /*
436  *  Lists of available memory chunks.
437  *  Starts with 16 bytes chunks until 1 PAGE chunks.
438  */
439 static struct m_link h[PAGE_SHIFT-MEMO_SHIFT+MEMO_PAGE_ORDER+1];
440 
441 /*
442  *  Allocate a memory area aligned on the lowest power of 2
443  *  greater than the requested size.
444  */
445 static void *__sym_malloc(int size)
446 {
447 	int i = 0;
448 	int s = (1 << MEMO_SHIFT);
449 	int j;
450 	addr a ;
451 
452 	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
453 		return 0;
454 
455 	while (size > s) {
456 		s <<= 1;
457 		++i;
458 	}
459 
460 	j = i;
461 	while (!h[j].next) {
462 		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
463 			h[j].next = (struct m_link *)get_pages();
464 			if (h[j].next)
465 				h[j].next->next = 0;
466 			break;
467 		}
468 		++j;
469 		s <<= 1;
470 	}
471 	a = (addr) h[j].next;
472 	if (a) {
473 		h[j].next = h[j].next->next;
474 		while (j > i) {
475 			j -= 1;
476 			s >>= 1;
477 			h[j].next = (struct m_link *) (a+s);
478 			h[j].next->next = 0;
479 		}
480 	}
481 #ifdef DEBUG
482 	printf("__sym_malloc(%d) = %p\n", size, (void *) a);
483 #endif
484 	return (void *) a;
485 }
486 
487 /*
488  *  Free a memory area allocated using sym_malloc().
489  *  Coalesce buddies.
490  *  Free pages that become unused if MEMO_FREE_UNUSED is
491  *  defined.
492  */
493 static void __sym_mfree(void *ptr, int size)
494 {
495 	int i = 0;
496 	int s = (1 << MEMO_SHIFT);
497 	struct m_link *q;
498 	addr a, b;
499 
500 #ifdef DEBUG
501 	printf("sym_mfree(%p, %d)\n", ptr, size);
502 #endif
503 
504 	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
505 		return;
506 
507 	while (size > s) {
508 		s <<= 1;
509 		++i;
510 	}
511 
512 	a = (addr) ptr;
513 
514 	while (1) {
515 #ifdef MEMO_FREE_UNUSED
516 		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
517 			free_pages(a);
518 			break;
519 		}
520 #endif
521 		b = a ^ s;
522 		q = &h[i];
523 		while (q->next && q->next != (struct m_link *) b) {
524 			q = q->next;
525 		}
526 		if (!q->next) {
527 			((struct m_link *) a)->next = h[i].next;
528 			h[i].next = (struct m_link *) a;
529 			break;
530 		}
531 		q->next = q->next->next;
532 		a = a & b;
533 		s <<= 1;
534 		++i;
535 	}
536 }
537 
538 #else	/* !defined SYSCONF_USE_INTERNAL_ALLOCATOR */
539 
540 /*
541  *  Using directly the system memory allocator.
542  */
543 
544 #define	__sym_mfree(ptr, size)		free((ptr), M_DEVBUF)
545 #define	__sym_malloc(size)		malloc((size), M_DEVBUF, M_NOWAIT)
546 
547 #endif	/* SYM_CONF_USE_INTERNAL_ALLOCATOR */
548 
549 #define MEMO_WARN	1
550 
551 static void *sym_calloc2(int size, char *name, int uflags)
552 {
553 	void *p;
554 
555 	p = __sym_malloc(size);
556 
557 	if (DEBUG_FLAGS & DEBUG_ALLOC)
558 		printf ("new %-10s[%4d] @%p.\n", name, size, p);
559 
560 	if (p)
561 		bzero(p, size);
562 	else if (uflags & MEMO_WARN)
563 		printf ("sym_calloc: failed to allocate %s[%d]\n", name, size);
564 
565 	return p;
566 }
567 
568 #define sym_calloc(s, n)	sym_calloc2(s, n, MEMO_WARN)
569 
570 static void sym_mfree(void *ptr, int size, char *name)
571 {
572 	if (DEBUG_FLAGS & DEBUG_ALLOC)
573 		printf ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
574 
575 	__sym_mfree(ptr, size);
576 }
577 
578 /*
579  *  Print a buffer in hexadecimal format.
580  */
581 static void sym_printb_hex (u_char *p, int n)
582 {
583 	while (n-- > 0)
584 		printf (" %x", *p++);
585 }
586 
587 /*
588  *  Same with a label at beginning and .\n at end.
589  */
590 static void sym_printl_hex (char *label, u_char *p, int n)
591 {
592 	printf ("%s", label);
593 	sym_printb_hex (p, n);
594 	printf (".\n");
595 }
596 
597 /*
598  *  Return a string for SCSI BUS mode.
599  */
600 static char *sym_scsi_bus_mode(int mode)
601 {
602 	switch(mode) {
603 	case SMODE_HVD:	return "HVD";
604 	case SMODE_SE:	return "SE";
605 	case SMODE_LVD: return "LVD";
606 	}
607 	return "??";
608 }
609 
610 /*
611  *  Some poor sync table that refers to Tekram NVRAM layout.
612  */
613 #ifdef SYM_CONF_NVRAM_SUPPORT
614 static u_char Tekram_sync[16] =
615 	{25,31,37,43, 50,62,75,125, 12,15,18,21, 6,7,9,10};
616 #endif
617 
618 /*
619  *  Union of supported NVRAM formats.
620  */
621 struct sym_nvram {
622 	int type;
623 #define	SYM_SYMBIOS_NVRAM	(1)
624 #define	SYM_TEKRAM_NVRAM	(2)
625 #ifdef	SYM_CONF_NVRAM_SUPPORT
626 	union {
627 		Symbios_nvram Symbios;
628 		Tekram_nvram Tekram;
629 	} data;
630 #endif
631 };
632 
633 /*
634  *  This one is hopefully useless, but actually useful. :-)
635  */
636 #ifndef assert
637 #define	assert(expression) { \
638 	if (!(expression)) { \
639 		(void)panic( \
640 			"assertion \"%s\" failed: file \"%s\", line %d\n", \
641 			#expression, \
642 			__FILE__, __LINE__); \
643 	} \
644 }
645 #endif
646 
647 /*
648  *  Some provision for a possible big endian support.
649  *  By the way some Symbios chips also may support some kind
650  *  of big endian byte ordering.
651  *  For now, this stuff does not deserve any comments. :)
652  */
653 
654 #define sym_offb(o)	(o)
655 #define sym_offw(o)	(o)
656 
657 #define cpu_to_scr(dw)	(dw)
658 #define scr_to_cpu(dw)	(dw)
659 
660 /*
661  *  Access to the controller chip.
662  *
663  *  If SYM_CONF_IOMAPPED is defined, the driver will use
664  *  normal IOs instead of the MEMORY MAPPED IO method
665  *  recommended by PCI specifications.
666  */
667 
668 /*
669  *  Define some understable verbs so we will not suffer of
670  *  having to deal with the stupid PC tokens for IO.
671  */
672 #define io_read8(p)	 scr_to_cpu(inb((p)))
673 #define	io_read16(p)	 scr_to_cpu(inw((p)))
674 #define io_read32(p)	 scr_to_cpu(inl((p)))
675 #define	io_write8(p, v)	 outb((p), cpu_to_scr(v))
676 #define io_write16(p, v) outw((p), cpu_to_scr(v))
677 #define io_write32(p, v) outl((p), cpu_to_scr(v))
678 
679 #ifdef	__alpha__
680 
681 #define mmio_read8(a)	     readb(a)
682 #define mmio_read16(a)	     readw(a)
683 #define mmio_read32(a)	     readl(a)
684 #define mmio_write8(a, b)    writeb(a, b)
685 #define mmio_write16(a, b)   writew(a, b)
686 #define mmio_write32(a, b)   writel(a, b)
687 
688 #else /*__i386__*/
689 
690 #define mmio_read8(a)	     scr_to_cpu((*(volatile unsigned char *) (a)))
691 #define mmio_read16(a)	     scr_to_cpu((*(volatile unsigned short *) (a)))
692 #define mmio_read32(a)	     scr_to_cpu((*(volatile unsigned int *) (a)))
693 #define mmio_write8(a, b)   (*(volatile unsigned char *) (a)) = cpu_to_scr(b)
694 #define mmio_write16(a, b)  (*(volatile unsigned short *) (a)) = cpu_to_scr(b)
695 #define mmio_write32(a, b)  (*(volatile unsigned int *) (a)) = cpu_to_scr(b)
696 
697 #endif
698 
699 /*
700  *  Normal IO
701  */
702 #if defined(SYM_CONF_IOMAPPED)
703 
704 #define	INB_OFF(o)	io_read8(np->io_port + sym_offb(o))
705 #define	OUTB_OFF(o, v)	io_write8(np->io_port + sym_offb(o), (v))
706 
707 #define	INW_OFF(o)	io_read16(np->io_port + sym_offw(o))
708 #define	OUTW_OFF(o, v)	io_write16(np->io_port + sym_offw(o), (v))
709 
710 #define	INL_OFF(o)	io_read32(np->io_port + (o))
711 #define	OUTL_OFF(o, v)	io_write32(np->io_port + (o), (v))
712 
713 #else	/* Memory mapped IO */
714 
715 #define	INB_OFF(o)	mmio_read8(np->mmio_va + sym_offb(o))
716 #define	OUTB_OFF(o, v)	mmio_write8(np->mmio_va + sym_offb(o), (v))
717 
718 #define	INW_OFF(o)	mmio_read16(np->mmio_va + sym_offw(o))
719 #define	OUTW_OFF(o, v)	mmio_write16(np->mmio_va + sym_offw(o), (v))
720 
721 #define	INL_OFF(o)	mmio_read32(np->mmio_va + (o))
722 #define	OUTL_OFF(o, v)	mmio_write32(np->mmio_va + (o), (v))
723 
724 #endif
725 
726 /*
727  *  Common to both normal IO and MMIO.
728  */
729 #define INB(r)		INB_OFF(offsetof(struct sym_reg,r))
730 #define INW(r)		INW_OFF(offsetof(struct sym_reg,r))
731 #define INL(r)		INL_OFF(offsetof(struct sym_reg,r))
732 
733 #define OUTB(r, v)	OUTB_OFF(offsetof(struct sym_reg,r), (v))
734 #define OUTW(r, v)	OUTW_OFF(offsetof(struct sym_reg,r), (v))
735 #define OUTL(r, v)	OUTL_OFF(offsetof(struct sym_reg,r), (v))
736 
737 #define OUTONB(r, m)	OUTB(r, INB(r) | (m))
738 #define OUTOFFB(r, m)	OUTB(r, INB(r) & ~(m))
739 #define OUTONW(r, m)	OUTW(r, INW(r) | (m))
740 #define OUTOFFW(r, m)	OUTW(r, INW(r) & ~(m))
741 #define OUTONL(r, m)	OUTL(r, INL(r) | (m))
742 #define OUTOFFL(r, m)	OUTL(r, INL(r) & ~(m))
743 
744 /*
745  *  Command control block states.
746  */
747 #define HS_IDLE		(0)
748 #define HS_BUSY		(1)
749 #define HS_NEGOTIATE	(2)	/* sync/wide data transfer*/
750 #define HS_DISCONNECT	(3)	/* Disconnected by target */
751 
752 #define HS_DONEMASK	(0x80)
753 #define HS_COMPLETE	(4|HS_DONEMASK)
754 #define HS_SEL_TIMEOUT	(5|HS_DONEMASK)	/* Selection timeout      */
755 #define HS_UNEXPECTED	(6|HS_DONEMASK)	/* Unexpected disconnect  */
756 #define HS_COMP_ERR	(7|HS_DONEMASK)	/* Completed with error	  */
757 
758 /*
759  *  Software Interrupt Codes
760  */
761 #define	SIR_BAD_SCSI_STATUS	(1)
762 #define	SIR_SEL_ATN_NO_MSG_OUT	(2)
763 #define	SIR_MSG_RECEIVED	(3)
764 #define	SIR_MSG_WEIRD		(4)
765 #define	SIR_NEGO_FAILED		(5)
766 #define	SIR_NEGO_PROTO		(6)
767 #define	SIR_SCRIPT_STOPPED	(7)
768 #define	SIR_REJECT_TO_SEND	(8)
769 #define	SIR_SWIDE_OVERRUN	(9)
770 #define	SIR_SODL_UNDERRUN	(10)
771 #define	SIR_RESEL_NO_MSG_IN	(11)
772 #define	SIR_RESEL_NO_IDENTIFY	(12)
773 #define	SIR_RESEL_BAD_LUN	(13)
774 #define	SIR_TARGET_SELECTED	(14)
775 #define	SIR_RESEL_BAD_I_T_L	(15)
776 #define	SIR_RESEL_BAD_I_T_L_Q	(16)
777 #define	SIR_ABORT_SENT		(17)
778 #define	SIR_RESEL_ABORTED	(18)
779 #define	SIR_MSG_OUT_DONE	(19)
780 #define	SIR_COMPLETE_ERROR	(20)
781 #define	SIR_MAX			(20)
782 
783 /*
784  *  Extended error bit codes.
785  *  xerr_status field of struct sym_ccb.
786  */
787 #define	XE_EXTRA_DATA	(1)	/* unexpected data phase	 */
788 #define	XE_BAD_PHASE	(1<<1)	/* illegal phase (4/5)		 */
789 #define	XE_PARITY_ERR	(1<<2)	/* unrecovered SCSI parity error */
790 #define	XE_SODL_UNRUN	(1<<3)	/* ODD transfer in DATA OUT phase */
791 #define	XE_SWIDE_OVRUN	(1<<4)	/* ODD transfer in DATA IN phase */
792 
793 /*
794  *  Negotiation status.
795  *  nego_status field of struct sym_ccb.
796  */
797 #define NS_SYNC		(1)
798 #define NS_WIDE		(2)
799 #define NS_PPR		(3)
800 
801 /*
802  *  A CCB hashed table is used to retrieve CCB address
803  *  from DSA value.
804  */
805 #define CCB_HASH_SHIFT		8
806 #define CCB_HASH_SIZE		(1UL << CCB_HASH_SHIFT)
807 #define CCB_HASH_MASK		(CCB_HASH_SIZE-1)
808 #define CCB_HASH_CODE(dsa)	(((dsa) >> 9) & CCB_HASH_MASK)
809 
810 /*
811  *  Device flags.
812  */
813 #define SYM_DISC_ENABLED	(1)
814 #define SYM_TAGS_ENABLED	(1<<1)
815 #define SYM_SCAN_BOOT_DISABLED	(1<<2)
816 #define SYM_SCAN_LUNS_DISABLED	(1<<3)
817 
818 /*
819  *  Host adapter miscellaneous flags.
820  */
821 #define SYM_AVOID_BUS_RESET	(1)
822 #define SYM_SCAN_TARGETS_HILO	(1<<1)
823 
824 /*
825  *  Device quirks.
826  *  Some devices, for example the CHEETAH 2 LVD, disconnects without
827  *  saving the DATA POINTER then reconnect and terminates the IO.
828  *  On reselection, the automatic RESTORE DATA POINTER makes the
829  *  CURRENT DATA POINTER not point at the end of the IO.
830  *  This behaviour just breaks our calculation of the residual.
831  *  For now, we just force an AUTO SAVE on disconnection and will
832  *  fix that in a further driver version.
833  */
834 #define SYM_QUIRK_AUTOSAVE 1
835 
836 /*
837  *  Misc.
838  */
839 #define SYM_SNOOP_TIMEOUT (10000000)
840 #define SYM_PCI_IO	PCIR_MAPS
841 #define SYM_PCI_MMIO	(PCIR_MAPS + 4)
842 #define SYM_PCI_RAM	(PCIR_MAPS + 8)
843 #define SYM_PCI_RAM64	(PCIR_MAPS + 12)
844 
845 /*
846  *  Back-pointer from the CAM CCB to our data structures.
847  */
848 #define sym_hcb_ptr	spriv_ptr0
849 /* #define sym_ccb_ptr	spriv_ptr1 */
850 
851 /*
852  *  We mostly have to deal with pointers.
853  *  Thus these typedef's.
854  */
855 typedef struct sym_tcb *tcb_p;
856 typedef struct sym_lcb *lcb_p;
857 typedef struct sym_ccb *ccb_p;
858 typedef struct sym_hcb *hcb_p;
859 typedef struct sym_scr  *script_p;
860 typedef struct sym_scrh *scripth_p;
861 
862 /*
863  *  Gather negotiable parameters value
864  */
865 struct sym_trans {
866 	u8 period;
867 	u8 offset;
868 	u8 width;
869 	u8 options;	/* PPR options */
870 };
871 
872 struct sym_tinfo {
873 	struct sym_trans current;
874 	struct sym_trans goal;
875 	struct sym_trans user;
876 };
877 
878 #define BUS_8_BIT	MSG_EXT_WDTR_BUS_8_BIT
879 #define BUS_16_BIT	MSG_EXT_WDTR_BUS_16_BIT
880 
881 /*
882  *  Target Control Block
883  */
884 struct sym_tcb {
885 	/*
886 	 *  LUN table used by the SCRIPTS processor.
887 	 *  An array of bus addresses is used on reselection.
888 	 *  LUN #0 is a special case, since multi-lun devices are rare,
889 	 *  and we we want to speed-up the general case and not waste
890 	 *  resources.
891 	 */
892 	u32	*luntbl;	/* LCBs bus address table	*/
893 	u32	luntbl_sa;	/* bus address of this table	*/
894 	u32	lun0_sa;	/* bus address of LCB #0	*/
895 
896 	/*
897 	 *  LUN table used by the C code.
898 	 */
899 	lcb_p	lun0p;		/* LCB of LUN #0 (usual case)	*/
900 #if SYM_CONF_MAX_LUN > 1
901 	lcb_p	*lunmp;		/* Other LCBs [1..MAX_LUN]	*/
902 #endif
903 
904 	/*
905 	 *  Bitmap that tells about LUNs that succeeded at least
906 	 *  1 IO and therefore assumed to be a real device.
907 	 *  Avoid useless allocation of the LCB structure.
908 	 */
909 	u32	lun_map[(SYM_CONF_MAX_LUN+31)/32];
910 
911 	/*
912 	 *  Bitmap that tells about LUNs that haven't yet an LCB
913 	 *  allocated (not discovered or LCB allocation failed).
914 	 */
915 	u32	busy0_map[(SYM_CONF_MAX_LUN+31)/32];
916 
917 	/*
918 	 *  Actual SYNC/WIDE IO registers value for this target.
919 	 *  'sval', 'wval' and 'uval' are read from SCRIPTS and
920 	 *  so have alignment constraints.
921 	 */
922 /*0*/	u_char	uval;		/* -> SCNTL4 register		*/
923 /*1*/	u_char	sval;		/* -> SXFER  io register	*/
924 /*2*/	u_char	filler1;
925 /*3*/	u_char	wval;		/* -> SCNTL3 io register	*/
926 
927 	/*
928 	 *  Transfer capabilities (SIP)
929 	 */
930 	struct sym_tinfo tinfo;
931 
932 	/*
933 	 * Keep track of the CCB used for the negotiation in order
934 	 * to ensure that only 1 negotiation is queued at a time.
935 	 */
936 	ccb_p   nego_cp;	/* CCB used for the nego		*/
937 
938 	/*
939 	 *  Set when we want to reset the device.
940 	 */
941 	u_char	to_reset;
942 
943 	/*
944 	 *  Other user settable limits and options.
945 	 *  These limits are read from the NVRAM if present.
946 	 */
947 	u_char	usrflags;
948 	u_short	usrtags;
949 };
950 
951 /*
952  *  Logical Unit Control Block
953  */
954 struct sym_lcb {
955 	/*
956 	 *  SCRIPTS address jumped by SCRIPTS on reselection.
957 	 *  For not probed logical units, this address points to
958 	 *  SCRIPTS that deal with bad LU handling (must be at
959 	 *  offset zero for that reason).
960 	 */
961 /*0*/	u32	resel_sa;
962 
963 	/*
964 	 *  Task (bus address of a CCB) read from SCRIPTS that points
965 	 *  to the unique ITL nexus allowed to be disconnected.
966 	 */
967 	u32	itl_task_sa;
968 
969 	/*
970 	 *  Task table read from SCRIPTS that contains pointers to
971 	 *  ITLQ nexuses (bus addresses read from SCRIPTS).
972 	 */
973 	u32	*itlq_tbl;	/* Kernel virtual address	*/
974 	u32	itlq_tbl_sa;	/* Bus address used by SCRIPTS	*/
975 
976 	/*
977 	 *  Busy CCBs management.
978 	 */
979 	u_short	busy_itlq;	/* Number of busy tagged CCBs	*/
980 	u_short	busy_itl;	/* Number of busy untagged CCBs	*/
981 
982 	/*
983 	 *  Circular tag allocation buffer.
984 	 */
985 	u_short	ia_tag;		/* Tag allocation index		*/
986 	u_short	if_tag;		/* Tag release index		*/
987 	u_char	*cb_tags;	/* Circular tags buffer		*/
988 
989 	/*
990 	 *  Set when we want to clear all tasks.
991 	 */
992 	u_char to_clear;
993 
994 	/*
995 	 *  Capabilities.
996 	 */
997 	u_char	user_flags;
998 	u_char	current_flags;
999 };
1000 
1001 /*
1002  *  Action from SCRIPTS on a task.
1003  *  Is part of the CCB, but is also used separately to plug
1004  *  error handling action to perform from SCRIPTS.
1005  */
1006 struct sym_actscr {
1007 	u32	start;		/* Jumped by SCRIPTS after selection	*/
1008 	u32	restart;	/* Jumped by SCRIPTS on relection	*/
1009 };
1010 
1011 /*
1012  *  Phase mismatch context.
1013  *
1014  *  It is part of the CCB and is used as parameters for the
1015  *  DATA pointer. We need two contexts to handle correctly the
1016  *  SAVED DATA POINTER.
1017  */
1018 struct sym_pmc {
1019 	struct	sym_tblmove sg;	/* Updated interrupted SG block	*/
1020 	u32	ret;		/* SCRIPT return address	*/
1021 };
1022 
1023 /*
1024  *  LUN control block lookup.
1025  *  We use a direct pointer for LUN #0, and a table of
1026  *  pointers which is only allocated for devices that support
1027  *  LUN(s) > 0.
1028  */
1029 #if SYM_CONF_MAX_LUN <= 1
1030 #define sym_lp(np, tp, lun) (!lun) ? (tp)->lun0p : 0
1031 #else
1032 #define sym_lp(np, tp, lun) \
1033 	(!lun) ? (tp)->lun0p : (tp)->lunmp ? (tp)->lunmp[(lun)] : 0
1034 #endif
1035 
1036 /*
1037  *  Status are used by the host and the script processor.
1038  *
1039  *  The last four bytes (status[4]) are copied to the
1040  *  scratchb register (declared as scr0..scr3) just after the
1041  *  select/reselect, and copied back just after disconnecting.
1042  *  Inside the script the XX_REG are used.
1043  *
1044  *  The first four bytes (scr_st[4]) are used inside the
1045  *  script by "LOAD/STORE" commands.
1046  *  Because source and destination must have the same alignment
1047  *  in a DWORD, the fields HAVE to be at the choosen offsets.
1048  *  	xerr_st		0	(0x34)	scratcha
1049  *  	nego_st		2
1050  */
1051 
1052 /*
1053  *  Last four bytes (script)
1054  */
1055 #define  QU_REG	scr0
1056 #define  HS_REG	scr1
1057 #define  HS_PRT	nc_scr1
1058 #define  SS_REG	scr2
1059 #define  SS_PRT	nc_scr2
1060 #define  HF_REG	scr3
1061 #define  HF_PRT	nc_scr3
1062 
1063 /*
1064  *  Last four bytes (host)
1065  */
1066 #define  actualquirks  phys.status[0]
1067 #define  host_status   phys.status[1]
1068 #define  ssss_status   phys.status[2]
1069 #define  host_flags    phys.status[3]
1070 
1071 /*
1072  *  Host flags
1073  */
1074 #define HF_IN_PM0	1u
1075 #define HF_IN_PM1	(1u<<1)
1076 #define HF_ACT_PM	(1u<<2)
1077 #define HF_DP_SAVED	(1u<<3)
1078 #define HF_SENSE	(1u<<4)
1079 #define HF_EXT_ERR	(1u<<5)
1080 #ifdef SYM_CONF_IARB_SUPPORT
1081 #define HF_HINT_IARB	(1u<<7)
1082 #endif
1083 
1084 /*
1085  *  First four bytes (script)
1086  */
1087 #define  xerr_st       scr_st[0]
1088 #define  nego_st       scr_st[2]
1089 
1090 /*
1091  *  First four bytes (host)
1092  */
1093 #define  xerr_status   phys.xerr_st
1094 #define  nego_status   phys.nego_st
1095 
1096 /*
1097  *  Data Structure Block
1098  *
1099  *  During execution of a ccb by the script processor, the
1100  *  DSA (data structure address) register points to this
1101  *  substructure of the ccb.
1102  */
1103 struct dsb {
1104 	/*
1105 	 *  Start and restart SCRIPTS addresses (must be at 0).
1106 	 */
1107 /*0*/	struct sym_actscr go;
1108 
1109 	/*
1110 	 *  SCRIPTS jump address that deal with data pointers.
1111 	 *  'savep' points to the position in the script responsible
1112 	 *  for the	actual transfer of data.
1113 	 *  It's written on reception of a SAVE_DATA_POINTER message.
1114 	 */
1115 	u32	savep;		/* Jump address to saved data pointer	*/
1116 	u32	lastp;		/* SCRIPTS address at end of data	*/
1117 	u32	goalp;		/* Not used for now			*/
1118 
1119 	/*
1120 	 *  Status fields.
1121 	 */
1122 	u8	scr_st[4];	/* script status		*/
1123 	u8	status[4];	/* host status			*/
1124 
1125 	/*
1126 	 *  Table data for Script
1127 	 */
1128 	struct sym_tblsel  select;
1129 	struct sym_tblmove smsg;
1130 	struct sym_tblmove smsg_ext;
1131 	struct sym_tblmove cmd;
1132 	struct sym_tblmove sense;
1133 	struct sym_tblmove data [SYM_CONF_MAX_SG];
1134 
1135 	/*
1136 	 *  Phase mismatch contexts.
1137 	 *  We need two to handle correctly the SAVED DATA POINTER.
1138 	 */
1139 	struct sym_pmc pm0;
1140 	struct sym_pmc pm1;
1141 
1142 	/*
1143 	 *  Extra bytes count transferred in case of data overrun.
1144 	 */
1145 	u32	extra_bytes;
1146 };
1147 
1148 /*
1149  *  Our Command Control Block
1150  */
1151 struct sym_ccb {
1152 	/*
1153 	 *  This is the data structure which is pointed by the DSA
1154 	 *  register when it is executed by the script processor.
1155 	 *  It must be the first entry.
1156 	 */
1157 	struct dsb phys;
1158 
1159 	/*
1160 	 *  Pointer to CAM ccb and related stuff.
1161 	 */
1162 	union ccb *cam_ccb;	/* CAM scsiio ccb		*/
1163 	int	data_len;	/* Total data length		*/
1164 	int	segments;	/* Number of SG segments	*/
1165 
1166 	/*
1167 	 *  Message areas.
1168 	 *  We prepare a message to be sent after selection.
1169 	 *  We may use a second one if the command is rescheduled
1170 	 *  due to CHECK_CONDITION or COMMAND TERMINATED.
1171 	 *  Contents are IDENTIFY and SIMPLE_TAG.
1172 	 *  While negotiating sync or wide transfer,
1173 	 *  a SDTR or WDTR message is appended.
1174 	 */
1175 	u_char	scsi_smsg [12];
1176 	u_char	scsi_smsg2[12];
1177 
1178 	/*
1179 	 *  Auto request sense related fields.
1180 	 */
1181 	u_char	sensecmd[6];	/* Request Sense command	*/
1182 	u_char	sv_scsi_status;	/* Saved SCSI status 		*/
1183 	u_char	sv_xerr_status;	/* Saved extended status	*/
1184 	int	sv_resid;	/* Saved residual		*/
1185 
1186 	/*
1187 	 *  Other fields.
1188 	 */
1189 	u_long	ccb_ba;		/* BUS address of this CCB	*/
1190 	u_short	tag;		/* Tag for this transfer	*/
1191 				/*  NO_TAG means no tag		*/
1192 	u_char	target;
1193 	u_char	lun;
1194 	ccb_p	link_ccbh;	/* Host adapter CCB hash chain	*/
1195 	SYM_QUEHEAD
1196 		link_ccbq;	/* Link to free/busy CCB queue	*/
1197 	u32	startp;		/* Initial data pointer		*/
1198 	int	ext_sg;		/* Extreme data pointer, used	*/
1199 	int	ext_ofs;	/*  to calculate the residual.	*/
1200 	u_char	to_abort;	/* Want this IO to be aborted	*/
1201 };
1202 
1203 #define CCB_PHYS(cp,lbl)	(cp->ccb_ba + offsetof(struct sym_ccb, lbl))
1204 
1205 /*
1206  *  Host Control Block
1207  */
1208 struct sym_hcb {
1209 	/*
1210 	 *  Idle task and invalid task actions and
1211 	 *  their bus addresses.
1212 	 */
1213 	struct sym_actscr idletask, notask, bad_itl, bad_itlq;
1214 	vm_offset_t idletask_ba, notask_ba, bad_itl_ba, bad_itlq_ba;
1215 
1216 	/*
1217 	 *  Dummy lun table to protect us against target
1218 	 *  returning bad lun number on reselection.
1219 	 */
1220 	u32	*badluntbl;	/* Table physical address	*/
1221 	u32	badlun_sa;	/* SCRIPT handler BUS address	*/
1222 
1223 	/*
1224 	 *  Bit 32-63 of the on-chip RAM bus address in LE format.
1225 	 *  The START_RAM64 script loads the MMRS and MMWS from this
1226 	 *  field.
1227 	 */
1228 	u32	scr_ram_seg;
1229 
1230 	/*
1231 	 *  Chip and controller indentification.
1232 	 */
1233 #ifdef FreeBSD_4_Bus
1234 	device_t device;
1235 #else
1236 	pcici_t	pci_tag;
1237 #endif
1238 	int	unit;
1239 	char	inst_name[8];
1240 
1241 	/*
1242 	 *  Initial value of some IO register bits.
1243 	 *  These values are assumed to have been set by BIOS, and may
1244 	 *  be used to probe adapter implementation differences.
1245 	 */
1246 	u_char	sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest3, sv_ctest4,
1247 		sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4, sv_scntl4,
1248 		sv_stest1;
1249 
1250 	/*
1251 	 *  Actual initial value of IO register bits used by the
1252 	 *  driver. They are loaded at initialisation according to
1253 	 *  features that are to be enabled/disabled.
1254 	 */
1255 	u_char	rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest3, rv_ctest4,
1256 		rv_ctest5, rv_stest2, rv_ccntl0, rv_ccntl1, rv_scntl4;
1257 
1258 	/*
1259 	 *  Target data used by the CPU.
1260 	 */
1261 	struct sym_tcb	target[SYM_CONF_MAX_TARGET];
1262 
1263 	/*
1264 	 *  Target control block bus address array used by the SCRIPT
1265 	 *  on reselection.
1266 	 */
1267 	u32		*targtbl;
1268 
1269 	/*
1270 	 *  CAM SIM information for this instance.
1271 	 */
1272 	struct		cam_sim  *sim;
1273 	struct		cam_path *path;
1274 
1275 	/*
1276 	 *  Allocated hardware resources.
1277 	 */
1278 #ifdef FreeBSD_4_Bus
1279 	struct resource	*irq_res;
1280 	struct resource	*io_res;
1281 	struct resource	*mmio_res;
1282 	struct resource	*ram_res;
1283 	int		ram_id;
1284 	void *intr;
1285 #endif
1286 
1287 	/*
1288 	 *  Bus stuff.
1289 	 *
1290 	 *  My understanding of PCI is that all agents must share the
1291 	 *  same addressing range and model.
1292 	 *  But some hardware architecture guys provide complex and
1293 	 *  brain-deaded stuff that makes shit.
1294 	 *  This driver only support PCI compliant implementations and
1295 	 *  deals with part of the BUS stuff complexity only to fit O/S
1296 	 *  requirements.
1297 	 */
1298 #ifdef FreeBSD_4_Bus
1299 	bus_space_handle_t	io_bsh;
1300 	bus_space_tag_t		io_tag;
1301 	bus_space_handle_t	mmio_bsh;
1302 	bus_space_tag_t		mmio_tag;
1303 	bus_space_handle_t	ram_bsh;
1304 	bus_space_tag_t		ram_tag;
1305 #endif
1306 
1307 	/*
1308 	 *  Virtual and physical bus addresses of the chip.
1309 	 */
1310 	vm_offset_t	mmio_va;	/* MMIO kernel virtual address	*/
1311 	vm_offset_t	mmio_pa;	/* MMIO CPU physical address	*/
1312 	vm_offset_t	mmio_ba;	/* MMIO BUS address		*/
1313 	int		mmio_ws;	/* MMIO Window size		*/
1314 
1315 	vm_offset_t	ram_va;		/* RAM kernel virtual address	*/
1316 	vm_offset_t	ram_pa;		/* RAM CPU physical address	*/
1317 	vm_offset_t	ram_ba;		/* RAM BUS address		*/
1318 	int		ram_ws;		/* RAM window size		*/
1319 	u32		io_port;	/* IO port address		*/
1320 
1321 	/*
1322 	 *  SCRIPTS virtual and physical bus addresses.
1323 	 *  'script'  is loaded in the on-chip RAM if present.
1324 	 *  'scripth' stays in main memory for all chips except the
1325 	 *  53C895A, 53C896 and 53C1010 that provide 8K on-chip RAM.
1326 	 */
1327 	struct sym_scr	*script0;	/* Copies of script and scripth	*/
1328 	struct sym_scrh	*scripth0;	/*  relocated for this host.	*/
1329 	vm_offset_t	script_ba;	/* Actual script and scripth	*/
1330 	vm_offset_t	scripth_ba;	/*  bus addresses.		*/
1331 	vm_offset_t	scripth0_ba;
1332 
1333 	/*
1334 	 *  General controller parameters and configuration.
1335 	 */
1336 	u_short	device_id;	/* PCI device id		*/
1337 	u_char	revision_id;	/* PCI device revision id	*/
1338 	u_int	features;	/* Chip features map		*/
1339 	u_char	myaddr;		/* SCSI id of the adapter	*/
1340 	u_char	maxburst;	/* log base 2 of dwords burst	*/
1341 	u_char	maxwide;	/* Maximum transfer width	*/
1342 	u_char	minsync;	/* Min sync period factor (ST)	*/
1343 	u_char	maxsync;	/* Max sync period factor (ST)	*/
1344 	u_char	minsync_dt;	/* Min sync period factor (DT)	*/
1345 	u_char	maxsync_dt;	/* Max sync period factor (DT)	*/
1346 	u_char	maxoffs;	/* Max scsi offset		*/
1347 	u_char	multiplier;	/* Clock multiplier (1,2,4)	*/
1348 	u_char	clock_divn;	/* Number of clock divisors	*/
1349 	u_long	clock_khz;	/* SCSI clock frequency in KHz	*/
1350 
1351 	/*
1352 	 *  Start queue management.
1353 	 *  It is filled up by the host processor and accessed by the
1354 	 *  SCRIPTS processor in order to start SCSI commands.
1355 	 */
1356 	volatile		/* Prevent code optimizations	*/
1357 	u32	*squeue;	/* Start queue			*/
1358 	u_short	squeueput;	/* Next free slot of the queue	*/
1359 	u_short	actccbs;	/* Number of allocated CCBs	*/
1360 
1361 	/*
1362 	 *  Command completion queue.
1363 	 *  It is the same size as the start queue to avoid overflow.
1364 	 */
1365 	u_short	dqueueget;	/* Next position to scan	*/
1366 	volatile		/* Prevent code optimizations	*/
1367 	u32	*dqueue;	/* Completion (done) queue	*/
1368 
1369 	/*
1370 	 *  Miscellaneous buffers accessed by the scripts-processor.
1371 	 *  They shall be DWORD aligned, because they may be read or
1372 	 *  written with a script command.
1373 	 */
1374 	u_char		msgout[8];	/* Buffer for MESSAGE OUT 	*/
1375 	u_char		msgin [8];	/* Buffer for MESSAGE IN	*/
1376 	u32		lastmsg;	/* Last SCSI message sent	*/
1377 	u_char		scratch;	/* Scratch for SCSI receive	*/
1378 
1379 	/*
1380 	 *  Miscellaneous configuration and status parameters.
1381 	 */
1382 	u_char		usrflags;	/* Miscellaneous user flags	*/
1383 	u_char		scsi_mode;	/* Current SCSI BUS mode	*/
1384 	u_char		verbose;	/* Verbosity for this controller*/
1385 	u32		cache;		/* Used for cache test at init.	*/
1386 
1387 	/*
1388 	 *  CCB lists and queue.
1389 	 */
1390 	ccb_p ccbh[CCB_HASH_SIZE];	/* CCB hashed by DSA value	*/
1391 	SYM_QUEHEAD	free_ccbq;	/* Queue of available CCBs	*/
1392 	SYM_QUEHEAD	busy_ccbq;	/* Queue of busy CCBs		*/
1393 
1394 	/*
1395 	 *  During error handling and/or recovery,
1396 	 *  active CCBs that are to be completed with
1397 	 *  error or requeued are moved from the busy_ccbq
1398 	 *  to the comp_ccbq prior to completion.
1399 	 */
1400 	SYM_QUEHEAD	comp_ccbq;
1401 
1402 	/*
1403 	 *  CAM CCB pending queue.
1404 	 */
1405 	SYM_QUEHEAD	cam_ccbq;
1406 
1407 	/*
1408 	 *  IMMEDIATE ARBITRATION (IARB) control.
1409 	 *
1410 	 *  We keep track in 'last_cp' of the last CCB that has been
1411 	 *  queued to the SCRIPTS processor and clear 'last_cp' when
1412 	 *  this CCB completes. If last_cp is not zero at the moment
1413 	 *  we queue a new CCB, we set a flag in 'last_cp' that is
1414 	 *  used by the SCRIPTS as a hint for setting IARB.
1415 	 *  We donnot set more than 'iarb_max' consecutive hints for
1416 	 *  IARB in order to leave devices a chance to reselect.
1417 	 *  By the way, any non zero value of 'iarb_max' is unfair. :)
1418 	 */
1419 #ifdef SYM_CONF_IARB_SUPPORT
1420 	u_short		iarb_max;	/* Max. # consecutive IARB hints*/
1421 	u_short		iarb_count;	/* Actual # of these hints	*/
1422 	ccb_p		last_cp;
1423 #endif
1424 
1425 	/*
1426 	 *  Command abort handling.
1427 	 *  We need to synchronize tightly with the SCRIPTS
1428 	 *  processor in order to handle things correctly.
1429 	 */
1430 	u_char		abrt_msg[4];	/* Message to send buffer	*/
1431 	struct sym_tblmove abrt_tbl;	/* Table for the MOV of it 	*/
1432 	struct sym_tblsel  abrt_sel;	/* Sync params for selection	*/
1433 	u_char		istat_sem;	/* Tells the chip to stop (SEM)	*/
1434 };
1435 
1436 #define SCRIPT_BA(np,lbl)   (np->script_ba   + offsetof(struct sym_scr, lbl))
1437 #define SCRIPTH_BA(np,lbl)  (np->scripth_ba  + offsetof(struct sym_scrh,lbl))
1438 #define SCRIPTH0_BA(np,lbl) (np->scripth0_ba + offsetof(struct sym_scrh,lbl))
1439 
1440 /*
1441  *  Scripts for SYMBIOS-Processor
1442  *
1443  *  Use sym_fill_scripts() to create the variable parts.
1444  *  Use sym_bind_script()  to make a copy and bind to
1445  *  physical bus addresses.
1446  *  We have to know the offsets of all labels before we reach
1447  *  them (for forward jumps). Therefore we declare a struct
1448  *  here. If you make changes inside the script,
1449  *
1450  *  DONT FORGET TO CHANGE THE LENGTHS HERE!
1451  */
1452 
1453 /*
1454  *  Script fragments which are loaded into the on-chip RAM
1455  *  of 825A, 875, 876, 895, 895A, 896 and 1010 chips.
1456  *  Must not exceed 4K bytes.
1457  */
1458 struct sym_scr {
1459 	u32 start		[ 14];
1460 	u32 getjob_begin	[  4];
1461 	u32 getjob_end		[  4];
1462 	u32 select		[  8];
1463 	u32 wf_sel_done		[  2];
1464 	u32 send_ident		[  2];
1465 #ifdef SYM_CONF_IARB_SUPPORT
1466 	u32 select2		[  8];
1467 #else
1468 	u32 select2		[  2];
1469 #endif
1470 	u32 command		[  2];
1471 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1472 	u32 dispatch		[ 18];
1473 #else
1474 	u32 dispatch		[ 30];
1475 #endif
1476 	u32 sel_no_cmd		[ 10];
1477 	u32 init		[  6];
1478 	u32 clrack		[  4];
1479 	u32 disp_msg_in		[  2];
1480 	u32 disp_status		[  4];
1481 	u32 datai_done		[ 16];
1482 	u32 datao_done		[ 10];
1483 	u32 ign_i_w_r_msg	[  4];
1484 	u32 dataphase		[  2];
1485 	u32 msg_in		[  2];
1486 	u32 msg_in2		[ 10];
1487 #ifdef SYM_CONF_IARB_SUPPORT
1488 	u32 status		[ 14];
1489 #else
1490 	u32 status		[ 10];
1491 #endif
1492 	u32 complete		[  8];
1493 	u32 complete2		[ 12];
1494 	u32 complete_error	[  4];
1495 	u32 done		[ 14];
1496 	u32 done_end		[  2];
1497 	u32 save_dp		[  8];
1498 	u32 restore_dp		[  4];
1499 	u32 disconnect		[ 20];
1500 #ifdef SYM_CONF_IARB_SUPPORT
1501 	u32 idle		[  4];
1502 #else
1503 	u32 idle		[  2];
1504 #endif
1505 #ifdef SYM_CONF_IARB_SUPPORT
1506 	u32 ungetjob		[  6];
1507 #else
1508 	u32 ungetjob		[  4];
1509 #endif
1510 	u32 reselect		[  4];
1511 	u32 reselected		[ 20];
1512 	u32 resel_scntl4	[ 28];
1513 #if   SYM_CONF_MAX_TASK*4 > 512
1514 	u32 resel_tag		[ 24];
1515 #elif SYM_CONF_MAX_TASK*4 > 256
1516 	u32 resel_tag		[ 18];
1517 #else
1518 	u32 resel_tag		[ 14];
1519 #endif
1520 	u32 resel_dsa		[  2];
1521 	u32 resel_dsa1		[  6];
1522 	u32 resel_no_tag	[  8];
1523 	u32 data_in		[SYM_CONF_MAX_SG * 2];
1524 	u32 data_in2		[  4];
1525 	u32 data_out		[SYM_CONF_MAX_SG * 2];
1526 	u32 data_out2		[  4];
1527 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1528 	u32 pm0_data		[ 28];
1529 	u32 pm1_data		[ 28];
1530 #else
1531 	u32 pm0_data		[ 16];
1532 	u32 pm1_data		[ 16];
1533 #endif
1534 };
1535 
1536 /*
1537  *  Script fragments which stay in main memory for all chips
1538  *  except for chips that support 8K on-chip RAM.
1539  */
1540 struct sym_scrh {
1541 	u32 start64		[  2];
1542 	u32 sel_for_abort	[ 18];
1543 	u32 sel_for_abort_1	[  2];
1544 	u32 select_no_atn	[  8];
1545 	u32 wf_sel_done_no_atn	[  4];
1546 
1547 	u32 msg_in_etc		[ 14];
1548 	u32 msg_received	[  4];
1549 	u32 msg_weird_seen	[  4];
1550 	u32 msg_extended	[ 20];
1551 	u32 msg_bad		[  6];
1552 	u32 msg_weird		[  4];
1553 	u32 msg_weird1		[  8];
1554 
1555 	u32 wdtr_resp		[  6];
1556 	u32 send_wdtr		[  4];
1557 	u32 sdtr_resp		[  6];
1558 	u32 send_sdtr		[  4];
1559 	u32 ppr_resp		[  6];
1560 	u32 send_ppr		[  4];
1561 	u32 nego_bad_phase	[  4];
1562 	u32 msg_out		[  4];
1563 	u32 msg_out_done	[  4];
1564 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1565 	u32 no_data		[ 36];
1566 #else
1567 	u32 no_data		[ 28];
1568 #endif
1569 	u32 abort_resel		[ 16];
1570 	u32 resend_ident	[  4];
1571 	u32 ident_break		[  4];
1572 	u32 ident_break_atn	[  4];
1573 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1574 	u32 sdata_in		[ 12];
1575 #else
1576 	u32 sdata_in		[  6];
1577 #endif
1578 	u32 resel_bad_lun	[  4];
1579 	u32 bad_i_t_l		[  4];
1580 	u32 bad_i_t_l_q		[  4];
1581 	u32 bad_status		[  6];
1582 	u32 pm_handle		[ 20];
1583 	u32 pm_handle1		[  4];
1584 	u32 pm_save		[  4];
1585 	u32 pm0_save		[ 14];
1586 	u32 pm1_save		[ 14];
1587 
1588 	/* SWIDE handling */
1589 	u32 swide_ma_32		[  4];
1590 	u32 swide_ma_64		[  6];
1591 	u32 swide_scr_64	[ 26];
1592 	u32 swide_scr_64_1	[ 12];
1593 	u32 swide_com_64	[  6];
1594 	u32 swide_common	[ 10];
1595 	u32 swide_fin_32	[ 24];
1596 
1597 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1598 	u32 dt_data_in		[SYM_CONF_MAX_SG * 2];
1599 	u32 dt_data_in2		[  4];
1600 	u32 dt_data_out		[SYM_CONF_MAX_SG * 2];
1601 	u32 dt_data_out2	[  4];
1602 #endif
1603 
1604 	/* Data area */
1605 	u32 zero		[  1];
1606 	u32 scratch		[  1];
1607 	u32 scratch1		[  1];
1608 	u32 pm0_data_addr	[  1];
1609 	u32 pm1_data_addr	[  1];
1610 	u32 saved_dsa		[  1];
1611 	u32 saved_drs		[  1];
1612 	u32 done_pos		[  1];
1613 	u32 startpos		[  1];
1614 	u32 targtbl		[  1];
1615 	/* End of data area */
1616 
1617 	u32 snooptest		[  6];
1618 	u32 snoopend		[  2];
1619 };
1620 
1621 /*
1622  *  Function prototypes.
1623  */
1624 static void sym_fill_scripts (script_p scr, scripth_p scrh);
1625 static void sym_bind_script (hcb_p np, u32 *src, u32 *dst, int len);
1626 static void sym_save_initial_setting (hcb_p np);
1627 static int  sym_prepare_setting (hcb_p np, struct sym_nvram *nvram);
1628 static int  sym_prepare_nego (hcb_p np, ccb_p cp, int nego, u_char *msgptr);
1629 static void sym_put_start_queue (hcb_p np, ccb_p cp);
1630 static void sym_chip_reset (hcb_p np);
1631 static void sym_soft_reset (hcb_p np);
1632 static void sym_start_reset (hcb_p np);
1633 static int  sym_reset_scsi_bus (hcb_p np, int enab_int);
1634 static int  sym_wakeup_done (hcb_p np);
1635 static void sym_flush_busy_queue (hcb_p np, int cam_status);
1636 static void sym_flush_comp_queue (hcb_p np, int cam_status);
1637 static void sym_init (hcb_p np, int reason);
1638 static int  sym_getsync(hcb_p np, u_char dt, u_char sfac, u_char *divp,
1639 		        u_char *fakp);
1640 static void sym_setsync (hcb_p np, ccb_p cp, u_char ofs, u_char per,
1641 			 u_char div, u_char fak);
1642 static void sym_setwide (hcb_p np, ccb_p cp, u_char wide);
1643 static void sym_setpprot(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
1644 			 u_char per, u_char wide, u_char div, u_char fak);
1645 static void sym_settrans(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
1646 			 u_char per, u_char wide, u_char div, u_char fak);
1647 static void sym_log_hard_error (hcb_p np, u_short sist, u_char dstat);
1648 static void sym_intr (void *arg);
1649 static void sym_poll (struct cam_sim *sim);
1650 static void sym_recover_scsi_int (hcb_p np, u_char hsts);
1651 static void sym_int_sto (hcb_p np);
1652 static void sym_int_udc (hcb_p np);
1653 static void sym_int_sbmc (hcb_p np);
1654 static void sym_int_par (hcb_p np, u_short sist);
1655 static void sym_int_ma (hcb_p np);
1656 static int  sym_dequeue_from_squeue(hcb_p np, int i, int target, int lun,
1657 				    int task);
1658 static void sym_sir_bad_scsi_status (hcb_p np, int num, ccb_p cp);
1659 static int  sym_clear_tasks (hcb_p np, int status, int targ, int lun, int task);
1660 static void sym_sir_task_recovery (hcb_p np, int num);
1661 static int  sym_evaluate_dp (hcb_p np, ccb_p cp, u32 scr, int *ofs);
1662 static void sym_modify_dp (hcb_p np, tcb_p tp, ccb_p cp, int ofs);
1663 static int  sym_compute_residual (hcb_p np, ccb_p cp);
1664 static int  sym_show_msg (u_char * msg);
1665 static void sym_print_msg (ccb_p cp, char *label, u_char *msg);
1666 static void sym_sync_nego (hcb_p np, tcb_p tp, ccb_p cp);
1667 static void sym_ppr_nego (hcb_p np, tcb_p tp, ccb_p cp);
1668 static void sym_wide_nego (hcb_p np, tcb_p tp, ccb_p cp);
1669 static void sym_nego_default (hcb_p np, tcb_p tp, ccb_p cp);
1670 static void sym_nego_rejected (hcb_p np, tcb_p tp, ccb_p cp);
1671 static void sym_int_sir (hcb_p np);
1672 static void sym_free_ccb (hcb_p np, ccb_p cp);
1673 static ccb_p sym_get_ccb (hcb_p np, u_char tn, u_char ln, u_char tag_order);
1674 static ccb_p sym_alloc_ccb (hcb_p np);
1675 static ccb_p sym_ccb_from_dsa (hcb_p np, u_long dsa);
1676 static lcb_p sym_alloc_lcb (hcb_p np, u_char tn, u_char ln);
1677 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln);
1678 static int  sym_snooptest (hcb_p np);
1679 static void sym_selectclock(hcb_p np, u_char scntl3);
1680 static void sym_getclock (hcb_p np, int mult);
1681 static int  sym_getpciclock (hcb_p np);
1682 static void sym_complete_ok (hcb_p np, ccb_p cp);
1683 static void sym_complete_error (hcb_p np, ccb_p cp);
1684 static void sym_timeout (void *arg);
1685 static int  sym_abort_scsiio (hcb_p np, union ccb *ccb, int timed_out);
1686 static void sym_reset_dev (hcb_p np, union ccb *ccb);
1687 static void sym_action (struct cam_sim *sim, union ccb *ccb);
1688 static void sym_action1 (struct cam_sim *sim, union ccb *ccb);
1689 static int  sym_setup_cdb (hcb_p np, struct ccb_scsiio *csio, ccb_p cp);
1690 static int  sym_setup_data(hcb_p np, struct ccb_scsiio *csio, ccb_p cp);
1691 static int  sym_scatter_virtual (hcb_p np, ccb_p cp, vm_offset_t vaddr,
1692 				 vm_size_t len);
1693 static int  sym_scatter_physical (hcb_p np, ccb_p cp, vm_offset_t vaddr,
1694 				 vm_size_t len);
1695 static void sym_action2 (struct cam_sim *sim, union ccb *ccb);
1696 static void sym_update_trans (hcb_p np, tcb_p tp, struct sym_trans *tip,
1697 			      struct ccb_trans_settings *cts);
1698 static void sym_update_dflags(hcb_p np, u_char *flags,
1699 			      struct ccb_trans_settings *cts);
1700 
1701 #ifdef FreeBSD_4_Bus
1702 static struct sym_pci_chip *sym_find_pci_chip (device_t dev);
1703 static int  sym_pci_probe (device_t dev);
1704 static int  sym_pci_attach (device_t dev);
1705 #else
1706 static struct sym_pci_chip *sym_find_pci_chip (pcici_t tag);
1707 static const char *sym_pci_probe (pcici_t tag, pcidi_t type);
1708 static void sym_pci_attach (pcici_t tag, int unit);
1709 static int sym_pci_attach2 (pcici_t tag, int unit);
1710 #endif
1711 
1712 static void sym_pci_free (hcb_p np);
1713 static int  sym_cam_attach (hcb_p np);
1714 static void sym_cam_free (hcb_p np);
1715 
1716 static void sym_nvram_setup_host (hcb_p np, struct sym_nvram *nvram);
1717 static void sym_nvram_setup_target (hcb_p np, int targ, struct sym_nvram *nvp);
1718 static int sym_read_nvram (hcb_p np, struct sym_nvram *nvp);
1719 
1720 /*
1721  *  Return the name of the controller.
1722  */
1723 static __inline char *sym_name(hcb_p np)
1724 {
1725 	return np->inst_name;
1726 }
1727 
1728 /*
1729  *  Scripts for SYMBIOS-Processor
1730  *
1731  *  Use sym_bind_script for binding to physical addresses.
1732  *
1733  *  NADDR generates a reference to a field of the controller data.
1734  *  PADDR generates a reference to another part of the script.
1735  *  RADDR generates a reference to a script processor register.
1736  *  FADDR generates a reference to a script processor register
1737  *        with offset.
1738  *
1739  */
1740 #define	RELOC_SOFTC	0x40000000
1741 #define	RELOC_LABEL	0x50000000
1742 #define	RELOC_REGISTER	0x60000000
1743 #if 0
1744 #define	RELOC_KVAR	0x70000000
1745 #endif
1746 #define	RELOC_LABELH	0x80000000
1747 #define	RELOC_MASK	0xf0000000
1748 
1749 #define	NADDR(label)	(RELOC_SOFTC  | offsetof(struct sym_hcb, label))
1750 #define PADDR(label)    (RELOC_LABEL  | offsetof(struct sym_scr, label))
1751 #define PADDRH(label)   (RELOC_LABELH | offsetof(struct sym_scrh, label))
1752 #define	RADDR(label)	(RELOC_REGISTER | REG(label))
1753 #define	FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1754 #define	KVAR(which)	(RELOC_KVAR | (which))
1755 
1756 #define SCR_DATA_ZERO	0xf00ff00f
1757 
1758 #ifdef	RELOC_KVAR
1759 #define	SCRIPT_KVAR_JIFFIES	(0)
1760 #define	SCRIPT_KVAR_FIRST	SCRIPT_KVAR_XXXXXXX
1761 #define	SCRIPT_KVAR_LAST	SCRIPT_KVAR_XXXXXXX
1762 /*
1763  * Kernel variables referenced in the scripts.
1764  * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
1765  */
1766 static void *script_kvars[] =
1767 	{ (void *)&xxxxxxx };
1768 #endif
1769 
1770 static struct sym_scr script0 = {
1771 /*--------------------------< START >-----------------------*/ {
1772 	/*
1773 	 *  This NOP will be patched with LED ON
1774 	 *  SCR_REG_REG (gpreg, SCR_AND, 0xfe)
1775 	 */
1776 	SCR_NO_OP,
1777 		0,
1778 	/*
1779 	 *      Clear SIGP.
1780 	 */
1781 	SCR_FROM_REG (ctest2),
1782 		0,
1783 	/*
1784 	 *  Stop here if the C code wants to perform
1785 	 *  some error recovery procedure manually.
1786 	 *  (Indicate this by setting SEM in ISTAT)
1787 	 */
1788 	SCR_FROM_REG (istat),
1789 		0,
1790 	/*
1791 	 *  Report to the C code the next position in
1792 	 *  the start queue the SCRIPTS will schedule.
1793 	 *  The C code must not change SCRATCHA.
1794 	 */
1795 	SCR_LOAD_ABS (scratcha, 4),
1796 		PADDRH (startpos),
1797 	SCR_INT ^ IFTRUE (MASK (SEM, SEM)),
1798 		SIR_SCRIPT_STOPPED,
1799 	/*
1800 	 *  Start the next job.
1801 	 *
1802 	 *  @DSA	 = start point for this job.
1803 	 *  SCRATCHA = address of this job in the start queue.
1804 	 *
1805 	 *  We will restore startpos with SCRATCHA if we fails the
1806 	 *  arbitration or if it is the idle job.
1807 	 *
1808 	 *  The below GETJOB_BEGIN to GETJOB_END section of SCRIPTS
1809 	 *  is a critical path. If it is partially executed, it then
1810 	 *  may happen that the job address is not yet in the DSA
1811 	 *  and the the next queue position points to the next JOB.
1812 	 */
1813 	SCR_LOAD_ABS (dsa, 4),
1814 		PADDRH (startpos),
1815 	SCR_LOAD_REL (temp, 4),
1816 		4,
1817 }/*-------------------------< GETJOB_BEGIN >------------------*/,{
1818 	SCR_STORE_ABS (temp, 4),
1819 		PADDRH (startpos),
1820 	SCR_LOAD_REL (dsa, 4),
1821 		0,
1822 }/*-------------------------< GETJOB_END >--------------------*/,{
1823 	SCR_LOAD_REL (temp, 4),
1824 		0,
1825 	SCR_RETURN,
1826 		0,
1827 }/*-------------------------< SELECT >----------------------*/,{
1828 	/*
1829 	 *  DSA	contains the address of a scheduled
1830 	 *  	data structure.
1831 	 *
1832 	 *  SCRATCHA contains the address of the start queue
1833 	 *  	entry which points to the next job.
1834 	 *
1835 	 *  Set Initiator mode.
1836 	 *
1837 	 *  (Target mode is left as an exercise for the reader)
1838 	 */
1839 	SCR_CLR (SCR_TRG),
1840 		0,
1841 	/*
1842 	 *      And try to select this target.
1843 	 */
1844 	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
1845 		PADDR (ungetjob),
1846 	/*
1847 	 *  Now there are 4 possibilities:
1848 	 *
1849 	 *  (1) The chip looses arbitration.
1850 	 *  This is ok, because it will try again,
1851 	 *  when the bus becomes idle.
1852 	 *  (But beware of the timeout function!)
1853 	 *
1854 	 *  (2) The chip is reselected.
1855 	 *  Then the script processor takes the jump
1856 	 *  to the RESELECT label.
1857 	 *
1858 	 *  (3) The chip wins arbitration.
1859 	 *  Then it will execute SCRIPTS instruction until
1860 	 *  the next instruction that checks SCSI phase.
1861 	 *  Then will stop and wait for selection to be
1862 	 *  complete or selection time-out to occur.
1863 	 *
1864 	 *  After having won arbitration, the SCRIPTS
1865 	 *  processor is able to execute instructions while
1866 	 *  the SCSI core is performing SCSI selection.
1867 	 */
1868 	/*
1869 	 *      load the savep (saved data pointer) into
1870 	 *      the actual data pointer.
1871 	 */
1872 	SCR_LOAD_REL (temp, 4),
1873 		offsetof (struct sym_ccb, phys.savep),
1874 	/*
1875 	 *      Initialize the status registers
1876 	 */
1877 	SCR_LOAD_REL (scr0, 4),
1878 		offsetof (struct sym_ccb, phys.status),
1879 }/*-------------------------< WF_SEL_DONE >----------------------*/,{
1880 	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
1881 		SIR_SEL_ATN_NO_MSG_OUT,
1882 }/*-------------------------< SEND_IDENT >----------------------*/,{
1883 	/*
1884 	 *  Selection complete.
1885 	 *  Send the IDENTIFY and possibly the TAG message
1886 	 *  and negotiation message if present.
1887 	 */
1888 	SCR_MOVE_TBL ^ SCR_MSG_OUT,
1889 		offsetof (struct dsb, smsg),
1890 }/*-------------------------< SELECT2 >----------------------*/,{
1891 #ifdef SYM_CONF_IARB_SUPPORT
1892 	/*
1893 	 *  Set IMMEDIATE ARBITRATION if we have been given
1894 	 *  a hint to do so. (Some job to do after this one).
1895 	 */
1896 	SCR_FROM_REG (HF_REG),
1897 		0,
1898 	SCR_JUMPR ^ IFFALSE (MASK (HF_HINT_IARB, HF_HINT_IARB)),
1899 		8,
1900 	SCR_REG_REG (scntl1, SCR_OR, IARB),
1901 		0,
1902 #endif
1903 	/*
1904 	 *  Anticipate the COMMAND phase.
1905 	 *  This is the PHASE we expect at this point.
1906 	 */
1907 	SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
1908 		PADDR (sel_no_cmd),
1909 }/*-------------------------< COMMAND >--------------------*/,{
1910 	/*
1911 	 *  ... and send the command
1912 	 */
1913 	SCR_MOVE_TBL ^ SCR_COMMAND,
1914 		offsetof (struct dsb, cmd),
1915 }/*-----------------------< DISPATCH >----------------------*/,{
1916 	/*
1917 	 *  MSG_IN is the only phase that shall be
1918 	 *  entered at least once for each (re)selection.
1919 	 *  So we test it first.
1920 	 */
1921 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
1922 		PADDR (msg_in),
1923 	SCR_JUMP ^ IFTRUE (IF (SCR_DATA_OUT)),
1924 		PADDR (dataphase),
1925 	SCR_JUMP ^ IFTRUE (IF (SCR_DATA_IN)),
1926 		PADDR (dataphase),
1927 	SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
1928 		PADDR (status),
1929 	SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
1930 		PADDR (command),
1931 	SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
1932 		PADDRH (msg_out),
1933 
1934 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
1935 	SCR_JUMP ^ IFTRUE (IF (SCR_DT_DATA_OUT)),
1936 		PADDR (dataphase),
1937 	SCR_JUMP ^ IFTRUE (IF (SCR_DT_DATA_IN)),
1938 		PADDR (dataphase),
1939 #else
1940 	/*
1941 	 *  Set the extended error flag.
1942 	 */
1943 	SCR_REG_REG (HF_REG, SCR_OR, HF_EXT_ERR),
1944 		0,
1945 	/*
1946 	 *  Discard one illegal phase byte, if required.
1947 	 */
1948 	SCR_LOAD_REL (scratcha, 1),
1949 		offsetof (struct sym_ccb, xerr_status),
1950 	SCR_REG_REG (scratcha,  SCR_OR,  XE_BAD_PHASE),
1951 		0,
1952 	SCR_STORE_REL (scratcha, 1),
1953 		offsetof (struct sym_ccb, xerr_status),
1954 	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
1955 		8,
1956 	SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
1957 		NADDR (scratch),
1958 	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
1959 		8,
1960 	SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
1961 		NADDR (scratch),
1962 #endif	/* SYM_CONF_BROKEN_U3EN_SUPPORT */
1963 
1964 	SCR_JUMP,
1965 		PADDR (dispatch),
1966 }/*---------------------< SEL_NO_CMD >----------------------*/,{
1967 	/*
1968 	 *  The target does not switch to command
1969 	 *  phase after IDENTIFY has been sent.
1970 	 *
1971 	 *  If it stays in MSG OUT phase send it
1972 	 *  the IDENTIFY again.
1973 	 */
1974 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
1975 		PADDRH (resend_ident),
1976 	/*
1977 	 *  If target does not switch to MSG IN phase
1978 	 *  and we sent a negotiation, assert the
1979 	 *  failure immediately.
1980 	 */
1981 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
1982 		PADDR (dispatch),
1983 	SCR_FROM_REG (HS_REG),
1984 		0,
1985 	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
1986 		SIR_NEGO_FAILED,
1987 	/*
1988 	 *  Jump to dispatcher.
1989 	 */
1990 	SCR_JUMP,
1991 		PADDR (dispatch),
1992 }/*-------------------------< INIT >------------------------*/,{
1993 	/*
1994 	 *  Wait for the SCSI RESET signal to be
1995 	 *  inactive before restarting operations,
1996 	 *  since the chip may hang on SEL_ATN
1997 	 *  if SCSI RESET is active.
1998 	 */
1999 	SCR_FROM_REG (sstat0),
2000 		0,
2001 	SCR_JUMPR ^ IFTRUE (MASK (IRST, IRST)),
2002 		-16,
2003 	SCR_JUMP,
2004 		PADDR (start),
2005 }/*-------------------------< CLRACK >----------------------*/,{
2006 	/*
2007 	 *  Terminate possible pending message phase.
2008 	 */
2009 	SCR_CLR (SCR_ACK),
2010 		0,
2011 	SCR_JUMP,
2012 		PADDR (dispatch),
2013 }/*-------------------------< DISP_MSG_IN >----------------------*/,{
2014 	/*
2015 	 *  Anticipate MSG_IN phase then STATUS phase.
2016 	 *
2017 	 *  May spare 2 SCRIPTS instructions when we have
2018 	 *  completed the OUTPUT of the data and the device
2019 	 *  goes directly to STATUS phase.
2020 	 */
2021 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2022 		PADDR (msg_in),
2023 }/*-------------------------< DISP_STATUS >----------------------*/,{
2024 	/*
2025 	 *  Anticipate STATUS phase.
2026 	 *
2027 	 *  Does spare 3 SCRIPTS instructions when we have
2028 	 *  completed the INPUT of the data.
2029 	 */
2030 	SCR_JUMP ^ IFTRUE (WHEN (SCR_STATUS)),
2031 		PADDR (status),
2032 	SCR_JUMP,
2033 		PADDR (dispatch),
2034 }/*-------------------------< DATAI_DONE >-------------------*/,{
2035 	/*
2036 	 *  If the SWIDE is not full, jump to dispatcher.
2037 	 *  We anticipate a STATUS phase.
2038 	 *  If we get later an IGNORE WIDE RESIDUE, we
2039 	 *  will alias it as a MODIFY DP (-1).
2040 	 */
2041 	SCR_FROM_REG (scntl2),
2042 		0,
2043 	SCR_JUMP ^ IFFALSE (MASK (WSR, WSR)),
2044 		PADDR (disp_status),
2045 	/*
2046 	 *  The SWIDE is full.
2047 	 *  Clear this condition.
2048 	 */
2049 	SCR_REG_REG (scntl2, SCR_OR, WSR),
2050 		0,
2051 	/*
2052 	 *  Since the device is required to send any
2053 	 *  IGNORE WIDE RESIDUE message prior to any
2054 	 *  other information, we just snoop the SCSI
2055 	 *  BUS to check for such a message.
2056 	 */
2057 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
2058 		16,
2059 	SCR_FROM_REG (sbdl),
2060 		0,
2061 	SCR_JUMP ^ IFTRUE (DATA (M_IGN_RESIDUE)),
2062 		PADDR (disp_msg_in),
2063 	/*
2064 	 *  We have been ODD at the end of the transfer,
2065 	 *  but the device hasn't be so.
2066 	 *  Signal a DATA OVERRUN condition to the C code.
2067 	 */
2068 	SCR_INT,
2069 		SIR_SWIDE_OVERRUN,
2070 	SCR_JUMP,
2071 		PADDR (dispatch),
2072 }/*-------------------------< DATAO_DONE >-------------------*/,{
2073 	/*
2074 	 *  If the SODL is not full jump to dispatcher.
2075 	 *  We anticipate a MSG IN phase or a STATUS phase.
2076 	 */
2077 	SCR_FROM_REG (scntl2),
2078 		0,
2079 	SCR_JUMP ^ IFFALSE (MASK (WSS, WSS)),
2080 		PADDR (disp_status),
2081 	/*
2082 	 *  The SODL is full, clear this condition.
2083 	 */
2084 	SCR_REG_REG (scntl2, SCR_OR, WSS),
2085 		0,
2086 	/*
2087 	 *  And signal a DATA UNDERRUN condition
2088 	 *  to the C code.
2089 	 */
2090 	SCR_INT,
2091 		SIR_SODL_UNDERRUN,
2092 	SCR_JUMP,
2093 		PADDR (dispatch),
2094 }/*-------------------------< IGN_I_W_R_MSG >--------------*/,{
2095 	/*
2096 	 *  We jump here from the phase mismatch interrupt,
2097 	 *  When we have a SWIDE and the device has presented
2098 	 *  a IGNORE WIDE RESIDUE message on the BUS.
2099 	 *  We just have to throw away this message and then
2100 	 *  to jump to dispatcher.
2101 	 */
2102 	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2103 		NADDR (scratch),
2104 	/*
2105 	 *  Clear ACK and jump to dispatcher.
2106 	 */
2107 	SCR_JUMP,
2108 		PADDR (clrack),
2109 }/*-------------------------< DATAPHASE >------------------*/,{
2110 	SCR_RETURN,
2111  		0,
2112 }/*-------------------------< MSG_IN >--------------------*/,{
2113 	/*
2114 	 *  Get the first byte of the message.
2115 	 *
2116 	 *  The script processor doesn't negate the
2117 	 *  ACK signal after this transfer.
2118 	 */
2119 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2120 		NADDR (msgin[0]),
2121 }/*-------------------------< MSG_IN2 >--------------------*/,{
2122 	/*
2123 	 *  Check first against 1 byte messages
2124 	 *  that we handle from SCRIPTS.
2125 	 */
2126 	SCR_JUMP ^ IFTRUE (DATA (M_COMPLETE)),
2127 		PADDR (complete),
2128 	SCR_JUMP ^ IFTRUE (DATA (M_DISCONNECT)),
2129 		PADDR (disconnect),
2130 	SCR_JUMP ^ IFTRUE (DATA (M_SAVE_DP)),
2131 		PADDR (save_dp),
2132 	SCR_JUMP ^ IFTRUE (DATA (M_RESTORE_DP)),
2133 		PADDR (restore_dp),
2134 	/*
2135 	 *  We handle all other messages from the
2136 	 *  C code, so no need to waste on-chip RAM
2137 	 *  for those ones.
2138 	 */
2139 	SCR_JUMP,
2140 		PADDRH (msg_in_etc),
2141 }/*-------------------------< STATUS >--------------------*/,{
2142 	/*
2143 	 *  get the status
2144 	 */
2145 	SCR_MOVE_ABS (1) ^ SCR_STATUS,
2146 		NADDR (scratch),
2147 #ifdef SYM_CONF_IARB_SUPPORT
2148 	/*
2149 	 *  If STATUS is not GOOD, clear IMMEDIATE ARBITRATION,
2150 	 *  since we may have to tamper the start queue from
2151 	 *  the C code.
2152 	 */
2153 	SCR_JUMPR ^ IFTRUE (DATA (S_GOOD)),
2154 		8,
2155 	SCR_REG_REG (scntl1, SCR_AND, ~IARB),
2156 		0,
2157 #endif
2158 	/*
2159 	 *  save status to scsi_status.
2160 	 *  mark as complete.
2161 	 */
2162 	SCR_TO_REG (SS_REG),
2163 		0,
2164 	SCR_LOAD_REG (HS_REG, HS_COMPLETE),
2165 		0,
2166 	/*
2167 	 *  Anticipate the MESSAGE PHASE for
2168 	 *  the TASK COMPLETE message.
2169 	 */
2170 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2171 		PADDR (msg_in),
2172 	SCR_JUMP,
2173 		PADDR (dispatch),
2174 }/*-------------------------< COMPLETE >-----------------*/,{
2175 	/*
2176 	 *  Complete message.
2177 	 *
2178 	 *  Copy the data pointer to LASTP.
2179 	 */
2180 	SCR_STORE_REL (temp, 4),
2181 		offsetof (struct sym_ccb, phys.lastp),
2182 	/*
2183 	 *  When we terminate the cycle by clearing ACK,
2184 	 *  the target may disconnect immediately.
2185 	 *
2186 	 *  We don't want to be told of an "unexpected disconnect",
2187 	 *  so we disable this feature.
2188 	 */
2189 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2190 		0,
2191 	/*
2192 	 *  Terminate cycle ...
2193 	 */
2194 	SCR_CLR (SCR_ACK|SCR_ATN),
2195 		0,
2196 	/*
2197 	 *  ... and wait for the disconnect.
2198 	 */
2199 	SCR_WAIT_DISC,
2200 		0,
2201 }/*-------------------------< COMPLETE2 >-----------------*/,{
2202 	/*
2203 	 *  Save host status.
2204 	 */
2205 	SCR_STORE_REL (scr0, 4),
2206 		offsetof (struct sym_ccb, phys.status),
2207 	/*
2208 	 *  Some bridges may reorder DMA writes to memory.
2209 	 *  We donnot want the CPU to deal with completions
2210 	 *  without all the posted write having been flushed
2211 	 *  to memory. This DUMMY READ should flush posted
2212 	 *  buffers prior to the CPU having to deal with
2213 	 *  completions.
2214 	 */
2215 	SCR_LOAD_REL (scr0, 4),	/* DUMMY READ */
2216 		offsetof (struct sym_ccb, phys.status),
2217 
2218 	/*
2219 	 *  If command resulted in not GOOD status,
2220 	 *  call the C code if needed.
2221 	 */
2222 	SCR_FROM_REG (SS_REG),
2223 		0,
2224 	SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
2225 		PADDRH (bad_status),
2226 	/*
2227 	 *  If we performed an auto-sense, call
2228 	 *  the C code to synchronyze task aborts
2229 	 *  with UNIT ATTENTION conditions.
2230 	 */
2231 	SCR_FROM_REG (HF_REG),
2232 		0,
2233 	SCR_JUMPR ^ IFTRUE (MASK (0 ,(HF_SENSE|HF_EXT_ERR))),
2234 		16,
2235 }/*-------------------------< COMPLETE_ERROR >-----------------*/,{
2236 	SCR_LOAD_ABS (scratcha, 4),
2237 		PADDRH (startpos),
2238 	SCR_INT,
2239 		SIR_COMPLETE_ERROR,
2240 }/*------------------------< DONE >-----------------*/,{
2241 	/*
2242 	 *  Copy the DSA to the DONE QUEUE and
2243 	 *  signal completion to the host.
2244 	 *  If we are interrupted between DONE
2245 	 *  and DONE_END, we must reset, otherwise
2246 	 *  the completed CCB may be lost.
2247 	 */
2248 	SCR_STORE_ABS (dsa, 4),
2249 		PADDRH (saved_dsa),
2250 	SCR_LOAD_ABS (dsa, 4),
2251 		PADDRH (done_pos),
2252 	SCR_LOAD_ABS (scratcha, 4),
2253 		PADDRH (saved_dsa),
2254 	SCR_STORE_REL (scratcha, 4),
2255 		0,
2256 	/*
2257 	 *  The instruction below reads the DONE QUEUE next
2258 	 *  free position from memory.
2259 	 *  In addition it ensures that all PCI posted writes
2260 	 *  are flushed and so the DSA value of the done
2261 	 *  CCB is visible by the CPU before INTFLY is raised.
2262 	 */
2263 	SCR_LOAD_REL (temp, 4),
2264 		4,
2265 	SCR_INT_FLY,
2266 		0,
2267 	SCR_STORE_ABS (temp, 4),
2268 		PADDRH (done_pos),
2269 }/*------------------------< DONE_END >-----------------*/,{
2270 	SCR_JUMP,
2271 		PADDR (start),
2272 }/*-------------------------< SAVE_DP >------------------*/,{
2273 	/*
2274 	 *  Clear ACK immediately.
2275 	 *  No need to delay it.
2276 	 */
2277 	SCR_CLR (SCR_ACK),
2278 		0,
2279 	/*
2280 	 *  Keep track we received a SAVE DP, so
2281 	 *  we will switch to the other PM context
2282 	 *  on the next PM since the DP may point
2283 	 *  to the current PM context.
2284 	 */
2285 	SCR_REG_REG (HF_REG, SCR_OR, HF_DP_SAVED),
2286 		0,
2287 	/*
2288 	 *  SAVE_DP message:
2289 	 *  Copy the data pointer to SAVEP.
2290 	 */
2291 	SCR_STORE_REL (temp, 4),
2292 		offsetof (struct sym_ccb, phys.savep),
2293 	SCR_JUMP,
2294 		PADDR (dispatch),
2295 }/*-------------------------< RESTORE_DP >---------------*/,{
2296 	/*
2297 	 *  RESTORE_DP message:
2298 	 *  Copy SAVEP to actual data pointer.
2299 	 */
2300 	SCR_LOAD_REL  (temp, 4),
2301 		offsetof (struct sym_ccb, phys.savep),
2302 	SCR_JUMP,
2303 		PADDR (clrack),
2304 }/*-------------------------< DISCONNECT >---------------*/,{
2305 	/*
2306 	 *  DISCONNECTing  ...
2307 	 *
2308 	 *  disable the "unexpected disconnect" feature,
2309 	 *  and remove the ACK signal.
2310 	 */
2311 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2312 		0,
2313 	SCR_CLR (SCR_ACK|SCR_ATN),
2314 		0,
2315 	/*
2316 	 *  Wait for the disconnect.
2317 	 */
2318 	SCR_WAIT_DISC,
2319 		0,
2320 	/*
2321 	 *  Status is: DISCONNECTED.
2322 	 */
2323 	SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2324 		0,
2325 	/*
2326 	 *  Save host status.
2327 	 */
2328 	SCR_STORE_REL (scr0, 4),
2329 		offsetof (struct sym_ccb, phys.status),
2330 	/*
2331 	 *  If QUIRK_AUTOSAVE is set,
2332 	 *  do an "save pointer" operation.
2333 	 */
2334 	SCR_FROM_REG (QU_REG),
2335 		0,
2336 	SCR_JUMP ^ IFFALSE (MASK (SYM_QUIRK_AUTOSAVE, SYM_QUIRK_AUTOSAVE)),
2337 		PADDR (start),
2338 	/*
2339 	 *  like SAVE_DP message:
2340 	 *  Remember we saved the data pointer.
2341 	 *  Copy data pointer to SAVEP.
2342 	 */
2343 	SCR_REG_REG (HF_REG, SCR_OR, HF_DP_SAVED),
2344 		0,
2345 	SCR_STORE_REL (temp, 4),
2346 		offsetof (struct sym_ccb, phys.savep),
2347 	SCR_JUMP,
2348 		PADDR (start),
2349 }/*-------------------------< IDLE >------------------------*/,{
2350 	/*
2351 	 *  Nothing to do?
2352 	 *  Wait for reselect.
2353 	 *  This NOP will be patched with LED OFF
2354 	 *  SCR_REG_REG (gpreg, SCR_OR, 0x01)
2355 	 */
2356 	SCR_NO_OP,
2357 		0,
2358 #ifdef SYM_CONF_IARB_SUPPORT
2359 	SCR_JUMPR,
2360 		8,
2361 #endif
2362 }/*-------------------------< UNGETJOB >-----------------*/,{
2363 #ifdef SYM_CONF_IARB_SUPPORT
2364 	/*
2365 	 *  Set IMMEDIATE ARBITRATION, for the next time.
2366 	 *  This will give us better chance to win arbitration
2367 	 *  for the job we just wanted to do.
2368 	 */
2369 	SCR_REG_REG (scntl1, SCR_OR, IARB),
2370 		0,
2371 #endif
2372 	/*
2373 	 *  We are not able to restart the SCRIPTS if we are
2374 	 *  interrupted and these instruction haven't been
2375 	 *  all executed. BTW, this is very unlikely to
2376 	 *  happen, but we check that from the C code.
2377 	 */
2378 	SCR_LOAD_REG (dsa, 0xff),
2379 		0,
2380 	SCR_STORE_ABS (scratcha, 4),
2381 		PADDRH (startpos),
2382 }/*-------------------------< RESELECT >--------------------*/,{
2383 	/*
2384 	 *  Make sure we are in initiator mode.
2385 	 */
2386 	SCR_CLR (SCR_TRG),
2387 		0,
2388 	/*
2389 	 *  Sleep waiting for a reselection.
2390 	 */
2391 	SCR_WAIT_RESEL,
2392 		PADDR(start),
2393 }/*-------------------------< RESELECTED >------------------*/,{
2394 	/*
2395 	 *  This NOP will be patched with LED ON
2396 	 *  SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2397 	 */
2398 	SCR_NO_OP,
2399 		0,
2400 	/*
2401 	 *  load the target id into the sdid
2402 	 */
2403 	SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2404 		0,
2405 	SCR_TO_REG (sdid),
2406 		0,
2407 	/*
2408 	 *  Load the target control block address
2409 	 */
2410 	SCR_LOAD_ABS (dsa, 4),
2411 		PADDRH (targtbl),
2412 	SCR_SFBR_REG (dsa, SCR_SHL, 0),
2413 		0,
2414 	SCR_REG_REG (dsa, SCR_SHL, 0),
2415 		0,
2416 	SCR_REG_REG (dsa, SCR_AND, 0x3c),
2417 		0,
2418 	SCR_LOAD_REL (dsa, 4),
2419 		0,
2420 	/*
2421 	 *  Load the legacy synchronous transfer registers.
2422 	 */
2423 	SCR_LOAD_REL (scntl3, 1),
2424 		offsetof(struct sym_tcb, wval),
2425 	SCR_LOAD_REL (sxfer, 1),
2426 		offsetof(struct sym_tcb, sval),
2427 }/*-------------------------< RESEL_SCNTL4 >------------------*/,{
2428 	/*
2429 	 *  If C1010, patched with the load of SCNTL4 that
2430 	 *  allows a new synchronous timing scheme.
2431 	 *
2432 	 *	SCR_LOAD_REL (scntl4, 1),
2433 	 * 		offsetof(struct tcb, uval),
2434 	 */
2435 	SCR_NO_OP,
2436 		0,
2437 	/*
2438 	 *  If MESSAGE IN phase as expected,
2439 	 *  Read the data directly from the BUS DATA lines.
2440 	 *  This helps to support very old SCSI devices that
2441 	 *  may reselect without sending an IDENTIFY.
2442 	 */
2443 	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2444 		SIR_RESEL_NO_MSG_IN,
2445 	SCR_FROM_REG (sbdl),
2446 		0,
2447 	/*
2448 	 *  If message phase but not an IDENTIFY,
2449 	 *  get some help from the C code.
2450 	 *  Old SCSI device may behave so.
2451 	 */
2452 	SCR_INT ^ IFFALSE (MASK (0x80, 0x80)),
2453 		SIR_RESEL_NO_IDENTIFY,
2454 	/*
2455 	 *  It is an IDENTIFY message,
2456 	 *  Load the LUN control block address.
2457 	 *  If LUN 0, avoid a PCI BUS ownership by loading
2458 	 *  directly 'lun0_sa' from the TCB.
2459 	 */
2460 	SCR_JUMPR ^ IFTRUE (MASK (0x0, 0x3f)),
2461 		48,
2462 	SCR_LOAD_REL (dsa, 4),
2463 		offsetof(struct sym_tcb, luntbl_sa),
2464 	SCR_SFBR_REG (dsa, SCR_SHL, 0),
2465 		0,
2466 	SCR_REG_REG (dsa, SCR_SHL, 0),
2467 		0,
2468 	SCR_REG_REG (dsa, SCR_AND, 0xfc),
2469 		0,
2470 	SCR_LOAD_REL (dsa, 4),
2471 		0,
2472 	SCR_JUMPR,
2473 		8,
2474 	/*
2475 	 *  LUN 0 special case (but usual one :))
2476 	 */
2477 	SCR_LOAD_REL (dsa, 4),
2478 		offsetof(struct sym_tcb, lun0_sa),
2479 	/*
2480 	 *  Jump indirectly to the reselect action for this LUN.
2481 	 */
2482 	SCR_LOAD_REL (temp, 4),
2483 		offsetof(struct sym_lcb, resel_sa),
2484 	SCR_RETURN,
2485 		0,
2486 	/* In normal situations, we jump to RESEL_TAG or RESEL_NO_TAG */
2487 }/*-------------------------< RESEL_TAG >-------------------*/,{
2488 	/*
2489 	 *  It shall be a tagged command.
2490 	 *  Read IDENTIFY+SIMPLE+TAG.
2491 	 *  The C code will deal with errors.
2492 	 *  Agressive optimization, is'nt it? :)
2493 	 */
2494 	SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2495 		NADDR (msgin),
2496 	/*
2497 	 *  Load the pointer to the tagged task
2498 	 *  table for this LUN.
2499 	 */
2500 	SCR_LOAD_REL (dsa, 4),
2501 		offsetof(struct sym_lcb, itlq_tbl_sa),
2502 	/*
2503 	 *  The SIDL still contains the TAG value.
2504 	 *  Agressive optimization, isn't it? :):)
2505 	 */
2506 	SCR_REG_SFBR (sidl, SCR_SHL, 0),
2507 		0,
2508 #if SYM_CONF_MAX_TASK*4 > 512
2509 	SCR_JUMPR ^ IFFALSE (CARRYSET),
2510 		8,
2511 	SCR_REG_REG (dsa1, SCR_OR, 2),
2512 		0,
2513 	SCR_REG_REG (sfbr, SCR_SHL, 0),
2514 		0,
2515 	SCR_JUMPR ^ IFFALSE (CARRYSET),
2516 		8,
2517 	SCR_REG_REG (dsa1, SCR_OR, 1),
2518 		0,
2519 #elif SYM_CONF_MAX_TASK*4 > 256
2520 	SCR_JUMPR ^ IFFALSE (CARRYSET),
2521 		8,
2522 	SCR_REG_REG (dsa1, SCR_OR, 1),
2523 		0,
2524 #endif
2525 	/*
2526 	 *  Retrieve the DSA of this task.
2527 	 *  JUMP indirectly to the restart point of the CCB.
2528 	 */
2529 	SCR_SFBR_REG (dsa, SCR_AND, 0xfc),
2530 		0,
2531 	SCR_LOAD_REL (dsa, 4),
2532 		0,
2533 	SCR_LOAD_REL (temp, 4),
2534 		offsetof(struct sym_ccb, phys.go.restart),
2535 	SCR_RETURN,
2536 		0,
2537 	/* In normal situations we branch to RESEL_DSA */
2538 }/*-------------------------< RESEL_DSA >-------------------*/,{
2539 	/*
2540 	 *  ACK the IDENTIFY or TAG previously received.
2541 	 */
2542 	SCR_CLR (SCR_ACK),
2543 		0,
2544 }/*-------------------------< RESEL_DSA1 >------------------*/,{
2545 	/*
2546 	 *      load the savep (saved pointer) into
2547 	 *      the actual data pointer.
2548 	 */
2549 	SCR_LOAD_REL (temp, 4),
2550 		offsetof (struct sym_ccb, phys.savep),
2551 	/*
2552 	 *      Initialize the status registers
2553 	 */
2554 	SCR_LOAD_REL (scr0, 4),
2555 		offsetof (struct sym_ccb, phys.status),
2556 	/*
2557 	 *  Jump to dispatcher.
2558 	 */
2559 	SCR_JUMP,
2560 		PADDR (dispatch),
2561 }/*-------------------------< RESEL_NO_TAG >-------------------*/,{
2562 	/*
2563 	 *  Throw away the IDENTIFY.
2564 	 */
2565 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2566 		NADDR (msgin),
2567 	/*
2568 	 *  Load the DSA with the unique ITL task.
2569 	 */
2570 	SCR_LOAD_REL (dsa, 4),
2571 		offsetof(struct sym_lcb, itl_task_sa),
2572 	/*
2573 	 *  JUMP indirectly to the restart point of the CCB.
2574 	 */
2575 	SCR_LOAD_REL (temp, 4),
2576 		offsetof(struct sym_ccb, phys.go.restart),
2577 	SCR_RETURN,
2578 		0,
2579 	/* In normal situations we branch to RESEL_DSA */
2580 }/*-------------------------< DATA_IN >--------------------*/,{
2581 /*
2582  *  Because the size depends on the
2583  *  #define SYM_CONF_MAX_SG parameter,
2584  *  it is filled in at runtime.
2585  *
2586  *  ##===========< i=0; i<SYM_CONF_MAX_SG >=========
2587  *  ||	SCR_CHMOV_TBL ^ SCR_DATA_IN,
2588  *  ||		offsetof (struct dsb, data[ i]),
2589  *  ##==========================================
2590  */
2591 0
2592 }/*-------------------------< DATA_IN2 >-------------------*/,{
2593 	SCR_CALL,
2594 		PADDR (datai_done),
2595 	SCR_JUMP,
2596 		PADDRH (no_data),
2597 }/*-------------------------< DATA_OUT >--------------------*/,{
2598 /*
2599  *  Because the size depends on the
2600  *  #define SYM_CONF_MAX_SG parameter,
2601  *  it is filled in at runtime.
2602  *
2603  *  ##===========< i=0; i<SYM_CONF_MAX_SG >=========
2604  *  ||	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
2605  *  ||		offsetof (struct dsb, data[ i]),
2606  *  ##==========================================
2607  */
2608 0
2609 }/*-------------------------< DATA_OUT2 >-------------------*/,{
2610 	SCR_CALL,
2611 		PADDR (datao_done),
2612 	SCR_JUMP,
2613 		PADDRH (no_data),
2614 }/*-------------------------< PM0_DATA >--------------------*/,{
2615 	/*
2616 	 *  Keep track we are executing the PM0 DATA
2617 	 *  mini-script.
2618 	 */
2619 	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM0),
2620 		0,
2621 	/*
2622 	 *  MOVE the data according to the actual
2623 	 *  DATA direction.
2624 	 */
2625 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
2626 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
2627 		16,
2628 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
2629 		offsetof (struct sym_ccb, phys.pm0.sg),
2630 	SCR_JUMPR,
2631 		56,
2632 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2633 		16,
2634 	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
2635 		offsetof (struct sym_ccb, phys.pm0.sg),
2636 	SCR_JUMPR,
2637 		32,
2638 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DT_DATA_IN)),
2639 		16,
2640 	SCR_CHMOV_TBL ^ SCR_DT_DATA_IN,
2641 		offsetof (struct sym_ccb, phys.pm0.sg),
2642 	SCR_JUMPR,
2643 		8,
2644 	SCR_CHMOV_TBL ^ SCR_DT_DATA_OUT,
2645 		offsetof (struct sym_ccb, phys.pm0.sg),
2646 #else
2647 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
2648 		16,
2649 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
2650 		offsetof (struct sym_ccb, phys.pm0.sg),
2651 	SCR_JUMPR,
2652 		8,
2653 	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
2654 		offsetof (struct sym_ccb, phys.pm0.sg),
2655 #endif
2656 	/*
2657 	 *  Clear the flag that told we were in
2658 	 *  the PM0 DATA mini-script.
2659 	 */
2660 	SCR_REG_REG (HF_REG, SCR_AND, (~HF_IN_PM0)),
2661 		0,
2662 	/*
2663 	 *  Return to the previous DATA script which
2664 	 *  is guaranteed by design (if no bug) to be
2665 	 *  the main DATA script for this transfer.
2666 	 */
2667 	SCR_LOAD_REL (temp, 4),
2668 		offsetof (struct sym_ccb, phys.pm0.ret),
2669 	SCR_RETURN,
2670 		0,
2671 }/*-------------------------< PM1_DATA >--------------------*/,{
2672 	/*
2673 	 *  Keep track we are executing the PM1 DATA
2674 	 *  mini-script.
2675 	 */
2676 	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM1),
2677 		0,
2678 	/*
2679 	 *  MOVE the data according to the actual
2680 	 *  DATA direction.
2681 	 */
2682 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
2683 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
2684 		16,
2685 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
2686 		offsetof (struct sym_ccb, phys.pm1.sg),
2687 	SCR_JUMPR,
2688 		56,
2689 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2690 		16,
2691 	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
2692 		offsetof (struct sym_ccb, phys.pm1.sg),
2693 	SCR_JUMPR,
2694 		32,
2695 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DT_DATA_IN)),
2696 		16,
2697 	SCR_CHMOV_TBL ^ SCR_DT_DATA_IN,
2698 		offsetof (struct sym_ccb, phys.pm1.sg),
2699 	SCR_JUMPR,
2700 		8,
2701 	SCR_CHMOV_TBL ^ SCR_DT_DATA_OUT,
2702 		offsetof (struct sym_ccb, phys.pm1.sg),
2703 #else
2704 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
2705 		16,
2706 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
2707 		offsetof (struct sym_ccb, phys.pm1.sg),
2708 	SCR_JUMPR,
2709 		8,
2710 	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
2711 		offsetof (struct sym_ccb, phys.pm1.sg),
2712 #endif
2713 	/*
2714 	 *  Clear the flag that told we were in
2715 	 *  the PM1 DATA mini-script.
2716 	 */
2717 	SCR_REG_REG (HF_REG, SCR_AND, (~HF_IN_PM1)),
2718 		0,
2719 	/*
2720 	 *  Return to the previous DATA script which
2721 	 *  is guaranteed by design (if no bug) to be
2722 	 *  the main DATA script for this transfer.
2723 	 */
2724 	SCR_LOAD_REL (temp, 4),
2725 		offsetof (struct sym_ccb, phys.pm1.ret),
2726 	SCR_RETURN,
2727 		0,
2728 }/*---------------------------------------------------------*/
2729 };
2730 
2731 static struct sym_scrh scripth0 = {
2732 /*------------------------< START64 >-----------------------*/{
2733 	/*
2734 	 *  SCRIPT entry point for the 895A, 896 and 1010.
2735 	 *  For now, there is no specific stuff for those
2736 	 *  chips at this point, but this may come.
2737 	 */
2738 	SCR_JUMP,
2739 		PADDR (init),
2740 }/*-----------------------< SEL_FOR_ABORT >------------------*/,{
2741 	/*
2742 	 *  We are jumped here by the C code, if we have
2743 	 *  some target to reset or some disconnected
2744 	 *  job to abort. Since error recovery is a serious
2745 	 *  busyness, we will really reset the SCSI BUS, if
2746 	 *  case of a SCSI interrupt occuring in this path.
2747 	 */
2748 
2749 	/*
2750 	 *  Set initiator mode.
2751 	 */
2752 	SCR_CLR (SCR_TRG),
2753 		0,
2754 	/*
2755 	 *      And try to select this target.
2756 	 */
2757 	SCR_SEL_TBL_ATN ^ offsetof (struct sym_hcb, abrt_sel),
2758 		PADDR (reselect),
2759 	/*
2760 	 *  Wait for the selection to complete or
2761 	 *  the selection to time out.
2762 	 */
2763 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2764 		-8,
2765 	/*
2766 	 *  Call the C code.
2767 	 */
2768 	SCR_INT,
2769 		SIR_TARGET_SELECTED,
2770 	/*
2771 	 *  The C code should let us continue here.
2772 	 *  Send the 'kiss of death' message.
2773 	 *  We expect an immediate disconnect once
2774 	 *  the target has eaten the message.
2775 	 */
2776 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2777 		0,
2778 	SCR_MOVE_TBL ^ SCR_MSG_OUT,
2779 		offsetof (struct sym_hcb, abrt_tbl),
2780 	SCR_CLR (SCR_ACK|SCR_ATN),
2781 		0,
2782 	SCR_WAIT_DISC,
2783 		0,
2784 	/*
2785 	 *  Tell the C code that we are done.
2786 	 */
2787 	SCR_INT,
2788 		SIR_ABORT_SENT,
2789 }/*-----------------------< SEL_FOR_ABORT_1 >--------------*/,{
2790 	/*
2791 	 *  Jump at scheduler.
2792 	 */
2793 	SCR_JUMP,
2794 		PADDR (start),
2795 
2796 }/*------------------------< SELECT_NO_ATN >-----------------*/,{
2797 	/*
2798 	 *  Set Initiator mode.
2799 	 *  And try to select this target without ATN.
2800 	 */
2801 	SCR_CLR (SCR_TRG),
2802 		0,
2803 	SCR_SEL_TBL ^ offsetof (struct dsb, select),
2804 		PADDR (ungetjob),
2805 	/*
2806 	 *  load the savep (saved pointer) into
2807 	 *  the actual data pointer.
2808 	 */
2809 	SCR_LOAD_REL (temp, 4),
2810 		offsetof (struct sym_ccb, phys.savep),
2811 	/*
2812 	 *  Initialize the status registers
2813 	 */
2814 	SCR_LOAD_REL (scr0, 4),
2815 		offsetof (struct sym_ccb, phys.status),
2816 }/*------------------------< WF_SEL_DONE_NO_ATN >-----------------*/,{
2817 	/*
2818 	 *  Wait immediately for the next phase or
2819 	 *  the selection to complete or time-out.
2820 	 */
2821 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2822 		0,
2823 	SCR_JUMP,
2824 		PADDR (select2),
2825 }/*-------------------------< MSG_IN_ETC >--------------------*/,{
2826 	/*
2827 	 *  If it is an EXTENDED (variable size message)
2828 	 *  Handle it.
2829 	 */
2830 	SCR_JUMP ^ IFTRUE (DATA (M_EXTENDED)),
2831 		PADDRH (msg_extended),
2832 	/*
2833 	 *  Let the C code handle any other
2834 	 *  1 byte message.
2835 	 */
2836 	SCR_INT ^ IFTRUE (MASK (0x00, 0xf0)),
2837 		SIR_MSG_RECEIVED,
2838 	SCR_INT ^ IFTRUE (MASK (0x10, 0xf0)),
2839 		SIR_MSG_RECEIVED,
2840 	/*
2841 	 *  We donnot handle 2 bytes messages from SCRIPTS.
2842 	 *  So, let the C code deal with these ones too.
2843 	 */
2844 	SCR_INT ^ IFFALSE (MASK (0x20, 0xf0)),
2845 		SIR_MSG_WEIRD,
2846 	SCR_CLR (SCR_ACK),
2847 		0,
2848 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2849 		NADDR (msgin[1]),
2850 	SCR_INT,
2851 		SIR_MSG_RECEIVED,
2852 
2853 }/*-------------------------< MSG_RECEIVED >--------------------*/,{
2854 	SCR_LOAD_REL (scratcha, 4),	/* DUMMY READ */
2855 		0,
2856 	SCR_INT,
2857 		SIR_MSG_RECEIVED,
2858 
2859 }/*-------------------------< MSG_WEIRD_SEEN >------------------*/,{
2860 	SCR_LOAD_REL (scratcha, 4),	/* DUMMY READ */
2861 		0,
2862 	SCR_INT,
2863 		SIR_MSG_WEIRD,
2864 
2865 }/*-------------------------< MSG_EXTENDED >--------------------*/,{
2866 	/*
2867 	 *  Clear ACK and get the next byte
2868 	 *  assumed to be the message length.
2869 	 */
2870 	SCR_CLR (SCR_ACK),
2871 		0,
2872 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2873 		NADDR (msgin[1]),
2874 	/*
2875 	 *  Try to catch some unlikely situations as 0 length
2876 	 *  or too large the length.
2877 	 */
2878 	SCR_JUMP ^ IFTRUE (DATA (0)),
2879 		PADDRH (msg_weird_seen),
2880 	SCR_TO_REG (scratcha),
2881 		0,
2882 	SCR_REG_REG (sfbr, SCR_ADD, (256-8)),
2883 		0,
2884 	SCR_JUMP ^ IFTRUE (CARRYSET),
2885 		PADDRH (msg_weird_seen),
2886 	/*
2887 	 *  We donnot handle extended messages from SCRIPTS.
2888 	 *  Read the amount of data correponding to the
2889 	 *  message length and call the C code.
2890 	 */
2891 	SCR_STORE_REL (scratcha, 1),
2892 		offsetof (struct dsb, smsg_ext.size),
2893 	SCR_CLR (SCR_ACK),
2894 		0,
2895 	SCR_MOVE_TBL ^ SCR_MSG_IN,
2896 		offsetof (struct dsb, smsg_ext),
2897 	SCR_JUMP,
2898 		PADDRH (msg_received),
2899 
2900 }/*-------------------------< MSG_BAD >------------------*/,{
2901 	/*
2902 	 *  unimplemented message - reject it.
2903 	 */
2904 	SCR_INT,
2905 		SIR_REJECT_TO_SEND,
2906 	SCR_SET (SCR_ATN),
2907 		0,
2908 	SCR_JUMP,
2909 		PADDR (clrack),
2910 }/*-------------------------< MSG_WEIRD >--------------------*/,{
2911 	/*
2912 	 *  weird message received
2913 	 *  ignore all MSG IN phases and reject it.
2914 	 */
2915 	SCR_INT,
2916 		SIR_REJECT_TO_SEND,
2917 	SCR_SET (SCR_ATN),
2918 		0,
2919 }/*-------------------------< MSG_WEIRD1 >--------------------*/,{
2920 	SCR_CLR (SCR_ACK),
2921 		0,
2922 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2923 		PADDR (dispatch),
2924 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2925 		NADDR (scratch),
2926 	SCR_JUMP,
2927 		PADDRH (msg_weird1),
2928 }/*-------------------------< WDTR_RESP >----------------*/,{
2929 	/*
2930 	 *  let the target fetch our answer.
2931 	 */
2932 	SCR_SET (SCR_ATN),
2933 		0,
2934 	SCR_CLR (SCR_ACK),
2935 		0,
2936 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2937 		PADDRH (nego_bad_phase),
2938 }/*-------------------------< SEND_WDTR >----------------*/,{
2939 	/*
2940 	 *  Send the M_X_WIDE_REQ
2941 	 */
2942 	SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
2943 		NADDR (msgout),
2944 	SCR_JUMP,
2945 		PADDRH (msg_out_done),
2946 }/*-------------------------< SDTR_RESP >-------------*/,{
2947 	/*
2948 	 *  let the target fetch our answer.
2949 	 */
2950 	SCR_SET (SCR_ATN),
2951 		0,
2952 	SCR_CLR (SCR_ACK),
2953 		0,
2954 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2955 		PADDRH (nego_bad_phase),
2956 }/*-------------------------< SEND_SDTR >-------------*/,{
2957 	/*
2958 	 *  Send the M_X_SYNC_REQ
2959 	 */
2960 	SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
2961 		NADDR (msgout),
2962 	SCR_JUMP,
2963 		PADDRH (msg_out_done),
2964 }/*-------------------------< PPR_RESP >-------------*/,{
2965 	/*
2966 	 *  let the target fetch our answer.
2967 	 */
2968 	SCR_SET (SCR_ATN),
2969 		0,
2970 	SCR_CLR (SCR_ACK),
2971 		0,
2972 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2973 		PADDRH (nego_bad_phase),
2974 }/*-------------------------< SEND_PPR >-------------*/,{
2975 	/*
2976 	 *  Send the M_X_PPR_REQ
2977 	 */
2978 	SCR_MOVE_ABS (8) ^ SCR_MSG_OUT,
2979 		NADDR (msgout),
2980 	SCR_JUMP,
2981 		PADDRH (msg_out_done),
2982 }/*-------------------------< NEGO_BAD_PHASE >------------*/,{
2983 	SCR_INT,
2984 		SIR_NEGO_PROTO,
2985 	SCR_JUMP,
2986 		PADDR (dispatch),
2987 }/*-------------------------< MSG_OUT >-------------------*/,{
2988 	/*
2989 	 *  The target requests a message.
2990 	 *  We donnot send messages that may
2991 	 *  require the device to go to bus free.
2992 	 */
2993 	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2994 		NADDR (msgout),
2995 	/*
2996 	 *  ... wait for the next phase
2997 	 *  if it's a message out, send it again, ...
2998 	 */
2999 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
3000 		PADDRH (msg_out),
3001 }/*-------------------------< MSG_OUT_DONE >--------------*/,{
3002 	/*
3003 	 *  Let the C code be aware of the
3004 	 *  sent message and clear the message.
3005 	 */
3006 	SCR_INT,
3007 		SIR_MSG_OUT_DONE,
3008 	/*
3009 	 *  ... and process the next phase
3010 	 */
3011 	SCR_JUMP,
3012 		PADDR (dispatch),
3013 
3014 }/*-------------------------< NO_DATA >--------------------*/,{
3015 	/*
3016 	 *  The target wants to tranfer too much data
3017 	 *  or in the wrong direction.
3018 	 *  Discard one data byte, if required.
3019 	 *  Count all discarded bytes.
3020 	 */
3021 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
3022 		8,
3023 	SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
3024 		NADDR (scratch),
3025 	SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
3026 		8,
3027 	SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
3028 		NADDR (scratch),
3029 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
3030 	SCR_JUMPR ^ IFFALSE (IF (SCR_DT_DATA_OUT)),
3031 		8,
3032 	SCR_MOVE_ABS (1) ^ SCR_DT_DATA_OUT,
3033 		NADDR (scratch),
3034 	SCR_JUMPR ^ IFFALSE (IF (SCR_DT_DATA_IN)),
3035 		8,
3036 	SCR_MOVE_ABS (1) ^ SCR_DT_DATA_IN,
3037 		NADDR (scratch),
3038 #endif
3039 	/*
3040 	 *  Set the extended error flag.
3041 	 */
3042 	SCR_REG_REG (HF_REG, SCR_OR, HF_EXT_ERR),
3043 		0,
3044 	SCR_LOAD_REL (scratcha, 1),
3045 		offsetof (struct sym_ccb, xerr_status),
3046 	SCR_REG_REG (scratcha,  SCR_OR,  XE_EXTRA_DATA),
3047 		0,
3048 	/*
3049 	 *  Count this byte.
3050 	 *  This will allow to return a positive
3051 	 *  residual to user.
3052 	 */
3053 	SCR_LOAD_REL (scratcha, 4),
3054 		offsetof (struct sym_ccb, phys.extra_bytes),
3055 	SCR_REG_REG (scratcha,  SCR_ADD,  0x01),
3056 		0,
3057 	SCR_REG_REG (scratcha1, SCR_ADDC, 0),
3058 		0,
3059 	SCR_REG_REG (scratcha2, SCR_ADDC, 0),
3060 		0,
3061 	SCR_STORE_REL (scratcha, 4),
3062 		offsetof (struct sym_ccb, phys.extra_bytes),
3063 	/*
3064 	 *  .. and repeat as required.
3065 	 */
3066 	SCR_CALL,
3067 		PADDR (dispatch),
3068 	SCR_JUMP,
3069 		PADDRH (no_data),
3070 
3071 }/*-------------------------< ABORT_RESEL >----------------*/,{
3072 	SCR_SET (SCR_ATN),
3073 		0,
3074 	SCR_CLR (SCR_ACK),
3075 		0,
3076 	/*
3077 	 *  send the abort/abortag/reset message
3078 	 *  we expect an immediate disconnect
3079 	 */
3080 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3081 		0,
3082 	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
3083 		NADDR (msgout),
3084 	SCR_CLR (SCR_ACK|SCR_ATN),
3085 		0,
3086 	SCR_WAIT_DISC,
3087 		0,
3088 	SCR_INT,
3089 		SIR_RESEL_ABORTED,
3090 	SCR_JUMP,
3091 		PADDR (start),
3092 }/*-------------------------< RESEND_IDENT >-------------------*/,{
3093 	/*
3094 	 *  The target stays in MSG OUT phase after having acked
3095 	 *  Identify [+ Tag [+ Extended message ]]. Targets shall
3096 	 *  behave this way on parity error.
3097 	 *  We must send it again all the messages.
3098 	 */
3099 	SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
3100 		0,         /* 1rst ACK = 90 ns. Hope the chip isn't too fast */
3101 	SCR_JUMP,
3102 		PADDR (send_ident),
3103 }/*-------------------------< IDENT_BREAK >-------------------*/,{
3104 	SCR_CLR (SCR_ATN),
3105 		0,
3106 	SCR_JUMP,
3107 		PADDR (select2),
3108 }/*-------------------------< IDENT_BREAK_ATN >----------------*/,{
3109 	SCR_SET (SCR_ATN),
3110 		0,
3111 	SCR_JUMP,
3112 		PADDR (select2),
3113 }/*-------------------------< SDATA_IN >-------------------*/,{
3114 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
3115 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
3116 		16,
3117 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
3118 		offsetof (struct dsb, sense),
3119 	SCR_JUMPR,
3120 		8,
3121 	SCR_CHMOV_TBL ^ SCR_DT_DATA_IN,
3122 		offsetof (struct dsb, sense),
3123 #else
3124 	SCR_CHMOV_TBL ^ SCR_DATA_IN,
3125 		offsetof (struct dsb, sense),
3126 #endif
3127 	SCR_CALL,
3128 		PADDR (dispatch),
3129 	SCR_JUMP,
3130 		PADDRH (no_data),
3131 
3132 }/*-------------------------< RESEL_BAD_LUN >---------------*/,{
3133 	/*
3134 	 *  Message is an IDENTIFY, but lun is unknown.
3135 	 *  Signal problem to C code for logging the event.
3136 	 *  Send a M_ABORT to clear all pending tasks.
3137 	 */
3138 	SCR_INT,
3139 		SIR_RESEL_BAD_LUN,
3140 	SCR_JUMP,
3141 		PADDRH (abort_resel),
3142 }/*-------------------------< BAD_I_T_L >------------------*/,{
3143 	/*
3144 	 *  We donnot have a task for that I_T_L.
3145 	 *  Signal problem to C code for logging the event.
3146 	 *  Send a M_ABORT message.
3147 	 */
3148 	SCR_INT,
3149 		SIR_RESEL_BAD_I_T_L,
3150 	SCR_JUMP,
3151 		PADDRH (abort_resel),
3152 }/*-------------------------< BAD_I_T_L_Q >----------------*/,{
3153 	/*
3154 	 *  We donnot have a task that matches the tag.
3155 	 *  Signal problem to C code for logging the event.
3156 	 *  Send a M_ABORTTAG message.
3157 	 */
3158 	SCR_INT,
3159 		SIR_RESEL_BAD_I_T_L_Q,
3160 	SCR_JUMP,
3161 		PADDRH (abort_resel),
3162 }/*-------------------------< BAD_STATUS >-----------------*/,{
3163 	/*
3164 	 *  Anything different from INTERMEDIATE
3165 	 *  CONDITION MET should be a bad SCSI status,
3166 	 *  given that GOOD status has already been tested.
3167 	 *  Call the C code.
3168 	 */
3169 	SCR_LOAD_ABS (scratcha, 4),
3170 		PADDRH (startpos),
3171 	SCR_INT ^ IFFALSE (DATA (S_COND_MET)),
3172 		SIR_BAD_SCSI_STATUS,
3173 	SCR_RETURN,
3174 		0,
3175 
3176 }/*-------------------------< PM_HANDLE >------------------*/,{
3177 	/*
3178 	 *  Phase mismatch handling.
3179 	 *
3180 	 *  Since we have to deal with 2 SCSI data pointers
3181 	 *  (current and saved), we need at least 2 contexts.
3182 	 *  Each context (pm0 and pm1) has a saved area, a
3183 	 *  SAVE mini-script and a DATA phase mini-script.
3184 	 */
3185 	/*
3186 	 *  Get the PM handling flags.
3187 	 */
3188 	SCR_FROM_REG (HF_REG),
3189 		0,
3190 	/*
3191 	 *  If no flags (1rst PM for example), avoid
3192 	 *  all the below heavy flags testing.
3193 	 *  This makes the normal case a bit faster.
3194 	 */
3195 	SCR_JUMP ^ IFTRUE (MASK (0, (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED))),
3196 		PADDRH (pm_handle1),
3197 	/*
3198 	 *  If we received a SAVE DP, switch to the
3199 	 *  other PM context since the savep may point
3200 	 *  to the current PM context.
3201 	 */
3202 	SCR_JUMPR ^ IFFALSE (MASK (HF_DP_SAVED, HF_DP_SAVED)),
3203 		8,
3204 	SCR_REG_REG (sfbr, SCR_XOR, HF_ACT_PM),
3205 		0,
3206 	/*
3207 	 *  If we have been interrupt in a PM DATA mini-script,
3208 	 *  we take the return address from the corresponding
3209 	 *  saved area.
3210 	 *  This ensure the return address always points to the
3211 	 *  main DATA script for this transfer.
3212 	 */
3213 	SCR_JUMP ^ IFTRUE (MASK (0, (HF_IN_PM0 | HF_IN_PM1))),
3214 		PADDRH (pm_handle1),
3215 	SCR_JUMPR ^ IFFALSE (MASK (HF_IN_PM0, HF_IN_PM0)),
3216 		16,
3217 	SCR_LOAD_REL (ia, 4),
3218 		offsetof(struct sym_ccb, phys.pm0.ret),
3219 	SCR_JUMP,
3220 		PADDRH (pm_save),
3221 	SCR_LOAD_REL (ia, 4),
3222 		offsetof(struct sym_ccb, phys.pm1.ret),
3223 	SCR_JUMP,
3224 		PADDRH (pm_save),
3225 }/*-------------------------< PM_HANDLE1 >-----------------*/,{
3226 	/*
3227 	 *  Normal case.
3228 	 *  Update the return address so that it
3229 	 *  will point after the interrupted MOVE.
3230 	 */
3231 	SCR_REG_REG (ia, SCR_ADD, 8),
3232 		0,
3233 	SCR_REG_REG (ia1, SCR_ADDC, 0),
3234 		0,
3235 }/*-------------------------< PM_SAVE >--------------------*/,{
3236 	/*
3237 	 *  Clear all the flags that told us if we were
3238 	 *  interrupted in a PM DATA mini-script and/or
3239 	 *  we received a SAVE DP.
3240 	 */
3241 	SCR_SFBR_REG (HF_REG, SCR_AND, (~(HF_IN_PM0|HF_IN_PM1|HF_DP_SAVED))),
3242 		0,
3243 	/*
3244 	 *  Choose the current PM context.
3245 	 */
3246 	SCR_JUMP ^ IFTRUE (MASK (HF_ACT_PM, HF_ACT_PM)),
3247 		PADDRH (pm1_save),
3248 }/*-------------------------< PM0_SAVE >-------------------*/,{
3249 	SCR_STORE_REL (ia, 4),
3250 		offsetof(struct sym_ccb, phys.pm0.ret),
3251 	/*
3252 	 *  If WSR bit is set, either UA and RBC may
3253 	 *  have to be changed whether the device wants
3254 	 *  to ignore this residue ot not.
3255 	 */
3256 	SCR_FROM_REG (scntl2),
3257 		0,
3258 	SCR_CALL ^ IFTRUE (MASK (WSR, WSR)),
3259 		PADDRH (swide_scr_64),
3260 	/*
3261 	 *  Save the remaining byte count, the updated
3262 	 *  address and the return address.
3263 	 */
3264 	SCR_STORE_REL (rbc, 4),
3265 		offsetof(struct sym_ccb, phys.pm0.sg.size),
3266 	SCR_STORE_REL (ua, 4),
3267 		offsetof(struct sym_ccb, phys.pm0.sg.addr),
3268 	/*
3269 	 *  Set the current pointer at the PM0 DATA mini-script.
3270 	 */
3271 	SCR_LOAD_ABS (temp, 4),
3272 		PADDRH (pm0_data_addr),
3273 	SCR_JUMP,
3274 		PADDR (dispatch),
3275 }/*-------------------------< PM1_SAVE >-------------------*/,{
3276 	SCR_STORE_REL (ia, 4),
3277 		offsetof(struct sym_ccb, phys.pm1.ret),
3278 	/*
3279 	 *  If WSR bit is set, either UA and RBC may
3280 	 *  have been changed whether the device wants
3281 	 *  to ignore this residue or not.
3282 	 */
3283 	SCR_FROM_REG (scntl2),
3284 		0,
3285 	SCR_CALL ^ IFTRUE (MASK (WSR, WSR)),
3286 		PADDRH (swide_scr_64),
3287 	/*
3288 	 *  Save the remaining byte count, the updated
3289 	 *  address and the return address.
3290 	 */
3291 	SCR_STORE_REL (rbc, 4),
3292 		offsetof(struct sym_ccb, phys.pm1.sg.size),
3293 	SCR_STORE_REL (ua, 4),
3294 		offsetof(struct sym_ccb, phys.pm1.sg.addr),
3295 	/*
3296 	 *  Set the current pointer at the PM1 DATA mini-script.
3297 	 */
3298 	SCR_LOAD_ABS (temp, 4),
3299 		PADDRH (pm1_data_addr),
3300 	SCR_JUMP,
3301 		PADDR (dispatch),
3302 }/*--------------------------< SWIDE_MA_32 >-----------------------*/,{
3303 	/*
3304 	 *  Handling of the SWIDE for 32 bit chips.
3305 	 *
3306 	 *  We jump here from the C code with SCRATCHA
3307 	 *  containing the address to write the SWIDE.
3308 	 *  - Save 32 bit address in <scratch>.
3309 	 */
3310 	SCR_STORE_ABS (scratcha, 4),
3311 		PADDRH (scratch),
3312 	SCR_JUMP,
3313 		PADDRH (swide_common),
3314 }/*--------------------------< SWIDE_MA_64 >-----------------------*/,{
3315 	/*
3316 	 *  Handling of the SWIDE for 64 bit chips when the
3317 	 *  hardware handling of phase mismatch is disabled.
3318 	 *
3319 	 *  We jump here from the C code with SCRATCHA
3320 	 *  containing the address to write the SWIDE and
3321 	 *  SBR containing bit 32..39 of this address.
3322 	 *  - Save 32 bit address in <scratch>.
3323 	 *  - Move address bit 32..39 to SFBR.
3324 	 */
3325 	SCR_STORE_ABS (scratcha, 4),
3326 		PADDRH (scratch),
3327 	SCR_FROM_REG (sbr),
3328 		0,
3329 	SCR_JUMP,
3330 		PADDRH (swide_com_64),
3331 }/*--------------------------< SWIDE_SCR_64 >-----------------------*/,{
3332 	/*
3333 	 *  Handling of the SWIDE for 64 bit chips when
3334 	 *  hardware phase mismatch is enabled.
3335 	 *  We are entered with a SCR_CALL from PMO_SAVE
3336 	 *  and PM1_SAVE sub-scripts.
3337 	 *
3338 	 *  Snoop the SCSI BUS in case of the device
3339 	 *  willing to ignore this residue.
3340 	 *  If it does, we must only increment the RBC,
3341 	 *  since this register does reflect all bytes
3342 	 *  received from the SCSI BUS including the SWIDE.
3343 	 */
3344 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3345 		PADDRH (swide_scr_64_1),
3346 	SCR_FROM_REG (sbdl),
3347 		0,
3348 	SCR_JUMP ^ IFFALSE (DATA (M_IGN_RESIDUE)),
3349 		PADDRH (swide_scr_64_1),
3350 	SCR_REG_REG (rbc, SCR_ADD, 1),
3351 		0,
3352 	SCR_REG_REG (rbc1, SCR_ADDC, 0),
3353 		0,
3354 	SCR_REG_REG (rbc2, SCR_ADDC, 0),
3355 		0,
3356 	/*
3357 	 *  Save UA and RBC, since the PM0/1_SAVE
3358 	 *  sub-scripts haven't moved them to the
3359 	 *  context yet and the below MOV may just
3360 	 *  change their value.
3361 	 */
3362 	SCR_STORE_ABS (ua, 4),
3363 		PADDRH (scratch),
3364 	SCR_STORE_ABS (rbc, 4),
3365 		PADDRH (scratch1),
3366 	/*
3367 	 *  Throw away the IGNORE WIDE RESIDUE message.
3368 	 *  since we just did take care of it.
3369 	 */
3370 	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
3371 		NADDR (scratch),
3372 	SCR_CLR (SCR_ACK),
3373 		0,
3374 	/*
3375 	 *  Restore UA and RBC registers and return.
3376 	 */
3377 	SCR_LOAD_ABS (ua, 4),
3378 		PADDRH (scratch),
3379 	SCR_LOAD_ABS (rbc, 4),
3380 		PADDRH (scratch1),
3381 	SCR_RETURN,
3382 		0,
3383 }/*--------------------------< SWIDE_SCR_64_1 >---------------------*/,{
3384 	/*
3385 	 *  We must grab the SWIDE and move it to
3386 	 *  memory.
3387 	 *
3388 	 *  - Save UA (32 bit address) in <scratch>.
3389 	 *  - Move address bit 32..39 to SFBR.
3390 	 *  - Increment UA (updated address).
3391 	 */
3392 	SCR_STORE_ABS (ua, 4),
3393 		PADDRH (scratch),
3394 	SCR_FROM_REG (rbc3),
3395 		0,
3396 	SCR_REG_REG (ua, SCR_ADD, 1),
3397 		0,
3398 	SCR_REG_REG (ua1, SCR_ADDC, 0),
3399 		0,
3400 	SCR_REG_REG (ua2, SCR_ADDC, 0),
3401 		0,
3402 	SCR_REG_REG (ua3, SCR_ADDC, 0),
3403 		0,
3404 }/*--------------------------< SWIDE_COM_64 >-----------------------*/,{
3405 	/*
3406 	 *  - Save DRS.
3407 	 *  - Load DRS with address bit 32..39 of the
3408 	 *    location to write the SWIDE.
3409 	 *    SFBR has been loaded with these bits.
3410 	 *    (Look above).
3411 	 */
3412 	SCR_STORE_ABS (drs, 4),
3413 		PADDRH (saved_drs),
3414 	SCR_LOAD_ABS (drs, 4),
3415 		PADDRH (zero),
3416 	SCR_TO_REG (drs),
3417 		0,
3418 }/*--------------------------< SWIDE_COMMON >-----------------------*/,{
3419 	/*
3420 	 *  - Save current DSA
3421 	 *  - Load DSA with bit 0..31 of the memory
3422 	 *    location to write the SWIDE.
3423 	 */
3424 	SCR_STORE_ABS (dsa, 4),
3425 		PADDRH (saved_dsa),
3426 	SCR_LOAD_ABS (dsa, 4),
3427 		PADDRH (scratch),
3428 	/*
3429 	 *  Move the SWIDE to memory.
3430 	 *  Clear the WSR bit.
3431 	 */
3432 	SCR_STORE_REL (swide, 1),
3433 		0,
3434 	SCR_REG_REG (scntl2, SCR_OR, WSR),
3435 		0,
3436 	/*
3437 	 *  Restore the original DSA.
3438 	 */
3439 	SCR_LOAD_ABS (dsa, 4),
3440 		PADDRH (saved_dsa),
3441 }/*--------------------------< SWIDE_FIN_32 >-----------------------*/,{
3442 	/*
3443 	 *  For 32 bit chip, the following SCRIPTS
3444 	 *  instruction is patched with a JUMP to dispatcher.
3445 	 *  (Look into the C code).
3446 	 */
3447 	SCR_LOAD_ABS (drs, 4),
3448 		PADDRH (saved_drs),
3449 	/*
3450 	 *  64 bit chip only.
3451 	 *  If PM handling from SCRIPTS, we are just
3452 	 *  a helper for the C code, so jump to
3453 	 *  dispatcher now.
3454 	 */
3455 	SCR_FROM_REG (ccntl0),
3456 		0,
3457 	SCR_JUMP ^ IFFALSE (MASK (ENPMJ, ENPMJ)),
3458 		PADDR (dispatch),
3459 	/*
3460 	 *  64 bit chip with hardware PM handling enabled.
3461 	 *
3462 	 *  Since we are paranoid:), we donnot want
3463 	 *  a SWIDE followed by a CHMOV(1) to lead to
3464 	 *  a CHMOV(0) in our PM context.
3465 	 *  We check against such a condition.
3466 	 *  Also does the C code.
3467 	 */
3468 	SCR_FROM_REG (rbc),
3469 		0,
3470 	SCR_RETURN ^ IFFALSE (DATA (0)),
3471 		0,
3472 	SCR_FROM_REG (rbc1),
3473 		0,
3474 	SCR_RETURN ^ IFFALSE (DATA (0)),
3475 		0,
3476 	SCR_FROM_REG (rbc2),
3477 		0,
3478 	SCR_RETURN ^ IFFALSE (DATA (0)),
3479 		0,
3480 	/*
3481 	 *  If we are there, RBC(0..23) is zero,
3482 	 *  and we just have to load the current
3483 	 *  DATA SCRIPTS address (register TEMP)
3484 	 *  with the IA and go to dispatch.
3485 	 *  No PM context is needed.
3486 	 */
3487 	SCR_STORE_ABS (ia, 4),
3488 		PADDRH (scratch),
3489 	SCR_LOAD_ABS (temp, 4),
3490 		PADDRH (scratch),
3491 	SCR_JUMP,
3492 		PADDR (dispatch),
3493 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
3494 }/*-------------------------< DT_DATA_IN >--------------------*/,{
3495 /*
3496  *  Because the size depends on the
3497  *  #define SYM_CONF_MAX_SG parameter,
3498  *  it is filled in at runtime.
3499  *
3500  *  ##===========< i=0; i<SYM_CONF_MAX_SG >=========
3501  *  ||	SCR_CHMOV_TBL ^ SCR_DT_DATA_IN,
3502  *  ||		offsetof (struct dsb, data[ i]),
3503  *  ##==========================================
3504  */
3505 0
3506 }/*-------------------------< DT_DATA_IN2 >-------------------*/,{
3507 	SCR_CALL,
3508 		PADDR (datai_done),
3509 	SCR_JUMP,
3510 		PADDRH (no_data),
3511 }/*-------------------------< DT_DATA_OUT >--------------------*/,{
3512 /*
3513  *  Because the size depends on the
3514  *  #define SYM_CONF_MAX_SG parameter,
3515  *  it is filled in at runtime.
3516  *
3517  *  ##===========< i=0; i<SYM_CONF_MAX_SG >=========
3518  *  ||	SCR_CHMOV_TBL ^ SCR_DT_DATA_OUT,
3519  *  ||		offsetof (struct dsb, data[ i]),
3520  *  ##==========================================
3521  */
3522 0
3523 }/*-------------------------< DT_DATA_OUT2 >-------------------*/,{
3524 	SCR_CALL,
3525 		PADDR (datao_done),
3526 	SCR_JUMP,
3527 		PADDRH (no_data),
3528 
3529 #endif	/* SYM_CONF_BROKEN_U3EN_SUPPORT */
3530 
3531 }/*-------------------------< ZERO >------------------------*/,{
3532 	SCR_DATA_ZERO,
3533 }/*-------------------------< SCRATCH >---------------------*/,{
3534 	SCR_DATA_ZERO,
3535 }/*-------------------------< SCRATCH1 >--------------------*/,{
3536 	SCR_DATA_ZERO,
3537 }/*-------------------------< PM0_DATA_ADDR >---------------*/,{
3538 	SCR_DATA_ZERO,
3539 }/*-------------------------< PM1_DATA_ADDR >---------------*/,{
3540 	SCR_DATA_ZERO,
3541 }/*-------------------------< SAVED_DSA >-------------------*/,{
3542 	SCR_DATA_ZERO,
3543 }/*-------------------------< SAVED_DRS >-------------------*/,{
3544 	SCR_DATA_ZERO,
3545 }/*-------------------------< DONE_POS >--------------------*/,{
3546 	SCR_DATA_ZERO,
3547 }/*-------------------------< STARTPOS >--------------------*/,{
3548 	SCR_DATA_ZERO,
3549 }/*-------------------------< TARGTBL >---------------------*/,{
3550 	SCR_DATA_ZERO,
3551 
3552 }/*-------------------------< SNOOPTEST >-------------------*/,{
3553 	/*
3554 	 *  Read the variable.
3555 	 */
3556 	SCR_LOAD_REL (scratcha, 4),
3557 		offsetof(struct sym_hcb, cache),
3558 	SCR_STORE_REL (temp, 4),
3559 		offsetof(struct sym_hcb, cache),
3560 	SCR_LOAD_REL (temp, 4),
3561 		offsetof(struct sym_hcb, cache),
3562 }/*-------------------------< SNOOPEND >-------------------*/,{
3563 	/*
3564 	 *  And stop.
3565 	 */
3566 	SCR_INT,
3567 		99,
3568 }/*--------------------------------------------------------*/
3569 };
3570 
3571 /*
3572  *  Fill in #define dependent parts of the scripts
3573  */
3574 static void sym_fill_scripts (script_p scr, scripth_p scrh)
3575 {
3576 	int	i;
3577 	u32	*p;
3578 
3579 	p = scr->data_in;
3580 	for (i=0; i<SYM_CONF_MAX_SG; i++) {
3581 		*p++ =SCR_CHMOV_TBL ^ SCR_DATA_IN;
3582 		*p++ =offsetof (struct dsb, data[i]);
3583 	};
3584 	assert ((u_long)p == (u_long)&scr->data_in + sizeof (scr->data_in));
3585 
3586 	p = scr->data_out;
3587 	for (i=0; i<SYM_CONF_MAX_SG; i++) {
3588 		*p++ =SCR_CHMOV_TBL ^ SCR_DATA_OUT;
3589 		*p++ =offsetof (struct dsb, data[i]);
3590 	};
3591 	assert ((u_long)p == (u_long)&scr->data_out + sizeof (scr->data_out));
3592 
3593 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
3594 	p = scrh->dt_data_in;
3595 	for (i=0; i<SYM_CONF_MAX_SG; i++) {
3596 		*p++ =SCR_CHMOV_TBL ^ SCR_DT_DATA_IN;
3597 		*p++ =offsetof (struct dsb, data[i]);
3598 	};
3599 	assert ((u_long)p ==
3600 		(u_long)&scrh->dt_data_in + sizeof (scrh->dt_data_in));
3601 
3602 	p = scrh->dt_data_out;
3603 	for (i=0; i<SYM_CONF_MAX_SG; i++) {
3604 		*p++ =SCR_CHMOV_TBL ^ SCR_DATA_OUT;
3605 		*p++ =offsetof (struct dsb, data[i]);
3606 	};
3607 	assert ((u_long)p ==
3608 		(u_long)&scrh->dt_data_out + sizeof (scrh->dt_data_out));
3609 #endif
3610 }
3611 
3612 /*
3613  *  Copy and bind a script.
3614  */
3615 static void sym_bind_script (hcb_p np, u32 *src, u32 *dst, int len)
3616 {
3617 	u32 opcode, new, old, tmp1, tmp2;
3618 	u32 *start, *end;
3619 	int relocs;
3620 	int opchanged = 0;
3621 
3622 	start = src;
3623 	end = src + len/4;
3624 
3625 	while (src < end) {
3626 
3627 		opcode = *src++;
3628 		*dst++ = cpu_to_scr(opcode);
3629 
3630 		/*
3631 		 *  If we forget to change the length
3632 		 *  in scripts, a field will be
3633 		 *  padded with 0. This is an illegal
3634 		 *  command.
3635 		 */
3636 		if (opcode == 0) {
3637 			printf ("%s: ERROR0 IN SCRIPT at %d.\n",
3638 				sym_name(np), (int) (src-start-1));
3639 			MDELAY (10000);
3640 			continue;
3641 		};
3642 
3643 		/*
3644 		 *  We use the bogus value 0xf00ff00f ;-)
3645 		 *  to reserve data area in SCRIPTS.
3646 		 */
3647 		if (opcode == SCR_DATA_ZERO) {
3648 			dst[-1] = 0;
3649 			continue;
3650 		}
3651 
3652 		if (DEBUG_FLAGS & DEBUG_SCRIPT)
3653 			printf ("%p:  <%x>\n", (src-1), (unsigned)opcode);
3654 
3655 		/*
3656 		 *  We don't have to decode ALL commands
3657 		 */
3658 		switch (opcode >> 28) {
3659 		case 0xf:
3660 			/*
3661 			 *  LOAD / STORE DSA relative, don't relocate.
3662 			 */
3663 			relocs = 0;
3664 			break;
3665 		case 0xe:
3666 			/*
3667 			 *  LOAD / STORE absolute.
3668 			 */
3669 			relocs = 1;
3670 			break;
3671 		case 0xc:
3672 			/*
3673 			 *  COPY has TWO arguments.
3674 			 */
3675 			relocs = 2;
3676 			tmp1 = src[0];
3677 			tmp2 = src[1];
3678 #ifdef	RELOC_KVAR
3679 			if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3680 				tmp1 = 0;
3681 			if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3682 				tmp2 = 0;
3683 #endif
3684 			if ((tmp1 ^ tmp2) & 3) {
3685 				printf ("%s: ERROR1 IN SCRIPT at %d.\n",
3686 					sym_name(np), (int) (src-start-1));
3687 				MDELAY (1000);
3688 			}
3689 			/*
3690 			 *  If PREFETCH feature not enabled, remove
3691 			 *  the NO FLUSH bit if present.
3692 			 */
3693 			if ((opcode & SCR_NO_FLUSH) &&
3694 			    !(np->features & FE_PFEN)) {
3695 				dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3696 				++opchanged;
3697 			}
3698 			break;
3699 		case 0x0:
3700 			/*
3701 			 *  MOVE/CHMOV (absolute address)
3702 			 */
3703 			if (!(np->features & FE_WIDE))
3704 				dst[-1] = cpu_to_scr(opcode | OPC_MOVE);
3705 			relocs = 1;
3706 			break;
3707 		case 0x1:
3708 			/*
3709 			 *  MOVE/CHMOV (table indirect)
3710 			 */
3711 			if (!(np->features & FE_WIDE))
3712 				dst[-1] = cpu_to_scr(opcode | OPC_MOVE);
3713 			relocs = 0;
3714 			break;
3715 		case 0x8:
3716 			/*
3717 			 *  JUMP / CALL
3718 			 *  dont't relocate if relative :-)
3719 			 */
3720 			if (opcode & 0x00800000)
3721 				relocs = 0;
3722 			else if ((opcode & 0xf8400000) == 0x80400000)/*JUMP64*/
3723 				relocs = 2;
3724 			else
3725 				relocs = 1;
3726 			break;
3727 		case 0x4:
3728 		case 0x5:
3729 		case 0x6:
3730 		case 0x7:
3731 			relocs = 1;
3732 			break;
3733 		default:
3734 			relocs = 0;
3735 			break;
3736 		};
3737 
3738 		if (!relocs) {
3739 			*dst++ = cpu_to_scr(*src++);
3740 			continue;
3741 		}
3742 		while (relocs--) {
3743 			old = *src++;
3744 
3745 			switch (old & RELOC_MASK) {
3746 			case RELOC_REGISTER:
3747 				new = (old & ~RELOC_MASK) + np->mmio_ba;
3748 				break;
3749 			case RELOC_LABEL:
3750 				new = (old & ~RELOC_MASK) + np->script_ba;
3751 				break;
3752 			case RELOC_LABELH:
3753 				new = (old & ~RELOC_MASK) + np->scripth_ba;
3754 				break;
3755 			case RELOC_SOFTC:
3756 				new = (old & ~RELOC_MASK) + vtobus(np);
3757 				break;
3758 #ifdef	RELOC_KVAR
3759 			case RELOC_KVAR:
3760 				if (((old & ~RELOC_MASK) < SCRIPT_KVAR_FIRST) ||
3761 				    ((old & ~RELOC_MASK) > SCRIPT_KVAR_LAST))
3762 					panic("KVAR out of range");
3763 				new = vtobus(script_kvars[old & ~RELOC_MASK]);
3764 #endif
3765 				break;
3766 			case 0:
3767 				/* Don't relocate a 0 address. */
3768 				if (old == 0) {
3769 					new = old;
3770 					break;
3771 				}
3772 				/* fall through */
3773 			default:
3774 				new = 0;	/* For 'cc' not to complain */
3775 				panic("sym_bind_script: "
3776 				      "weird relocation %x\n", old);
3777 				break;
3778 			}
3779 
3780 			*dst++ = cpu_to_scr(new);
3781 		}
3782 	};
3783 }
3784 
3785 /*
3786  *  Print something which allows to retrieve the controler type,
3787  *  unit, target, lun concerned by a kernel message.
3788  */
3789 static void PRINT_TARGET (hcb_p np, int target)
3790 {
3791 	printf ("%s:%d:", sym_name(np), target);
3792 }
3793 
3794 static void PRINT_LUN(hcb_p np, int target, int lun)
3795 {
3796 	printf ("%s:%d:%d:", sym_name(np), target, lun);
3797 }
3798 
3799 static void PRINT_ADDR (ccb_p cp)
3800 {
3801 	if (cp && cp->cam_ccb)
3802 		xpt_print_path(cp->cam_ccb->ccb_h.path);
3803 }
3804 
3805 /*
3806  *  Take into account this ccb in the freeze count.
3807  *  The flag that tells user about avoids doing that
3808  *  more than once for a ccb.
3809  */
3810 static void sym_freeze_cam_ccb(union ccb *ccb)
3811 {
3812 	if (!(ccb->ccb_h.flags & CAM_DEV_QFRZDIS)) {
3813 		if (!(ccb->ccb_h.status & CAM_DEV_QFRZN)) {
3814 			ccb->ccb_h.status |= CAM_DEV_QFRZN;
3815 			xpt_freeze_devq(ccb->ccb_h.path, 1);
3816 		}
3817 	}
3818 }
3819 
3820 /*
3821  *  Set the status field of a CAM CCB.
3822  */
3823 static __inline void sym_set_cam_status(union ccb *ccb, cam_status status)
3824 {
3825 	ccb->ccb_h.status &= ~CAM_STATUS_MASK;
3826 	ccb->ccb_h.status |= status;
3827 }
3828 
3829 /*
3830  *  Get the status field of a CAM CCB.
3831  */
3832 static __inline int sym_get_cam_status(union ccb *ccb)
3833 {
3834 	return ccb->ccb_h.status & CAM_STATUS_MASK;
3835 }
3836 
3837 /*
3838  *  Enqueue a CAM CCB.
3839  */
3840 static void sym_enqueue_cam_ccb(hcb_p np, union ccb *ccb)
3841 {
3842 	assert(!(ccb->ccb_h.status & CAM_SIM_QUEUED));
3843 	ccb->ccb_h.status = CAM_REQ_INPROG;
3844 
3845 	ccb->ccb_h.timeout_ch = timeout(sym_timeout, (caddr_t) ccb,
3846 				       ccb->ccb_h.timeout*hz/1000);
3847 	ccb->ccb_h.status |= CAM_SIM_QUEUED;
3848 	ccb->ccb_h.sym_hcb_ptr = np;
3849 
3850 	sym_insque_tail(sym_qptr(&ccb->ccb_h.sim_links), &np->cam_ccbq);
3851 }
3852 
3853 /*
3854  *  Complete a pending CAM CCB.
3855  */
3856 static void sym_xpt_done(hcb_p np, union ccb *ccb)
3857 {
3858 	if (ccb->ccb_h.status & CAM_SIM_QUEUED) {
3859 		untimeout(sym_timeout, (caddr_t) ccb, ccb->ccb_h.timeout_ch);
3860 		sym_remque(sym_qptr(&ccb->ccb_h.sim_links));
3861 		ccb->ccb_h.status &= ~CAM_SIM_QUEUED;
3862 		ccb->ccb_h.sym_hcb_ptr = 0;
3863 	}
3864 	if (ccb->ccb_h.flags & CAM_DEV_QFREEZE)
3865 		sym_freeze_cam_ccb(ccb);
3866 	xpt_done(ccb);
3867 }
3868 
3869 static void sym_xpt_done2(hcb_p np, union ccb *ccb, int cam_status)
3870 {
3871 	sym_set_cam_status(ccb, cam_status);
3872 	sym_xpt_done(np, ccb);
3873 }
3874 
3875 /*
3876  *  SYMBIOS chip clock divisor table.
3877  *
3878  *  Divisors are multiplied by 10,000,000 in order to make
3879  *  calculations more simple.
3880  */
3881 #define _5M 5000000
3882 static u_long div_10M[] =
3883 	{2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3884 
3885 /*
3886  *  SYMBIOS chips allow burst lengths of 2, 4, 8, 16, 32, 64,
3887  *  128 transfers. All chips support at least 16 transfers
3888  *  bursts. The 825A, 875 and 895 chips support bursts of up
3889  *  to 128 transfers and the 895A and 896 support bursts of up
3890  *  to 64 transfers. All other chips support up to 16
3891  *  transfers bursts.
3892  *
3893  *  For PCI 32 bit data transfers each transfer is a DWORD.
3894  *  It is a QUADWORD (8 bytes) for PCI 64 bit data transfers.
3895  *  Only the 896 is able to perform 64 bit data transfers.
3896  *
3897  *  We use log base 2 (burst length) as internal code, with
3898  *  value 0 meaning "burst disabled".
3899  */
3900 
3901 /*
3902  *  Burst length from burst code.
3903  */
3904 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3905 
3906 /*
3907  *  Burst code from io register bits.
3908  */
3909 #define burst_code(dmode, ctest4, ctest5) \
3910 	(ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
3911 
3912 /*
3913  *  Set initial io register bits from burst code.
3914  */
3915 static __inline void sym_init_burst(hcb_p np, u_char bc)
3916 {
3917 	np->rv_ctest4	&= ~0x80;
3918 	np->rv_dmode	&= ~(0x3 << 6);
3919 	np->rv_ctest5	&= ~0x4;
3920 
3921 	if (!bc) {
3922 		np->rv_ctest4	|= 0x80;
3923 	}
3924 	else {
3925 		--bc;
3926 		np->rv_dmode	|= ((bc & 0x3) << 6);
3927 		np->rv_ctest5	|= (bc & 0x4);
3928 	}
3929 }
3930 
3931 
3932 /*
3933  * Print out the list of targets that have some flag disabled by user.
3934  */
3935 static void sym_print_targets_flag(hcb_p np, int mask, char *msg)
3936 {
3937 	int cnt;
3938 	int i;
3939 
3940 	for (cnt = 0, i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
3941 		if (i == np->myaddr)
3942 			continue;
3943 		if (np->target[i].usrflags & mask) {
3944 			if (!cnt++)
3945 				printf("%s: %s disabled for targets",
3946 					sym_name(np), msg);
3947 			printf(" %d", i);
3948 		}
3949 	}
3950 	if (cnt)
3951 		printf(".\n");
3952 }
3953 
3954 /*
3955  *  Save initial settings of some IO registers.
3956  *  Assumed to have been set by BIOS.
3957  *  We cannot reset the chip prior to reading the
3958  *  IO registers, since informations will be lost.
3959  *  Since the SCRIPTS processor may be running, this
3960  *  is not safe on paper, but it seems to work quite
3961  *  well. :)
3962  */
3963 static void sym_save_initial_setting (hcb_p np)
3964 {
3965 	np->sv_scntl0	= INB(nc_scntl0) & 0x0a;
3966 	np->sv_scntl3	= INB(nc_scntl3) & 0x07;
3967 	np->sv_dmode	= INB(nc_dmode)  & 0xce;
3968 	np->sv_dcntl	= INB(nc_dcntl)  & 0xa8;
3969 	np->sv_ctest3	= INB(nc_ctest3) & 0x01;
3970 	np->sv_ctest4	= INB(nc_ctest4) & 0x80;
3971 	np->sv_gpcntl	= INB(nc_gpcntl);
3972 	np->sv_stest1	= INB(nc_stest1);
3973 	np->sv_stest2	= INB(nc_stest2) & 0x20;
3974 	np->sv_stest4	= INB(nc_stest4);
3975 	if (np->features & FE_C10) {	/* Always large DMA fifo + ultra3 */
3976 		np->sv_scntl4	= INB(nc_scntl4);
3977 		np->sv_ctest5	= INB(nc_ctest5) & 0x04;
3978 	}
3979 	else
3980 		np->sv_ctest5	= INB(nc_ctest5) & 0x24;
3981 }
3982 
3983 /*
3984  *  Prepare io register values used by sym_init() according
3985  *  to selected and supported features.
3986  */
3987 static int sym_prepare_setting(hcb_p np, struct sym_nvram *nvram)
3988 {
3989 	u_char	burst_max;
3990 	u_long	period;
3991 	int i;
3992 
3993 	/*
3994 	 *  Wide ?
3995 	 */
3996 	np->maxwide	= (np->features & FE_WIDE)? 1 : 0;
3997 
3998 	/*
3999 	 *  Get the frequency of the chip's clock.
4000 	 */
4001 	if	(np->features & FE_QUAD)
4002 		np->multiplier	= 4;
4003 	else if	(np->features & FE_DBLR)
4004 		np->multiplier	= 2;
4005 	else
4006 		np->multiplier	= 1;
4007 
4008 	np->clock_khz	= (np->features & FE_CLK80)? 80000 : 40000;
4009 	np->clock_khz	*= np->multiplier;
4010 
4011 	if (np->clock_khz != 40000)
4012 		sym_getclock(np, np->multiplier);
4013 
4014 	/*
4015 	 * Divisor to be used for async (timer pre-scaler).
4016 	 */
4017 	i = np->clock_divn - 1;
4018 	while (--i >= 0) {
4019 		if (10ul * SYM_CONF_MIN_ASYNC * np->clock_khz > div_10M[i]) {
4020 			++i;
4021 			break;
4022 		}
4023 	}
4024 	np->rv_scntl3 = i+1;
4025 
4026 	/*
4027 	 * The C1010 uses hardwired divisors for async.
4028 	 * So, we just throw away, the async. divisor.:-)
4029 	 */
4030 	if (np->features & FE_C10)
4031 		np->rv_scntl3 = 0;
4032 
4033 	/*
4034 	 * Minimum synchronous period factor supported by the chip.
4035 	 * Btw, 'period' is in tenths of nanoseconds.
4036 	 */
4037 	period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
4038 	if	(period <= 250)		np->minsync = 10;
4039 	else if	(period <= 303)		np->minsync = 11;
4040 	else if	(period <= 500)		np->minsync = 12;
4041 	else				np->minsync = (period + 40 - 1) / 40;
4042 
4043 	/*
4044 	 * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
4045 	 */
4046 	if	(np->minsync < 25 &&
4047 		 !(np->features & (FE_ULTRA|FE_ULTRA2|FE_ULTRA3)))
4048 		np->minsync = 25;
4049 	else if	(np->minsync < 12 &&
4050 		 !(np->features & (FE_ULTRA2|FE_ULTRA3)))
4051 		np->minsync = 12;
4052 
4053 	/*
4054 	 * Maximum synchronous period factor supported by the chip.
4055 	 */
4056 	period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
4057 	np->maxsync = period > 2540 ? 254 : period / 10;
4058 
4059 	/*
4060 	 * If chip is a C1010, guess the sync limits in DT mode.
4061 	 */
4062 	if ((np->features & (FE_C10|FE_ULTRA3)) == (FE_C10|FE_ULTRA3)) {
4063 		if (np->clock_khz == 160000) {
4064 			np->minsync_dt = 9;
4065 			np->maxsync_dt = 50;
4066 		}
4067 	}
4068 
4069 	/*
4070 	 *  64 bit (53C895A or 53C896) ?
4071 	 */
4072 	if (np->features & FE_64BIT)
4073 #if BITS_PER_LONG > 32
4074 		np->rv_ccntl1	|= (XTIMOD | EXTIBMV);
4075 #else
4076 		np->rv_ccntl1	|= (DDAC);
4077 #endif
4078 
4079 	/*
4080 	 *  Phase mismatch handled by SCRIPTS (895A/896/1010) ?
4081   	 */
4082 	if (np->features & FE_NOPM)
4083 		np->rv_ccntl0	|= (ENPMJ);
4084 
4085  	/*
4086 	 *  C1010 Errata.
4087 	 *  In dual channel mode, contention occurs if internal cycles
4088 	 *  are used. Disable internal cycles.
4089 	 */
4090 	if (np->device_id == PCI_ID_LSI53C1010 && np->revision_id < 0x45)
4091 		np->rv_ccntl0	|=  DILS;
4092 
4093 	/*
4094 	 *  Select burst length (dwords)
4095 	 */
4096 	burst_max	= SYM_SETUP_BURST_ORDER;
4097 	if (burst_max == 255)
4098 		burst_max = burst_code(np->sv_dmode, np->sv_ctest4,
4099 				       np->sv_ctest5);
4100 	if (burst_max > 7)
4101 		burst_max = 7;
4102 	if (burst_max > np->maxburst)
4103 		burst_max = np->maxburst;
4104 
4105 	/*
4106 	 *  DEL 352 - 53C810 Rev x11 - Part Number 609-0392140 - ITEM 2.
4107 	 *  This chip and the 860 Rev 1 may wrongly use PCI cache line
4108 	 *  based transactions on LOAD/STORE instructions. So we have
4109 	 *  to prevent these chips from using such PCI transactions in
4110 	 *  this driver. The generic ncr driver that does not use
4111 	 *  LOAD/STORE instructions does not need this work-around.
4112 	 */
4113 	if ((np->device_id == PCI_ID_SYM53C810 &&
4114 	     np->revision_id >= 0x10 && np->revision_id <= 0x11) ||
4115 	    (np->device_id == PCI_ID_SYM53C860 &&
4116 	     np->revision_id <= 0x1))
4117 		np->features &= ~(FE_WRIE|FE_ERL|FE_ERMP);
4118 
4119 	/*
4120 	 *  Select all supported special features.
4121 	 *  If we are using on-board RAM for scripts, prefetch (PFEN)
4122 	 *  does not help, but burst op fetch (BOF) does.
4123 	 *  Disabling PFEN makes sure BOF will be used.
4124 	 */
4125 	if (np->features & FE_ERL)
4126 		np->rv_dmode	|= ERL;		/* Enable Read Line */
4127 	if (np->features & FE_BOF)
4128 		np->rv_dmode	|= BOF;		/* Burst Opcode Fetch */
4129 	if (np->features & FE_ERMP)
4130 		np->rv_dmode	|= ERMP;	/* Enable Read Multiple */
4131 #if 1
4132 	if ((np->features & FE_PFEN) && !np->ram_ba)
4133 #else
4134 	if (np->features & FE_PFEN)
4135 #endif
4136 		np->rv_dcntl	|= PFEN;	/* Prefetch Enable */
4137 	if (np->features & FE_CLSE)
4138 		np->rv_dcntl	|= CLSE;	/* Cache Line Size Enable */
4139 	if (np->features & FE_WRIE)
4140 		np->rv_ctest3	|= WRIE;	/* Write and Invalidate */
4141 	if (np->features & FE_DFS)
4142 		np->rv_ctest5	|= DFS;		/* Dma Fifo Size */
4143 
4144 	/*
4145 	 *  Select some other
4146 	 */
4147 	if (SYM_SETUP_PCI_PARITY)
4148 		np->rv_ctest4	|= MPEE; /* Master parity checking */
4149 	if (SYM_SETUP_SCSI_PARITY)
4150 		np->rv_scntl0	|= 0x0a; /*  full arb., ena parity, par->ATN  */
4151 
4152 	/*
4153 	 *  Get parity checking, host ID and verbose mode from NVRAM
4154 	 */
4155 	np->myaddr = 255;
4156 	sym_nvram_setup_host (np, nvram);
4157 
4158 	/*
4159 	 *  Get SCSI addr of host adapter (set by bios?).
4160 	 */
4161 	if (np->myaddr == 255) {
4162 		np->myaddr = INB(nc_scid) & 0x07;
4163 		if (!np->myaddr)
4164 			np->myaddr = SYM_SETUP_HOST_ID;
4165 	}
4166 
4167 	/*
4168 	 *  Prepare initial io register bits for burst length
4169 	 */
4170 	sym_init_burst(np, burst_max);
4171 
4172 	/*
4173 	 *  Set SCSI BUS mode.
4174 	 *  - LVD capable chips (895/895A/896/1010) report the
4175 	 *    current BUS mode through the STEST4 IO register.
4176 	 *  - For previous generation chips (825/825A/875),
4177 	 *    user has to tell us how to check against HVD,
4178 	 *    since a 100% safe algorithm is not possible.
4179 	 */
4180 	np->scsi_mode = SMODE_SE;
4181 	if (np->features & (FE_ULTRA2|FE_ULTRA3))
4182 		np->scsi_mode = (np->sv_stest4 & SMODE);
4183 	else if	(np->features & FE_DIFF) {
4184 		if (SYM_SETUP_SCSI_DIFF == 1) {
4185 			if (np->sv_scntl3) {
4186 				if (np->sv_stest2 & 0x20)
4187 					np->scsi_mode = SMODE_HVD;
4188 			}
4189 			else if (nvram->type == SYM_SYMBIOS_NVRAM) {
4190 				if (INB(nc_gpreg) & 0x08)
4191 					np->scsi_mode = SMODE_HVD;
4192 			}
4193 		}
4194 		else if	(SYM_SETUP_SCSI_DIFF == 2)
4195 			np->scsi_mode = SMODE_HVD;
4196 	}
4197 	if (np->scsi_mode == SMODE_HVD)
4198 		np->rv_stest2 |= 0x20;
4199 
4200 	/*
4201 	 *  Set LED support from SCRIPTS.
4202 	 *  Ignore this feature for boards known to use a
4203 	 *  specific GPIO wiring and for the 895A or 896
4204 	 *  that drive the LED directly.
4205 	 */
4206 	if ((SYM_SETUP_SCSI_LED || nvram->type == SYM_SYMBIOS_NVRAM) &&
4207 	    !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
4208 		np->features |= FE_LED0;
4209 
4210 	/*
4211 	 *  Set irq mode.
4212 	 */
4213 	switch(SYM_SETUP_IRQ_MODE & 3) {
4214 	case 2:
4215 		np->rv_dcntl	|= IRQM;
4216 		break;
4217 	case 1:
4218 		np->rv_dcntl	|= (np->sv_dcntl & IRQM);
4219 		break;
4220 	default:
4221 		break;
4222 	}
4223 
4224 	/*
4225 	 *  Configure targets according to driver setup.
4226 	 *  If NVRAM present get targets setup from NVRAM.
4227 	 */
4228 	for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
4229 		tcb_p tp = &np->target[i];
4230 
4231 		tp->tinfo.user.period = np->minsync;
4232 		tp->tinfo.user.offset = np->maxoffs;
4233 		tp->tinfo.user.width  = np->maxwide ? BUS_16_BIT : BUS_8_BIT;
4234 		tp->usrflags |= (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
4235 		tp->usrtags = SYM_SETUP_MAX_TAG;
4236 
4237 		sym_nvram_setup_target (np, i, nvram);
4238 
4239 		if (!tp->usrtags)
4240 			tp->usrflags &= ~SYM_TAGS_ENABLED;
4241 	}
4242 
4243 	/*
4244 	 *  Let user know about the settings.
4245 	 */
4246 	i = nvram->type;
4247 	printf("%s: %s NVRAM, ID %d, Fast-%d, %s, %s\n", sym_name(np),
4248 		i  == SYM_SYMBIOS_NVRAM ? "Symbios" :
4249 		(i == SYM_TEKRAM_NVRAM  ? "Tekram" : "No"),
4250 		np->myaddr,
4251 		(np->features & FE_ULTRA3) ? 80 :
4252 		(np->features & FE_ULTRA2) ? 40 :
4253 		(np->features & FE_ULTRA)  ? 20 : 10,
4254 		sym_scsi_bus_mode(np->scsi_mode),
4255 		(np->rv_scntl0 & 0xa)	? "parity checking" : "NO parity");
4256 	/*
4257 	 *  Tell him more on demand.
4258 	 */
4259 	if (sym_verbose) {
4260 		printf("%s: %s IRQ line driver%s\n",
4261 			sym_name(np),
4262 			np->rv_dcntl & IRQM ? "totem pole" : "open drain",
4263 			np->ram_ba ? ", using on-chip SRAM" : "");
4264 		if (np->features & FE_NOPM)
4265 			printf("%s: handling phase mismatch from SCRIPTS.\n",
4266 			       sym_name(np));
4267 	}
4268 	/*
4269 	 *  And still more.
4270 	 */
4271 	if (sym_verbose > 1) {
4272 		printf ("%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
4273 			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
4274 			sym_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
4275 			np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
4276 
4277 		printf ("%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
4278 			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
4279 			sym_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
4280 			np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
4281 	}
4282 	/*
4283 	 *  Let user be aware of targets that have some disable flags set.
4284 	 */
4285 	sym_print_targets_flag(np, SYM_SCAN_BOOT_DISABLED, "SCAN AT BOOT");
4286 	if (sym_verbose)
4287 		sym_print_targets_flag(np, SYM_SCAN_LUNS_DISABLED,
4288 				       "SCAN FOR LUNS");
4289 
4290 	return 0;
4291 }
4292 
4293 /*
4294  *  Prepare the next negotiation message if needed.
4295  *
4296  *  Fill in the part of message buffer that contains the
4297  *  negotiation and the nego_status field of the CCB.
4298  *  Returns the size of the message in bytes.
4299  */
4300 
4301 static int sym_prepare_nego(hcb_p np, ccb_p cp, int nego, u_char *msgptr)
4302 {
4303 	tcb_p tp = &np->target[cp->target];
4304 	int msglen = 0;
4305 
4306 #if 1
4307 	/*
4308 	 *  For now, only use PPR with DT option if period factor = 9.
4309 	 */
4310 	if (tp->tinfo.goal.period == 9) {
4311 		tp->tinfo.goal.width = BUS_16_BIT;
4312 		tp->tinfo.goal.options |= PPR_OPT_DT;
4313 	}
4314 	else
4315 		tp->tinfo.goal.options &= ~PPR_OPT_DT;
4316 #endif
4317 	/*
4318 	 *  Early C1010 chips need a work-around for DT
4319 	 *  data transfer to work.
4320 	 */
4321 #ifndef	SYM_CONF_BROKEN_U3EN_SUPPORT
4322 	if (!(np->features & FE_U3EN))
4323 		tp->tinfo.goal.options = 0;
4324 #endif
4325 	/*
4326 	 *  negotiate using PPR ?
4327 	 */
4328 	if (tp->tinfo.goal.options & PPR_OPT_MASK)
4329 		nego = NS_PPR;
4330 	/*
4331 	 *  negotiate wide transfers ?
4332 	 */
4333 	else if (tp->tinfo.current.width != tp->tinfo.goal.width)
4334 		nego = NS_WIDE;
4335 	/*
4336 	 *  negotiate synchronous transfers?
4337 	 */
4338 	else if (tp->tinfo.current.period != tp->tinfo.goal.period ||
4339 		 tp->tinfo.current.offset != tp->tinfo.goal.offset)
4340 		nego = NS_SYNC;
4341 
4342 	switch (nego) {
4343 	case NS_SYNC:
4344 		msgptr[msglen++] = M_EXTENDED;
4345 		msgptr[msglen++] = 3;
4346 		msgptr[msglen++] = M_X_SYNC_REQ;
4347 		msgptr[msglen++] = tp->tinfo.goal.period;
4348 		msgptr[msglen++] = tp->tinfo.goal.offset;
4349 		break;
4350 	case NS_WIDE:
4351 		msgptr[msglen++] = M_EXTENDED;
4352 		msgptr[msglen++] = 2;
4353 		msgptr[msglen++] = M_X_WIDE_REQ;
4354 		msgptr[msglen++] = tp->tinfo.goal.width;
4355 		break;
4356 	case NS_PPR:
4357 		msgptr[msglen++] = M_EXTENDED;
4358 		msgptr[msglen++] = 6;
4359 		msgptr[msglen++] = M_X_PPR_REQ;
4360 		msgptr[msglen++] = tp->tinfo.goal.period;
4361 		msgptr[msglen++] = 0;
4362 		msgptr[msglen++] = tp->tinfo.goal.offset;
4363 		msgptr[msglen++] = tp->tinfo.goal.width;
4364 		msgptr[msglen++] = tp->tinfo.goal.options & PPR_OPT_DT;
4365 		break;
4366 	};
4367 
4368 	cp->nego_status = nego;
4369 
4370 	if (nego) {
4371 		tp->nego_cp = cp; /* Keep track a nego will be performed */
4372 		if (DEBUG_FLAGS & DEBUG_NEGO) {
4373 			sym_print_msg(cp, nego == NS_SYNC ? "sync msgout" :
4374 					  nego == NS_WIDE ? "wide msgout" :
4375 					  "ppr msgout", msgptr);
4376 		};
4377 	};
4378 
4379 	return msglen;
4380 }
4381 
4382 /*
4383  *  Insert a job into the start queue.
4384  */
4385 static void sym_put_start_queue(hcb_p np, ccb_p cp)
4386 {
4387 	u_short	qidx;
4388 
4389 #ifdef SYM_CONF_IARB_SUPPORT
4390 	/*
4391 	 *  If the previously queued CCB is not yet done,
4392 	 *  set the IARB hint. The SCRIPTS will go with IARB
4393 	 *  for this job when starting the previous one.
4394 	 *  We leave devices a chance to win arbitration by
4395 	 *  not using more than 'iarb_max' consecutive
4396 	 *  immediate arbitrations.
4397 	 */
4398 	if (np->last_cp && np->iarb_count < np->iarb_max) {
4399 		np->last_cp->host_flags |= HF_HINT_IARB;
4400 		++np->iarb_count;
4401 	}
4402 	else
4403 		np->iarb_count = 0;
4404 	np->last_cp = cp;
4405 #endif
4406 
4407 	/*
4408 	 *  Insert first the idle task and then our job.
4409 	 *  The MB should ensure proper ordering.
4410 	 */
4411 	qidx = np->squeueput + 2;
4412 	if (qidx >= MAX_QUEUE*2) qidx = 0;
4413 
4414 	np->squeue [qidx]	   = cpu_to_scr(np->idletask_ba);
4415 	MEMORY_BARRIER();
4416 	np->squeue [np->squeueput] = cpu_to_scr(cp->ccb_ba);
4417 
4418 	np->squeueput = qidx;
4419 
4420 	if (DEBUG_FLAGS & DEBUG_QUEUE)
4421 		printf ("%s: queuepos=%d.\n", sym_name (np), np->squeueput);
4422 
4423 	/*
4424 	 *  Script processor may be waiting for reselect.
4425 	 *  Wake it up.
4426 	 */
4427 	MEMORY_BARRIER();
4428 	OUTB (nc_istat, SIGP|np->istat_sem);
4429 }
4430 
4431 
4432 /*
4433  *  Soft reset the chip.
4434  *
4435  *  Raising SRST when the chip is running may cause
4436  *  problems on dual function chips (see below).
4437  *  On the other hand, LVD devices need some delay
4438  *  to settle and report actual BUS mode in STEST4.
4439  */
4440 static void sym_chip_reset (hcb_p np)
4441 {
4442 	OUTB (nc_istat, SRST);
4443 	UDELAY (10);
4444 	OUTB (nc_istat, 0);
4445 	UDELAY(2000);	/* For BUS MODE to settle */
4446 }
4447 
4448 /*
4449  *  Soft reset the chip.
4450  *
4451  *  Some 896 and 876 chip revisions may hang-up if we set
4452  *  the SRST (soft reset) bit at the wrong time when SCRIPTS
4453  *  are running.
4454  *  So, we need to abort the current operation prior to
4455  *  soft resetting the chip.
4456  */
4457 static void sym_soft_reset (hcb_p np)
4458 {
4459 	u_char istat;
4460 	int i;
4461 
4462 	OUTB (nc_istat, CABRT);
4463 	for (i = 1000000 ; i ; --i) {
4464 		istat = INB (nc_istat);
4465 		if (istat & SIP) {
4466 			INW (nc_sist);
4467 			continue;
4468 		}
4469 		if (istat & DIP) {
4470 			OUTB (nc_istat, 0);
4471 			INB (nc_dstat);
4472 			break;
4473 		}
4474 	}
4475 	if (!i)
4476 		printf("%s: unable to abort current chip operation.\n",
4477 			sym_name(np));
4478 	sym_chip_reset (np);
4479 }
4480 
4481 /*
4482  *  Start reset process.
4483  *
4484  *  The interrupt handler will reinitialize the chip.
4485  */
4486 static void sym_start_reset(hcb_p np)
4487 {
4488 	(void) sym_reset_scsi_bus(np, 1);
4489 }
4490 
4491 static int sym_reset_scsi_bus(hcb_p np, int enab_int)
4492 {
4493 	u32 term;
4494 	int retv = 0;
4495 
4496 	sym_soft_reset(np);	/* Soft reset the chip */
4497 	if (enab_int)
4498 		OUTW (nc_sien, RST);
4499 	/*
4500 	 *  Enable Tolerant, reset IRQD if present and
4501 	 *  properly set IRQ mode, prior to resetting the bus.
4502 	 */
4503 	OUTB (nc_stest3, TE);
4504 	OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
4505 	OUTB (nc_scntl1, CRST);
4506 	UDELAY (200);
4507 
4508 	if (!SYM_SETUP_SCSI_BUS_CHECK)
4509 		goto out;
4510 	/*
4511 	 *  Check for no terminators or SCSI bus shorts to ground.
4512 	 *  Read SCSI data bus, data parity bits and control signals.
4513 	 *  We are expecting RESET to be TRUE and other signals to be
4514 	 *  FALSE.
4515 	 */
4516 	term =	INB(nc_sstat0);
4517 	term =	((term & 2) << 7) + ((term & 1) << 17);	/* rst sdp0 */
4518 	term |= ((INB(nc_sstat2) & 0x01) << 26) |	/* sdp1     */
4519 		((INW(nc_sbdl) & 0xff)   << 9)  |	/* d7-0     */
4520 		((INW(nc_sbdl) & 0xff00) << 10) |	/* d15-8    */
4521 		INB(nc_sbcl);	/* req ack bsy sel atn msg cd io    */
4522 
4523 	if (!(np->features & FE_WIDE))
4524 		term &= 0x3ffff;
4525 
4526 	if (term != (2<<7)) {
4527 		printf("%s: suspicious SCSI data while resetting the BUS.\n",
4528 			sym_name(np));
4529 		printf("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4530 			"0x%lx, expecting 0x%lx\n",
4531 			sym_name(np),
4532 			(np->features & FE_WIDE) ? "dp1,d15-8," : "",
4533 			(u_long)term, (u_long)(2<<7));
4534 		if (SYM_SETUP_SCSI_BUS_CHECK == 1)
4535 			retv = 1;
4536 	}
4537 out:
4538 	OUTB (nc_scntl1, 0);
4539 	/* MDELAY(100); */
4540 	return retv;
4541 }
4542 
4543 /*
4544  *  The chip may have completed jobs. Look at the DONE QUEUE.
4545  */
4546 static int sym_wakeup_done (hcb_p np)
4547 {
4548 	ccb_p cp;
4549 	int i, n;
4550 	u_long dsa;
4551 
4552 	n = 0;
4553 	i = np->dqueueget;
4554 	while (1) {
4555 		dsa = scr_to_cpu(np->dqueue[i]);
4556 		if (!dsa)
4557 			break;
4558 		np->dqueue[i] = 0;
4559 		if ((i = i+2) >= MAX_QUEUE*2)
4560 			i = 0;
4561 
4562 		cp = sym_ccb_from_dsa(np, dsa);
4563 		if (cp) {
4564 			sym_complete_ok (np, cp);
4565 			++n;
4566 		}
4567 		else
4568 			printf ("%s: bad DSA (%lx) in done queue.\n",
4569 				sym_name(np), dsa);
4570 	}
4571 	np->dqueueget = i;
4572 
4573 	return n;
4574 }
4575 
4576 /*
4577  *  Complete all active CCBs with error.
4578  *  Used on CHIP/SCSI RESET.
4579  */
4580 static void sym_flush_busy_queue (hcb_p np, int cam_status)
4581 {
4582 	/*
4583 	 *  Move all active CCBs to the COMP queue
4584 	 *  and flush this queue.
4585 	 */
4586 	sym_que_splice(&np->busy_ccbq, &np->comp_ccbq);
4587 	sym_que_init(&np->busy_ccbq);
4588 	sym_flush_comp_queue(np, cam_status);
4589 }
4590 
4591 /*
4592  *  Start chip.
4593  *
4594  *  'reason' means:
4595  *     0: initialisation.
4596  *     1: SCSI BUS RESET delivered or received.
4597  *     2: SCSI BUS MODE changed.
4598  */
4599 static void sym_init (hcb_p np, int reason)
4600 {
4601  	int	i;
4602 	u_long	phys;
4603 
4604  	/*
4605 	 *  Reset chip if asked, otherwise just clear fifos.
4606  	 */
4607 	if (reason == 1)
4608 		sym_soft_reset(np);
4609 	else {
4610 		OUTB (nc_stest3, TE|CSF);
4611 		OUTONB (nc_ctest3, CLF);
4612 	}
4613 
4614 	/*
4615 	 *  Clear Start Queue
4616 	 */
4617 	phys = vtobus(np->squeue);
4618 	for (i = 0; i < MAX_QUEUE*2; i += 2) {
4619 		np->squeue[i]   = cpu_to_scr(np->idletask_ba);
4620 		np->squeue[i+1] = cpu_to_scr(phys + (i+2)*4);
4621 	}
4622 	np->squeue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
4623 
4624 	/*
4625 	 *  Start at first entry.
4626 	 */
4627 	np->squeueput = 0;
4628 	np->scripth0->startpos[0] = cpu_to_scr(phys);
4629 
4630 	/*
4631 	 *  Clear Done Queue
4632 	 */
4633 	phys = vtobus(np->dqueue);
4634 	for (i = 0; i < MAX_QUEUE*2; i += 2) {
4635 		np->dqueue[i]   = 0;
4636 		np->dqueue[i+1] = cpu_to_scr(phys + (i+2)*4);
4637 	}
4638 	np->dqueue[MAX_QUEUE*2-1] = cpu_to_scr(phys);
4639 
4640 	/*
4641 	 *  Start at first entry.
4642 	 */
4643 	np->scripth0->done_pos[0] = cpu_to_scr(phys);
4644 	np->dqueueget = 0;
4645 
4646 	/*
4647 	 *  Wakeup all pending jobs.
4648 	 */
4649 	sym_flush_busy_queue(np, CAM_SCSI_BUS_RESET);
4650 
4651 	/*
4652 	 *  Init chip.
4653 	 */
4654 	OUTB (nc_istat,  0x00   );	/*  Remove Reset, abort */
4655 	UDELAY (2000);	/* The 895 needs time for the bus mode to settle */
4656 
4657 	OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
4658 					/*  full arb., ena parity, par->ATN  */
4659 	OUTB (nc_scntl1, 0x00);		/*  odd parity, and remove CRST!! */
4660 
4661 	sym_selectclock(np, np->rv_scntl3);	/* Select SCSI clock */
4662 
4663 	OUTB (nc_scid  , RRE|np->myaddr);	/* Adapter SCSI address */
4664 	OUTW (nc_respid, 1ul<<np->myaddr);	/* Id to respond to */
4665 	OUTB (nc_istat , SIGP	);		/*  Signal Process */
4666 	OUTB (nc_dmode , np->rv_dmode);		/* Burst length, dma mode */
4667 	OUTB (nc_ctest5, np->rv_ctest5);	/* Large fifo + large burst */
4668 
4669 	OUTB (nc_dcntl , NOCOM|np->rv_dcntl);	/* Protect SFBR */
4670 	OUTB (nc_ctest3, np->rv_ctest3);	/* Write and invalidate */
4671 	OUTB (nc_ctest4, np->rv_ctest4);	/* Master parity checking */
4672 
4673 	/* Extended Sreq/Sack filtering not supported on the C10 */
4674 	if (np->features & FE_C10)
4675 		OUTB (nc_stest2, np->rv_stest2);
4676 	else
4677 		OUTB (nc_stest2, EXT|np->rv_stest2);
4678 
4679 	OUTB (nc_stest3, TE);			/* TolerANT enable */
4680 	OUTB (nc_stime0, 0x0c);			/* HTH disabled  STO 0.25 sec */
4681 
4682 	/*
4683 	 *  C10101 Errata.
4684 	 *  Errant SGE's when in narrow. Write bits 4 & 5 of
4685 	 *  STEST1 register to disable SGE. We probably should do
4686 	 *  that from SCRIPTS for each selection/reselection, but
4687 	 *  I just don't want. :)
4688 	 */
4689 	if (np->device_id == PCI_ID_LSI53C1010 && np->revision_id < 0x45)
4690 		OUTB (nc_stest1, INB(nc_stest1) | 0x30);
4691 
4692 	/*
4693 	 *  DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
4694 	 *  Disable overlapped arbitration for some dual function devices,
4695 	 *  regardless revision id (kind of post-chip-design feature. ;-))
4696 	 */
4697 	if (np->device_id == PCI_ID_SYM53C875)
4698 		OUTB (nc_ctest0, (1<<5));
4699 	else if (np->device_id == PCI_ID_SYM53C896)
4700 		np->rv_ccntl0 |= DPR;
4701 
4702 	/*
4703 	 *  If 64 bit (895A/896/1010) write CCNTL1 to enable 40 bit
4704 	 *  address table indirect addressing for MOVE.
4705 	 *  Also write CCNTL0 if 64 bit chip, since this register seems
4706 	 *  to only be used by 64 bit cores.
4707 	 */
4708 	if (np->features & FE_64BIT) {
4709 		OUTB (nc_ccntl0, np->rv_ccntl0);
4710 		OUTB (nc_ccntl1, np->rv_ccntl1);
4711 	}
4712 
4713 	/*
4714 	 *  If phase mismatch handled by scripts (895A/896/1010),
4715 	 *  set PM jump addresses.
4716 	 */
4717 	if (np->features & FE_NOPM) {
4718 		OUTL (nc_pmjad1, SCRIPTH_BA (np, pm_handle));
4719 		OUTL (nc_pmjad2, SCRIPTH_BA (np, pm_handle));
4720 	}
4721 
4722 	/*
4723 	 *    Enable GPIO0 pin for writing if LED support from SCRIPTS.
4724 	 *    Also set GPIO5 and clear GPIO6 if hardware LED control.
4725 	 */
4726 	if (np->features & FE_LED0)
4727 		OUTB(nc_gpcntl, INB(nc_gpcntl) & ~0x01);
4728 	else if (np->features & FE_LEDC)
4729 		OUTB(nc_gpcntl, (INB(nc_gpcntl) & ~0x41) | 0x20);
4730 
4731 	/*
4732 	 *      enable ints
4733 	 */
4734 	OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
4735 	OUTB (nc_dien , MDPE|BF|SSI|SIR|IID);
4736 
4737 	/*
4738 	 *  For 895/6 enable SBMC interrupt and save current SCSI bus mode.
4739 	 *  Try to eat the spurious SBMC interrupt that may occur when
4740 	 *  we reset the chip but not the SCSI BUS (at initialization).
4741 	 */
4742 	if (np->features & (FE_ULTRA2|FE_ULTRA3)) {
4743 		OUTONW (nc_sien, SBMC);
4744 		if (reason == 0) {
4745 			MDELAY(100);
4746 			INW (nc_sist);
4747 		}
4748 		np->scsi_mode = INB (nc_stest4) & SMODE;
4749 	}
4750 
4751 	/*
4752 	 *  Fill in target structure.
4753 	 *  Reinitialize usrsync.
4754 	 *  Reinitialize usrwide.
4755 	 *  Prepare sync negotiation according to actual SCSI bus mode.
4756 	 */
4757 	for (i=0;i<SYM_CONF_MAX_TARGET;i++) {
4758 		tcb_p tp = &np->target[i];
4759 
4760 		tp->to_reset = 0;
4761 		tp->sval    = 0;
4762 		tp->wval    = np->rv_scntl3;
4763 		tp->uval    = 0;
4764 
4765 		tp->tinfo.current.period = 0;
4766 		tp->tinfo.current.offset = 0;
4767 		tp->tinfo.current.width  = BUS_8_BIT;
4768 		tp->tinfo.current.options = 0;
4769 	}
4770 
4771 	/*
4772 	 *  Download SCSI SCRIPTS to on-chip RAM if present,
4773 	 *  and start script processor.
4774 	 */
4775 	if (np->ram_ba) {
4776 		if (sym_verbose > 1)
4777 			printf ("%s: Downloading SCSI SCRIPTS.\n",
4778 				sym_name(np));
4779 		if (np->ram_ws == 8192) {
4780 			memcpy_to_pci(np->ram_va + 4096,
4781 					np->scripth0, sizeof(struct sym_scrh));
4782 			OUTL (nc_mmws, np->scr_ram_seg);
4783 			OUTL (nc_mmrs, np->scr_ram_seg);
4784 			OUTL (nc_sfs,  np->scr_ram_seg);
4785 			phys = SCRIPTH_BA (np, start64);
4786 		}
4787 		else
4788 			phys = SCRIPT_BA (np, init);
4789 		memcpy_to_pci(np->ram_va,np->script0,sizeof(struct sym_scr));
4790 	}
4791 	else
4792 		phys = SCRIPT_BA (np, init);
4793 
4794 	np->istat_sem = 0;
4795 
4796 	MEMORY_BARRIER();
4797 	OUTL (nc_dsa, vtobus(np));
4798 	OUTL (nc_dsp, phys);
4799 
4800 	/*
4801 	 *  Notify the XPT about the RESET condition.
4802 	 */
4803 	if (reason != 0)
4804 		xpt_async(AC_BUS_RESET, np->path, NULL);
4805 }
4806 
4807 /*
4808  *  Get clock factor and sync divisor for a given
4809  *  synchronous factor period.
4810  */
4811 static int
4812 sym_getsync(hcb_p np, u_char dt, u_char sfac, u_char *divp, u_char *fakp)
4813 {
4814 	u32	clk = np->clock_khz;	/* SCSI clock frequency in kHz	*/
4815 	int	div = np->clock_divn;	/* Number of divisors supported	*/
4816 	u32	fak;			/* Sync factor in sxfer		*/
4817 	u32	per;			/* Period in tenths of ns	*/
4818 	u32	kpc;			/* (per * clk)			*/
4819 	int	ret;
4820 
4821 	/*
4822 	 *  Compute the synchronous period in tenths of nano-seconds
4823 	 */
4824 	if (dt && sfac <= 9)	per = 125;
4825 	else if	(sfac <= 10)	per = 250;
4826 	else if	(sfac == 11)	per = 303;
4827 	else if	(sfac == 12)	per = 500;
4828 	else			per = 40 * sfac;
4829 	ret = per;
4830 
4831 	kpc = per * clk;
4832 	if (dt)
4833 		kpc <<= 1;
4834 
4835 	/*
4836 	 *  For earliest C10, the extra clocks does not apply
4837 	 *  to CRC cycles, so it may be safe not to use them.
4838 	 *  Note that this limits the lowest sync data transfer
4839 	 *  to 5 Mega-transfers per second and may result in
4840 	 *  using higher clock divisors.
4841 	 */
4842 #if 1
4843 	if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
4844 		/*
4845 		 *  Look for the lowest clock divisor that allows an
4846 		 *  output speed not faster than the period.
4847 		 */
4848 		while (div > 0) {
4849 			--div;
4850 			if (kpc > (div_10M[div] << 2)) {
4851 				++div;
4852 				break;
4853 			}
4854 		}
4855 		fak = 0;			/* No extra clocks */
4856 		if (div == np->clock_divn) {	/* Are we too fast ? */
4857 			ret = -1;
4858 		}
4859 		*divp = div;
4860 		*fakp = fak;
4861 		return ret;
4862 	}
4863 #endif
4864 
4865 	/*
4866 	 *  Look for the greatest clock divisor that allows an
4867 	 *  input speed faster than the period.
4868 	 */
4869 	while (div-- > 0)
4870 		if (kpc >= (div_10M[div] << 2)) break;
4871 
4872 	/*
4873 	 *  Calculate the lowest clock factor that allows an output
4874 	 *  speed not faster than the period, and the max output speed.
4875 	 *  If fak >= 1 we will set both XCLKH_ST and XCLKH_DT.
4876 	 *  If fak >= 2 we will also set XCLKS_ST and XCLKS_DT.
4877 	 */
4878 	if (dt) {
4879 		fak = (kpc - 1) / (div_10M[div] << 1) + 1 - 2;
4880 		/* ret = ((2+fak)*div_10M[div])/np->clock_khz; */
4881 	}
4882 	else {
4883 		fak = (kpc - 1) / div_10M[div] + 1 - 4;
4884 		/* ret = ((4+fak)*div_10M[div])/np->clock_khz; */
4885 	}
4886 
4887 	/*
4888 	 *  Check against our hardware limits, or bugs :).
4889 	 */
4890 	if (fak < 0)	{fak = 0; ret = -1;}
4891 	if (fak > 2)	{fak = 2; ret = -1;}
4892 
4893 	/*
4894 	 *  Compute and return sync parameters.
4895 	 */
4896 	*divp = div;
4897 	*fakp = fak;
4898 
4899 	return ret;
4900 }
4901 
4902 /*
4903  *  We received a WDTR.
4904  *  Let everything be aware of the changes.
4905  */
4906 static void sym_setwide(hcb_p np, ccb_p cp, u_char wide)
4907 {
4908 	struct	ccb_trans_settings neg;
4909 	union ccb *ccb = cp->cam_ccb;
4910 	tcb_p tp = &np->target[cp->target];
4911 
4912 	sym_settrans(np, cp, 0, 0, 0, wide, 0, 0);
4913 
4914 	/*
4915 	 *  Tell the SCSI layer about the new transfer parameters.
4916 	 */
4917 	tp->tinfo.goal.width = tp->tinfo.current.width = wide;
4918 	tp->tinfo.current.offset = 0;
4919 	tp->tinfo.current.period = 0;
4920 	tp->tinfo.current.options = 0;
4921 	neg.bus_width = wide ? BUS_16_BIT : BUS_8_BIT;
4922 	neg.sync_period = tp->tinfo.current.period;
4923 	neg.sync_offset = tp->tinfo.current.offset;
4924 	neg.valid = CCB_TRANS_BUS_WIDTH_VALID
4925 		  | CCB_TRANS_SYNC_RATE_VALID
4926 		  | CCB_TRANS_SYNC_OFFSET_VALID;
4927 	xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path, /*priority*/1);
4928 	xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
4929 }
4930 
4931 /*
4932  *  We received a SDTR.
4933  *  Let everything be aware of the changes.
4934  */
4935 static void
4936 sym_setsync(hcb_p np, ccb_p cp, u_char ofs, u_char per, u_char div, u_char fak)
4937 {
4938 	struct	ccb_trans_settings neg;
4939 	union ccb *ccb = cp->cam_ccb;
4940 	tcb_p tp = &np->target[cp->target];
4941 	u_char wide = (cp->phys.select.sel_scntl3 & EWS) ? 1 : 0;
4942 
4943 	sym_settrans(np, cp, 0, ofs, per, wide, div, fak);
4944 
4945 	/*
4946 	 *  Tell the SCSI layer about the new transfer parameters.
4947 	 */
4948 	tp->tinfo.goal.period	= tp->tinfo.current.period  = per;
4949 	tp->tinfo.goal.offset	= tp->tinfo.current.offset  = ofs;
4950 	tp->tinfo.goal.options	= tp->tinfo.current.options = 0;
4951 	neg.sync_period = tp->tinfo.current.period;
4952 	neg.sync_offset = tp->tinfo.current.offset;
4953 	neg.valid = CCB_TRANS_SYNC_RATE_VALID
4954 		  | CCB_TRANS_SYNC_OFFSET_VALID;
4955 	xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path, /*priority*/1);
4956 	xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
4957 }
4958 
4959 /*
4960  *  We received a PPR.
4961  *  Let everything be aware of the changes.
4962  */
4963 static void sym_setpprot(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
4964 			 u_char per, u_char wide, u_char div, u_char fak)
4965 {
4966 	struct	ccb_trans_settings neg;
4967 	union ccb *ccb = cp->cam_ccb;
4968 	tcb_p tp = &np->target[cp->target];
4969 
4970 	sym_settrans(np, cp, dt, ofs, per, wide, div, fak);
4971 
4972 	/*
4973 	 *  Tell the SCSI layer about the new transfer parameters.
4974 	 */
4975 	tp->tinfo.goal.width	= tp->tinfo.current.width  = wide;
4976 	tp->tinfo.goal.period	= tp->tinfo.current.period = per;
4977 	tp->tinfo.goal.offset	= tp->tinfo.current.offset = ofs;
4978 	tp->tinfo.goal.options	= tp->tinfo.current.options = dt;
4979 	neg.sync_period = tp->tinfo.current.period;
4980 	neg.sync_offset = tp->tinfo.current.offset;
4981 	neg.bus_width = wide ? BUS_16_BIT : BUS_8_BIT;
4982 	neg.valid = CCB_TRANS_BUS_WIDTH_VALID
4983 		  | CCB_TRANS_SYNC_RATE_VALID
4984 		  | CCB_TRANS_SYNC_OFFSET_VALID;
4985 	xpt_setup_ccb(&neg.ccb_h, ccb->ccb_h.path, /*priority*/1);
4986 	xpt_async(AC_TRANSFER_NEG, ccb->ccb_h.path, &neg);
4987 }
4988 
4989 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
4990 /*
4991  *  Patch a script address if it points to a data script to
4992  *  the same position within another data script.
4993  *  Accept up to endp + 8, due to the SCR_CALL
4994  *  after end data script that moves to goalp.
4995  */
4996 static u32 sym_chgp(u32 scrp, u32 old_endp, u32 new_endp)
4997 {
4998 	scrp = scr_to_cpu(scrp);
4999 	if (old_endp != new_endp &&
5000 	    old_endp + 8 - scrp <= SYM_CONF_MAX_SG*8 + 8)
5001 		scrp = new_endp + 8 - (old_endp + 8 - scrp);
5002 	return cpu_to_scr(scrp);
5003 }
5004 
5005 /*
5006  *  Called on negotiation, since the device may have
5007  *  changed mind about DT versus ST data transfers.
5008  *  Patches all data scripts address for a CCB, to fit
5009  *  the new data script, if needed.
5010  */
5011 static u32 sym_chg_ccb_scrp(hcb_p np, u_char dt, ccb_p cp, u32 scrp)
5012 {
5013 	u32 old_endp  = scr_to_cpu(cp->phys.goalp) - 8;
5014 	u32 new_endp  = 0;
5015 
5016 	/*
5017 	 *  Locate the data script we have to move to:
5018 	 *  Given the end data script pointer value (old)
5019 	 *  and the new type of transfert (DT/ST) deduce
5020 	 *  the new end data script pointer(s).
5021 	 */
5022 	if (dt) {
5023 		if	(old_endp == SCRIPT_BA(np, data_in2))
5024 			new_endp  =  SCRIPTH_BA(np, dt_data_in2);
5025 		else if	(old_endp == SCRIPT_BA(np, data_out2))
5026 			new_endp  =  SCRIPTH_BA(np, dt_data_out2);
5027 	}
5028 	else {
5029 		if	(old_endp == SCRIPTH_BA(np, dt_data_in2))
5030 			new_endp  =  SCRIPT_BA(np, data_in2);
5031 		else if	(old_endp == SCRIPTH_BA(np, dt_data_out2))
5032 			new_endp  =  SCRIPT_BA(np, data_out2);
5033 	}
5034 	/*
5035 	 *  If the end data script pointer was not
5036 	 *  inside a data script or if we must stay
5037 	 *  in the same data script, we are done.
5038 	 */
5039 	if (!new_endp || new_endp == old_endp)
5040 		goto out;
5041 
5042 	/*
5043 	 *  Move to new data script all data script pointers
5044 	 *  that point inside the previous data script.
5045 	 */
5046 	cp->phys.savep	 = sym_chgp(cp->phys.savep,   old_endp, new_endp);
5047 	cp->phys.lastp	 = sym_chgp(cp->phys.lastp,   old_endp, new_endp);
5048 	cp->phys.goalp	 = sym_chgp(cp->phys.goalp,   old_endp, new_endp);
5049 	cp->phys.pm0.ret = sym_chgp(cp->phys.pm0.ret, old_endp, new_endp);
5050 	cp->phys.pm1.ret = sym_chgp(cp->phys.pm1.ret, old_endp, new_endp);
5051 	cp->startp	 = sym_chgp(cp->startp,	      old_endp, new_endp);
5052 
5053 	/*
5054 	 *  Also move an additionnal script pointer
5055 	 *  if passed by user. For the current CCB,
5056 	 *  this is useful to know the new value for
5057 	 *  TEMP register (current data script address).
5058 	 */
5059 	if (scrp)
5060 		scrp = scr_to_cpu(sym_chgp(scrp, old_endp, new_endp));
5061 out:
5062 	return scrp;
5063 }
5064 #endif	/* SYM_CONF_BROKEN_U3EN_SUPPORT */
5065 
5066 /*
5067  *  Switch trans mode for current job and it's target.
5068  */
5069 static void sym_settrans(hcb_p np, ccb_p cp, u_char dt, u_char ofs,
5070 			 u_char per, u_char wide, u_char div, u_char fak)
5071 {
5072 	SYM_QUEHEAD *qp;
5073 	union	ccb *ccb;
5074 	tcb_p tp;
5075 	u_char target = INB (nc_sdid) & 0x0f;
5076 	u_char sval, wval, uval;
5077 
5078 	assert (cp);
5079 	if (!cp) return;
5080 	ccb = cp->cam_ccb;
5081 	assert (ccb);
5082 	if (!ccb) return;
5083 	assert (target == (cp->target & 0xf));
5084 	tp = &np->target[target];
5085 
5086 	sval = tp->sval;
5087 	wval = tp->wval;
5088 	uval = tp->uval;
5089 #if 0
5090 	printf("XXXXX sval=%x wval=%x uval=%x (%x)\n",
5091 		sval, wval, uval, np->rv_scntl3);
5092 #endif
5093 	/*
5094 	 *  Set the offset.
5095 	 */
5096 	if (!(np->features & FE_C10))
5097 		sval = (sval & ~0x1f) | ofs;
5098 	else
5099 		sval = (sval & ~0x3f) | ofs;
5100 
5101 	/*
5102 	 *  Set the sync divisor and extra clock factor.
5103 	 */
5104 	if (ofs != 0) {
5105 		wval = (wval & ~0x70) | ((div+1) << 4);
5106 		if (!(np->features & FE_C10))
5107 			sval = (sval & ~0xe0) | (fak << 5);
5108 		else {
5109 			uval = uval & ~(XCLKH_ST|XCLKH_DT|XCLKS_ST|XCLKS_DT);
5110 			if (fak >= 1) uval |= (XCLKH_ST|XCLKH_DT);
5111 			if (fak >= 2) uval |= (XCLKS_ST|XCLKS_DT);
5112 		}
5113 	}
5114 
5115 	/*
5116 	 *  Set the bus width.
5117 	 */
5118 	wval = wval & ~EWS;
5119 	if (wide != 0)
5120 		wval |= EWS;
5121 
5122 	/*
5123 	 *  Set misc. ultra enable bits.
5124 	 */
5125 	if (np->features & FE_C10) {
5126 		uval = uval & ~U3EN;
5127 #ifndef	SYM_CONF_BROKEN_U3EN_SUPPORT
5128 		if (dt)	{
5129 			assert(np->features & FE_U3EN);
5130 			uval |= U3EN;
5131 		}
5132 #endif
5133 	}
5134 	else {
5135 		wval = wval & ~ULTRA;
5136 		if (per <= 12)	wval |= ULTRA;
5137 	}
5138 
5139 	/*
5140 	 *   Stop there if sync parameters are unchanged.
5141 	 */
5142 	if (tp->sval == sval && tp->wval == wval && tp->uval == uval) return;
5143 	tp->sval = sval;
5144 	tp->wval = wval;
5145 	tp->uval = uval;
5146 
5147 	/*
5148 	 *  Disable extended Sreq/Sack filtering if per < 50.
5149 	 *  Not supported on the C1010.
5150 	 */
5151 	if (per < 50 && !(np->features & FE_C10))
5152 		OUTOFFB (nc_stest2, EXT);
5153 
5154 	/*
5155 	 *  set actual value and sync_status
5156 	 */
5157 	OUTB (nc_sxfer, tp->sval);
5158 	OUTB (nc_scntl3, tp->wval);
5159 
5160 	if (np->features & FE_C10) {
5161 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
5162 		if (!(np->features & FE_U3EN)) {
5163 			u32 temp = INL (nc_temp);
5164 			temp = sym_chg_ccb_scrp(np, dt, cp, temp);
5165 			OUTL (nc_temp, temp);
5166 		}
5167 #endif
5168 		OUTB (nc_scntl4, tp->uval);
5169 	}
5170 
5171 	/*
5172 	 *  patch ALL busy ccbs of this target.
5173 	 */
5174 	FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
5175 		cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
5176 		if (cp->target != target)
5177 			continue;
5178 		cp->phys.select.sel_scntl3 = tp->wval;
5179 		cp->phys.select.sel_sxfer  = tp->sval;
5180 		if (np->features & FE_C10) {
5181 			cp->phys.select.sel_scntl4 = tp->uval;
5182 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
5183 			if (!(np->features & FE_U3EN))
5184 				(void) sym_chg_ccb_scrp(np, dt, cp, 0);
5185 #endif
5186 		}
5187 	}
5188 }
5189 
5190 /*
5191  *  log message for real hard errors
5192  *
5193  *  sym0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc).
5194  *  	      reg: r0 r1 r2 r3 r4 r5 r6 ..... rf.
5195  *
5196  *  exception register:
5197  *  	ds:	dstat
5198  *  	si:	sist
5199  *
5200  *  SCSI bus lines:
5201  *  	so:	control lines as driven by chip.
5202  *  	si:	control lines as seen by chip.
5203  *  	sd:	scsi data lines as seen by chip.
5204  *
5205  *  wide/fastmode:
5206  *  	sxfer:	(see the manual)
5207  *  	scntl3:	(see the manual)
5208  *
5209  *  current script command:
5210  *  	dsp:	script adress (relative to start of script).
5211  *  	dbc:	first word of script command.
5212  *
5213  *  First 24 register of the chip:
5214  *  	r0..rf
5215  */
5216 static void sym_log_hard_error(hcb_p np, u_short sist, u_char dstat)
5217 {
5218 	u32	dsp;
5219 	int	script_ofs;
5220 	int	script_size;
5221 	char	*script_name;
5222 	u_char	*script_base;
5223 	int	i;
5224 
5225 	dsp	= INL (nc_dsp);
5226 
5227 	if (dsp > np->script_ba &&
5228 	    dsp <= np->script_ba + sizeof(struct sym_scr)) {
5229 		script_ofs	= dsp - np->script_ba;
5230 		script_size	= sizeof(struct sym_scr);
5231 		script_base	= (u_char *) np->script0;
5232 		script_name	= "script";
5233 	}
5234 	else if (np->scripth_ba < dsp &&
5235 		 dsp <= np->scripth_ba + sizeof(struct sym_scrh)) {
5236 		script_ofs	= dsp - np->scripth_ba;
5237 		script_size	= sizeof(struct sym_scrh);
5238 		script_base	= (u_char *) np->scripth0;
5239 		script_name	= "scripth";
5240 	} else {
5241 		script_ofs	= dsp;
5242 		script_size	= 0;
5243 		script_base	= 0;
5244 		script_name	= "mem";
5245 	}
5246 
5247 	printf ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
5248 		sym_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
5249 		(unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl),
5250 		(unsigned)INB (nc_sbdl), (unsigned)INB (nc_sxfer),
5251 		(unsigned)INB (nc_scntl3), script_name, script_ofs,
5252 		(unsigned)INL (nc_dbc));
5253 
5254 	if (((script_ofs & 3) == 0) &&
5255 	    (unsigned)script_ofs < script_size) {
5256 		printf ("%s: script cmd = %08x\n", sym_name(np),
5257 			scr_to_cpu((int) *(u32 *)(script_base + script_ofs)));
5258 	}
5259 
5260         printf ("%s: regdump:", sym_name(np));
5261         for (i=0; i<24;i++)
5262             printf (" %02x", (unsigned)INB_OFF(i));
5263         printf (".\n");
5264 
5265 	/*
5266 	 *  PCI BUS error, read the PCI ststus register.
5267 	 */
5268 	if (dstat & (MDPE|BF)) {
5269 		u_short pci_sts;
5270 #ifdef FreeBSD_4_Bus
5271 		pci_sts = pci_read_config(np->device, PCIR_STATUS, 2);
5272 #else
5273 		pci_sts = pci_cfgread(np->pci_tag, PCIR_STATUS, 2);
5274 #endif
5275 		if (pci_sts & 0xf900) {
5276 #ifdef FreeBSD_4_Bus
5277 			pci_write_config(np->device, PCIR_STATUS, pci_sts, 2);
5278 #else
5279 			pci_cfgwrite(np->pci_tag, PCIR_STATUS, pci_sts, 2);
5280 #endif
5281 			printf("%s: PCI STATUS = 0x%04x\n",
5282 				sym_name(np), pci_sts & 0xf900);
5283 		}
5284 	}
5285 }
5286 
5287 /*
5288  *  chip interrupt handler
5289  *
5290  *  In normal situations, interrupt conditions occur one at
5291  *  a time. But when something bad happens on the SCSI BUS,
5292  *  the chip may raise several interrupt flags before
5293  *  stopping and interrupting the CPU. The additionnal
5294  *  interrupt flags are stacked in some extra registers
5295  *  after the SIP and/or DIP flag has been raised in the
5296  *  ISTAT. After the CPU has read the interrupt condition
5297  *  flag from SIST or DSTAT, the chip unstacks the other
5298  *  interrupt flags and sets the corresponding bits in
5299  *  SIST or DSTAT. Since the chip starts stacking once the
5300  *  SIP or DIP flag is set, there is a small window of time
5301  *  where the stacking does not occur.
5302  *
5303  *  Typically, multiple interrupt conditions may happen in
5304  *  the following situations:
5305  *
5306  *  - SCSI parity error + Phase mismatch  (PAR|MA)
5307  *    When an parity error is detected in input phase
5308  *    and the device switches to msg-in phase inside a
5309  *    block MOV.
5310  *  - SCSI parity error + Unexpected disconnect (PAR|UDC)
5311  *    When a stupid device does not want to handle the
5312  *    recovery of an SCSI parity error.
5313  *  - Some combinations of STO, PAR, UDC, ...
5314  *    When using non compliant SCSI stuff, when user is
5315  *    doing non compliant hot tampering on the BUS, when
5316  *    something really bad happens to a device, etc ...
5317  *
5318  *  The heuristic suggested by SYMBIOS to handle
5319  *  multiple interrupts is to try unstacking all
5320  *  interrupts conditions and to handle them on some
5321  *  priority based on error severity.
5322  *  This will work when the unstacking has been
5323  *  successful, but we cannot be 100 % sure of that,
5324  *  since the CPU may have been faster to unstack than
5325  *  the chip is able to stack. Hmmm ... But it seems that
5326  *  such a situation is very unlikely to happen.
5327  *
5328  *  If this happen, for example STO caught by the CPU
5329  *  then UDC happenning before the CPU have restarted
5330  *  the SCRIPTS, the driver may wrongly complete the
5331  *  same command on UDC, since the SCRIPTS didn't restart
5332  *  and the DSA still points to the same command.
5333  *  We avoid this situation by setting the DSA to an
5334  *  invalid value when the CCB is completed and before
5335  *  restarting the SCRIPTS.
5336  *
5337  *  Another issue is that we need some section of our
5338  *  recovery procedures to be somehow uninterruptible but
5339  *  the SCRIPTS processor does not provides such a
5340  *  feature. For this reason, we handle recovery preferently
5341  *  from the C code and check against some SCRIPTS critical
5342  *  sections from the C code.
5343  *
5344  *  Hopefully, the interrupt handling of the driver is now
5345  *  able to resist to weird BUS error conditions, but donnot
5346  *  ask me for any guarantee that it will never fail. :-)
5347  *  Use at your own decision and risk.
5348  */
5349 
5350 static void sym_intr1 (hcb_p np)
5351 {
5352 	u_char	istat, istatc;
5353 	u_char	dstat;
5354 	u_short	sist;
5355 
5356 	/*
5357 	 *  interrupt on the fly ?
5358 	 */
5359 	istat = INB (nc_istat);
5360 	if (istat & INTF) {
5361 		OUTB (nc_istat, (istat & SIGP) | INTF | np->istat_sem);
5362 #if 1
5363 		istat = INB (nc_istat);		/* DUMMY READ */
5364 #endif
5365 		if (DEBUG_FLAGS & DEBUG_TINY) printf ("F ");
5366 		(void)sym_wakeup_done (np);
5367 	};
5368 
5369 	if (!(istat & (SIP|DIP)))
5370 		return;
5371 
5372 #if 0	/* We should never get this one */
5373 	if (istat & CABRT)
5374 		OUTB (nc_istat, CABRT);
5375 #endif
5376 
5377 	/*
5378 	 *  PAR and MA interrupts may occur at the same time,
5379 	 *  and we need to know of both in order to handle
5380 	 *  this situation properly. We try to unstack SCSI
5381 	 *  interrupts for that reason. BTW, I dislike a LOT
5382 	 *  such a loop inside the interrupt routine.
5383 	 *  Even if DMA interrupt stacking is very unlikely to
5384 	 *  happen, we also try unstacking these ones, since
5385 	 *  this has no performance impact.
5386 	 */
5387 	sist	= 0;
5388 	dstat	= 0;
5389 	istatc	= istat;
5390 	do {
5391 		if (istatc & SIP)
5392 			sist  |= INW (nc_sist);
5393 		if (istatc & DIP)
5394 			dstat |= INB (nc_dstat);
5395 		istatc = INB (nc_istat);
5396 		istat |= istatc;
5397 	} while (istatc & (SIP|DIP));
5398 
5399 	if (DEBUG_FLAGS & DEBUG_TINY)
5400 		printf ("<%d|%x:%x|%x:%x>",
5401 			(int)INB(nc_scr0),
5402 			dstat,sist,
5403 			(unsigned)INL(nc_dsp),
5404 			(unsigned)INL(nc_dbc));
5405 	/*
5406 	 *  First, interrupts we want to service cleanly.
5407 	 *
5408 	 *  Phase mismatch (MA) is the most frequent interrupt
5409 	 *  for chip earlier than the 896 and so we have to service
5410 	 *  it as quickly as possible.
5411 	 *  A SCSI parity error (PAR) may be combined with a phase
5412 	 *  mismatch condition (MA).
5413 	 *  Programmed interrupts (SIR) are used to call the C code
5414 	 *  from SCRIPTS.
5415 	 *  The single step interrupt (SSI) is not used in this
5416 	 *  driver.
5417 	 */
5418 	if (!(sist  & (STO|GEN|HTH|SGE|UDC|SBMC|RST)) &&
5419 	    !(dstat & (MDPE|BF|ABRT|IID))) {
5420 		if	(sist & PAR)	sym_int_par (np, sist);
5421 		else if (sist & MA)	sym_int_ma (np);
5422 		else if (dstat & SIR)	sym_int_sir (np);
5423 		else if (dstat & SSI)	OUTONB (nc_dcntl, (STD|NOCOM));
5424 		else			goto unknown_int;
5425 		return;
5426 	};
5427 
5428 	/*
5429 	 *  Now, interrupts that donnot happen in normal
5430 	 *  situations and that we may need to recover from.
5431 	 *
5432 	 *  On SCSI RESET (RST), we reset everything.
5433 	 *  On SCSI BUS MODE CHANGE (SBMC), we complete all
5434 	 *  active CCBs with RESET status, prepare all devices
5435 	 *  for negotiating again and restart the SCRIPTS.
5436 	 *  On STO and UDC, we complete the CCB with the corres-
5437 	 *  ponding status and restart the SCRIPTS.
5438 	 */
5439 	if (sist & RST) {
5440 		xpt_print_path(np->path);
5441 		printf("SCSI BUS reset detected.\n");
5442 		sym_init (np, 1);
5443 		return;
5444 	};
5445 
5446 	OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* clear dma fifo  */
5447 	OUTB (nc_stest3, TE|CSF);		/* clear scsi fifo */
5448 
5449 	if (!(sist  & (GEN|HTH|SGE)) &&
5450 	    !(dstat & (MDPE|BF|ABRT|IID))) {
5451 		if	(sist & SBMC)	sym_int_sbmc (np);
5452 		else if (sist & STO)	sym_int_sto (np);
5453 		else if (sist & UDC)	sym_int_udc (np);
5454 		else			goto unknown_int;
5455 		return;
5456 	};
5457 
5458 	/*
5459 	 *  Now, interrupts we are not able to recover cleanly.
5460 	 *
5461 	 *  Log message for hard errors.
5462 	 *  Reset everything.
5463 	 */
5464 
5465 	sym_log_hard_error(np, sist, dstat);
5466 
5467 	if ((sist & (GEN|HTH|SGE)) ||
5468 		(dstat & (MDPE|BF|ABRT|IID))) {
5469 		sym_start_reset(np);
5470 		return;
5471 	};
5472 
5473 unknown_int:
5474 	/*
5475 	 *  We just miss the cause of the interrupt. :(
5476 	 *  Print a message. The timeout will do the real work.
5477 	 */
5478 	printf(	"%s: unknown interrupt(s) ignored, "
5479 		"ISTAT=0x%x DSTAT=0x%x SIST=0x%x\n",
5480 		sym_name(np), istat, dstat, sist);
5481 }
5482 
5483 static void sym_intr(void *arg)
5484 {
5485 	if (DEBUG_FLAGS & DEBUG_TINY) printf ("[");
5486 	sym_intr1((hcb_p) arg);
5487 	if (DEBUG_FLAGS & DEBUG_TINY) printf ("]");
5488 	return;
5489 }
5490 
5491 static void sym_poll(struct cam_sim *sim)
5492 {
5493 	int s = splcam();
5494 	sym_intr(cam_sim_softc(sim));
5495 	splx(s);
5496 }
5497 
5498 
5499 /*
5500  *  generic recovery from scsi interrupt
5501  *
5502  *  The doc says that when the chip gets an SCSI interrupt,
5503  *  it tries to stop in an orderly fashion, by completing
5504  *  an instruction fetch that had started or by flushing
5505  *  the DMA fifo for a write to memory that was executing.
5506  *  Such a fashion is not enough to know if the instruction
5507  *  that was just before the current DSP value has been
5508  *  executed or not.
5509  *
5510  *  There are some small SCRIPTS sections that deal with
5511  *  the start queue and the done queue that may break any
5512  *  assomption from the C code if we are interrupted
5513  *  inside, so we reset if this happens. Btw, since these
5514  *  SCRIPTS sections are executed while the SCRIPTS hasn't
5515  *  started SCSI operations, it is very unlikely to happen.
5516  *
5517  *  All the driver data structures are supposed to be
5518  *  allocated from the same 4 GB memory window, so there
5519  *  is a 1 to 1 relationship between DSA and driver data
5520  *  structures. Since we are careful :) to invalidate the
5521  *  DSA when we complete a command or when the SCRIPTS
5522  *  pushes a DSA into a queue, we can trust it when it
5523  *  points to a CCB.
5524  */
5525 static void sym_recover_scsi_int (hcb_p np, u_char hsts)
5526 {
5527 	u32	dsp	= INL (nc_dsp);
5528 	u32	dsa	= INL (nc_dsa);
5529 	ccb_p cp	= sym_ccb_from_dsa(np, dsa);
5530 
5531 	/*
5532 	 *  If we haven't been interrupted inside the SCRIPTS
5533 	 *  critical pathes, we can safely restart the SCRIPTS
5534 	 *  and trust the DSA value if it matches a CCB.
5535 	 */
5536 	if ((!(dsp > SCRIPT_BA (np, getjob_begin) &&
5537 	       dsp < SCRIPT_BA (np, getjob_end) + 1)) &&
5538 	    (!(dsp > SCRIPT_BA (np, ungetjob) &&
5539 	       dsp < SCRIPT_BA (np, reselect) + 1)) &&
5540 	    (!(dsp > SCRIPTH_BA (np, sel_for_abort) &&
5541 	       dsp < SCRIPTH_BA (np, sel_for_abort_1) + 1)) &&
5542 	    (!(dsp > SCRIPT_BA (np, done) &&
5543 	       dsp < SCRIPT_BA (np, done_end) + 1))) {
5544 		OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* clear dma fifo  */
5545 		OUTB (nc_stest3, TE|CSF);		/* clear scsi fifo */
5546 		/*
5547 		 *  If we have a CCB, let the SCRIPTS call us back for
5548 		 *  the handling of the error with SCRATCHA filled with
5549 		 *  STARTPOS. This way, we will be able to freeze the
5550 		 *  device queue and requeue awaiting IOs.
5551 		 */
5552 		if (cp) {
5553 			cp->host_status = hsts;
5554 			OUTL (nc_dsp, SCRIPT_BA (np, complete_error));
5555 		}
5556 		/*
5557 		 *  Otherwise just restart the SCRIPTS.
5558 		 */
5559 		else {
5560 			OUTL (nc_dsa, 0xffffff);
5561 			OUTL (nc_dsp, SCRIPT_BA (np, start));
5562 		}
5563 	}
5564 	else
5565 		goto reset_all;
5566 
5567 	return;
5568 
5569 reset_all:
5570 	sym_start_reset(np);
5571 }
5572 
5573 /*
5574  *  chip exception handler for selection timeout
5575  */
5576 void sym_int_sto (hcb_p np)
5577 {
5578 	u32 dsp	= INL (nc_dsp);
5579 
5580 	if (DEBUG_FLAGS & DEBUG_TINY) printf ("T");
5581 
5582 	if (dsp == SCRIPT_BA (np, wf_sel_done) + 8)
5583 		sym_recover_scsi_int(np, HS_SEL_TIMEOUT);
5584 	else
5585 		sym_start_reset(np);
5586 }
5587 
5588 /*
5589  *  chip exception handler for unexpected disconnect
5590  */
5591 void sym_int_udc (hcb_p np)
5592 {
5593 	printf ("%s: unexpected disconnect\n", sym_name(np));
5594 	sym_recover_scsi_int(np, HS_UNEXPECTED);
5595 }
5596 
5597 /*
5598  *  chip exception handler for SCSI bus mode change
5599  *
5600  *  spi2-r12 11.2.3 says a transceiver mode change must
5601  *  generate a reset event and a device that detects a reset
5602  *  event shall initiate a hard reset. It says also that a
5603  *  device that detects a mode change shall set data transfer
5604  *  mode to eight bit asynchronous, etc...
5605  *  So, just reinitializing all except chip should be enough.
5606  */
5607 static void sym_int_sbmc (hcb_p np)
5608 {
5609 	u_char scsi_mode = INB (nc_stest4) & SMODE;
5610 
5611 	/*
5612 	 *  Notify user.
5613 	 */
5614 	xpt_print_path(np->path);
5615 	printf("SCSI BUS mode change from %s to %s.\n",
5616 		sym_scsi_bus_mode(np->scsi_mode), sym_scsi_bus_mode(scsi_mode));
5617 
5618 	/*
5619 	 *  Should suspend command processing for a few seconds and
5620 	 *  reinitialize all except the chip.
5621 	 */
5622 	sym_init (np, 2);
5623 }
5624 
5625 /*
5626  *  chip exception handler for SCSI parity error.
5627  *
5628  *  When the chip detects a SCSI parity error and is
5629  *  currently executing a (CH)MOV instruction, it does
5630  *  not interrupt immediately, but tries to finish the
5631  *  transfer of the current scatter entry before
5632  *  interrupting. The following situations may occur:
5633  *
5634  *  - The complete scatter entry has been transferred
5635  *    without the device having changed phase.
5636  *    The chip will then interrupt with the DSP pointing
5637  *    to the instruction that follows the MOV.
5638  *
5639  *  - A phase mismatch occurs before the MOV finished
5640  *    and phase errors are to be handled by the C code.
5641  *    The chip will then interrupt with both PAR and MA
5642  *    conditions set.
5643  *
5644  *  - A phase mismatch occurs before the MOV finished and
5645  *    phase errors are to be handled by SCRIPTS.
5646  *    The chip will load the DSP with the phase mismatch
5647  *    JUMP address and interrupt the host processor.
5648  */
5649 static void sym_int_par (hcb_p np, u_short sist)
5650 {
5651 	u_char	hsts	= INB (HS_PRT);
5652 	u32	dsp	= INL (nc_dsp);
5653 	u32	dbc	= INL (nc_dbc);
5654 	u32	dsa	= INL (nc_dsa);
5655 	u_char	sbcl	= INB (nc_sbcl);
5656 	u_char	cmd	= dbc >> 24;
5657 	int phase	= cmd & 7;
5658 	ccb_p	cp	= sym_ccb_from_dsa(np, dsa);
5659 
5660 	printf("%s: SCSI parity error detected: SCR1=%d DBC=%x SBCL=%x\n",
5661 		sym_name(np), hsts, dbc, sbcl);
5662 
5663 	/*
5664 	 *  Check that the chip is connected to the SCSI BUS.
5665 	 */
5666 	if (!(INB (nc_scntl1) & ISCON)) {
5667 		sym_recover_scsi_int(np, HS_UNEXPECTED);
5668 		return;
5669 	}
5670 
5671 	/*
5672 	 *  If the nexus is not clearly identified, reset the bus.
5673 	 *  We will try to do better later.
5674 	 */
5675 	if (!cp)
5676 		goto reset_all;
5677 
5678 	/*
5679 	 *  Check instruction was a MOV, direction was INPUT and
5680 	 *  ATN is asserted.
5681 	 */
5682 	if ((cmd & 0xc0) || !(phase & 1) || !(sbcl & 0x8))
5683 		goto reset_all;
5684 
5685 	/*
5686 	 *  Keep track of the parity error.
5687 	 */
5688 	OUTONB (HF_PRT, HF_EXT_ERR);
5689 	cp->xerr_status |= XE_PARITY_ERR;
5690 
5691 	/*
5692 	 *  Prepare the message to send to the device.
5693 	 */
5694 	np->msgout[0] = (phase == 7) ? M_PARITY : M_ID_ERROR;
5695 
5696 	/*
5697 	 *  If the old phase was DATA IN phase, we have to deal with
5698 	 *  the 3 situations described above.
5699 	 *  For other input phases (MSG IN and STATUS), the device
5700 	 *  must resend the whole thing that failed parity checking
5701 	 *  or signal error. So, jumping to dispatcher should be OK.
5702 	 */
5703 	if (phase == 1) {
5704 		/* Phase mismatch handled by SCRIPTS */
5705 		if (dsp == SCRIPTH_BA (np, pm_handle))
5706 			OUTL (nc_dsp, dsp);
5707 		/* Phase mismatch handled by the C code */
5708 		else if (sist & MA)
5709 			sym_int_ma (np);
5710 		/* No phase mismatch occurred */
5711 		else {
5712 			OUTL (nc_temp, dsp);
5713 			OUTL (nc_dsp, SCRIPT_BA (np, dispatch));
5714 		}
5715 	}
5716 	else
5717 		OUTL (nc_dsp, SCRIPT_BA (np, clrack));
5718 	return;
5719 
5720 reset_all:
5721 	sym_start_reset(np);
5722 	return;
5723 }
5724 
5725 /*
5726  *  chip exception handler for phase errors.
5727  *
5728  *  We have to construct a new transfer descriptor,
5729  *  to transfer the rest of the current block.
5730  */
5731 static void sym_int_ma (hcb_p np)
5732 {
5733 	u32	dbc;
5734 	u32	rest;
5735 	u32	dsp;
5736 	u32	dsa;
5737 	u32	nxtdsp;
5738 	u32	*vdsp;
5739 	u32	oadr, olen;
5740 	u32	*tblp;
5741         u32	newcmd;
5742 	u_int	delta;
5743 	u_char	cmd;
5744 	u_char	hflags, hflags0;
5745 	struct	sym_pmc *pm;
5746 	ccb_p	cp;
5747 
5748 	dsp	= INL (nc_dsp);
5749 	dbc	= INL (nc_dbc);
5750 	dsa	= INL (nc_dsa);
5751 
5752 	cmd	= dbc >> 24;
5753 	rest	= dbc & 0xffffff;
5754 	delta	= 0;
5755 
5756 	/*
5757 	 *  locate matching cp if any.
5758 	 */
5759 	cp = sym_ccb_from_dsa(np, dsa);
5760 
5761 	/*
5762 	 *  Donnot take into account dma fifo and various buffers in
5763 	 *  INPUT phase since the chip flushes everything before
5764 	 *  raising the MA interrupt for interrupted INPUT phases.
5765 	 *  For DATA IN phase, we will check for the SWIDE later.
5766 	 */
5767 	if ((cmd & 7) != 1) {
5768 		u_char ss0, ss2;
5769 
5770 		if (np->features & FE_DFBC)
5771 			delta = INW (nc_dfbc);
5772 		else {
5773 			u32 dfifo;
5774 
5775 			/*
5776 			 * Read DFIFO, CTEST[4-6] using 1 PCI bus ownership.
5777 			 */
5778 			dfifo = INL(nc_dfifo);
5779 
5780 			/*
5781 			 *  Calculate remaining bytes in DMA fifo.
5782 			 *  (CTEST5 = dfifo >> 16)
5783 			 */
5784 			if (dfifo & (DFS << 16))
5785 				delta = ((((dfifo >> 8) & 0x300) |
5786 				          (dfifo & 0xff)) - rest) & 0x3ff;
5787 			else
5788 				delta = ((dfifo & 0xff) - rest) & 0x7f;
5789 		}
5790 
5791 		/*
5792 		 *  The data in the dma fifo has not been transfered to
5793 		 *  the target -> add the amount to the rest
5794 		 *  and clear the data.
5795 		 *  Check the sstat2 register in case of wide transfer.
5796 		 */
5797 		rest += delta;
5798 		ss0  = INB (nc_sstat0);
5799 		if (ss0 & OLF) rest++;
5800 		if (!(np->features & FE_C10))
5801 			if (ss0 & ORF) rest++;
5802 		if (cp && (cp->phys.select.sel_scntl3 & EWS)) {
5803 			ss2 = INB (nc_sstat2);
5804 			if (ss2 & OLF1) rest++;
5805 			if (!(np->features & FE_C10))
5806 				if (ss2 & ORF1) rest++;
5807 		};
5808 
5809 		/*
5810 		 *  Clear fifos.
5811 		 */
5812 		OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* dma fifo  */
5813 		OUTB (nc_stest3, TE|CSF);		/* scsi fifo */
5814 	}
5815 
5816 	/*
5817 	 *  log the information
5818 	 */
5819 	if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
5820 		printf ("P%x%x RL=%d D=%d ", cmd&7, INB(nc_sbcl)&7,
5821 			(unsigned) rest, (unsigned) delta);
5822 
5823 	/*
5824 	 *  try to find the interrupted script command,
5825 	 *  and the address at which to continue.
5826 	 */
5827 	vdsp	= 0;
5828 	nxtdsp	= 0;
5829 	if	(dsp >  np->script_ba &&
5830 		 dsp <= np->script_ba + sizeof(struct sym_scr)) {
5831 		vdsp = (u32 *)((char*)np->script0 + (dsp-np->script_ba-8));
5832 		nxtdsp = dsp;
5833 	}
5834 	else if	(dsp >  np->scripth_ba &&
5835 		 dsp <= np->scripth_ba + sizeof(struct sym_scrh)) {
5836 		vdsp = (u32 *)((char*)np->scripth0 + (dsp-np->scripth_ba-8));
5837 		nxtdsp = dsp;
5838 	}
5839 
5840 	/*
5841 	 *  log the information
5842 	 */
5843 	if (DEBUG_FLAGS & DEBUG_PHASE) {
5844 		printf ("\nCP=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
5845 			cp, (unsigned)dsp, (unsigned)nxtdsp, vdsp, cmd);
5846 	};
5847 
5848 	if (!vdsp) {
5849 		printf ("%s: interrupted SCRIPT address not found.\n",
5850 			sym_name (np));
5851 		goto reset_all;
5852 	}
5853 
5854 	if (!cp) {
5855 		printf ("%s: SCSI phase error fixup: CCB already dequeued.\n",
5856 			sym_name (np));
5857 		goto reset_all;
5858 	}
5859 
5860 	/*
5861 	 *  get old startaddress and old length.
5862 	 */
5863 	oadr = scr_to_cpu(vdsp[1]);
5864 
5865 	if (cmd & 0x10) {	/* Table indirect */
5866 		tblp = (u32 *) ((char*) &cp->phys + oadr);
5867 		olen = scr_to_cpu(tblp[0]);
5868 		oadr = scr_to_cpu(tblp[1]);
5869 	} else {
5870 		tblp = (u32 *) 0;
5871 		olen = scr_to_cpu(vdsp[0]) & 0xffffff;
5872 	};
5873 
5874 	if (DEBUG_FLAGS & DEBUG_PHASE) {
5875 		printf ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
5876 			(unsigned) (scr_to_cpu(vdsp[0]) >> 24),
5877 			tblp,
5878 			(unsigned) olen,
5879 			(unsigned) oadr);
5880 	};
5881 
5882 	/*
5883 	 *  check cmd against assumed interrupted script command.
5884 	 */
5885 	if (cmd != (scr_to_cpu(vdsp[0]) >> 24)) {
5886 		PRINT_ADDR(cp);
5887 		printf ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
5888 			(unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
5889 
5890 		goto reset_all;
5891 	};
5892 
5893 	/*
5894 	 *  if old phase not dataphase, leave here.
5895 	 */
5896 	if ((cmd & 5) != (cmd & 7)) {
5897 		PRINT_ADDR(cp);
5898 		printf ("phase change %x-%x %d@%08x resid=%d.\n",
5899 			cmd&7, INB(nc_sbcl)&7, (unsigned)olen,
5900 			(unsigned)oadr, (unsigned)rest);
5901 		goto unexpected_phase;
5902 	};
5903 
5904 	/*
5905 	 *  Choose the correct PM save area.
5906 	 *
5907 	 *  Look at the PM_SAVE SCRIPT if you want to understand
5908 	 *  this stuff. The equivalent code is implemented in
5909 	 *  SCRIPTS for the 895A and 896 that are able to handle
5910 	 *  PM from the SCRIPTS processor.
5911 	 */
5912 	hflags0 = INB (HF_PRT);
5913 	hflags = hflags0;
5914 
5915 	if (hflags & (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED)) {
5916 		if (hflags & HF_IN_PM0)
5917 			nxtdsp = scr_to_cpu(cp->phys.pm0.ret);
5918 		else if	(hflags & HF_IN_PM1)
5919 			nxtdsp = scr_to_cpu(cp->phys.pm1.ret);
5920 
5921 		if (hflags & HF_DP_SAVED)
5922 			hflags ^= HF_ACT_PM;
5923 	}
5924 
5925 	if (!(hflags & HF_ACT_PM)) {
5926 		pm = &cp->phys.pm0;
5927 		newcmd = SCRIPT_BA(np, pm0_data);
5928 	}
5929 	else {
5930 		pm = &cp->phys.pm1;
5931 		newcmd = SCRIPT_BA(np, pm1_data);
5932 	}
5933 
5934 	hflags &= ~(HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED);
5935 	if (hflags != hflags0)
5936 		OUTB (HF_PRT, hflags);
5937 
5938 	/*
5939 	 *  fillin the phase mismatch context
5940 	 */
5941 	pm->sg.addr = cpu_to_scr(oadr + olen - rest);
5942 	pm->sg.size = cpu_to_scr(rest);
5943 	pm->ret     = cpu_to_scr(nxtdsp);
5944 
5945 	/*
5946 	 *  If we have a SWIDE,
5947 	 *  - prepare the address to write the SWIDE from SCRIPTS,
5948 	 *  - compute the SCRIPTS address to restart from,
5949 	 *  - move current data pointer context by one byte.
5950 	 */
5951 	nxtdsp = SCRIPT_BA (np, dispatch);
5952 	if ((cmd & 7) == 1 && cp && (cp->phys.select.sel_scntl3 & EWS) &&
5953 	    (INB (nc_scntl2) & WSR)) {
5954 		/*
5955 		 *  Hmmm... The device may want to also ignore
5956 		 *  this residue but it must send immediately the
5957 		 *  appropriate message. We snoop the SCSI BUS
5958 		 *  and will just throw away this message from
5959 		 *  SCRIPTS if the SWIDE is to be ignored.
5960 		 */
5961 		if ((INB (nc_sbcl) & 7) == 7 &&
5962 		    INB (nc_sbdl) == M_IGN_RESIDUE) {
5963 			nxtdsp = SCRIPT_BA (np, ign_i_w_r_msg);
5964 		}
5965 		/*
5966 		 *  We must grab the SWIDE.
5967 		 *  We will use some complex SCRIPTS for that.
5968 		 */
5969 		else {
5970 			OUTL (nc_scratcha, pm->sg.addr);
5971 			nxtdsp = SCRIPTH_BA (np, swide_ma_32);
5972 			if (np->features & FE_64BIT) {
5973 				OUTB (nc_sbr, (pm->sg.size >> 24));
5974 				nxtdsp = SCRIPTH_BA (np, swide_ma_64);
5975 			}
5976 			/*
5977 			 *  Adjust our data pointer context.
5978 			 */
5979 			++pm->sg.addr;
5980 			--pm->sg.size;
5981 			/*
5982 			 *  Hmmm... Could it be possible that a SWIDE that
5983 			 *  is followed by a 1 byte CHMOV would lead to
5984 			 *  a CHMOV(0). Anyway, we handle it by just
5985 			 *  skipping context that would attempt a CHMOV(0).
5986 			 */
5987 			if (!pm->sg.size)
5988 				newcmd = pm->ret;
5989 		}
5990 	}
5991 
5992 	if (DEBUG_FLAGS & DEBUG_PHASE) {
5993 		PRINT_ADDR(cp);
5994 		printf ("PM %x %x %x / %x %x %x.\n",
5995 			hflags0, hflags, newcmd,
5996 			(unsigned)scr_to_cpu(pm->sg.addr),
5997 			(unsigned)scr_to_cpu(pm->sg.size),
5998 			(unsigned)scr_to_cpu(pm->ret));
5999 	}
6000 
6001 	/*
6002 	 *  Restart the SCRIPTS processor.
6003 	 */
6004 	OUTL (nc_temp, newcmd);
6005 	OUTL (nc_dsp,  nxtdsp);
6006 	return;
6007 
6008 	/*
6009 	 *  Unexpected phase changes that occurs when the current phase
6010 	 *  is not a DATA IN or DATA OUT phase are due to error conditions.
6011 	 *  Such event may only happen when the SCRIPTS is using a
6012 	 *  multibyte SCSI MOVE.
6013 	 *
6014 	 *  Phase change		Some possible cause
6015 	 *
6016 	 *  COMMAND  --> MSG IN	SCSI parity error detected by target.
6017 	 *  COMMAND  --> STATUS	Bad command or refused by target.
6018 	 *  MSG OUT  --> MSG IN     Message rejected by target.
6019 	 *  MSG OUT  --> COMMAND    Bogus target that discards extended
6020 	 *  			negotiation messages.
6021 	 *
6022 	 *  The code below does not care of the new phase and so
6023 	 *  trusts the target. Why to annoy it ?
6024 	 *  If the interrupted phase is COMMAND phase, we restart at
6025 	 *  dispatcher.
6026 	 *  If a target does not get all the messages after selection,
6027 	 *  the code assumes blindly that the target discards extended
6028 	 *  messages and clears the negotiation status.
6029 	 *  If the target does not want all our response to negotiation,
6030 	 *  we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids
6031 	 *  bloat for such a should_not_happen situation).
6032 	 *  In all other situation, we reset the BUS.
6033 	 *  Are these assumptions reasonnable ? (Wait and see ...)
6034 	 */
6035 unexpected_phase:
6036 	dsp -= 8;
6037 	nxtdsp = 0;
6038 
6039 	switch (cmd & 7) {
6040 	case 2:	/* COMMAND phase */
6041 		nxtdsp = SCRIPT_BA (np, dispatch);
6042 		break;
6043 #if 0
6044 	case 3:	/* STATUS  phase */
6045 		nxtdsp = SCRIPT_BA (np, dispatch);
6046 		break;
6047 #endif
6048 	case 6:	/* MSG OUT phase */
6049 		/*
6050 		 *  If the device may want to use untagged when we want
6051 		 *  tagged, we prepare an IDENTIFY without disc. granted,
6052 		 *  since we will not be able to handle reselect.
6053 		 *  Otherwise, we just don't care.
6054 		 */
6055 		if	(dsp == SCRIPT_BA (np, send_ident)) {
6056 			if (cp->tag != NO_TAG && olen - rest <= 3) {
6057 				cp->host_status = HS_BUSY;
6058 				np->msgout[0] = M_IDENTIFY | cp->lun;
6059 				nxtdsp = SCRIPTH_BA (np, ident_break_atn);
6060 			}
6061 			else
6062 				nxtdsp = SCRIPTH_BA (np, ident_break);
6063 		}
6064 		else if	(dsp == SCRIPTH_BA (np, send_wdtr) ||
6065 			 dsp == SCRIPTH_BA (np, send_sdtr) ||
6066 			 dsp == SCRIPTH_BA (np, send_ppr)) {
6067 			nxtdsp = SCRIPTH_BA (np, nego_bad_phase);
6068 		}
6069 		break;
6070 #if 0
6071 	case 7:	/* MSG IN  phase */
6072 		nxtdsp = SCRIPT_BA (np, clrack);
6073 		break;
6074 #endif
6075 	}
6076 
6077 	if (nxtdsp) {
6078 		OUTL (nc_dsp, nxtdsp);
6079 		return;
6080 	}
6081 
6082 reset_all:
6083 	sym_start_reset(np);
6084 }
6085 
6086 /*
6087  *  Dequeue from the START queue all CCBs that match
6088  *  a given target/lun/task condition (-1 means all),
6089  *  and move them from the BUSY queue to the COMP queue
6090  *  with CAM_REQUEUE_REQ status condition.
6091  *  This function is used during error handling/recovery.
6092  *  It is called with SCRIPTS not running.
6093  */
6094 static int
6095 sym_dequeue_from_squeue(hcb_p np, int i, int target, int lun, int task)
6096 {
6097 	int j;
6098 	ccb_p cp;
6099 
6100 	/*
6101 	 *  Make sure the starting index is within range.
6102 	 */
6103 	assert((i >= 0) && (i < 2*MAX_QUEUE));
6104 
6105 	/*
6106 	 *  Walk until end of START queue and dequeue every job
6107 	 *  that matches the target/lun/task condition.
6108 	 */
6109 	j = i;
6110 	while (i != np->squeueput) {
6111 		cp = sym_ccb_from_dsa(np, scr_to_cpu(np->squeue[i]));
6112 		assert(cp);
6113 #ifdef SYM_CONF_IARB_SUPPORT
6114 		/* Forget hints for IARB, they may be no longer relevant */
6115 		cp->host_flags &= ~HF_HINT_IARB;
6116 #endif
6117 		if ((target == -1 || cp->target == target) &&
6118 		    (lun    == -1 || cp->lun    == lun)    &&
6119 		    (task   == -1 || cp->tag    == task)) {
6120 			sym_set_cam_status(cp->cam_ccb, CAM_REQUEUE_REQ);
6121 			sym_remque(&cp->link_ccbq);
6122 			sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
6123 		}
6124 		else {
6125 			if (i != j)
6126 				np->squeue[j] = np->squeue[i];
6127 			if ((j += 2) >= MAX_QUEUE*2) j = 0;
6128 		}
6129 		if ((i += 2) >= MAX_QUEUE*2) i = 0;
6130 	}
6131 	if (i != j)		/* Copy back the idle task if needed */
6132 		np->squeue[j] = np->squeue[i];
6133 	np->squeueput = j;	/* Update our current start queue pointer */
6134 
6135 	return (i - j) / 2;
6136 }
6137 
6138 /*
6139  *  Complete all CCBs queued to the COMP queue.
6140  *
6141  *  These CCBs are assumed:
6142  *  - Not to be referenced either by devices or
6143  *    SCRIPTS-related queues and datas.
6144  *  - To have to be completed with an error condition
6145  *    or requeued.
6146  *
6147  *  The device queue freeze count is incremented
6148  *  for each CCB that does not prevent this.
6149  *  This function is called when all CCBs involved
6150  *  in error handling/recovery have been reaped.
6151  */
6152 static void
6153 sym_flush_comp_queue(hcb_p np, int cam_status)
6154 {
6155 	SYM_QUEHEAD *qp;
6156 	ccb_p cp;
6157 
6158 	while ((qp = sym_remque_head(&np->comp_ccbq)) != 0) {
6159 		union ccb *ccb;
6160 		cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6161 		sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
6162 		ccb = cp->cam_ccb;
6163 		if (cam_status)
6164 			sym_set_cam_status(ccb, cam_status);
6165 		sym_free_ccb(np, cp);
6166 		sym_freeze_cam_ccb(ccb);
6167 		sym_xpt_done(np, ccb);
6168 	}
6169 }
6170 
6171 /*
6172  *  chip handler for bad SCSI status condition
6173  *
6174  *  In case of bad SCSI status, we unqueue all the tasks
6175  *  currently queued to the controller but not yet started
6176  *  and then restart the SCRIPTS processor immediately.
6177  *
6178  *  QUEUE FULL and BUSY conditions are handled the same way.
6179  *  Basically all the not yet started tasks are requeued in
6180  *  device queue and the queue is frozen until a completion.
6181  *
6182  *  For CHECK CONDITION and COMMAND TERMINATED status, we use
6183  *  the CCB of the failed command to prepare a REQUEST SENSE
6184  *  SCSI command and queue it to the controller queue.
6185  *
6186  *  SCRATCHA is assumed to have been loaded with STARTPOS
6187  *  before the SCRIPTS called the C code.
6188  */
6189 static void sym_sir_bad_scsi_status(hcb_p np, int num, ccb_p cp)
6190 {
6191 	tcb_p tp	= &np->target[cp->target];
6192 	u32		startp;
6193 	u_char		s_status = cp->ssss_status;
6194 	u_char		h_flags  = cp->host_flags;
6195 	int		msglen;
6196 	int		nego;
6197 	int		i;
6198 
6199 	/*
6200 	 *  Compute the index of the next job to start from SCRIPTS.
6201 	 */
6202 	i = (INL (nc_scratcha) - vtobus(np->squeue)) / 4;
6203 
6204 	/*
6205 	 *  The last CCB queued used for IARB hint may be
6206 	 *  no longer relevant. Forget it.
6207 	 */
6208 #ifdef SYM_CONF_IARB_SUPPORT
6209 	if (np->last_cp)
6210 		np->last_cp = 0;
6211 #endif
6212 
6213 	/*
6214 	 *  Now deal with the SCSI status.
6215 	 */
6216 	switch(s_status) {
6217 	case S_BUSY:
6218 	case S_QUEUE_FULL:
6219 		if (sym_verbose >= 2) {
6220 			PRINT_ADDR(cp);
6221 			printf (s_status == S_BUSY ? "BUSY" : "QUEUE FULL\n");
6222 		}
6223 	default:	/* S_INT, S_INT_COND_MET, S_CONFLICT */
6224 		sym_complete_error (np, cp);
6225 		break;
6226 	case S_TERMINATED:
6227 	case S_CHECK_COND:
6228 		/*
6229 		 *  If we get an SCSI error when requesting sense, give up.
6230 		 */
6231 		if (h_flags & HF_SENSE) {
6232 			sym_complete_error (np, cp);
6233 			break;
6234 		}
6235 
6236 		/*
6237 		 *  Dequeue all queued CCBs for that device not yet started,
6238 		 *  and restart the SCRIPTS processor immediately.
6239 		 */
6240 		(void) sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
6241 		OUTL (nc_dsp, SCRIPT_BA (np, start));
6242 
6243  		/*
6244 		 *  Save some info of the actual IO.
6245 		 *  Compute the data residual.
6246 		 */
6247 		cp->sv_scsi_status = cp->ssss_status;
6248 		cp->sv_xerr_status = cp->xerr_status;
6249 		cp->sv_resid = sym_compute_residual(np, cp);
6250 
6251 		/*
6252 		 *  Prepare all needed data structures for
6253 		 *  requesting sense data.
6254 		 */
6255 
6256 		/*
6257 		 *  identify message
6258 		 */
6259 		cp->scsi_smsg2[0] = M_IDENTIFY | cp->lun;
6260 		msglen = 1;
6261 
6262 		/*
6263 		 *  If we are currently using anything different from
6264 		 *  async. 8 bit data transfers with that target,
6265 		 *  start a negotiation, since the device may want
6266 		 *  to report us a UNIT ATTENTION condition due to
6267 		 *  a cause we currently ignore, and we donnot want
6268 		 *  to be stuck with WIDE and/or SYNC data transfer.
6269 		 *
6270 		 *  cp->nego_status is filled by sym_prepare_nego().
6271 		 */
6272 		cp->nego_status = 0;
6273 		nego = 0;
6274 		if	(tp->tinfo.current.options & PPR_OPT_MASK)
6275 			nego = NS_PPR;
6276 		else if	(tp->tinfo.current.width != BUS_8_BIT)
6277 			nego = NS_WIDE;
6278 		else if (tp->tinfo.current.offset != 0)
6279 			nego = NS_SYNC;
6280 		if (nego)
6281 			msglen +=
6282 			sym_prepare_nego (np,cp, nego, &cp->scsi_smsg2[msglen]);
6283 		/*
6284 		 *  Message table indirect structure.
6285 		 */
6286 		cp->phys.smsg.addr	= cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
6287 		cp->phys.smsg.size	= cpu_to_scr(msglen);
6288 
6289 		/*
6290 		 *  sense command
6291 		 */
6292 		cp->phys.cmd.addr	= cpu_to_scr(CCB_PHYS (cp, sensecmd));
6293 		cp->phys.cmd.size	= cpu_to_scr(6);
6294 
6295 		/*
6296 		 *  patch requested size into sense command
6297 		 */
6298 		cp->sensecmd[0]		= 0x03;
6299 		cp->sensecmd[1]		= cp->lun << 5;
6300 		cp->sensecmd[4]		= cp->cam_ccb->csio.sense_len;
6301 		cp->data_len		= cp->cam_ccb->csio.sense_len;
6302 
6303 		/*
6304 		 *  sense data
6305 		 */
6306 		cp->phys.sense.addr	=
6307 			cpu_to_scr(vtobus(&cp->cam_ccb->csio.sense_data));
6308 		cp->phys.sense.size	=
6309 			cpu_to_scr(cp->cam_ccb->csio.sense_len);
6310 
6311 		/*
6312 		 *  requeue the command.
6313 		 */
6314 		startp = SCRIPTH_BA (np, sdata_in);
6315 
6316 		cp->phys.savep	= cpu_to_scr(startp);
6317 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
6318 		cp->phys.goalp	= cpu_to_scr(startp + 40);
6319 #else
6320 		cp->phys.goalp	= cpu_to_scr(startp + 16);
6321 #endif
6322 		cp->phys.lastp	= cpu_to_scr(startp);
6323 		cp->startp	= cpu_to_scr(startp);
6324 
6325 		cp->actualquirks = SYM_QUIRK_AUTOSAVE;
6326 		cp->host_status	= cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
6327 		cp->ssss_status = S_ILLEGAL;
6328 		cp->host_flags	= HF_SENSE;
6329 		cp->xerr_status = 0;
6330 		cp->phys.extra_bytes = 0;
6331 
6332 		cp->phys.go.start =
6333 			cpu_to_scr(SCRIPT_BA (np, select));
6334 
6335 		/*
6336 		 *  Requeue the command.
6337 		 */
6338 		sym_put_start_queue(np, cp);
6339 
6340 		/*
6341 		 *  Give back to upper layer everything we have dequeued.
6342 		 */
6343 		sym_flush_comp_queue(np, 0);
6344 		break;
6345 	}
6346 }
6347 
6348 /*
6349  *  After a device has accepted some management message
6350  *  as BUS DEVICE RESET, ABORT TASK, etc ..., or when
6351  *  a device signals a UNIT ATTENTION condition, some
6352  *  tasks are thrown away by the device. We are required
6353  *  to reflect that on our tasks list since the device
6354  *  will never complete these tasks.
6355  *
6356  *  This function move from the BUSY queue to the COMP
6357  *  queue all disconnected CCBs for a given target that
6358  *  match the following criteria:
6359  *  - lun=-1  means any logical UNIT otherwise a given one.
6360  *  - task=-1 means any task, otherwise a given one.
6361  */
6362 static int
6363 sym_clear_tasks(hcb_p np, int cam_status, int target, int lun, int task)
6364 {
6365 	SYM_QUEHEAD qtmp, *qp;
6366 	int i = 0;
6367 	ccb_p cp;
6368 
6369 	/*
6370 	 *  Move the entire BUSY queue to our temporary queue.
6371 	 */
6372 	sym_que_init(&qtmp);
6373 	sym_que_splice(&np->busy_ccbq, &qtmp);
6374 	sym_que_init(&np->busy_ccbq);
6375 
6376 	/*
6377 	 *  Put all CCBs that matches our criteria into
6378 	 *  the COMP queue and put back other ones into
6379 	 *  the BUSY queue.
6380 	 */
6381 	while ((qp = sym_remque_head(&qtmp)) != 0) {
6382 		union ccb *ccb;
6383 		cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6384 		ccb = cp->cam_ccb;
6385 		if (cp->host_status != HS_DISCONNECT ||
6386 		    cp->target != target	     ||
6387 		    (lun  != -1 && cp->lun != lun)   ||
6388 		    (task != -1 &&
6389 			(cp->tag != NO_TAG && cp->scsi_smsg[2] != task))) {
6390 			sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
6391 			continue;
6392 		}
6393 		sym_insque_tail(&cp->link_ccbq, &np->comp_ccbq);
6394 
6395 		/* Preserve the software timeout condition */
6396 		if (sym_get_cam_status(ccb) != CAM_CMD_TIMEOUT)
6397 			sym_set_cam_status(ccb, cam_status);
6398 		++i;
6399 #if 0
6400 printf("XXXXX TASK @%p CLEARED\n", cp);
6401 #endif
6402 	}
6403 	return i;
6404 }
6405 
6406 /*
6407  *  chip handler for TASKS recovery
6408  *
6409  *  We cannot safely abort a command, while the SCRIPTS
6410  *  processor is running, since we just would be in race
6411  *  with it.
6412  *
6413  *  As long as we have tasks to abort, we keep the SEM
6414  *  bit set in the ISTAT. When this bit is set, the
6415  *  SCRIPTS processor interrupts (SIR_SCRIPT_STOPPED)
6416  *  each time it enters the scheduler.
6417  *
6418  *  If we have to reset a target, clear tasks of a unit,
6419  *  or to perform the abort of a disconnected job, we
6420  *  restart the SCRIPTS for selecting the target. Once
6421  *  selected, the SCRIPTS interrupts (SIR_TARGET_SELECTED).
6422  *  If it loses arbitration, the SCRIPTS will interrupt again
6423  *  the next time it will enter its scheduler, and so on ...
6424  *
6425  *  On SIR_TARGET_SELECTED, we scan for the more
6426  *  appropriate thing to do:
6427  *
6428  *  - If nothing, we just sent a M_ABORT message to the
6429  *    target to get rid of the useless SCSI bus ownership.
6430  *    According to the specs, no tasks shall be affected.
6431  *  - If the target is to be reset, we send it a M_RESET
6432  *    message.
6433  *  - If a logical UNIT is to be cleared , we send the
6434  *    IDENTIFY(lun) + M_ABORT.
6435  *  - If an untagged task is to be aborted, we send the
6436  *    IDENTIFY(lun) + M_ABORT.
6437  *  - If a tagged task is to be aborted, we send the
6438  *    IDENTIFY(lun) + task attributes + M_ABORT_TAG.
6439  *
6440  *  Once our 'kiss of death' :) message has been accepted
6441  *  by the target, the SCRIPTS interrupts again
6442  *  (SIR_ABORT_SENT). On this interrupt, we complete
6443  *  all the CCBs that should have been aborted by the
6444  *  target according to our message.
6445  */
6446 static void sym_sir_task_recovery(hcb_p np, int num)
6447 {
6448 	SYM_QUEHEAD *qp;
6449 	ccb_p cp;
6450 	tcb_p tp;
6451 	int target=-1, lun=-1, task;
6452 	int i, k;
6453 
6454 	switch(num) {
6455 	/*
6456 	 *  The SCRIPTS processor stopped before starting
6457 	 *  the next command in order to allow us to perform
6458 	 *  some task recovery.
6459 	 */
6460 	case SIR_SCRIPT_STOPPED:
6461 		/*
6462 		 *  Do we have any target to reset or unit to clear ?
6463 		 */
6464 		for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
6465 			tp = &np->target[i];
6466 			if (tp->to_reset ||
6467 			    (tp->lun0p && tp->lun0p->to_clear)) {
6468 				target = i;
6469 				break;
6470 			}
6471 			if (!tp->lunmp)
6472 				continue;
6473 			for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
6474 				if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
6475 					target	= i;
6476 					break;
6477 				}
6478 			}
6479 			if (target != -1)
6480 				break;
6481 		}
6482 
6483 		/*
6484 		 *  If not, walk the busy queue for any
6485 		 *  disconnected CCB to be aborted.
6486 		 */
6487 		if (target == -1) {
6488 			FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
6489 				cp = sym_que_entry(qp,struct sym_ccb,link_ccbq);
6490 				if (cp->host_status != HS_DISCONNECT)
6491 					continue;
6492 				if (cp->to_abort) {
6493 					target = cp->target;
6494 					break;
6495 				}
6496 			}
6497 		}
6498 
6499 		/*
6500 		 *  If some target is to be selected,
6501 		 *  prepare and start the selection.
6502 		 */
6503 		if (target != -1) {
6504 			tp = &np->target[target];
6505 			np->abrt_sel.sel_id	= target;
6506 			np->abrt_sel.sel_scntl3 = tp->wval;
6507 			np->abrt_sel.sel_sxfer  = tp->sval;
6508 			OUTL(nc_dsa, vtobus(np));
6509 			OUTL (nc_dsp, SCRIPTH_BA (np, sel_for_abort));
6510 			return;
6511 		}
6512 
6513 		/*
6514 		 *  Now look for a CCB to abort that haven't started yet.
6515 		 *  Btw, the SCRIPTS processor is still stopped, so
6516 		 *  we are not in race.
6517 		 */
6518 		i = 0;
6519 		cp = 0;
6520 		FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
6521 			cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6522 			if (cp->host_status != HS_BUSY &&
6523 			    cp->host_status != HS_NEGOTIATE)
6524 				continue;
6525 			if (!cp->to_abort)
6526 				continue;
6527 #ifdef SYM_CONF_IARB_SUPPORT
6528 			/*
6529 			 *    If we are using IMMEDIATE ARBITRATION, we donnot
6530 			 *    want to cancel the last queued CCB, since the
6531 			 *    SCRIPTS may have anticipated the selection.
6532 			 */
6533 			if (cp == np->last_cp) {
6534 				cp->to_abort = 0;
6535 				continue;
6536 			}
6537 #endif
6538 			i = 1;	/* Means we have found some */
6539 			break;
6540 		}
6541 		if (!i) {
6542 			/*
6543 			 *  We are done, so we donnot need
6544 			 *  to synchronize with the SCRIPTS anylonger.
6545 			 *  Remove the SEM flag from the ISTAT.
6546 			 */
6547 			np->istat_sem = 0;
6548 			OUTB (nc_istat, SIGP);
6549 			break;
6550 		}
6551 		/*
6552 		 *  Compute index of next position in the start
6553 		 *  queue the SCRIPTS intends to start and dequeue
6554 		 *  all CCBs for that device that haven't been started.
6555 		 */
6556 		i = (INL (nc_scratcha) - vtobus(np->squeue)) / 4;
6557 		i = sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
6558 
6559 		/*
6560 		 *  Make sure at least our IO to abort has been dequeued.
6561 		 */
6562 		assert(i && sym_get_cam_status(cp->cam_ccb) == CAM_REQUEUE_REQ);
6563 
6564 		/*
6565 		 *  Keep track in cam status of the reason of the abort.
6566 		 */
6567 		if (cp->to_abort == 2)
6568 			sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
6569 		else
6570 			sym_set_cam_status(cp->cam_ccb, CAM_REQ_ABORTED);
6571 
6572 		/*
6573 		 *  Complete with error everything that we have dequeued.
6574 	 	 */
6575 		sym_flush_comp_queue(np, 0);
6576 		break;
6577 	/*
6578 	 *  The SCRIPTS processor has selected a target
6579 	 *  we may have some manual recovery to perform for.
6580 	 */
6581 	case SIR_TARGET_SELECTED:
6582 		target = (INB (nc_sdid) & 0xf);
6583 		tp = &np->target[target];
6584 
6585 		np->abrt_tbl.addr = vtobus(np->abrt_msg);
6586 
6587 		/*
6588 		 *  If the target is to be reset, prepare a
6589 		 *  M_RESET message and clear the to_reset flag
6590 		 *  since we donnot expect this operation to fail.
6591 		 */
6592 		if (tp->to_reset) {
6593 			np->abrt_msg[0] = M_RESET;
6594 			np->abrt_tbl.size = 1;
6595 			tp->to_reset = 0;
6596 			break;
6597 		}
6598 
6599 		/*
6600 		 *  Otherwise, look for some logical unit to be cleared.
6601 		 */
6602 		if (tp->lun0p && tp->lun0p->to_clear)
6603 			lun = 0;
6604 		else if (tp->lunmp) {
6605 			for (k = 1 ; k < SYM_CONF_MAX_LUN ; k++) {
6606 				if (tp->lunmp[k] && tp->lunmp[k]->to_clear) {
6607 					lun = k;
6608 					break;
6609 				}
6610 			}
6611 		}
6612 
6613 		/*
6614 		 *  If a logical unit is to be cleared, prepare
6615 		 *  an IDENTIFY(lun) + ABORT MESSAGE.
6616 		 */
6617 		if (lun != -1) {
6618 			lcb_p lp = sym_lp(np, tp, lun);
6619 			lp->to_clear = 0; /* We donnot expect to fail here */
6620 			np->abrt_msg[0] = M_IDENTIFY | lun;
6621 			np->abrt_msg[1] = M_ABORT;
6622 			np->abrt_tbl.size = 2;
6623 			break;
6624 		}
6625 
6626 		/*
6627 		 *  Otherwise, look for some disconnected job to
6628 		 *  abort for this target.
6629 		 */
6630 		i = 0;
6631 		cp = 0;
6632 		FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
6633 			cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
6634 			if (cp->host_status != HS_DISCONNECT)
6635 				continue;
6636 			if (cp->target != target)
6637 				continue;
6638 			if (!cp->to_abort)
6639 				continue;
6640 			i = 1;	/* Means we have some */
6641 			break;
6642 		}
6643 
6644 		/*
6645 		 *  If we have none, probably since the device has
6646 		 *  completed the command before we won abitration,
6647 		 *  send a M_ABORT message without IDENTIFY.
6648 		 *  According to the specs, the device must just
6649 		 *  disconnect the BUS and not abort any task.
6650 		 */
6651 		if (!i) {
6652 			np->abrt_msg[0] = M_ABORT;
6653 			np->abrt_tbl.size = 1;
6654 			break;
6655 		}
6656 
6657 		/*
6658 		 *  We have some task to abort.
6659 		 *  Set the IDENTIFY(lun)
6660 		 */
6661 		np->abrt_msg[0] = M_IDENTIFY | cp->lun;
6662 
6663 		/*
6664 		 *  If we want to abort an untagged command, we
6665 		 *  will send a IDENTIFY + M_ABORT.
6666 		 *  Otherwise (tagged command), we will send
6667 		 *  a IDENTITFY + task attributes + ABORT TAG.
6668 		 */
6669 		if (cp->tag == NO_TAG) {
6670 			np->abrt_msg[1] = M_ABORT;
6671 			np->abrt_tbl.size = 2;
6672 		}
6673 		else {
6674 			np->abrt_msg[1] = cp->scsi_smsg[1];
6675 			np->abrt_msg[2] = cp->scsi_smsg[2];
6676 			np->abrt_msg[3] = M_ABORT_TAG;
6677 			np->abrt_tbl.size = 4;
6678 		}
6679 		/*
6680 		 *  Keep track of software timeout condition, since the
6681 		 *  peripheral driver may not count retries on abort
6682 		 *  conditions not due to timeout.
6683 		 */
6684 		if (cp->to_abort == 2)
6685 			sym_set_cam_status(cp->cam_ccb, CAM_CMD_TIMEOUT);
6686 		cp->to_abort = 0; /* We donnot expect to fail here */
6687 		break;
6688 
6689 	/*
6690 	 *  The target has accepted our message and switched
6691 	 *  to BUS FREE phase as we expected.
6692 	 */
6693 	case SIR_ABORT_SENT:
6694 		target = (INB (nc_sdid) & 0xf);
6695 		tp = &np->target[target];
6696 
6697 		/*
6698 		**  If we didn't abort anything, leave here.
6699 		*/
6700 		if (np->abrt_msg[0] == M_ABORT)
6701 			break;
6702 
6703 		/*
6704 		 *  If we sent a M_RESET, then a hardware reset has
6705 		 *  been performed by the target.
6706 		 *  - Reset everything to async 8 bit
6707 		 *  - Tell ourself to negotiate next time :-)
6708 		 *  - Prepare to clear all disconnected CCBs for
6709 		 *    this target from our task list (lun=task=-1)
6710 		 */
6711 		lun = -1;
6712 		task = -1;
6713 		if (np->abrt_msg[0] == M_RESET) {
6714 			tp->sval = 0;
6715 			tp->wval = np->rv_scntl3;
6716 			tp->uval = 0;
6717 			tp->tinfo.current.period = 0;
6718 			tp->tinfo.current.offset = 0;
6719 			tp->tinfo.current.width  = BUS_8_BIT;
6720 			tp->tinfo.current.options = 0;
6721 		}
6722 
6723 		/*
6724 		 *  Otherwise, check for the LUN and TASK(s)
6725 		 *  concerned by the cancelation.
6726 		 *  If it is not ABORT_TAG then it is CLEAR_QUEUE
6727 		 *  or an ABORT message :-)
6728 		 */
6729 		else {
6730 			lun = np->abrt_msg[0] & 0x3f;
6731 			if (np->abrt_msg[1] == M_ABORT_TAG)
6732 				task = np->abrt_msg[2];
6733 		}
6734 
6735 		/*
6736 		 *  Complete all the CCBs the device should have
6737 		 *  aborted due to our 'kiss of death' message.
6738 		 */
6739 		i = (INL (nc_scratcha) - vtobus(np->squeue)) / 4;
6740 		(void) sym_dequeue_from_squeue(np, i, target, lun, -1);
6741 		(void) sym_clear_tasks(np, CAM_REQ_ABORTED, target, lun, task);
6742 		sym_flush_comp_queue(np, 0);
6743 
6744 		/*
6745 		 *  If we sent a BDR, make uper layer aware of that.
6746 		 */
6747 		if (np->abrt_msg[0] == M_RESET)
6748 			xpt_async(AC_SENT_BDR, np->path, NULL);
6749 		break;
6750 	}
6751 
6752 	/*
6753 	 *  Print to the log the message we intend to send.
6754 	 */
6755 	if (num == SIR_TARGET_SELECTED) {
6756 		PRINT_TARGET(np, target);
6757 		sym_printl_hex("control msgout:", np->abrt_msg,
6758 			      np->abrt_tbl.size);
6759 		np->abrt_tbl.size = cpu_to_scr(np->abrt_tbl.size);
6760 	}
6761 
6762 	/*
6763 	 *  Let the SCRIPTS processor continue.
6764 	 */
6765 	OUTONB (nc_dcntl, (STD|NOCOM));
6766 }
6767 
6768 /*
6769  *  Gerard's alchemy:) that deals with with the data
6770  *  pointer for both MDP and the residual calculation.
6771  *
6772  *  I didn't want to bloat the code by more than 200
6773  *  lignes for the handling of both MDP and the residual.
6774  *  This has been achieved by using a data pointer
6775  *  representation consisting in an index in the data
6776  *  array (dp_sg) and a negative offset (dp_ofs) that
6777  *  have the following meaning:
6778  *
6779  *  - dp_sg = SYM_CONF_MAX_SG
6780  *    we are at the end of the data script.
6781  *  - dp_sg < SYM_CONF_MAX_SG
6782  *    dp_sg points to the next entry of the scatter array
6783  *    we want to transfer.
6784  *  - dp_ofs < 0
6785  *    dp_ofs represents the residual of bytes of the
6786  *    previous entry scatter entry we will send first.
6787  *  - dp_ofs = 0
6788  *    no residual to send first.
6789  *
6790  *  The function sym_evaluate_dp() accepts an arbitray
6791  *  offset (basically from the MDP message) and returns
6792  *  the corresponding values of dp_sg and dp_ofs.
6793  */
6794 
6795 static int sym_evaluate_dp(hcb_p np, ccb_p cp, u32 scr, int *ofs)
6796 {
6797 	u32	dp_scr;
6798 	int	dp_ofs, dp_sg, dp_sgmin;
6799 	int	tmp;
6800 	struct sym_pmc *pm;
6801 
6802 	/*
6803 	 *  Compute the resulted data pointer in term of a script
6804 	 *  address within some DATA script and a signed byte offset.
6805 	 */
6806 	dp_scr = scr;
6807 	dp_ofs = *ofs;
6808 	if	(dp_scr == SCRIPT_BA (np, pm0_data))
6809 		pm = &cp->phys.pm0;
6810 	else if (dp_scr == SCRIPT_BA (np, pm1_data))
6811 		pm = &cp->phys.pm1;
6812 	else
6813 		pm = 0;
6814 
6815 	if (pm) {
6816 		dp_scr  = scr_to_cpu(pm->ret);
6817 		dp_ofs -= scr_to_cpu(pm->sg.size);
6818 	}
6819 
6820 	/*
6821 	 *  If we are auto-sensing, then we are done.
6822 	 */
6823 	if (cp->host_flags & HF_SENSE) {
6824 		*ofs = dp_ofs;
6825 		return 0;
6826 	}
6827 
6828 	/*
6829 	 *  Deduce the index of the sg entry.
6830 	 *  Keep track of the index of the first valid entry.
6831 	 *  If result is dp_sg = SYM_CONF_MAX_SG, then we are at the
6832 	 *  end of the data.
6833 	 */
6834 	tmp = scr_to_cpu(cp->phys.goalp);
6835 	dp_sg = SYM_CONF_MAX_SG;
6836 	if (dp_sg != tmp)
6837 		dp_sg -= (tmp - 8 - (int)dp_scr) / (2*4);
6838 	dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
6839 
6840 	/*
6841 	 *  Move to the sg entry the data pointer belongs to.
6842 	 *
6843 	 *  If we are inside the data area, we expect result to be:
6844 	 *
6845 	 *  Either,
6846 	 *      dp_ofs = 0 and dp_sg is the index of the sg entry
6847 	 *      the data pointer belongs to (or the end of the data)
6848 	 *  Or,
6849 	 *      dp_ofs < 0 and dp_sg is the index of the sg entry
6850 	 *      the data pointer belongs to + 1.
6851 	 */
6852 	if (dp_ofs < 0) {
6853 		int n;
6854 		while (dp_sg > dp_sgmin) {
6855 			--dp_sg;
6856 			tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
6857 			n = dp_ofs + (tmp & 0xffffff);
6858 			if (n > 0) {
6859 				++dp_sg;
6860 				break;
6861 			}
6862 			dp_ofs = n;
6863 		}
6864 	}
6865 	else if (dp_ofs > 0) {
6866 		while (dp_sg < SYM_CONF_MAX_SG) {
6867 			tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
6868 			dp_ofs -= (tmp & 0xffffff);
6869 			++dp_sg;
6870 			if (dp_ofs <= 0)
6871 				break;
6872 		}
6873 	}
6874 
6875 	/*
6876 	 *  Make sure the data pointer is inside the data area.
6877 	 *  If not, return some error.
6878 	 */
6879 	if	(dp_sg < dp_sgmin || (dp_sg == dp_sgmin && dp_ofs < 0))
6880 		goto out_err;
6881 	else if	(dp_sg > SYM_CONF_MAX_SG ||
6882 		 (dp_sg == SYM_CONF_MAX_SG && dp_ofs > 0))
6883 		goto out_err;
6884 
6885 	/*
6886 	 *  Save the extreme pointer if needed.
6887 	 */
6888 	if (dp_sg > cp->ext_sg ||
6889             (dp_sg == cp->ext_sg && dp_ofs > cp->ext_ofs)) {
6890 		cp->ext_sg  = dp_sg;
6891 		cp->ext_ofs = dp_ofs;
6892 	}
6893 
6894 	/*
6895 	 *  Return data.
6896 	 */
6897 	*ofs = dp_ofs;
6898 	return dp_sg;
6899 
6900 out_err:
6901 	return -1;
6902 }
6903 
6904 /*
6905  *  chip handler for MODIFY DATA POINTER MESSAGE
6906  *
6907  *  We also call this function on IGNORE WIDE RESIDUE
6908  *  messages that do not match a SWIDE full condition.
6909  *  Btw, we assume in that situation that such a message
6910  *  is equivalent to a MODIFY DATA POINTER (offset=-1).
6911  */
6912 
6913 static void sym_modify_dp(hcb_p np, tcb_p tp, ccb_p cp, int ofs)
6914 {
6915 	int dp_ofs	= ofs;
6916 	u32	dp_scr	= INL (nc_temp);
6917 	u32	dp_ret;
6918 	u32	tmp;
6919 	u_char	hflags;
6920 	int	dp_sg;
6921 	struct	sym_pmc *pm;
6922 
6923 	/*
6924 	 *  Not supported for auto-sense.
6925 	 */
6926 	if (cp->host_flags & HF_SENSE)
6927 		goto out_reject;
6928 
6929 	/*
6930 	 *  Apply our alchemy:) (see comments in sym_evaluate_dp()),
6931 	 *  to the resulted data pointer.
6932 	 */
6933 	dp_sg = sym_evaluate_dp(np, cp, dp_scr, &dp_ofs);
6934 	if (dp_sg < 0)
6935 		goto out_reject;
6936 
6937 	/*
6938 	 *  And our alchemy:) allows to easily calculate the data
6939 	 *  script address we want to return for the next data phase.
6940 	 */
6941 	dp_ret = cpu_to_scr(cp->phys.goalp);
6942 	dp_ret = dp_ret - 8 - (SYM_CONF_MAX_SG - dp_sg) * (2*4);
6943 
6944 	/*
6945 	 *  If offset / scatter entry is zero we donnot need
6946 	 *  a context for the new current data pointer.
6947 	 */
6948 	if (dp_ofs == 0) {
6949 		dp_scr = dp_ret;
6950 		goto out_ok;
6951 	}
6952 
6953 	/*
6954 	 *  Get a context for the new current data pointer.
6955 	 */
6956 	hflags = INB (HF_PRT);
6957 
6958 	if (hflags & HF_DP_SAVED)
6959 		hflags ^= HF_ACT_PM;
6960 
6961 	if (!(hflags & HF_ACT_PM)) {
6962 		pm  = &cp->phys.pm0;
6963 		dp_scr = SCRIPT_BA (np, pm0_data);
6964 	}
6965 	else {
6966 		pm = &cp->phys.pm1;
6967 		dp_scr = SCRIPT_BA (np, pm1_data);
6968 	}
6969 
6970 	hflags &= ~(HF_DP_SAVED);
6971 
6972 	OUTB (HF_PRT, hflags);
6973 
6974 	/*
6975 	 *  Set up the new current data pointer.
6976 	 *  ofs < 0 there, and for the next data phase, we
6977 	 *  want to transfer part of the data of the sg entry
6978 	 *  corresponding to index dp_sg-1 prior to returning
6979 	 *  to the main data script.
6980 	 */
6981 	pm->ret = cpu_to_scr(dp_ret);
6982 	tmp  = scr_to_cpu(cp->phys.data[dp_sg-1].addr);
6983 	tmp += scr_to_cpu(cp->phys.data[dp_sg-1].size) + dp_ofs;
6984 	pm->sg.addr = cpu_to_scr(tmp);
6985 	pm->sg.size = cpu_to_scr(-dp_ofs);
6986 
6987 out_ok:
6988 	OUTL (nc_temp, dp_scr);
6989 	OUTL (nc_dsp, SCRIPT_BA (np, clrack));
6990 	return;
6991 
6992 out_reject:
6993 	OUTL (nc_dsp, SCRIPTH_BA (np, msg_bad));
6994 }
6995 
6996 
6997 /*
6998  *  chip calculation of the data residual.
6999  *
7000  *  As I used to say, the requirement of data residual
7001  *  in SCSI is broken, useless and cannot be achieved
7002  *  without huge complexity.
7003  *  But most OSes and even the official CAM require it.
7004  *  When stupidity happens to be so widely spread inside
7005  *  a community, it gets hard to convince.
7006  *
7007  *  Anyway, I don't care, since I am not going to use
7008  *  any software that considers this data residual as
7009  *  a relevant information. :)
7010  */
7011 
7012 static int sym_compute_residual(hcb_p np, ccb_p cp)
7013 {
7014 	int dp_sg, dp_sgmin, resid;
7015 	int dp_ofs = 0;
7016 
7017 	/*
7018 	 *  Check for some data lost or just thrown away.
7019 	 *  We are not required to be quite accurate in this
7020 	 *  situation. Btw, if we are odd for output and the
7021 	 *  device claims some more data, it may well happen
7022 	 *  than our residual be zero. :-)
7023 	 */
7024 	if (cp->xerr_status & (XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN)) {
7025 		resid = 0;
7026 		if (cp->xerr_status & XE_EXTRA_DATA)
7027 			resid -= scr_to_cpu(cp->phys.extra_bytes);
7028 		if (cp->xerr_status & XE_SODL_UNRUN)
7029 			++resid;
7030 		if (cp->xerr_status & XE_SWIDE_OVRUN)
7031 			--resid;
7032 	}
7033 
7034 	/*
7035 	 *  If all data has been transferred,
7036 	 *  there is no residual.
7037 	 */
7038 	if (cp->phys.lastp == cp->phys.goalp)
7039 		return 0;
7040 
7041 	/*
7042 	 *  If no data transfer occurs, or if the data
7043 	 *  pointer is weird, return full residual.
7044 	 */
7045 	if (cp->startp == cp->phys.lastp ||
7046 	    sym_evaluate_dp(np, cp, scr_to_cpu(cp->phys.lastp), &dp_ofs) < 0) {
7047 		return cp->data_len;
7048 	}
7049 
7050 	/*
7051 	 *  If we were auto-sensing, then we are done.
7052 	 */
7053 	if (cp->host_flags & HF_SENSE) {
7054 		return -dp_ofs;
7055 	}
7056 
7057 	/*
7058 	 *  We are now full comfortable in the computation
7059 	 *  of the data residual (2's complement).
7060 	 */
7061 	dp_sgmin = SYM_CONF_MAX_SG - cp->segments;
7062 	resid = -cp->ext_ofs;
7063 	for (dp_sg = cp->ext_sg; dp_sg < SYM_CONF_MAX_SG; ++dp_sg) {
7064 		u_long tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
7065 		resid += (tmp & 0xffffff);
7066 	}
7067 
7068 	/*
7069 	 *  Hopefully, the result is not too wrong.
7070 	 */
7071 	return resid;
7072 }
7073 
7074 /*
7075  *  Print out the containt of a SCSI message.
7076  */
7077 
7078 static int sym_show_msg (u_char * msg)
7079 {
7080 	u_char i;
7081 	printf ("%x",*msg);
7082 	if (*msg==M_EXTENDED) {
7083 		for (i=1;i<8;i++) {
7084 			if (i-1>msg[1]) break;
7085 			printf ("-%x",msg[i]);
7086 		};
7087 		return (i+1);
7088 	} else if ((*msg & 0xf0) == 0x20) {
7089 		printf ("-%x",msg[1]);
7090 		return (2);
7091 	};
7092 	return (1);
7093 }
7094 
7095 static void sym_print_msg (ccb_p cp, char *label, u_char *msg)
7096 {
7097 	PRINT_ADDR(cp);
7098 	if (label)
7099 		printf ("%s: ", label);
7100 
7101 	(void) sym_show_msg (msg);
7102 	printf (".\n");
7103 }
7104 
7105 /*
7106  *  Negotiation for WIDE and SYNCHRONOUS DATA TRANSFER.
7107  *
7108  *  We try to negotiate sync and wide transfer only after
7109  *  a successfull inquire command. We look at byte 7 of the
7110  *  inquire data to determine the capabilities of the target.
7111  *
7112  *  When we try to negotiate, we append the negotiation message
7113  *  to the identify and (maybe) simple tag message.
7114  *  The host status field is set to HS_NEGOTIATE to mark this
7115  *  situation.
7116  *
7117  *  If the target doesn't answer this message immediately
7118  *  (as required by the standard), the SIR_NEGO_FAILED interrupt
7119  *  will be raised eventually.
7120  *  The handler removes the HS_NEGOTIATE status, and sets the
7121  *  negotiated value to the default (async / nowide).
7122  *
7123  *  If we receive a matching answer immediately, we check it
7124  *  for validity, and set the values.
7125  *
7126  *  If we receive a Reject message immediately, we assume the
7127  *  negotiation has failed, and fall back to standard values.
7128  *
7129  *  If we receive a negotiation message while not in HS_NEGOTIATE
7130  *  state, it's a target initiated negotiation. We prepare a
7131  *  (hopefully) valid answer, set our parameters, and send back
7132  *  this answer to the target.
7133  *
7134  *  If the target doesn't fetch the answer (no message out phase),
7135  *  we assume the negotiation has failed, and fall back to default
7136  *  settings (SIR_NEGO_PROTO interrupt).
7137  *
7138  *  When we set the values, we adjust them in all ccbs belonging
7139  *  to this target, in the controller's register, and in the "phys"
7140  *  field of the controller's struct sym_hcb.
7141  */
7142 
7143 /*
7144  *  chip handler for SYNCHRONOUS DATA TRANSFER REQUEST (SDTR) message.
7145  */
7146 static void sym_sync_nego(hcb_p np, tcb_p tp, ccb_p cp)
7147 {
7148 	u_char	chg, ofs, per, fak, div;
7149 	int	req = 1;
7150 
7151 	/*
7152 	 *  Synchronous request message received.
7153 	 */
7154 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7155 		sym_print_msg(cp, "sync msgin", np->msgin);
7156 	};
7157 
7158 	/*
7159 	 * request or answer ?
7160 	 */
7161 	if (INB (HS_PRT) == HS_NEGOTIATE) {
7162 		OUTB (HS_PRT, HS_BUSY);
7163 		if (cp->nego_status && cp->nego_status != NS_SYNC)
7164 			goto reject_it;
7165 		req = 0;
7166 	}
7167 
7168 	/*
7169 	 *  get requested values.
7170 	 */
7171 	chg = 0;
7172 	per = np->msgin[3];
7173 	ofs = np->msgin[4];
7174 
7175 	/*
7176 	 *  check values against our limits.
7177 	 */
7178 	if (ofs) {
7179 		if (ofs > np->maxoffs)
7180 			{chg = 1; ofs = np->maxoffs;}
7181 		if (req) {
7182 			if (ofs > tp->tinfo.user.offset)
7183 				{chg = 1; ofs = tp->tinfo.user.offset;}
7184 		}
7185 	}
7186 
7187 	if (ofs) {
7188 		if (per < np->minsync)
7189 			{chg = 1; per = np->minsync;}
7190 		if (req) {
7191 			if (per < tp->tinfo.user.period)
7192 				{chg = 1; per = tp->tinfo.user.period;}
7193 		}
7194 	}
7195 
7196 	div = fak = 0;
7197 	if (ofs && sym_getsync(np, 0, per, &div, &fak) < 0)
7198 		goto reject_it;
7199 
7200 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7201 		PRINT_ADDR(cp);
7202 		printf ("sdtr: ofs=%d per=%d div=%d fak=%d chg=%d.\n",
7203 			ofs, per, div, fak, chg);
7204 	}
7205 
7206 	/*
7207 	 *  This was an answer message
7208 	 */
7209 	if (req == 0) {
7210 		if (chg) 	/* Answer wasn't acceptable. */
7211 			goto reject_it;
7212 		sym_setsync (np, cp, ofs, per, div, fak);
7213 		OUTL (nc_dsp, SCRIPT_BA (np, clrack));
7214 		return;
7215 	}
7216 
7217 	/*
7218 	 *  It was a request. Set value and
7219 	 *  prepare an answer message
7220 	 */
7221 	sym_setsync (np, cp, ofs, per, div, fak);
7222 
7223 	np->msgout[0] = M_EXTENDED;
7224 	np->msgout[1] = 3;
7225 	np->msgout[2] = M_X_SYNC_REQ;
7226 	np->msgout[3] = per;
7227 	np->msgout[4] = ofs;
7228 
7229 	cp->nego_status = NS_SYNC;
7230 
7231 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7232 		sym_print_msg(cp, "sync msgout", np->msgout);
7233 	}
7234 
7235 	np->msgin [0] = M_NOOP;
7236 
7237 	OUTL (nc_dsp, SCRIPTH_BA (np, sdtr_resp));
7238 	return;
7239 reject_it:
7240 	sym_setsync (np, cp, 0, 0, 0, 0);
7241 	OUTL (nc_dsp, SCRIPTH_BA (np, msg_bad));
7242 }
7243 
7244 /*
7245  *  chip handler for PARALLEL PROTOCOL REQUEST (PPR) message.
7246  */
7247 static void sym_ppr_nego(hcb_p np, tcb_p tp, ccb_p cp)
7248 {
7249 	u_char	chg, ofs, per, fak, dt, div, wide;
7250 	int	req = 1;
7251 
7252 	/*
7253 	 * Synchronous request message received.
7254 	 */
7255 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7256 		sym_print_msg(cp, "ppr msgin", np->msgin);
7257 	};
7258 
7259 	/*
7260 	 * request or answer ?
7261 	 */
7262 	if (INB (HS_PRT) == HS_NEGOTIATE) {
7263 		OUTB (HS_PRT, HS_BUSY);
7264 		if (cp->nego_status && cp->nego_status != NS_PPR)
7265 			goto reject_it;
7266 		req = 0;
7267 	}
7268 
7269 	/*
7270 	 *  get requested values.
7271 	 */
7272 	chg  = 0;
7273 	per  = np->msgin[3];
7274 	ofs  = np->msgin[5];
7275 	wide = np->msgin[6];
7276 	dt   = np->msgin[7] & PPR_OPT_DT;
7277 
7278 	/*
7279 	 *  check values against our limits.
7280 	 */
7281 	if (wide > np->maxwide)
7282 		{chg = 1; wide = np->maxwide;}
7283 	if (!wide || !(np->features & FE_ULTRA3))
7284 		dt &= ~PPR_OPT_DT;
7285 	if (req) {
7286 		if (wide > tp->tinfo.user.width)
7287 			{chg = 1; wide = tp->tinfo.user.width;}
7288 	}
7289 #ifndef	SYM_CONF_BROKEN_U3EN_SUPPORT
7290 	if (!(np->features & FE_U3EN))	/* Broken U3EN bit not supported */
7291 		dt &= ~PPR_OPT_DT;
7292 #endif
7293 	if (dt != (np->msgin[7] & PPR_OPT_MASK)) chg = 1;
7294 
7295 	if (ofs) {
7296 		if (ofs > np->maxoffs)
7297 			{chg = 1; ofs = np->maxoffs;}
7298 		if (req) {
7299 			if (ofs > tp->tinfo.user.offset)
7300 				{chg = 1; ofs = tp->tinfo.user.offset;}
7301 		}
7302 	}
7303 
7304 	if (ofs) {
7305 		if (dt) {
7306 			if (per < np->minsync_dt)
7307 				{chg = 1; per = np->minsync_dt;}
7308 		}
7309 		else if (per < np->minsync)
7310 			{chg = 1; per = np->minsync;}
7311 		if (req) {
7312 			if (per < tp->tinfo.user.period)
7313 				{chg = 1; per = tp->tinfo.user.period;}
7314 		}
7315 	}
7316 
7317 	div = fak = 0;
7318 	if (ofs && sym_getsync(np, dt, per, &div, &fak) < 0)
7319 		goto reject_it;
7320 
7321 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7322 		PRINT_ADDR(cp);
7323 		printf ("ppr: "
7324 			"dt=%x ofs=%d per=%d wide=%d div=%d fak=%d chg=%d.\n",
7325 			dt, ofs, per, wide, div, fak, chg);
7326 	}
7327 
7328 	/*
7329 	 *  It was an answer.
7330 	 */
7331 	if (req == 0) {
7332 		if (chg) 	/* Answer wasn't acceptable */
7333 			goto reject_it;
7334 		sym_setpprot (np, cp, dt, ofs, per, wide, div, fak);
7335 		OUTL (nc_dsp, SCRIPT_BA (np, clrack));
7336 		return;
7337 	}
7338 
7339 	/*
7340 	 *  It was a request. Set value and
7341 	 *  prepare an answer message
7342 	 */
7343 	sym_setpprot (np, cp, dt, ofs, per, wide, div, fak);
7344 
7345 	np->msgout[0] = M_EXTENDED;
7346 	np->msgout[1] = 6;
7347 	np->msgout[2] = M_X_PPR_REQ;
7348 	np->msgout[3] = per;
7349 	np->msgout[4] = 0;
7350 	np->msgout[5] = ofs;
7351 	np->msgout[6] = wide;
7352 	np->msgout[7] = dt;
7353 
7354 	cp->nego_status = NS_PPR;
7355 
7356 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7357 		sym_print_msg(cp, "ppr msgout", np->msgout);
7358 	}
7359 
7360 	np->msgin [0] = M_NOOP;
7361 
7362 	OUTL (nc_dsp, SCRIPTH_BA (np, ppr_resp));
7363 	return;
7364 reject_it:
7365 	sym_setpprot (np, cp, 0, 0, 0, 0, 0, 0);
7366 	OUTL (nc_dsp, SCRIPTH_BA (np, msg_bad));
7367 }
7368 
7369 /*
7370  *  chip handler for WIDE DATA TRANSFER REQUEST (WDTR) message.
7371  */
7372 static void sym_wide_nego(hcb_p np, tcb_p tp, ccb_p cp)
7373 {
7374 	u_char	chg, wide;
7375 	int	req = 1;
7376 
7377 	/*
7378 	 *  Wide request message received.
7379 	 */
7380 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7381 		sym_print_msg(cp, "wide msgin", np->msgin);
7382 	};
7383 
7384 	/*
7385 	 * Is it an request from the device?
7386 	 */
7387 	if (INB (HS_PRT) == HS_NEGOTIATE) {
7388 		OUTB (HS_PRT, HS_BUSY);
7389 		if (cp->nego_status && cp->nego_status != NS_WIDE)
7390 			goto reject_it;
7391 		req = 0;
7392 	}
7393 
7394 	/*
7395 	 *  get requested values.
7396 	 */
7397 	chg  = 0;
7398 	wide = np->msgin[3];
7399 
7400 	/*
7401 	 *  check values against driver limits.
7402 	 */
7403 	if (wide > np->maxoffs)
7404 		{chg = 1; wide = np->maxoffs;}
7405 	if (req) {
7406 		if (wide > tp->tinfo.user.width)
7407 			{chg = 1; wide = tp->tinfo.user.width;}
7408 	}
7409 
7410 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7411 		PRINT_ADDR(cp);
7412 		printf ("wdtr: wide=%d chg=%d.\n", wide, chg);
7413 	}
7414 
7415 	/*
7416 	 * This was an answer message
7417 	 */
7418 	if (req == 0) {
7419 		if (chg)	/*  Answer wasn't acceptable. */
7420 			goto reject_it;
7421 		sym_setwide (np, cp, wide);
7422 #if 1
7423 		/*
7424 		 * Negotiate for SYNC immediately after WIDE response.
7425 		 * This allows to negotiate for both WIDE and SYNC on
7426 		 * a single SCSI command (Suggested by Justin Gibbs).
7427 		 */
7428 		if (tp->tinfo.goal.offset) {
7429 			np->msgout[0] = M_EXTENDED;
7430 			np->msgout[1] = 3;
7431 			np->msgout[2] = M_X_SYNC_REQ;
7432 			np->msgout[3] = tp->tinfo.goal.period;
7433 			np->msgout[4] = tp->tinfo.goal.offset;
7434 
7435 			if (DEBUG_FLAGS & DEBUG_NEGO) {
7436 				sym_print_msg(cp, "sync msgout", np->msgout);
7437 			}
7438 
7439 			cp->nego_status = NS_SYNC;
7440 			OUTB (HS_PRT, HS_NEGOTIATE);
7441 			OUTL (nc_dsp, SCRIPTH_BA (np, sdtr_resp));
7442 			return;
7443 		}
7444 #endif
7445 		OUTL (nc_dsp, SCRIPT_BA (np, clrack));
7446 		return;
7447 	};
7448 
7449 	/*
7450 	 *  It was a request, set value and
7451 	 *  prepare an answer message
7452 	 */
7453 	sym_setwide (np, cp, wide);
7454 
7455 	np->msgout[0] = M_EXTENDED;
7456 	np->msgout[1] = 2;
7457 	np->msgout[2] = M_X_WIDE_REQ;
7458 	np->msgout[3] = wide;
7459 
7460 	np->msgin [0] = M_NOOP;
7461 
7462 	cp->nego_status = NS_WIDE;
7463 
7464 	if (DEBUG_FLAGS & DEBUG_NEGO) {
7465 		sym_print_msg(cp, "wide msgout", np->msgout);
7466 	}
7467 
7468 	OUTL (nc_dsp, SCRIPTH_BA (np, wdtr_resp));
7469 	return;
7470 reject_it:
7471 	OUTL (nc_dsp, SCRIPTH_BA (np, msg_bad));
7472 }
7473 
7474 /*
7475  *  Reset SYNC or WIDE to default settings.
7476  *
7477  *  Called when a negotiation does not succeed either
7478  *  on rejection or on protocol error.
7479  */
7480 static void sym_nego_default(hcb_p np, tcb_p tp, ccb_p cp)
7481 {
7482 	/*
7483 	 *  any error in negotiation:
7484 	 *  fall back to default mode.
7485 	 */
7486 	switch (cp->nego_status) {
7487 	case NS_PPR:
7488 		sym_setpprot (np, cp, 0, 0, 0, 0, 0, 0);
7489 		break;
7490 	case NS_SYNC:
7491 		sym_setsync (np, cp, 0, 0, 0, 0);
7492 		break;
7493 	case NS_WIDE:
7494 		sym_setwide (np, cp, 0);
7495 		break;
7496 	};
7497 	np->msgin [0] = M_NOOP;
7498 	np->msgout[0] = M_NOOP;
7499 	cp->nego_status = 0;
7500 }
7501 
7502 /*
7503  *  chip handler for MESSAGE REJECT received in response to
7504  *  a WIDE or SYNCHRONOUS negotiation.
7505  */
7506 static void sym_nego_rejected(hcb_p np, tcb_p tp, ccb_p cp)
7507 {
7508 	sym_nego_default(np, tp, cp);
7509 	OUTB (HS_PRT, HS_BUSY);
7510 }
7511 
7512 /*
7513  *  chip exception handler for programmed interrupts.
7514  */
7515 void sym_int_sir (hcb_p np)
7516 {
7517 	u_char	num	= INB (nc_dsps);
7518 	u_long	dsa	= INL (nc_dsa);
7519 	ccb_p	cp	= sym_ccb_from_dsa(np, dsa);
7520 	u_char	target	= INB (nc_sdid) & 0x0f;
7521 	tcb_p	tp	= &np->target[target];
7522 	int	tmp;
7523 
7524 	if (DEBUG_FLAGS & DEBUG_TINY) printf ("I#%d", num);
7525 
7526 	switch (num) {
7527 	/*
7528 	 *  Command has been completed with error condition
7529 	 *  or has been auto-sensed.
7530 	 */
7531 	case SIR_COMPLETE_ERROR:
7532 		sym_complete_error(np, cp);
7533 		return;
7534 	/*
7535 	 *  The C code is currently trying to recover from something.
7536 	 *  Typically, user want to abort some command.
7537 	 */
7538 	case SIR_SCRIPT_STOPPED:
7539 	case SIR_TARGET_SELECTED:
7540 	case SIR_ABORT_SENT:
7541 		sym_sir_task_recovery(np, num);
7542 		return;
7543 	/*
7544 	 *  The device didn't go to MSG OUT phase after having
7545 	 *  been selected with ATN. We donnot want to handle
7546 	 *  that.
7547 	 */
7548 	case SIR_SEL_ATN_NO_MSG_OUT:
7549 		printf ("%s:%d: No MSG OUT phase after selection with ATN.\n",
7550 			sym_name (np), target);
7551 		goto out_stuck;
7552 	/*
7553 	 *  The device didn't switch to MSG IN phase after
7554 	 *  having reseleted the initiator.
7555 	 */
7556 	case SIR_RESEL_NO_MSG_IN:
7557 	/*
7558 	 *  After reselection, the device sent a message that wasn't
7559 	 *  an IDENTIFY.
7560 	 */
7561 	case SIR_RESEL_NO_IDENTIFY:
7562 		/*
7563 		 *  If devices reselecting without sending an IDENTIFY
7564 		 *  message still exist, this should help.
7565 		 *  We just assume lun=0, 1 CCB, no tag.
7566 		 */
7567 		if (tp->lun0p) {
7568 			OUTL (nc_dsa, scr_to_cpu(tp->lun0p->itl_task_sa));
7569 			OUTL (nc_dsp, SCRIPT_BA (np, resel_dsa1));
7570 			return;
7571 		}
7572 	/*
7573 	 *  The device reselected a LUN we donnot know about.
7574 	 */
7575 	case SIR_RESEL_BAD_LUN:
7576 		np->msgout[0] = M_RESET;
7577 		goto out;
7578 	/*
7579 	 *  The device reselected for an untagged nexus and we
7580 	 *  haven't any.
7581 	 */
7582 	case SIR_RESEL_BAD_I_T_L:
7583 		np->msgout[0] = M_ABORT;
7584 		goto out;
7585 	/*
7586 	 *  The device reselected for a tagged nexus that we donnot
7587 	 *  have.
7588 	 */
7589 	case SIR_RESEL_BAD_I_T_L_Q:
7590 		np->msgout[0] = M_ABORT_TAG;
7591 		goto out;
7592 	/*
7593 	 *  The SCRIPTS let us know that the device has grabbed
7594 	 *  our message and will abort the job.
7595 	 */
7596 	case SIR_RESEL_ABORTED:
7597 		np->lastmsg = np->msgout[0];
7598 		np->msgout[0] = M_NOOP;
7599 		printf ("%s:%d: message %x sent on bad reselection.\n",
7600 			sym_name (np), target, np->lastmsg);
7601 		goto out;
7602 	/*
7603 	 *  The SCRIPTS let us know that a message has been
7604 	 *  successfully sent to the device.
7605 	 */
7606 	case SIR_MSG_OUT_DONE:
7607 		np->lastmsg = np->msgout[0];
7608 		np->msgout[0] = M_NOOP;
7609 		/* Should we really care of that */
7610 		if (np->lastmsg == M_PARITY || np->lastmsg == M_ID_ERROR) {
7611 			if (cp) {
7612 				cp->xerr_status &= ~XE_PARITY_ERR;
7613 				if (!cp->xerr_status)
7614 					OUTOFFB (HF_PRT, HF_EXT_ERR);
7615 			}
7616 		}
7617 		goto out;
7618 	/*
7619 	 *  The device didn't send a GOOD SCSI status.
7620 	 *  We may have some work to do prior to allow
7621 	 *  the SCRIPTS processor to continue.
7622 	 */
7623 	case SIR_BAD_SCSI_STATUS:
7624 		if (!cp)
7625 			goto out;
7626 		sym_sir_bad_scsi_status(np, num, cp);
7627 		return;
7628 	/*
7629 	 *  We are asked by the SCRIPTS to prepare a
7630 	 *  REJECT message.
7631 	 */
7632 	case SIR_REJECT_TO_SEND:
7633 		sym_print_msg(cp, "M_REJECT to send for ", np->msgin);
7634 		np->msgout[0] = M_REJECT;
7635 		goto out;
7636 	/*
7637 	 *  We have been ODD at the end of a DATA IN
7638 	 *  transfer and the device didn't send a
7639 	 *  IGNORE WIDE RESIDUE message.
7640 	 *  It is a data overrun condition.
7641 	 */
7642 	case SIR_SWIDE_OVERRUN:
7643 		if (cp) {
7644 			OUTONB (HF_PRT, HF_EXT_ERR);
7645 			cp->xerr_status |= XE_SWIDE_OVRUN;
7646 		}
7647 		goto out;
7648 	/*
7649 	 *  We have been ODD at the end of a DATA OUT
7650 	 *  transfer.
7651 	 *  It is a data underrun condition.
7652 	 */
7653 	case SIR_SODL_UNDERRUN:
7654 		if (cp) {
7655 			OUTONB (HF_PRT, HF_EXT_ERR);
7656 			cp->xerr_status |= XE_SODL_UNRUN;
7657 		}
7658 		goto out;
7659 	/*
7660 	 *  We received a message.
7661 	 */
7662 	case SIR_MSG_RECEIVED:
7663 		if (!cp)
7664 			goto out_stuck;
7665 		switch (np->msgin [0]) {
7666 		/*
7667 		 *  We received an extended message.
7668 		 *  We handle MODIFY DATA POINTER, SDTR, WDTR
7669 		 *  and reject all other extended messages.
7670 		 */
7671 		case M_EXTENDED:
7672 			switch (np->msgin [2]) {
7673 			case M_X_MODIFY_DP:
7674 				if (DEBUG_FLAGS & DEBUG_POINTER)
7675 					sym_print_msg(cp,"modify DP",np->msgin);
7676 				tmp = (np->msgin[3]<<24) + (np->msgin[4]<<16) +
7677 				      (np->msgin[5]<<8)  + (np->msgin[6]);
7678 				sym_modify_dp(np, tp, cp, tmp);
7679 				return;
7680 			case M_X_SYNC_REQ:
7681 				sym_sync_nego(np, tp, cp);
7682 				return;
7683 			case M_X_PPR_REQ:
7684 				sym_ppr_nego(np, tp, cp);
7685 				return;
7686 			case M_X_WIDE_REQ:
7687 				sym_wide_nego(np, tp, cp);
7688 				return;
7689 			default:
7690 				goto out_reject;
7691 			}
7692 			break;
7693 		/*
7694 		 *  We received a 1/2 byte message not handled from SCRIPTS.
7695 		 *  We are only expecting MESSAGE REJECT and IGNORE WIDE
7696 		 *  RESIDUE messages that haven't been anticipated by
7697 		 *  SCRIPTS on SWIDE full condition. Unanticipated IGNORE
7698 		 *  WIDE RESIDUE messages are aliased as MODIFY DP (-1).
7699 		 */
7700 		case M_IGN_RESIDUE:
7701 			if (DEBUG_FLAGS & DEBUG_POINTER)
7702 				sym_print_msg(cp,"ign wide residue", np->msgin);
7703 			sym_modify_dp(np, tp, cp, -1);
7704 			return;
7705 		case M_REJECT:
7706 			if (INB (HS_PRT) == HS_NEGOTIATE)
7707 				sym_nego_rejected(np, tp, cp);
7708 			else {
7709 				PRINT_ADDR(cp);
7710 				printf ("M_REJECT received (%x:%x).\n",
7711 					scr_to_cpu(np->lastmsg), np->msgout[0]);
7712 			}
7713 			goto out_clrack;
7714 			break;
7715 		default:
7716 			goto out_reject;
7717 		}
7718 		break;
7719 	/*
7720 	 *  We received an unknown message.
7721 	 *  Ignore all MSG IN phases and reject it.
7722 	 */
7723 	case SIR_MSG_WEIRD:
7724 		sym_print_msg(cp, "WEIRD message received", np->msgin);
7725 		OUTL (nc_dsp, SCRIPTH_BA (np, msg_weird));
7726 		return;
7727 	/*
7728 	 *  Negotiation failed.
7729 	 *  Target does not send us the reply.
7730 	 *  Remove the HS_NEGOTIATE status.
7731 	 */
7732 	case SIR_NEGO_FAILED:
7733 		OUTB (HS_PRT, HS_BUSY);
7734 	/*
7735 	 *  Negotiation failed.
7736 	 *  Target does not want answer message.
7737 	 */
7738 	case SIR_NEGO_PROTO:
7739 		sym_nego_default(np, tp, cp);
7740 		goto out;
7741 	};
7742 
7743 out:
7744 	OUTONB (nc_dcntl, (STD|NOCOM));
7745 	return;
7746 out_reject:
7747 	OUTL (nc_dsp, SCRIPTH_BA (np, msg_bad));
7748 	return;
7749 out_clrack:
7750 	OUTL (nc_dsp, SCRIPT_BA (np, clrack));
7751 	return;
7752 out_stuck:
7753 }
7754 
7755 /*
7756  *  Acquire a control block
7757  */
7758 static	ccb_p sym_get_ccb (hcb_p np, u_char tn, u_char ln, u_char tag_order)
7759 {
7760 	tcb_p tp = &np->target[tn];
7761 	lcb_p lp = sym_lp(np, tp, ln);
7762 	u_short tag = NO_TAG;
7763 	SYM_QUEHEAD *qp;
7764 	ccb_p cp = (ccb_p) 0;
7765 
7766 	/*
7767 	 *  Look for a free CCB
7768 	 */
7769 	if (sym_que_empty(&np->free_ccbq))
7770 		(void) sym_alloc_ccb(np);
7771 	qp = sym_remque_head(&np->free_ccbq);
7772 	if (!qp)
7773 		goto out;
7774 	cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
7775 
7776 	/*
7777 	 *  If the LCB is not yet available and the LUN
7778 	 *  has been probed ok, try to allocate the LCB.
7779 	 */
7780 	if (!lp && sym_is_bit(tp->lun_map, ln)) {
7781 		lp = sym_alloc_lcb(np, tn, ln);
7782 		if (!lp)
7783 			goto out_free;
7784 	}
7785 
7786 	/*
7787 	 *  If the LCB is not available here, then the
7788 	 *  logical unit is not yet discovered. For those
7789 	 *  ones only accept 1 SCSI IO per logical unit,
7790 	 *  since we cannot allow disconnections.
7791 	 */
7792 	if (!lp) {
7793 		if (!sym_is_bit(tp->busy0_map, ln))
7794 			sym_set_bit(tp->busy0_map, ln);
7795 		else
7796 			goto out_free;
7797 	} else {
7798 		/*
7799 		 *  If we have been asked for a tagged command.
7800 		 */
7801 		if (tag_order) {
7802 			/*
7803 			 *  Debugging purpose.
7804 			 */
7805 			assert(lp->busy_itl == 0);
7806 			/*
7807 			 *  Allocate resources for tags if not yet.
7808 			 */
7809 			if (!lp->cb_tags) {
7810 				sym_alloc_lcb_tags(np, tn, ln);
7811 				if (!lp->cb_tags)
7812 					goto out_free;
7813 			}
7814 			/*
7815 			 *  Get a tag for this SCSI IO and set up
7816 			 *  the CCB bus address for reselection,
7817 			 *  and count it for this LUN.
7818 			 *  Toggle reselect path to tagged.
7819 			 */
7820 			if (lp->busy_itlq < SYM_CONF_MAX_TASK) {
7821 				tag = lp->cb_tags[lp->ia_tag];
7822 				if (++lp->ia_tag == SYM_CONF_MAX_TASK)
7823 					lp->ia_tag = 0;
7824 				lp->itlq_tbl[tag] = cpu_to_scr(cp->ccb_ba);
7825 				++lp->busy_itlq;
7826 				lp->resel_sa =
7827 					cpu_to_scr(SCRIPT_BA (np, resel_tag));
7828 			}
7829 			else
7830 				goto out_free;
7831 		}
7832 		/*
7833 		 *  This command will not be tagged.
7834 		 *  If we already have either a tagged or untagged
7835 		 *  one, refuse to overlap this untagged one.
7836 		 */
7837 		else {
7838 			/*
7839 			 *  Debugging purpose.
7840 			 */
7841 			assert(lp->busy_itl == 0 && lp->busy_itlq == 0);
7842 			/*
7843 			 *  Count this nexus for this LUN.
7844 			 *  Set up the CCB bus address for reselection.
7845 			 *  Toggle reselect path to untagged.
7846 			 */
7847 			if (++lp->busy_itl == 1) {
7848 				lp->itl_task_sa = cpu_to_scr(cp->ccb_ba);
7849 				lp->resel_sa =
7850 					cpu_to_scr(SCRIPT_BA (np,resel_no_tag));
7851 			}
7852 			else
7853 				goto out_free;
7854 		}
7855 	}
7856 	/*
7857 	 *  Put the CCB into the busy queue.
7858 	 */
7859 	sym_insque_tail(&cp->link_ccbq, &np->busy_ccbq);
7860 
7861 	/*
7862 	 *  Remember all informations needed to free this CCB.
7863 	 */
7864 	cp->to_abort = 0;
7865 	cp->tag	   = tag;
7866 	cp->target = tn;
7867 	cp->lun    = ln;
7868 
7869 	if (DEBUG_FLAGS & DEBUG_TAGS) {
7870 		PRINT_LUN(np, tn, ln);
7871 		printf ("ccb @%p using tag %d.\n", cp, tag);
7872 	}
7873 
7874 out:
7875 	return cp;
7876 out_free:
7877 	sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
7878 	return (ccb_p) 0;
7879 }
7880 
7881 /*
7882  *  Release one control block
7883  */
7884 static void sym_free_ccb (hcb_p np, ccb_p cp)
7885 {
7886 	tcb_p tp = &np->target[cp->target];
7887 	lcb_p lp = sym_lp(np, tp, cp->lun);
7888 
7889 	if (DEBUG_FLAGS & DEBUG_TAGS) {
7890 		PRINT_LUN(np, cp->target, cp->lun);
7891 		printf ("ccb @%p freeing tag %d.\n", cp, cp->tag);
7892 	}
7893 
7894 	/*
7895 	 *  If LCB available,
7896 	 */
7897 	if (lp) {
7898 		/*
7899 		 *  If tagged, release the tag, set the relect path
7900 		 */
7901 		if (cp->tag != NO_TAG) {
7902 			/*
7903 			 *  Free the tag value.
7904 			 */
7905 			lp->cb_tags[lp->if_tag] = cp->tag;
7906 			if (++lp->if_tag == SYM_CONF_MAX_TASK)
7907 				lp->if_tag = 0;
7908 			/*
7909 			 *  Make the reselect path invalid,
7910 			 *  and uncount this CCB.
7911 			 */
7912 			lp->itlq_tbl[cp->tag] = cpu_to_scr(np->bad_itlq_ba);
7913 			--lp->busy_itlq;
7914 		} else {	/* Untagged */
7915 			/*
7916 			 *  Make the reselect path invalid,
7917 			 *  and uncount this CCB.
7918 			 */
7919 			lp->itl_task_sa = cpu_to_scr(np->bad_itl_ba);
7920 			--lp->busy_itl;
7921 		}
7922 		/*
7923 		 *  If no JOB active, make the LUN reselect path invalid.
7924 		 */
7925 		if (lp->busy_itlq == 0 && lp->busy_itl == 0)
7926 			lp->resel_sa = cpu_to_scr(SCRIPTH_BA(np,resel_bad_lun));
7927 	}
7928 	/*
7929 	 *  Otherwise, we only accept 1 IO per LUN.
7930 	 *  Clear the bit that keeps track of this IO.
7931 	 */
7932 	else
7933 		sym_clr_bit(tp->busy0_map, cp->lun);
7934 
7935 	/*
7936 	 *  We donnot queue more than 1 ccb per target
7937 	 *  with negotiation at any time. If this ccb was
7938 	 *  used for negotiation, clear this info in the tcb.
7939 	 */
7940 	if (cp == tp->nego_cp)
7941 		tp->nego_cp = 0;
7942 
7943 #ifdef SYM_CONF_IARB_SUPPORT
7944 	/*
7945 	 *  If we just complete the last queued CCB,
7946 	 *  clear this info that is no longer relevant.
7947 	 */
7948 	if (cp == np->last_cp)
7949 		np->last_cp = 0;
7950 #endif
7951 	/*
7952 	 *  Make this CCB available.
7953 	 */
7954 	cp->cam_ccb = 0;
7955 	cp->host_status = HS_IDLE;
7956 	sym_remque(&cp->link_ccbq);
7957 	sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
7958 }
7959 
7960 /*
7961  *  Allocate a CCB from memory and initialize its fixed part.
7962  */
7963 static ccb_p sym_alloc_ccb(hcb_p np)
7964 {
7965 	ccb_p cp = 0;
7966 	int hcode;
7967 
7968 	/*
7969 	 *  Prevent from allocating more CCBs than we can
7970 	 *  queue to the controller.
7971 	 */
7972 	if (np->actccbs >= SYM_CONF_MAX_START)
7973 		return 0;
7974 
7975 	/*
7976 	 *  Allocate memory for this CCB.
7977 	 */
7978 	cp = sym_calloc(sizeof(struct sym_ccb), "CCB");
7979 	if (!cp)
7980 		return 0;
7981 
7982 	/*
7983 	 *  Count it.
7984 	 */
7985 	np->actccbs++;
7986 
7987 	/*
7988 	 *  Compute the bus address of this ccb.
7989 	 */
7990 	cp->ccb_ba = vtobus(cp);
7991 
7992 	/*
7993 	 *  Insert this ccb into the hashed list.
7994 	 */
7995 	hcode = CCB_HASH_CODE(cp->ccb_ba);
7996 	cp->link_ccbh = np->ccbh[hcode];
7997 	np->ccbh[hcode] = cp;
7998 
7999 	/*
8000 	 *  Initialyze the start and restart actions.
8001 	 */
8002 	cp->phys.go.start   = cpu_to_scr(SCRIPT_BA (np, idle));
8003 	cp->phys.go.restart = cpu_to_scr(SCRIPTH_BA(np, bad_i_t_l));
8004 
8005  	/*
8006 	 *  Initilialyze some other fields.
8007 	 */
8008 	cp->phys.smsg_ext.addr = cpu_to_scr(vtobus(&np->msgin[2]));
8009 
8010 	/*
8011 	 *  Chain into free ccb queue.
8012 	 */
8013 	sym_insque_head(&cp->link_ccbq, &np->free_ccbq);
8014 
8015 	return cp;
8016 }
8017 
8018 /*
8019  *  Look up a CCB from a DSA value.
8020  */
8021 static ccb_p sym_ccb_from_dsa(hcb_p np, u_long dsa)
8022 {
8023 	int hcode;
8024 	ccb_p cp;
8025 
8026 	hcode = CCB_HASH_CODE(dsa);
8027 	cp = np->ccbh[hcode];
8028 	while (cp) {
8029 		if (cp->ccb_ba == dsa)
8030 			break;
8031 		cp = cp->link_ccbh;
8032 	}
8033 
8034 	return cp;
8035 }
8036 
8037 /*
8038  *  Target control block initialisation.
8039  *  Nothing important to do at the moment.
8040  */
8041 static void sym_init_tcb (hcb_p np, u_char tn)
8042 {
8043 	/*
8044 	 *  Check some alignments required by the chip.
8045 	 */
8046 	assert (((offsetof(struct sym_reg, nc_sxfer) ^
8047 		offsetof(struct sym_tcb, sval)) &3) == 0);
8048 	assert (((offsetof(struct sym_reg, nc_scntl3) ^
8049 		offsetof(struct sym_tcb, wval)) &3) == 0);
8050 }
8051 
8052 /*
8053  *  Lun control block allocation and initialization.
8054  */
8055 static lcb_p sym_alloc_lcb (hcb_p np, u_char tn, u_char ln)
8056 {
8057 	tcb_p tp = &np->target[tn];
8058 	lcb_p lp = sym_lp(np, tp, ln);
8059 
8060 	/*
8061 	 *  Already done, just return.
8062 	 */
8063 	if (lp)
8064 		return lp;
8065 	/*
8066 	 *  Check against some race.
8067 	 */
8068 	assert(!sym_is_bit(tp->busy0_map, ln));
8069 
8070 	/*
8071 	 *  Initialize the target control block if not yet.
8072 	 */
8073 	sym_init_tcb (np, tn);
8074 
8075 	/*
8076 	 *  Allocate the LCB bus address array.
8077 	 *  Compute the bus address of this table.
8078 	 */
8079 	if (ln && !tp->luntbl) {
8080 		int i;
8081 
8082 		tp->luntbl = sym_calloc(256, "LUNTBL");
8083 		if (!tp->luntbl)
8084 			goto fail;
8085 		for (i = 0 ; i < 64 ; i++)
8086 			tp->luntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
8087 		tp->luntbl_sa = cpu_to_scr(vtobus(tp->luntbl));
8088 	}
8089 
8090 	/*
8091 	 *  Allocate the table of pointers for LUN(s) > 0, if needed.
8092 	 */
8093 	if (ln && !tp->lunmp) {
8094 		tp->lunmp = sym_calloc(SYM_CONF_MAX_LUN * sizeof(lcb_p),
8095 				   "LUNMP");
8096 		if (!tp->lunmp)
8097 			goto fail;
8098 	}
8099 
8100 	/*
8101 	 *  Allocate the lcb.
8102 	 *  Make it available to the chip.
8103 	 */
8104 	lp = sym_calloc(sizeof(struct sym_lcb), "LCB");
8105 	if (!lp)
8106 		goto fail;
8107 	if (ln) {
8108 		tp->lunmp[ln] = lp;
8109 		tp->luntbl[ln] = cpu_to_scr(vtobus(lp));
8110 	}
8111 	else {
8112 		tp->lun0p = lp;
8113 		tp->lun0_sa = cpu_to_scr(vtobus(lp));
8114 	}
8115 
8116 	/*
8117 	 *  Let the itl task point to error handling.
8118 	 */
8119 	lp->itl_task_sa = cpu_to_scr(np->bad_itl_ba);
8120 
8121 	/*
8122 	 *  Set the reselect pattern to our default. :)
8123 	 */
8124 	lp->resel_sa = cpu_to_scr(SCRIPTH_BA(np, resel_bad_lun));
8125 
8126 	/*
8127 	 *  Set user capabilities.
8128 	 */
8129 	lp->user_flags = tp->usrflags & (SYM_DISC_ENABLED | SYM_TAGS_ENABLED);
8130 
8131 fail:
8132 	return lp;
8133 }
8134 
8135 /*
8136  *  Allocate LCB resources for tagged command queuing.
8137  */
8138 static void sym_alloc_lcb_tags (hcb_p np, u_char tn, u_char ln)
8139 {
8140 	tcb_p tp = &np->target[tn];
8141 	lcb_p lp = sym_lp(np, tp, ln);
8142 	int i;
8143 
8144 	/*
8145 	 *  If LCB not available, try to allocate it.
8146 	 */
8147 	if (!lp && !(lp = sym_alloc_lcb(np, tn, ln)))
8148 		goto fail;
8149 
8150 	/*
8151 	 *  Allocate the task table and and the tag allocation
8152 	 *  circular buffer. We want both or none.
8153 	 */
8154 	lp->itlq_tbl = sym_calloc(SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
8155 	if (!lp->itlq_tbl)
8156 		goto fail;
8157 	lp->cb_tags = sym_calloc(SYM_CONF_MAX_TASK, "CB_TAGS");
8158 	if (!lp->cb_tags) {
8159 		sym_mfree(lp->itlq_tbl, SYM_CONF_MAX_TASK*4, "ITLQ_TBL");
8160 		lp->itlq_tbl = 0;
8161 		goto fail;
8162 	}
8163 
8164 	/*
8165 	 *  Initialize the task table with invalid entries.
8166 	 */
8167 	for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
8168 		lp->itlq_tbl[i] = cpu_to_scr(np->notask_ba);
8169 
8170 	/*
8171 	 *  Fill up the tag buffer with tag numbers.
8172 	 */
8173 	for (i = 0 ; i < SYM_CONF_MAX_TASK ; i++)
8174 		lp->cb_tags[i] = i;
8175 
8176 	/*
8177 	 *  Make the task table available to SCRIPTS,
8178 	 *  And accept tagged commands now.
8179 	 */
8180 	lp->itlq_tbl_sa = cpu_to_scr(vtobus(lp->itlq_tbl));
8181 
8182 	return;
8183 fail:
8184 }
8185 
8186 /*
8187  *  Test the pci bus snoop logic :-(
8188  *
8189  *  Has to be called with interrupts disabled.
8190  */
8191 #ifndef SYM_CONF_IOMAPPED
8192 static int sym_regtest (hcb_p np)
8193 {
8194 	register volatile u32 data;
8195 	/*
8196 	 *  chip registers may NOT be cached.
8197 	 *  write 0xffffffff to a read only register area,
8198 	 *  and try to read it back.
8199 	 */
8200 	data = 0xffffffff;
8201 	OUTL_OFF(offsetof(struct sym_reg, nc_dstat), data);
8202 	data = INL_OFF(offsetof(struct sym_reg, nc_dstat));
8203 #if 1
8204 	if (data == 0xffffffff) {
8205 #else
8206 	if ((data & 0xe2f0fffd) != 0x02000080) {
8207 #endif
8208 		printf ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
8209 			(unsigned) data);
8210 		return (0x10);
8211 	};
8212 	return (0);
8213 }
8214 #endif
8215 
8216 static int sym_snooptest (hcb_p np)
8217 {
8218 	u32	sym_rd, sym_wr, sym_bk, host_rd, host_wr, pc;
8219 	int	i, err=0;
8220 #ifndef SYM_CONF_IOMAPPED
8221 	err |= sym_regtest (np);
8222 	if (err) return (err);
8223 #endif
8224 	/*
8225 	 *  init
8226 	 */
8227 	pc  = SCRIPTH0_BA (np, snooptest);
8228 	host_wr = 1;
8229 	sym_wr  = 2;
8230 	/*
8231 	 *  Set memory and register.
8232 	 */
8233 	np->cache = cpu_to_scr(host_wr);
8234 	OUTL (nc_temp, sym_wr);
8235 	/*
8236 	 *  Start script (exchange values)
8237 	 */
8238 	OUTL (nc_dsa, vtobus(np));
8239 	OUTL (nc_dsp, pc);
8240 	/*
8241 	 *  Wait 'til done (with timeout)
8242 	 */
8243 	for (i=0; i<SYM_SNOOP_TIMEOUT; i++)
8244 		if (INB(nc_istat) & (INTF|SIP|DIP))
8245 			break;
8246 	/*
8247 	 *  Save termination position.
8248 	 */
8249 	pc = INL (nc_dsp);
8250 	/*
8251 	 *  Read memory and register.
8252 	 */
8253 	host_rd = scr_to_cpu(np->cache);
8254 	sym_rd  = INL (nc_scratcha);
8255 	sym_bk  = INL (nc_temp);
8256 
8257 	/*
8258 	 *  check for timeout
8259 	 */
8260 	if (i>=SYM_SNOOP_TIMEOUT) {
8261 		printf ("CACHE TEST FAILED: timeout.\n");
8262 		return (0x20);
8263 	};
8264 	/*
8265 	 *  Check termination position.
8266 	 */
8267 	if (pc != SCRIPTH0_BA (np, snoopend)+8) {
8268 		printf ("CACHE TEST FAILED: script execution failed.\n");
8269 		printf ("start=%08lx, pc=%08lx, end=%08lx\n",
8270 			(u_long) SCRIPTH0_BA (np, snooptest), (u_long) pc,
8271 			(u_long) SCRIPTH0_BA (np, snoopend) +8);
8272 		return (0x40);
8273 	};
8274 	/*
8275 	 *  Show results.
8276 	 */
8277 	if (host_wr != sym_rd) {
8278 		printf ("CACHE TEST FAILED: host wrote %d, chip read %d.\n",
8279 			(int) host_wr, (int) sym_rd);
8280 		err |= 1;
8281 	};
8282 	if (host_rd != sym_wr) {
8283 		printf ("CACHE TEST FAILED: chip wrote %d, host read %d.\n",
8284 			(int) sym_wr, (int) host_rd);
8285 		err |= 2;
8286 	};
8287 	if (sym_bk != sym_wr) {
8288 		printf ("CACHE TEST FAILED: chip wrote %d, read back %d.\n",
8289 			(int) sym_wr, (int) sym_bk);
8290 		err |= 4;
8291 	};
8292 	return (err);
8293 }
8294 
8295 /*
8296  *  Determine the chip's clock frequency.
8297  *
8298  *  This is essential for the negotiation of the synchronous
8299  *  transfer rate.
8300  *
8301  *  Note: we have to return the correct value.
8302  *  THERE IS NO SAFE DEFAULT VALUE.
8303  *
8304  *  Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
8305  *  53C860 and 53C875 rev. 1 support fast20 transfers but
8306  *  do not have a clock doubler and so are provided with a
8307  *  80 MHz clock. All other fast20 boards incorporate a doubler
8308  *  and so should be delivered with a 40 MHz clock.
8309  *  The recent fast40 chips (895/896/895A/1010) use a 40 Mhz base
8310  *  clock and provide a clock quadrupler (160 Mhz).
8311  */
8312 
8313 /*
8314  *  Select SCSI clock frequency
8315  */
8316 static void sym_selectclock(hcb_p np, u_char scntl3)
8317 {
8318 	/*
8319 	 *  If multiplier not present or not selected, leave here.
8320 	 */
8321 	if (np->multiplier <= 1) {
8322 		OUTB(nc_scntl3,	scntl3);
8323 		return;
8324 	}
8325 
8326 	if (sym_verbose >= 2)
8327 		printf ("%s: enabling clock multiplier\n", sym_name(np));
8328 
8329 	OUTB(nc_stest1, DBLEN);	   /* Enable clock multiplier		  */
8330 	/*
8331 	 *  Wait for the LCKFRQ bit to be set if supported by the chip.
8332 	 *  Otherwise wait 20 micro-seconds.
8333 	 */
8334 	if (np->features & FE_LCKFRQ) {
8335 		int i = 20;
8336 		while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
8337 			UDELAY (20);
8338 		if (!i)
8339 			printf("%s: the chip cannot lock the frequency\n",
8340 				sym_name(np));
8341 	} else
8342 		UDELAY (20);
8343 	OUTB(nc_stest3, HSC);		/* Halt the scsi clock		*/
8344 	OUTB(nc_scntl3,	scntl3);
8345 	OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier	*/
8346 	OUTB(nc_stest3, 0x00);		/* Restart scsi clock 		*/
8347 }
8348 
8349 /*
8350  *  calculate SCSI clock frequency (in KHz)
8351  */
8352 static unsigned getfreq (hcb_p np, int gen)
8353 {
8354 	unsigned int ms = 0;
8355 	unsigned int f;
8356 
8357 	/*
8358 	 * Measure GEN timer delay in order
8359 	 * to calculate SCSI clock frequency
8360 	 *
8361 	 * This code will never execute too
8362 	 * many loop iterations (if DELAY is
8363 	 * reasonably correct). It could get
8364 	 * too low a delay (too high a freq.)
8365 	 * if the CPU is slow executing the
8366 	 * loop for some reason (an NMI, for
8367 	 * example). For this reason we will
8368 	 * if multiple measurements are to be
8369 	 * performed trust the higher delay
8370 	 * (lower frequency returned).
8371 	 */
8372 	OUTW (nc_sien , 0);	/* mask all scsi interrupts */
8373 	(void) INW (nc_sist);	/* clear pending scsi interrupt */
8374 	OUTB (nc_dien , 0);	/* mask all dma interrupts */
8375 	(void) INW (nc_sist);	/* another one, just to be sure :) */
8376 	OUTB (nc_scntl3, 4);	/* set pre-scaler to divide by 3 */
8377 	OUTB (nc_stime1, 0);	/* disable general purpose timer */
8378 	OUTB (nc_stime1, gen);	/* set to nominal delay of 1<<gen * 125us */
8379 	while (!(INW(nc_sist) & GEN) && ms++ < 100000)
8380 		UDELAY (1000);	/* count ms */
8381 	OUTB (nc_stime1, 0);	/* disable general purpose timer */
8382  	/*
8383  	 * set prescaler to divide by whatever 0 means
8384  	 * 0 ought to choose divide by 2, but appears
8385  	 * to set divide by 3.5 mode in my 53c810 ...
8386  	 */
8387  	OUTB (nc_scntl3, 0);
8388 
8389   	/*
8390  	 * adjust for prescaler, and convert into KHz
8391   	 */
8392 	f = ms ? ((1 << gen) * 4340) / ms : 0;
8393 
8394 	if (sym_verbose >= 2)
8395 		printf ("%s: Delay (GEN=%d): %u msec, %u KHz\n",
8396 			sym_name(np), gen, ms, f);
8397 
8398 	return f;
8399 }
8400 
8401 static unsigned sym_getfreq (hcb_p np)
8402 {
8403 	u_int f1, f2;
8404 	int gen = 11;
8405 
8406 	(void) getfreq (np, gen);	/* throw away first result */
8407 	f1 = getfreq (np, gen);
8408 	f2 = getfreq (np, gen);
8409 	if (f1 > f2) f1 = f2;		/* trust lower result	*/
8410 	return f1;
8411 }
8412 
8413 /*
8414  *  Get/probe chip SCSI clock frequency
8415  */
8416 static void sym_getclock (hcb_p np, int mult)
8417 {
8418 	unsigned char scntl3 = np->sv_scntl3;
8419 	unsigned char stest1 = np->sv_stest1;
8420 	unsigned f1;
8421 
8422 	/*
8423 	 *  For the C10 core, assume 40 MHz.
8424 	 */
8425 	if (np->features & FE_C10) {
8426 		np->multiplier = mult;
8427 		np->clock_khz = 40000 * mult;
8428 		return;
8429 	}
8430 
8431 	np->multiplier = 1;
8432 	f1 = 40000;
8433 	/*
8434 	 *  True with 875/895/896/895A with clock multiplier selected
8435 	 */
8436 	if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
8437 		if (sym_verbose >= 2)
8438 			printf ("%s: clock multiplier found\n", sym_name(np));
8439 		np->multiplier = mult;
8440 	}
8441 
8442 	/*
8443 	 *  If multiplier not found or scntl3 not 7,5,3,
8444 	 *  reset chip and get frequency from general purpose timer.
8445 	 *  Otherwise trust scntl3 BIOS setting.
8446 	 */
8447 	if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
8448 		OUTB (nc_stest1, 0);		/* make sure doubler is OFF */
8449 		f1 = sym_getfreq (np);
8450 
8451 		if (sym_verbose)
8452 			printf ("%s: chip clock is %uKHz\n", sym_name(np), f1);
8453 
8454 		if	(f1 <	45000)		f1 =  40000;
8455 		else if (f1 <	55000)		f1 =  50000;
8456 		else				f1 =  80000;
8457 
8458 		if (f1 < 80000 && mult > 1) {
8459 			if (sym_verbose >= 2)
8460 				printf ("%s: clock multiplier assumed\n",
8461 					sym_name(np));
8462 			np->multiplier	= mult;
8463 		}
8464 	} else {
8465 		if	((scntl3 & 7) == 3)	f1 =  40000;
8466 		else if	((scntl3 & 7) == 5)	f1 =  80000;
8467 		else 				f1 = 160000;
8468 
8469 		f1 /= np->multiplier;
8470 	}
8471 
8472 	/*
8473 	 *  Compute controller synchronous parameters.
8474 	 */
8475 	f1		*= np->multiplier;
8476 	np->clock_khz	= f1;
8477 }
8478 
8479 /*
8480  *  Get/probe PCI clock frequency
8481  */
8482 static int sym_getpciclock (hcb_p np)
8483 {
8484 	static int f = 0;
8485 
8486 	/* For the C10, this will not work */
8487 	if (!f && !(np->features & FE_C10)) {
8488 		OUTB (nc_stest1, SCLK);	/* Use the PCI clock as SCSI clock */
8489 		f = (int) sym_getfreq (np);
8490 		OUTB (nc_stest1, 0);
8491 	}
8492 	return f;
8493 }
8494 
8495 /*============= DRIVER ACTION/COMPLETION ====================*/
8496 
8497 /*
8498  *  Print something that tells about extended errors.
8499  */
8500 static void sym_print_xerr(ccb_p cp, int x_status)
8501 {
8502 	if (x_status & XE_PARITY_ERR) {
8503 		PRINT_ADDR(cp);
8504 		printf ("unrecovered SCSI parity error.\n");
8505 	}
8506 	if (x_status & XE_EXTRA_DATA) {
8507 		PRINT_ADDR(cp);
8508 		printf ("extraneous data discarded.\n");
8509 	}
8510 	if (x_status & XE_BAD_PHASE) {
8511 		PRINT_ADDR(cp);
8512 		printf ("illegal scsi phase (4/5).\n");
8513 	}
8514 	if (x_status & XE_SODL_UNRUN) {
8515 		PRINT_ADDR(cp);
8516 		printf ("ODD transfer in DATA OUT phase.\n");
8517 	}
8518 	if (x_status & XE_SWIDE_OVRUN) {
8519 		PRINT_ADDR(cp);
8520 		printf ("ODD transfer in DATA IN phase.\n");
8521 	}
8522 }
8523 
8524 /*
8525  *  Choose the more appropriate CAM status if
8526  *  the IO encountered an extended error.
8527  */
8528 static int sym_xerr_cam_status(int cam_status, int x_status)
8529 {
8530 	if (x_status) {
8531 		if	(x_status & XE_PARITY_ERR)
8532 			cam_status = CAM_UNCOR_PARITY;
8533 		else if	(x_status &(XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN))
8534 			cam_status = CAM_DATA_RUN_ERR;
8535 		else if	(x_status & XE_BAD_PHASE)
8536 			cam_status = CAM_REQ_CMP_ERR;
8537 		else
8538 			cam_status = CAM_REQ_CMP_ERR;
8539 	}
8540 	return cam_status;
8541 }
8542 
8543 /*
8544  *  Complete execution of a SCSI command with extented
8545  *  error, SCSI status error, or having been auto-sensed.
8546  *
8547  *  The SCRIPTS processor is not running there, so we
8548  *  can safely access IO registers and remove JOBs from
8549  *  the START queue.
8550  *  SCRATCHA is assumed to have been loaded with STARTPOS
8551  *  before the SCRIPTS called the C code.
8552  */
8553 static void sym_complete_error (hcb_p np, ccb_p cp)
8554 {
8555 	struct ccb_scsiio *csio;
8556 	u_int cam_status;
8557 	int i;
8558 
8559 	/*
8560 	 *  Paranoid check. :)
8561 	 */
8562 	if (!cp || !cp->cam_ccb)
8563 		return;
8564 
8565 	if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_RESULT)) {
8566 		printf ("CCB=%lx STAT=%x/%x/%x DEV=%d/%d\n", (unsigned long)cp,
8567 			cp->host_status, cp->ssss_status, cp->host_flags,
8568 			cp->target, cp->lun);
8569 		MDELAY(100);
8570 	}
8571 
8572 	/*
8573 	 *  Get command, target and lun pointers.
8574 	 */
8575 	csio = &cp->cam_ccb->csio;
8576 
8577 	/*
8578 	 *  Check for extended errors.
8579 	 */
8580 	if (cp->xerr_status) {
8581 		if (sym_verbose)
8582 			sym_print_xerr(cp, cp->xerr_status);
8583 		if (cp->host_status == HS_COMPLETE)
8584 			cp->host_status = HS_COMP_ERR;
8585 	}
8586 
8587 	/*
8588 	 *  Calculate the residual.
8589 	 */
8590 	csio->sense_resid = 0;
8591 	csio->resid = sym_compute_residual(np, cp);
8592 
8593 	if (!SYM_CONF_RESIDUAL_SUPPORT) {/* If user does not want residuals */
8594 		csio->resid  = 0;	/* throw them away. :)		   */
8595 		cp->sv_resid = 0;
8596 	}
8597 
8598 	if (cp->host_flags & HF_SENSE) {		/* Auto sense     */
8599 		csio->scsi_status = cp->sv_scsi_status;	/* Restore status */
8600 		csio->sense_resid = csio->resid;	/* Swap residuals */
8601 		csio->resid       = cp->sv_resid;
8602 		cp->sv_resid	  = 0;
8603 		if (sym_verbose && cp->sv_xerr_status)
8604 			sym_print_xerr(cp, cp->sv_xerr_status);
8605 		if (cp->host_status == HS_COMPLETE &&
8606 		    cp->ssss_status == S_GOOD &&
8607 		    cp->xerr_status == 0) {
8608 			cam_status = sym_xerr_cam_status(CAM_SCSI_STATUS_ERROR,
8609 							 cp->sv_xerr_status);
8610 			cam_status |= CAM_AUTOSNS_VALID;
8611 #if 0
8612 			/*
8613 			 *  If the device reports a UNIT ATTENTION condition
8614 			 *  due to a RESET condition, we should consider all
8615 			 *  disconnect CCBs for this unit as aborted.
8616 			 */
8617 			if (1) {
8618 				u_char *p;
8619 				p  = (u_char *) &cp->cam_ccb->csio.sense_data;
8620 				if (p[0]==0x70 && p[2]==0x6 && p[12]==0x29)
8621 					sym_clear_tasks(np, CAM_REQ_ABORTED,
8622 							cp->target,cp->lun, -1);
8623 			}
8624 #endif
8625 		}
8626 		else
8627 			cam_status = CAM_AUTOSENSE_FAIL;
8628 	}
8629 	else if (cp->host_status == HS_COMPLETE) {	/* Bad SCSI status */
8630 		csio->scsi_status = cp->ssss_status;
8631 		cam_status = CAM_SCSI_STATUS_ERROR;
8632 	}
8633 	else if (cp->host_status == HS_SEL_TIMEOUT)	/* Selection timeout */
8634 		cam_status = CAM_SEL_TIMEOUT;
8635 	else if (cp->host_status == HS_UNEXPECTED)	/* Unexpected BUS FREE*/
8636 		cam_status = CAM_UNEXP_BUSFREE;
8637 	else {						/* Extended error */
8638 		if (sym_verbose) {
8639 			PRINT_ADDR(cp);
8640 			printf ("COMMAND FAILED (%x %x %x).\n",
8641 				cp->host_status, cp->ssss_status,
8642 				cp->xerr_status);
8643 		}
8644 		csio->scsi_status = cp->ssss_status;
8645 		/*
8646 		 *  Set the most appropriate value for CAM status.
8647 		 */
8648 		cam_status = sym_xerr_cam_status(CAM_REQ_CMP_ERR,
8649 						 cp->xerr_status);
8650 	}
8651 
8652 	/*
8653 	 *  Dequeue all queued CCBs for that device
8654 	 *  not yet started by SCRIPTS.
8655 	 */
8656 	i = (INL (nc_scratcha) - vtobus(np->squeue)) / 4;
8657 	(void) sym_dequeue_from_squeue(np, i, cp->target, cp->lun, -1);
8658 
8659 	/*
8660 	 *  Restart the SCRIPTS processor.
8661 	 */
8662 	OUTL (nc_dsp, SCRIPT_BA (np, start));
8663 
8664 	/*
8665 	 *  Add this one to the COMP queue.
8666 	 *  Complete all those commands with either error
8667 	 *  or requeue condition.
8668 	 */
8669 	sym_set_cam_status((union ccb *) csio, cam_status);
8670 	sym_remque(&cp->link_ccbq);
8671 	sym_insque_head(&cp->link_ccbq, &np->comp_ccbq);
8672 	sym_flush_comp_queue(np, 0);
8673 }
8674 
8675 /*
8676  *  Complete execution of a successful SCSI command.
8677  *
8678  *  Only successful commands go to the DONE queue,
8679  *  since we need to have the SCRIPTS processor
8680  *  stopped on any error condition.
8681  *  The SCRIPTS processor is running while we are
8682  *  completing successful commands.
8683  */
8684 static void sym_complete_ok (hcb_p np, ccb_p cp)
8685 {
8686 	struct ccb_scsiio *csio;
8687 	tcb_p tp;
8688 	lcb_p lp;
8689 
8690 	/*
8691 	 *  Paranoid check. :)
8692 	 */
8693 	if (!cp || !cp->cam_ccb)
8694 		return;
8695 	assert (cp->host_status == HS_COMPLETE);
8696 
8697 	/*
8698 	 *  Get command, target and lun pointers.
8699 	 */
8700 	csio = &cp->cam_ccb->csio;
8701 	tp = &np->target[cp->target];
8702 	lp = sym_lp(np, tp, cp->lun);
8703 
8704 	/*
8705 	 *  Assume device discovered on first success.
8706 	 */
8707 	if (!lp)
8708 		sym_set_bit(tp->lun_map, cp->lun);
8709 
8710 	/*
8711 	 *  If all data have been transferred, given than no
8712 	 *  extended error did occur, there is no residual.
8713 	 */
8714 	csio->resid = 0;
8715 	if (cp->phys.lastp != cp->phys.goalp)
8716 		csio->resid = sym_compute_residual(np, cp);
8717 
8718 	/*
8719 	 *  Wrong transfer residuals may be worse than just always
8720 	 *  returning zero. User can disable this feature from
8721 	 *  sym_conf.h. Residual support is enabled by default.
8722 	 */
8723 	if (!SYM_CONF_RESIDUAL_SUPPORT)
8724 		csio->resid  = 0;
8725 
8726 	/*
8727 	 *  Set status and complete the command.
8728 	 */
8729 	csio->scsi_status = cp->ssss_status;
8730 	sym_set_cam_status((union ccb *) csio, CAM_REQ_CMP);
8731 	sym_free_ccb (np, cp);
8732 	sym_xpt_done(np, (union ccb *) csio);
8733 }
8734 
8735 /*
8736  *  Our timeout handler.
8737  */
8738 static void sym_timeout1(void *arg)
8739 {
8740 	union ccb *ccb = (union ccb *) arg;
8741 	hcb_p np = ccb->ccb_h.sym_hcb_ptr;
8742 
8743 	/*
8744 	 *  Check that the CAM CCB is still queued.
8745 	 */
8746 	if (!np)
8747 		return;
8748 
8749 	switch(ccb->ccb_h.func_code) {
8750 	case XPT_SCSI_IO:
8751 		(void) sym_abort_scsiio(np, ccb, 1);
8752 		break;
8753 	default:
8754 		break;
8755 	}
8756 }
8757 
8758 static void sym_timeout(void *arg)
8759 {
8760 	int s = splcam();
8761 	sym_timeout1(arg);
8762 	splx(s);
8763 }
8764 
8765 /*
8766  *  Abort an SCSI IO.
8767  */
8768 static int sym_abort_scsiio(hcb_p np, union ccb *ccb, int timed_out)
8769 {
8770 	ccb_p cp;
8771 	SYM_QUEHEAD *qp;
8772 
8773 	/*
8774 	 *  Look up our CCB control block.
8775 	 */
8776 	cp = 0;
8777 	FOR_EACH_QUEUED_ELEMENT(&np->busy_ccbq, qp) {
8778 		ccb_p cp2 = sym_que_entry(qp, struct sym_ccb, link_ccbq);
8779 		if (cp2->cam_ccb == ccb) {
8780 			cp = cp2;
8781 			break;
8782 		}
8783 	}
8784 	if (!cp)
8785 		return -1;
8786 
8787 	/*
8788 	 *  If a previous abort didn't succeed in time,
8789 	 *  perform a BUS reset.
8790 	 */
8791 	if (cp->to_abort) {
8792 		sym_reset_scsi_bus(np, 1);
8793 		return 0;
8794 	}
8795 
8796 	/*
8797 	 *  Mark the CCB for abort and allow time for.
8798 	 */
8799 	cp->to_abort = timed_out ? 2 : 1;
8800 	ccb->ccb_h.timeout_ch = timeout(sym_timeout, (caddr_t) ccb, 10*hz);
8801 
8802 	/*
8803 	 *  Tell the SCRIPTS processor to stop and synchronize with us.
8804 	 */
8805 	np->istat_sem = SEM;
8806 	OUTB (nc_istat, SIGP|SEM);
8807 	return 0;
8808 }
8809 
8810 /*
8811  *  Reset a SCSI device (all LUNs of a target).
8812  */
8813 static void sym_reset_dev(hcb_p np, union ccb *ccb)
8814 {
8815 	tcb_p tp;
8816 	struct ccb_hdr *ccb_h = &ccb->ccb_h;
8817 
8818 	if (ccb_h->target_id   == np->myaddr ||
8819 	    ccb_h->target_id   >= SYM_CONF_MAX_TARGET ||
8820 	    ccb_h->target_lun  >= SYM_CONF_MAX_LUN) {
8821 		sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
8822 		return;
8823 	}
8824 
8825 	tp = &np->target[ccb_h->target_id];
8826 
8827 	tp->to_reset = 1;
8828 	sym_xpt_done2(np, ccb, CAM_REQ_CMP);
8829 
8830 	np->istat_sem = SEM;
8831 	OUTB (nc_istat, SIGP|SEM);
8832 	return;
8833 }
8834 
8835 /*
8836  *  SIM action entry point.
8837  */
8838 static void sym_action(struct cam_sim *sim, union ccb *ccb)
8839 {
8840 	int s = splcam();
8841 	sym_action1(sim, ccb);
8842 	splx(s);
8843 }
8844 
8845 static void sym_action1(struct cam_sim *sim, union ccb *ccb)
8846 {
8847 	hcb_p	np;
8848 	tcb_p	tp;
8849 	lcb_p	lp;
8850 	ccb_p	cp;
8851 	int 	tmp;
8852 	u_char	idmsg, *msgptr;
8853 	u_int   msglen;
8854 	struct	ccb_scsiio *csio;
8855 	struct	ccb_hdr  *ccb_h;
8856 
8857 	CAM_DEBUG(ccb->ccb_h.path, CAM_DEBUG_TRACE, ("sym_action\n"));
8858 
8859 	/*
8860 	 *  Retrieve our controller data structure.
8861 	 */
8862 	np = (hcb_p) cam_sim_softc(sim);
8863 
8864 	/*
8865 	 *  The common case is SCSI IO.
8866 	 *  We deal with other ones elsewhere.
8867 	 */
8868 	if (ccb->ccb_h.func_code != XPT_SCSI_IO) {
8869 		sym_action2(sim, ccb);
8870 		return;
8871 	}
8872 	csio  = &ccb->csio;
8873 	ccb_h = &csio->ccb_h;
8874 
8875 	/*
8876 	 *  Work around races.
8877 	 */
8878 	if ((ccb_h->status & CAM_STATUS_MASK) != CAM_REQ_INPROG) {
8879 		xpt_done(ccb);
8880 		return;
8881 	}
8882 
8883 	/*
8884 	 *  Minimal checkings, so that we will not
8885 	 *  go outside our tables.
8886 	 */
8887 	if (ccb_h->target_id   == np->myaddr ||
8888 	    ccb_h->target_id   >= SYM_CONF_MAX_TARGET ||
8889 	    ccb_h->target_lun  >= SYM_CONF_MAX_LUN) {
8890 		sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
8891 		return;
8892         }
8893 
8894 	/*
8895 	 *  Retreive the target and lun descriptors.
8896 	 */
8897 	tp = &np->target[ccb_h->target_id];
8898 	lp = sym_lp(np, tp, ccb_h->target_lun);
8899 
8900 	/*
8901 	 *  Complete the 1st INQUIRY command with error
8902 	 *  condition if the device is flagged NOSCAN
8903 	 *  at BOOT in the NVRAM. This may speed up
8904 	 *  the boot and maintain coherency with BIOS
8905 	 *  device numbering. Clearing the flag allows
8906 	 *  user to rescan skipped devices later.
8907 	 *  We also return error for devices not flagged
8908 	 *  for SCAN LUNS in the NVRAM since some mono-lun
8909 	 *  devices behave badly when asked for some non
8910 	 *  zero LUN. Btw, this is an absolute hack.:-)
8911 	 */
8912 	if (!(ccb_h->flags & CAM_CDB_PHYS) &&
8913 	    (0x12 == ((ccb_h->flags & CAM_CDB_POINTER) ?
8914 		  csio->cdb_io.cdb_ptr[0] : csio->cdb_io.cdb_bytes[0]))) {
8915 		if ((tp->usrflags & SYM_SCAN_BOOT_DISABLED) ||
8916 		    ((tp->usrflags & SYM_SCAN_LUNS_DISABLED) &&
8917 		     ccb_h->target_lun != 0)) {
8918 			tp->usrflags &= ~SYM_SCAN_BOOT_DISABLED;
8919 			sym_xpt_done2(np, ccb, CAM_DEV_NOT_THERE);
8920 			return;
8921 		}
8922 	}
8923 
8924 	/*
8925 	 *  Get a control block for this IO.
8926 	 */
8927 	tmp = ((ccb_h->flags & CAM_TAG_ACTION_VALID) != 0);
8928 	cp = sym_get_ccb(np, ccb_h->target_id, ccb_h->target_lun, tmp);
8929 	if (!cp) {
8930 		sym_xpt_done2(np, ccb, CAM_RESRC_UNAVAIL);
8931 		return;
8932 	}
8933 
8934 	/*
8935 	 *  Enqueue this IO in our pending queue.
8936 	 */
8937 	cp->cam_ccb = ccb;
8938 	sym_enqueue_cam_ccb(np, ccb);
8939 
8940 	/*
8941 	 *  Build the IDENTIFY message.
8942 	 */
8943 	idmsg = M_IDENTIFY | cp->lun;
8944 	if (cp->tag != NO_TAG || (lp && (lp->current_flags & SYM_DISC_ENABLED)))
8945 		idmsg |= 0x40;
8946 
8947 	msgptr = cp->scsi_smsg;
8948 	msglen = 0;
8949 	msgptr[msglen++] = idmsg;
8950 
8951 	/*
8952 	 *  Build the tag message if present.
8953 	 */
8954 	if (cp->tag != NO_TAG) {
8955 		u_char order = csio->tag_action;
8956 
8957 		switch(order) {
8958 		case M_ORDERED_TAG:
8959 			break;
8960 		case M_HEAD_TAG:
8961 			break;
8962 		default:
8963 			order = M_SIMPLE_TAG;
8964 		}
8965 		msgptr[msglen++] = order;
8966 
8967 		/*
8968 		 *  For less than 128 tags, actual tags are numbered
8969 		 *  1,3,5,..2*MAXTAGS+1,since we may have to deal
8970 		 *  with devices that have problems with #TAG 0 or too
8971 		 *  great #TAG numbers. For more tags (up to 256),
8972 		 *  we use directly our tag number.
8973 		 */
8974 #if SYM_CONF_MAX_TASK > (512/4)
8975 		msgptr[msglen++] = cp->tag;
8976 #else
8977 		msgptr[msglen++] = (cp->tag << 1) + 1;
8978 #endif
8979 	}
8980 
8981 	/*
8982 	 *  Build a negotiation message if needed.
8983 	 *  (nego_status is filled by sym_prepare_nego())
8984 	 */
8985 	cp->nego_status = 0;
8986 	if (tp->tinfo.current.width   != tp->tinfo.goal.width  ||
8987 	    tp->tinfo.current.period  != tp->tinfo.goal.period ||
8988 	    tp->tinfo.current.offset  != tp->tinfo.goal.offset ||
8989 #if 0 /* For now only renegotiate, based on width, period and offset */
8990 	    tp->tinfo.current.options != tp->tinfo.goal.options) {
8991 #else
8992 	    0) {
8993 #endif
8994 		if (!tp->nego_cp && lp)
8995 			msglen += sym_prepare_nego(np, cp, 0, msgptr + msglen);
8996 	}
8997 
8998 	/*
8999 	 *  Fill in our ccb
9000 	 */
9001 
9002 	/*
9003 	 *  Startqueue
9004 	 */
9005 	cp->phys.go.start   = cpu_to_scr(SCRIPT_BA (np, select));
9006 	cp->phys.go.restart = cpu_to_scr(SCRIPT_BA (np, resel_dsa));
9007 
9008 	/*
9009 	 *  select
9010 	 */
9011 	cp->phys.select.sel_id		= cp->target;
9012 	cp->phys.select.sel_scntl3	= tp->wval;
9013 	cp->phys.select.sel_sxfer	= tp->sval;
9014 	cp->phys.select.sel_scntl4	= tp->uval;
9015 
9016 	/*
9017 	 *  message
9018 	 */
9019 	cp->phys.smsg.addr	= cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
9020 	cp->phys.smsg.size	= cpu_to_scr(msglen);
9021 
9022 	/*
9023 	 *  command
9024 	 */
9025 	if (sym_setup_cdb(np, csio, cp) < 0) {
9026 		sym_free_ccb(np, cp);
9027 		sym_xpt_done(np, ccb);
9028 		return;
9029 	}
9030 
9031 	/*
9032 	 *  status
9033 	 */
9034 #if	0	/* Provision */
9035 	cp->actualquirks	= tp->quirks;
9036 #endif
9037 	cp->actualquirks	= SYM_QUIRK_AUTOSAVE;
9038 	cp->host_status		= cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
9039 	cp->ssss_status		= S_ILLEGAL;
9040 	cp->xerr_status		= 0;
9041 	cp->host_flags		= 0;
9042 	cp->phys.extra_bytes	= 0;
9043 
9044 	/*
9045 	 *  extreme data pointer.
9046 	 *  shall be positive, so -1 is lower than lowest.:)
9047 	 */
9048 	cp->ext_sg  = -1;
9049 	cp->ext_ofs = 0;
9050 
9051 	/*
9052 	 *  Build the data descriptor block
9053 	 *  and start the IO.
9054 	 */
9055 	if (sym_setup_data(np, csio, cp) < 0) {
9056 		sym_free_ccb(np, cp);
9057 		sym_xpt_done(np, ccb);
9058 		return;
9059 	}
9060 }
9061 
9062 /*
9063  *  How complex it gets to deal with the CDB in CAM.
9064  *  I bet, physical CDBs will never be used on the planet.
9065  */
9066 static int sym_setup_cdb(hcb_p np, struct ccb_scsiio *csio, ccb_p cp)
9067 {
9068 	struct ccb_hdr *ccb_h;
9069 	u32	cmd_ba;
9070 	int	cmd_len;
9071 
9072 	ccb_h = &csio->ccb_h;
9073 
9074 	/*
9075 	 *  CDB is 16 bytes max.
9076 	 */
9077 	if (csio->cdb_len > 16) {
9078 		sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
9079 		return -1;
9080 	}
9081 	cmd_len = csio->cdb_len;
9082 
9083 	if (ccb_h->flags & CAM_CDB_POINTER) {
9084 		/* CDB is a pointer */
9085 		if (!(ccb_h->flags & CAM_CDB_PHYS)) {
9086 			/* CDB pointer is virtual */
9087 			cmd_ba = vtobus(csio->cdb_io.cdb_ptr);
9088 		} else {
9089 			/* CDB pointer is physical */
9090 #if 0
9091 			cmd_ba = ((u32)csio->cdb_io.cdb_ptr) & 0xffffffff;
9092 #else
9093 			sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
9094 			return -1;
9095 #endif
9096 		}
9097 	} else {
9098 		/* CDB is in the ccb (buffer) */
9099 		cmd_ba = vtobus(csio->cdb_io.cdb_bytes);
9100 	}
9101 
9102 	cp->phys.cmd.addr	= cpu_to_scr(cmd_ba);
9103 	cp->phys.cmd.size	= cpu_to_scr(cmd_len);
9104 
9105 	return 0;
9106 }
9107 
9108 /*
9109  *  How complex it gets to deal with the data in CAM.
9110  *  I bet physical data will never be used in our galaxy.
9111  */
9112 static int sym_setup_data(hcb_p np, struct ccb_scsiio *csio, ccb_p cp)
9113 {
9114 	struct ccb_hdr *ccb_h;
9115 	int dir, retv;
9116 	u32 lastp, goalp;
9117 
9118 	ccb_h = &csio->ccb_h;
9119 
9120 	/*
9121 	 *  Now deal with the data.
9122 	 */
9123 	cp->data_len = 0;
9124 	cp->segments = 0;
9125 
9126 	/*
9127 	 *  No direction means no data.
9128 	 */
9129 	dir = (ccb_h->flags & CAM_DIR_MASK);
9130 	if (dir == CAM_DIR_NONE)
9131 		goto end_scatter;
9132 
9133 	if (!(ccb_h->flags & CAM_SCATTER_VALID)) {
9134 		/* Single buffer */
9135 		if (!(ccb_h->flags & CAM_DATA_PHYS)) {
9136 			/* Buffer is virtual */
9137 			retv = sym_scatter_virtual(np, cp,
9138 						(vm_offset_t) csio->data_ptr,
9139 						(vm_size_t) csio->dxfer_len);
9140 		} else {
9141 			/* Buffer is physical */
9142 			retv = sym_scatter_physical(np, cp,
9143 						(vm_offset_t) csio->data_ptr,
9144 						(vm_size_t) csio->dxfer_len);
9145 		}
9146 		if (retv < 0)
9147 			goto too_big;
9148 	} else {
9149 		/* Scatter/gather list */
9150 		int i;
9151 		struct bus_dma_segment *segs;
9152 		segs = (struct bus_dma_segment *)csio->data_ptr;
9153 
9154 		if ((ccb_h->flags & CAM_SG_LIST_PHYS) != 0) {
9155 			/* The SG list pointer is physical */
9156 			sym_set_cam_status(cp->cam_ccb, CAM_REQ_INVALID);
9157 			return -1;
9158 		}
9159 		retv = 0;
9160 		if (!(ccb_h->flags & CAM_DATA_PHYS)) {
9161 			/* SG buffer pointers are virtual */
9162 			for (i = csio->sglist_cnt - 1 ;  i >= 0 ; --i) {
9163 				retv = sym_scatter_virtual(np, cp,
9164 							   segs[i].ds_addr,
9165 							   segs[i].ds_len);
9166 				if (retv < 0)
9167 					break;
9168 			}
9169 		} else {
9170 			/* SG buffer pointers are physical */
9171 			for (i = csio->sglist_cnt - 1 ;  i >= 0 ; --i) {
9172 				retv = sym_scatter_physical(np, cp,
9173 							    segs[i].ds_addr,
9174 							    segs[i].ds_len);
9175 				if (retv < 0)
9176 					break;
9177 			}
9178 		}
9179 		if (retv < 0)
9180 			goto too_big;
9181 	}
9182 
9183 end_scatter:
9184 	/*
9185 	 *  No segments means no data.
9186 	 */
9187 	if (!cp->segments)
9188 		dir = CAM_DIR_NONE;
9189 
9190 	/*
9191 	 *  Set the data pointer.
9192 	 */
9193 	switch(dir) {
9194 	case CAM_DIR_OUT:
9195 		goalp = SCRIPT_BA (np, data_out2) + 8;
9196 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
9197 		if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
9198 			tcb_p tp = &np->target[cp->target];
9199 			if (tp->tinfo.current.options & PPR_OPT_DT)
9200 				goalp = SCRIPTH_BA (np, dt_data_out2) + 8;
9201 		}
9202 #endif
9203 		lastp = goalp - 8 - (cp->segments * (2*4));
9204 		break;
9205 	case CAM_DIR_IN:
9206 		goalp = SCRIPT_BA (np, data_in2) + 8;
9207 #ifdef	SYM_CONF_BROKEN_U3EN_SUPPORT
9208 		if ((np->features & (FE_C10|FE_U3EN)) == FE_C10) {
9209 			tcb_p tp = &np->target[cp->target];
9210 			if (tp->tinfo.current.options & PPR_OPT_DT)
9211 				goalp = SCRIPTH_BA (np, dt_data_in2) + 8;
9212 		}
9213 #endif
9214 		lastp = goalp - 8 - (cp->segments * (2*4));
9215 		break;
9216 	case CAM_DIR_NONE:
9217 	default:
9218 		lastp = goalp = SCRIPTH_BA (np, no_data);
9219 		break;
9220 	}
9221 
9222 	cp->phys.lastp = cpu_to_scr(lastp);
9223 	cp->phys.goalp = cpu_to_scr(goalp);
9224 	cp->phys.savep = cpu_to_scr(lastp);
9225 	cp->startp     = cp->phys.savep;
9226 
9227 	/*
9228 	 *  Activate this job.
9229 	 */
9230 	sym_put_start_queue(np, cp);
9231 
9232 	/*
9233 	 *  Command is successfully queued.
9234 	 */
9235 	return 0;
9236 too_big:
9237 	sym_set_cam_status(cp->cam_ccb, CAM_REQ_TOO_BIG);
9238 	return -1;
9239 }
9240 
9241 /*
9242  *  Scatter a virtual buffer into bus addressable chunks.
9243  */
9244 static int
9245 sym_scatter_virtual(hcb_p np, ccb_p cp, vm_offset_t vaddr, vm_size_t len)
9246 {
9247 	u_long	pe, pn;
9248 	u_long	n, k;
9249 	int s;
9250 
9251 	cp->data_len += len;
9252 
9253 	pe = vaddr + len;
9254 	n  = len;
9255 	s  = SYM_CONF_MAX_SG - 1 - cp->segments;
9256 
9257 	while (n && s >= 0) {
9258 		pn = (pe - 1) & ~PAGE_MASK;
9259 		k = pe - pn;
9260 		if (k > n) {
9261 			k  = n;
9262 			pn = pe - n;
9263 		}
9264 		if (DEBUG_FLAGS & DEBUG_SCATTER) {
9265 			printf ("%s scatter: va=%lx pa=%lx siz=%lx\n",
9266 				sym_name(np), pn, (u_long) vtobus(pn), k);
9267 		}
9268 		cp->phys.data[s].addr = cpu_to_scr(vtobus(pn));
9269 		cp->phys.data[s].size = cpu_to_scr(k);
9270 		pe = pn;
9271 		n -= k;
9272 		--s;
9273 	}
9274 	cp->segments = SYM_CONF_MAX_SG - 1 - s;
9275 
9276 	return n ? -1 : 0;
9277 }
9278 
9279 /*
9280  *  Will stay so forever, in my opinion.
9281  */
9282 static int
9283 sym_scatter_physical(hcb_p np, ccb_p cp, vm_offset_t vaddr, vm_size_t len)
9284 {
9285 	return -1;
9286 }
9287 
9288 /*
9289  *  SIM action for non performance critical stuff.
9290  */
9291 static void sym_action2(struct cam_sim *sim, union ccb *ccb)
9292 {
9293 	hcb_p	np;
9294 	tcb_p	tp;
9295 	lcb_p	lp;
9296 	struct	ccb_hdr  *ccb_h;
9297 
9298 	/*
9299 	 *  Retrieve our controller data structure.
9300 	 */
9301 	np = (hcb_p) cam_sim_softc(sim);
9302 
9303 	ccb_h = &ccb->ccb_h;
9304 
9305 	switch (ccb_h->func_code) {
9306 	case XPT_SET_TRAN_SETTINGS:
9307 	{
9308 		struct ccb_trans_settings *cts;
9309 
9310 		cts  = &ccb->cts;
9311 		tp = &np->target[ccb_h->target_id];
9312 
9313 		/*
9314 		 *  Update our transfer settings (basically WIDE/SYNC).
9315 		 *  These features are to be handled in a per target
9316 		 *  basis according to SCSI specifications.
9317 		 */
9318 		if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0)
9319 			sym_update_trans(np, tp, &tp->tinfo.user, cts);
9320 
9321 		if ((cts->flags & CCB_TRANS_CURRENT_SETTINGS) != 0)
9322 			sym_update_trans(np, tp, &tp->tinfo.goal, cts);
9323 
9324 		/*
9325 		 *  Update our disconnect and tag settings.
9326 		 *  SCSI requires CmdQue feature to be handled in a per
9327 		 *  device (logical unit) basis.
9328 		 */
9329 		lp = sym_lp(np, tp, ccb_h->target_lun);
9330 		if (lp) {
9331 			if ((cts->flags & CCB_TRANS_USER_SETTINGS) != 0)
9332 				sym_update_dflags(np, &lp->user_flags, cts);
9333 			if ((cts->flags & CCB_TRANS_CURRENT_SETTINGS) != 0)
9334 				sym_update_dflags(np, &lp->current_flags, cts);
9335 		}
9336 
9337 		sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9338 		break;
9339 	}
9340 	case XPT_GET_TRAN_SETTINGS:
9341 	{
9342 		struct ccb_trans_settings *cts;
9343 		struct sym_trans *tip;
9344 		u_char dflags;
9345 
9346 		cts = &ccb->cts;
9347 		tp = &np->target[ccb_h->target_id];
9348 		lp = sym_lp(np, tp, ccb_h->target_lun);
9349 
9350 		if ((cts->flags & CCB_TRANS_CURRENT_SETTINGS) != 0) {
9351 			tip = &tp->tinfo.current;
9352 			dflags = lp ? lp->current_flags : 0;
9353 		}
9354 		else {
9355 			tip = &tp->tinfo.user;
9356 			dflags = lp ? lp->user_flags : tp->usrflags;
9357 		}
9358 
9359 		cts->sync_period = tip->period;
9360 		cts->sync_offset = tip->offset;
9361 		cts->bus_width   = tip->width;
9362 
9363 		cts->valid = CCB_TRANS_SYNC_RATE_VALID
9364 			   | CCB_TRANS_SYNC_OFFSET_VALID
9365 			   | CCB_TRANS_BUS_WIDTH_VALID;
9366 
9367 		if (lp) {
9368 			cts->flags &= ~(CCB_TRANS_DISC_ENB|CCB_TRANS_TAG_ENB);
9369 
9370 			if (dflags & SYM_DISC_ENABLED)
9371 				cts->flags |= CCB_TRANS_DISC_ENB;
9372 
9373 			if (dflags & SYM_TAGS_ENABLED)
9374 				cts->flags |= CCB_TRANS_TAG_ENB;
9375 
9376 			cts->valid |= CCB_TRANS_DISC_VALID;
9377 			cts->valid |= CCB_TRANS_TQ_VALID;
9378 		}
9379 
9380 		sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9381 		break;
9382 	}
9383 	case XPT_CALC_GEOMETRY:
9384 	{
9385 		struct ccb_calc_geometry *ccg;
9386 		u32 size_mb;
9387 		u32 secs_per_cylinder;
9388 		int extended;
9389 
9390 		/*
9391 		 *  Silly DOS geometry.
9392 		 */
9393 		ccg = &ccb->ccg;
9394 		size_mb = ccg->volume_size
9395 			/ ((1024L * 1024L) / ccg->block_size);
9396 		extended = 1;
9397 
9398 		if (size_mb > 1024 && extended) {
9399 			ccg->heads = 255;
9400 			ccg->secs_per_track = 63;
9401 		} else {
9402 			ccg->heads = 64;
9403 			ccg->secs_per_track = 32;
9404 		}
9405 		secs_per_cylinder = ccg->heads * ccg->secs_per_track;
9406 		ccg->cylinders = ccg->volume_size / secs_per_cylinder;
9407 		sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9408 		break;
9409 	}
9410 	case XPT_PATH_INQ:
9411 	{
9412 		struct ccb_pathinq *cpi = &ccb->cpi;
9413 		cpi->version_num = 1;
9414 		cpi->hba_inquiry = PI_MDP_ABLE|PI_SDTR_ABLE|PI_TAG_ABLE;
9415 		if ((np->features & FE_WIDE) != 0)
9416 			cpi->hba_inquiry |= PI_WIDE_16;
9417 		cpi->target_sprt = 0;
9418 		cpi->hba_misc = 0;
9419 		if (np->usrflags & SYM_SCAN_TARGETS_HILO)
9420 			cpi->hba_misc |= PIM_SCANHILO;
9421 		if (np->usrflags & SYM_AVOID_BUS_RESET)
9422 			cpi->hba_misc |= PIM_NOBUSRESET;
9423 		cpi->hba_eng_cnt = 0;
9424 		cpi->max_target = (np->features & FE_WIDE) ? 15 : 7;
9425 		/* Semantic problem:)LUN number max = max number of LUNs - 1 */
9426 		cpi->max_lun = SYM_CONF_MAX_LUN-1;
9427 		if (SYM_SETUP_MAX_LUN < SYM_CONF_MAX_LUN)
9428 			cpi->max_lun = SYM_SETUP_MAX_LUN-1;
9429 		cpi->bus_id = cam_sim_bus(sim);
9430 		cpi->initiator_id = np->myaddr;
9431 		cpi->base_transfer_speed = 3300;
9432 		strncpy(cpi->sim_vid, "FreeBSD", SIM_IDLEN);
9433 		strncpy(cpi->hba_vid, "Symbios", HBA_IDLEN);
9434 		strncpy(cpi->dev_name, cam_sim_name(sim), DEV_IDLEN);
9435 		cpi->unit_number = cam_sim_unit(sim);
9436 		sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9437 		break;
9438 	}
9439 	case XPT_ABORT:
9440 	{
9441 		union ccb *abort_ccb = ccb->cab.abort_ccb;
9442 		switch(abort_ccb->ccb_h.func_code) {
9443 		case XPT_SCSI_IO:
9444 			if (sym_abort_scsiio(np, abort_ccb, 0) == 0) {
9445 				sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9446 				break;
9447 			}
9448 		default:
9449 			sym_xpt_done2(np, ccb, CAM_UA_ABORT);
9450 			break;
9451 		}
9452 		break;
9453 	}
9454 	case XPT_RESET_DEV:
9455 	{
9456 		sym_reset_dev(np, ccb);
9457 		break;
9458 	}
9459 	case XPT_RESET_BUS:
9460 	{
9461 		sym_reset_scsi_bus(np, 0);
9462 		if (sym_verbose) {
9463 			xpt_print_path(np->path);
9464 			printf("SCSI BUS reset delivered.\n");
9465 		}
9466 		sym_init (np, 1);
9467 		sym_xpt_done2(np, ccb, CAM_REQ_CMP);
9468 		break;
9469 	}
9470 	case XPT_ACCEPT_TARGET_IO:
9471 	case XPT_CONT_TARGET_IO:
9472 	case XPT_EN_LUN:
9473 	case XPT_NOTIFY_ACK:
9474 	case XPT_IMMED_NOTIFY:
9475 	case XPT_TERM_IO:
9476 	default:
9477 		sym_xpt_done2(np, ccb, CAM_REQ_INVALID);
9478 		break;
9479 	}
9480 }
9481 
9482 /*
9483  *  Update transfer settings of a target.
9484  */
9485 static void sym_update_trans(hcb_p np, tcb_p tp, struct sym_trans *tip,
9486 			    struct ccb_trans_settings *cts)
9487 {
9488 	/*
9489 	 *  Update the infos.
9490 	 */
9491 	if ((cts->valid & CCB_TRANS_BUS_WIDTH_VALID) != 0)
9492 		tip->width = cts->bus_width;
9493 	if ((cts->valid & CCB_TRANS_SYNC_OFFSET_VALID) != 0)
9494 		tip->offset = cts->sync_offset;
9495 	if ((cts->valid & CCB_TRANS_SYNC_RATE_VALID) != 0)
9496 		tip->period = cts->sync_period;
9497 
9498 	/*
9499 	 *  Scale against out limits.
9500 	 */
9501 	if (tip->width  > SYM_SETUP_MAX_WIDE)	tip->width  =SYM_SETUP_MAX_WIDE;
9502 	if (tip->width  > np->maxwide)		tip->width  = np->maxwide;
9503 	if (tip->offset > SYM_SETUP_MAX_OFFS)	tip->offset =SYM_SETUP_MAX_OFFS;
9504 	if (tip->offset > np->maxoffs)		tip->offset = np->maxoffs;
9505 	if (tip->period) {
9506 		if (tip->period < SYM_SETUP_MIN_SYNC)
9507 			tip->period = SYM_SETUP_MIN_SYNC;
9508 		if (np->features & FE_ULTRA3) {
9509 			if (tip->period < np->minsync_dt)
9510 				tip->period = np->minsync_dt;
9511 		}
9512 		else {
9513 			if (tip->period < np->minsync)
9514 				tip->period = np->minsync;
9515 		}
9516 		if (tip->period > np->maxsync)
9517 			tip->period = np->maxsync;
9518 	}
9519 }
9520 
9521 /*
9522  *  Update flags for a device (logical unit).
9523  */
9524 static void
9525 sym_update_dflags(hcb_p np, u_char *flags, struct ccb_trans_settings *cts)
9526 {
9527 	if ((cts->valid & CCB_TRANS_DISC_VALID) != 0) {
9528 		if ((cts->flags & CCB_TRANS_DISC_ENB) != 0)
9529 			*flags |= SYM_DISC_ENABLED;
9530 		else
9531 			*flags &= ~SYM_DISC_ENABLED;
9532 	}
9533 
9534 	if ((cts->valid & CCB_TRANS_TQ_VALID) != 0) {
9535 		if ((cts->flags & CCB_TRANS_TAG_ENB) != 0)
9536 			*flags |= SYM_TAGS_ENABLED;
9537 		else
9538 			*flags &= ~SYM_TAGS_ENABLED;
9539 	}
9540 }
9541 
9542 
9543 /*============= DRIVER INITIALISATION ==================*/
9544 
9545 #ifdef FreeBSD_4_Bus
9546 
9547 static device_method_t sym_pci_methods[] = {
9548 	DEVMETHOD(device_probe,	 sym_pci_probe),
9549 	DEVMETHOD(device_attach, sym_pci_attach),
9550 	{ 0, 0 }
9551 };
9552 
9553 static driver_t sym_pci_driver = {
9554 	"sym",
9555 	sym_pci_methods,
9556 	sizeof(struct sym_hcb)
9557 };
9558 
9559 static devclass_t sym_devclass;
9560 
9561 DRIVER_MODULE(sym, pci, sym_pci_driver, sym_devclass, 0, 0);
9562 
9563 #else	/* Pre-FreeBSD_4_Bus */
9564 
9565 static u_long sym_unit;
9566 
9567 static struct	pci_device sym_pci_driver = {
9568 	"sym",
9569 	sym_pci_probe,
9570 	sym_pci_attach,
9571 	&sym_unit,
9572 	NULL
9573 };
9574 
9575 DATA_SET (pcidevice_set, sym_pci_driver);
9576 
9577 #endif /* FreeBSD_4_Bus */
9578 
9579 static struct sym_pci_chip sym_pci_dev_table[] = {
9580  {PCI_ID_SYM53C810, 0x0f, "810", 4, 8, 4, 0,
9581  FE_ERL}
9582  ,
9583  {PCI_ID_SYM53C810, 0xff, "810a", 4,  8, 4, 1,
9584  FE_CACHE_SET|FE_LDSTR|FE_PFEN|FE_BOF}
9585  ,
9586  {PCI_ID_SYM53C825, 0x0f, "825", 6,  8, 4, 0,
9587  FE_WIDE|FE_BOF|FE_ERL|FE_DIFF}
9588  ,
9589  {PCI_ID_SYM53C825, 0xff, "825a", 6,  8, 4, 2,
9590  FE_WIDE|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|FE_RAM|FE_DIFF}
9591  ,
9592  {PCI_ID_SYM53C860, 0xff, "860", 4,  8, 5, 1,
9593  FE_ULTRA|FE_CLK80|FE_CACHE_SET|FE_BOF|FE_LDSTR|FE_PFEN}
9594  ,
9595  {PCI_ID_SYM53C875, 0x01, "875", 6, 16, 5, 2,
9596  FE_WIDE|FE_ULTRA|FE_CLK80|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9597  FE_RAM|FE_DIFF}
9598  ,
9599  {PCI_ID_SYM53C875, 0xff, "875", 6, 16, 5, 2,
9600  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9601  FE_RAM|FE_DIFF}
9602  ,
9603  {PCI_ID_SYM53C875_2, 0xff, "875", 6, 16, 5, 2,
9604  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9605  FE_RAM|FE_DIFF}
9606  ,
9607  {PCI_ID_SYM53C885, 0xff, "885", 6, 16, 5, 2,
9608  FE_WIDE|FE_ULTRA|FE_DBLR|FE_CACHE0_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9609  FE_RAM|FE_DIFF}
9610  ,
9611  {PCI_ID_SYM53C895, 0xff, "895", 6, 31, 7, 2,
9612  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9613  FE_RAM|FE_LCKFRQ}
9614  ,
9615  {PCI_ID_SYM53C896, 0xff, "896", 6, 31, 7, 4,
9616  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9617  FE_RAM|FE_RAM8K|FE_64BIT|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
9618  ,
9619  {PCI_ID_SYM53C895A, 0xff, "895a", 6, 31, 7, 4,
9620  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9621  FE_RAM|FE_RAM8K|FE_64BIT|FE_IO256|FE_NOPM|FE_LEDC|FE_LCKFRQ}
9622  ,
9623  {PCI_ID_LSI53C1010, 0x00, "1010", 6, 62, 7, 8,
9624  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
9625  FE_RAM|FE_RAM8K|FE_64BIT|FE_IO256|FE_NOPM|FE_LEDC|FE_PCI66|FE_CRC|
9626  FE_C10}
9627  ,
9628  {PCI_ID_LSI53C1010, 0xff, "1010", 6, 62, 7, 8,
9629  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
9630  FE_RAM|FE_RAM8K|FE_64BIT|FE_IO256|FE_NOPM|FE_LEDC|FE_CRC|
9631  FE_C10|FE_U3EN}
9632  ,
9633  {PCI_ID_LSI53C1010_2, 0xff, "1010", 6, 62, 7, 8,
9634  FE_WIDE|FE_ULTRA3|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFBC|FE_LDSTR|FE_PFEN|
9635  FE_RAM|FE_RAM8K|FE_64BIT|FE_IO256|FE_NOPM|FE_LEDC|FE_PCI66|FE_CRC|
9636  FE_C10|FE_U3EN}
9637  ,
9638  {PCI_ID_LSI53C1510D, 0xff, "1510d", 6, 31, 7, 4,
9639  FE_WIDE|FE_ULTRA2|FE_QUAD|FE_CACHE_SET|FE_BOF|FE_DFS|FE_LDSTR|FE_PFEN|
9640  FE_RAM|FE_IO256|FE_LEDC}
9641 };
9642 
9643 #define sym_pci_num_devs \
9644 	(sizeof(sym_pci_dev_table) / sizeof(sym_pci_dev_table[0]))
9645 
9646 /*
9647  *  Look up the chip table.
9648  *
9649  *  Return a pointer to the chip entry if found,
9650  *  zero otherwise.
9651  */
9652 static struct sym_pci_chip *
9653 #ifdef FreeBSD_4_Bus
9654 sym_find_pci_chip(device_t dev)
9655 #else
9656 sym_find_pci_chip(pcici_t pci_tag)
9657 #endif
9658 {
9659 	struct	sym_pci_chip *chip;
9660 	int	i;
9661 	u_short	device_id;
9662 	u_char	revision;
9663 
9664 #ifdef FreeBSD_4_Bus
9665 	if (pci_get_vendor(dev) != PCI_VENDOR_NCR)
9666 		return 0;
9667 
9668 	device_id = pci_get_device(dev);
9669 	revision  = pci_get_revid(dev);
9670 #else
9671 	if (pci_cfgread(pci_tag, PCIR_VENDOR, 2) != PCI_VENDOR_NCR)
9672 		return 0;
9673 
9674 	device_id = pci_cfgread(pci_tag, PCIR_DEVICE, 2);
9675 	revision  = pci_cfgread(pci_tag, PCIR_REVID,  1);
9676 #endif
9677 
9678 	for (i = 0; i < sym_pci_num_devs; i++) {
9679 		chip = &sym_pci_dev_table[i];
9680 		if (device_id != chip->device_id)
9681 			continue;
9682 		if (revision > chip->revision_id)
9683 			continue;
9684 		if (FE_LDSTR & chip->features)
9685 			return chip;
9686 		break;
9687 	}
9688 
9689 	return 0;
9690 }
9691 
9692 /*
9693  *  Tell upper layer if the chip is supported.
9694  */
9695 #ifdef FreeBSD_4_Bus
9696 static int
9697 sym_pci_probe(device_t dev)
9698 {
9699 	struct	sym_pci_chip *chip;
9700 
9701 	chip = sym_find_pci_chip(dev);
9702 	if (chip) {
9703 		device_set_desc(dev, chip->name);
9704 		return (chip->lp_probe_bit & SYM_SETUP_LP_PROBE_MAP)? -2000 : 0;
9705 	}
9706 	return ENXIO;
9707 }
9708 #else /* Pre-FreeBSD_4_Bus */
9709 static const char *
9710 sym_pci_probe(pcici_t pci_tag, pcidi_t type)
9711 {
9712 	struct	sym_pci_chip *chip;
9713 
9714 	chip = sym_find_pci_chip(pci_tag);
9715 	if (chip)
9716 		return chip->name;
9717 	return 0;
9718 }
9719 #endif
9720 
9721 /*
9722  *  Attach a sym53c8xx device.
9723  */
9724 #ifdef FreeBSD_4_Bus
9725 static int
9726 sym_pci_attach(device_t dev)
9727 #else
9728 static void
9729 sym_pci_attach(pcici_t pci_tag, int unit)
9730 {
9731 	int err = sym_pci_attach2(pci_tag, unit);
9732 	if (err)
9733 		printf("sym: failed to attach unit %d - err=%d.\n", unit, err);
9734 }
9735 static int
9736 sym_pci_attach2(pcici_t pci_tag, int unit)
9737 #endif
9738 {
9739 	struct	sym_pci_chip *chip;
9740 	u_short	command;
9741 	u_char	cachelnsz;
9742 	struct	sym_hcb *np = 0;
9743 	struct	sym_nvram nvram;
9744 	int 	i;
9745 
9746 	/*
9747 	 *  Only probed devices should be attached.
9748 	 *  We just enjoy being paranoid. :)
9749 	 */
9750 #ifdef FreeBSD_4_Bus
9751 	chip = sym_find_pci_chip(dev);
9752 #else
9753 	chip = sym_find_pci_chip(pci_tag);
9754 #endif
9755 	if (chip == NULL)
9756 		return (ENXIO);
9757 
9758 	/*
9759 	 *  Allocate immediately the host control block,
9760 	 *  since we are only expecting to succeed. :)
9761 	 *  We keep track in the HCB of all the resources that
9762 	 *  are to be released on error.
9763 	 */
9764 	np = sym_calloc(sizeof(*np), "HCB");
9765 	if (!np)
9766 		goto attach_failed;
9767 
9768 	/*
9769 	 *  Copy some useful infos to the HCB.
9770 	 */
9771 	np->verbose	 = bootverbose;
9772 #ifdef FreeBSD_4_Bus
9773 	np->device	 = dev;
9774 	np->unit	 = device_get_unit(dev);
9775 	np->device_id	 = pci_get_device(dev);
9776 	np->revision_id  = pci_get_revid(dev);
9777 #else
9778 	np->pci_tag	 = pci_tag;
9779 	np->unit	 = unit;
9780 	np->device_id	 = pci_cfgread(pci_tag, PCIR_DEVICE, 2);
9781 	np->revision_id  = pci_cfgread(pci_tag, PCIR_REVID,  1);
9782 #endif
9783 	np->features	 = chip->features;
9784 	np->clock_divn	 = chip->nr_divisor;
9785 	np->maxoffs	 = chip->offset_max;
9786 	np->maxburst	 = chip->burst_max;
9787 
9788 	/*
9789 	 * Edit its name.
9790 	 */
9791 	snprintf(np->inst_name, sizeof(np->inst_name), "sym%d", np->unit);
9792 
9793 	/*
9794 	 *  Read and apply some fix-ups to the PCI COMMAND
9795 	 *  register. We want the chip to be enabled for:
9796 	 *  - BUS mastering
9797 	 *  - PCI parity checking (reporting would also be fine)
9798 	 *  - Write And Invalidate.
9799 	 */
9800 #ifdef FreeBSD_4_Bus
9801 	command = pci_read_config(dev, PCIR_COMMAND, 2);
9802 #else
9803 	command = pci_cfgread(pci_tag, PCIR_COMMAND, 2);
9804 #endif
9805 	command |= PCIM_CMD_BUSMASTEREN;
9806 	command |= PCIM_CMD_PERRESPEN;
9807 	command |= /* PCIM_CMD_MWIEN */ 0x0010;
9808 #ifdef FreeBSD_4_Bus
9809 	pci_write_config(dev, PCIR_COMMAND, command, 2);
9810 #else
9811 	pci_cfgwrite(pci_tag, PCIR_COMMAND, command, 2);
9812 #endif
9813 
9814 	/*
9815 	 *  Let the device know about the cache line size,
9816 	 *  if it doesn't yet.
9817 	 */
9818 #ifdef FreeBSD_4_Bus
9819 	cachelnsz = pci_read_config(dev, PCIR_CACHELNSZ, 1);
9820 #else
9821 	cachelnsz = pci_cfgread(pci_tag, PCIR_CACHELNSZ, 1);
9822 #endif
9823 	if (!cachelnsz) {
9824 		cachelnsz = 8;
9825 #ifdef FreeBSD_4_Bus
9826 		pci_write_config(dev, PCIR_CACHELNSZ, cachelnsz, 1);
9827 #else
9828 		pci_cfgwrite(pci_tag, PCIR_CACHELNSZ, cachelnsz, 1);
9829 #endif
9830 	}
9831 
9832 	/*
9833 	 *  Alloc/get/map/retrieve everything that deals with MMIO.
9834 	 */
9835 #ifdef FreeBSD_4_Bus
9836 	if ((command & PCIM_CMD_MEMEN) != 0) {
9837 		int regs_id = SYM_PCI_MMIO;
9838 		np->mmio_res = bus_alloc_resource(dev, SYS_RES_MEMORY, &regs_id,
9839 						  0, ~0, 1, RF_ACTIVE);
9840 	}
9841 	if (!np->mmio_res) {
9842 		device_printf(dev, "failed to allocate MMIO resources\n");
9843 		goto attach_failed;
9844 	}
9845 	np->mmio_bsh = rman_get_bushandle(np->mmio_res);
9846 	np->mmio_tag = rman_get_bustag(np->mmio_res);
9847 	np->mmio_pa  = rman_get_start(np->mmio_res);
9848 	np->mmio_va  = (vm_offset_t) rman_get_virtual(np->mmio_res);
9849 	np->mmio_ba  = np->mmio_pa;
9850 #else
9851 	if ((command & PCIM_CMD_MEMEN) != 0) {
9852 		vm_offset_t vaddr, paddr;
9853 		if (!pci_map_mem(pci_tag, SYM_PCI_MMIO, &vaddr, &paddr)) {
9854 			printf("%s: failed to map MMIO window\n", sym_name(np));
9855 			goto attach_failed;
9856 		}
9857 		np->mmio_va = vaddr;
9858 		np->mmio_pa = paddr;
9859 		np->mmio_ba = paddr;
9860 	}
9861 #endif
9862 
9863 	/*
9864 	 *  Allocate the IRQ.
9865 	 */
9866 #ifdef FreeBSD_4_Bus
9867 	i = 0;
9868 	np->irq_res = bus_alloc_resource(dev, SYS_RES_IRQ, &i,
9869 					 0, ~0, 1, RF_ACTIVE | RF_SHAREABLE);
9870 	if (!np->irq_res) {
9871 		device_printf(dev, "failed to allocate IRQ resource\n");
9872 		goto attach_failed;
9873 	}
9874 #endif
9875 
9876 #ifdef	SYM_CONF_IOMAPPED
9877 	/*
9878 	 *  User want us to use normal IO with PCI.
9879 	 *  Alloc/get/map/retrieve everything that deals with IO.
9880 	 */
9881 #ifdef FreeBSD_4_Bus
9882 	if ((command & PCI_COMMAND_IO_ENABLE) != 0) {
9883 		int regs_id = SYM_PCI_IO;
9884 		np->io_res = bus_alloc_resource(dev, SYS_RES_IOPORT, &regs_id,
9885 						0, ~0, 1, RF_ACTIVE);
9886 	}
9887 	if (!np->io_res) {
9888 		device_printf(dev, "failed to allocate IO resources\n");
9889 		goto attach_failed;
9890 	}
9891 	np->io_bsh  = rman_get_bushandle(np->io_res);
9892 	np->io_tag  = rman_get_bustag(np->io_res);
9893 	np->io_port = rman_get_start(np->io_res);
9894 #else
9895 	if ((command & PCI_COMMAND_IO_ENABLE) != 0) {
9896 		pci_port_t io_port;
9897 		if (!pci_map_port (pci_tag, SYM_PCI_IO, &io_port)) {
9898 			printf("%s: failed to map IO window\n", sym_name(np));
9899 			goto attach_failed;
9900 		}
9901 		np->io_port = io_port;
9902 	}
9903 #endif
9904 
9905 #endif /* SYM_CONF_IOMAPPED */
9906 
9907 	/*
9908 	 *  If the chip has RAM.
9909 	 *  Alloc/get/map/retrieve the corresponding resources.
9910 	 */
9911 	if ((np->features & (FE_RAM|FE_RAM8K)) &&
9912 	    (command & PCIM_CMD_MEMEN) != 0) {
9913 #ifdef FreeBSD_4_Bus
9914 		int regs_id = SYM_PCI_RAM;
9915 		if (np->features & FE_64BIT)
9916 			regs_id = SYM_PCI_RAM64;
9917 		np->ram_res = bus_alloc_resource(dev, SYS_RES_MEMORY, &regs_id,
9918 						 0, ~0, 1, RF_ACTIVE);
9919 		if (!np->ram_res) {
9920 			device_printf(dev,"failed to allocate RAM resources\n");
9921 			goto attach_failed;
9922 		}
9923 		np->ram_id  = regs_id;
9924 		np->ram_bsh = rman_get_bushandle(np->ram_res);
9925 		np->ram_tag = rman_get_bustag(np->ram_res);
9926 		np->ram_pa  = rman_get_start(np->ram_res);
9927 		np->ram_va  = (vm_offset_t) rman_get_virtual(np->ram_res);
9928 		np->ram_ba  = np->ram_pa;
9929 #else
9930 		vm_offset_t vaddr, paddr;
9931 		int regs_id = SYM_PCI_RAM;
9932 		if (np->features & FE_64BIT)
9933 			regs_id = SYM_PCI_RAM64;
9934 		if (!pci_map_mem(pci_tag, regs_id, &vaddr, &paddr)) {
9935 			printf("%s: failed to map RAM window\n", sym_name(np));
9936 			goto attach_failed;
9937 		}
9938 		np->ram_va = vaddr;
9939 		np->ram_pa = paddr;
9940 		np->ram_ba = paddr;
9941 #endif
9942 	}
9943 
9944 	/*
9945 	 *  Save setting of some IO registers, so we will
9946 	 *  be able to probe specific implementations.
9947 	 */
9948 	sym_save_initial_setting (np);
9949 
9950 	/*
9951 	 *  Reset the chip now, since it has been reported
9952 	 *  that SCSI clock calibration may not work properly
9953 	 *  if the chip is currently active.
9954 	 */
9955 	sym_chip_reset (np);
9956 
9957 	/*
9958 	 *  Try to read the user set-up.
9959 	 */
9960 	(void) sym_read_nvram(np, &nvram);
9961 
9962 	/*
9963 	 *  Prepare controller and devices settings, according
9964 	 *  to chip features, user set-up and driver set-up.
9965 	 */
9966 	(void) sym_prepare_setting(np, &nvram);
9967 
9968 	/*
9969 	 *  Check the PCI clock frequency.
9970 	 *  Must be performed after prepare_setting since it destroys
9971 	 *  STEST1 that is used to probe for the clock doubler.
9972 	 */
9973 	i = sym_getpciclock(np);
9974 	if (i > 37000)
9975 #ifdef FreeBSD_4_Bus
9976 		device_printf(dev, "PCI BUS clock seems too high: %u KHz.\n",i);
9977 #else
9978 		printf("%s: PCI BUS clock seems too high: %u KHz.\n",
9979 			sym_name(np), i);
9980 #endif
9981 
9982 	/*
9983 	 *  Allocate the start queue.
9984 	 */
9985 	np->squeue = (u32 *) sym_calloc(sizeof(u32)*(MAX_QUEUE*2), "SQUEUE");
9986 	if (!np->squeue)
9987 		goto attach_failed;
9988 
9989 	/*
9990 	 *  Allocate the done queue.
9991 	 */
9992 	np->dqueue = (u32 *) sym_calloc(sizeof(u32)*(MAX_QUEUE*2), "DQUEUE");
9993 	if (!np->dqueue)
9994 		goto attach_failed;
9995 
9996 	/*
9997 	 *  Allocate the target bus address array.
9998 	 */
9999 	np->targtbl = (u32 *) sym_calloc(256, "TARGTBL");
10000 	if (!np->targtbl)
10001 		goto attach_failed;
10002 
10003 	/*
10004 	 *  Allocate SCRIPTS areas.
10005 	 */
10006 	np->script0  = (struct sym_scr *)
10007 			sym_calloc(sizeof(struct sym_scr), "SCRIPT0");
10008 	np->scripth0 = (struct sym_scrh *)
10009 			sym_calloc(sizeof(struct sym_scrh), "SCRIPTH0");
10010 	if (!np->script0 || !np->scripth0)
10011 		goto attach_failed;
10012 
10013 	/*
10014 	 *  Initialyze the CCB free and busy queues.
10015 	 *  Allocate some CCB. We need at least ONE.
10016 	 */
10017 	sym_que_init(&np->free_ccbq);
10018 	sym_que_init(&np->busy_ccbq);
10019 	sym_que_init(&np->comp_ccbq);
10020 	if (!sym_alloc_ccb(np))
10021 		goto attach_failed;
10022 
10023 	/*
10024 	 * Initialyze the CAM CCB pending queue.
10025 	 */
10026 	sym_que_init(&np->cam_ccbq);
10027 
10028 	/*
10029 	 *  Fill-up variable-size parts of the SCRIPTS.
10030 	 */
10031 	sym_fill_scripts(&script0, &scripth0);
10032 
10033 	/*
10034 	 *  Calculate BUS addresses where we are going
10035 	 *  to load the SCRIPTS.
10036 	 */
10037 	np->script_ba	= vtobus(np->script0);
10038 	np->scripth_ba	= vtobus(np->scripth0);
10039 	np->scripth0_ba	= np->scripth_ba;
10040 
10041 	if (np->ram_ba) {
10042 		np->script_ba	= np->ram_ba;
10043 		if (np->features & FE_RAM8K) {
10044 			np->ram_ws = 8192;
10045 			np->scripth_ba = np->script_ba + 4096;
10046 #if BITS_PER_LONG > 32
10047 			np->scr_ram_seg = cpu_to_scr(np->script_ba >> 32);
10048 #endif
10049 		}
10050 		else
10051 			np->ram_ws = 4096;
10052 	}
10053 
10054 	/*
10055 	 *  Bind SCRIPTS with physical addresses usable by the
10056 	 *  SCRIPTS processor (as seen from the BUS = BUS addresses).
10057 	 */
10058 	sym_bind_script(np, (u32 *) &script0,
10059 			    (u32 *) np->script0, sizeof(struct sym_scr));
10060 	sym_bind_script(np, (u32 *) &scripth0,
10061 			    (u32 *) np->scripth0, sizeof(struct sym_scrh));
10062 
10063 	/*
10064 	 *  If not 64 bit chip, patch some places in SCRIPTS.
10065 	 */
10066 	if (!(np->features & FE_64BIT)) {
10067 		np->scripth0->swide_fin_32[0] = cpu_to_scr(SCR_JUMP);
10068 		np->scripth0->swide_fin_32[1] =
10069 				cpu_to_scr(SCRIPT_BA(np, dispatch));
10070 	}
10071 
10072 	/*
10073 	 *  Patch some variables in SCRIPTS.
10074 	 *  These ones are loaded by the SCRIPTS processor.
10075 	 */
10076 	np->scripth0->pm0_data_addr[0] = cpu_to_scr(SCRIPT_BA(np,pm0_data));
10077 	np->scripth0->pm1_data_addr[0] = cpu_to_scr(SCRIPT_BA(np,pm1_data));
10078 
10079 
10080 	/*
10081 	 *  Still some for LED support.
10082 	 */
10083 	if (np->features & FE_LED0) {
10084 		np->script0->idle[0]  =
10085 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
10086 		np->script0->reselected[0] =
10087 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
10088 		np->script0->start[0] =
10089 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
10090 	}
10091 
10092 	/*
10093 	 *  Load SCNTL4 on reselection for the C10.
10094 	 */
10095 	if (np->features & FE_C10) {
10096 		np->script0->resel_scntl4[0] =
10097 				cpu_to_scr(SCR_LOAD_REL (scntl4, 1));
10098 		np->script0->resel_scntl4[1] =
10099 				cpu_to_scr(offsetof(struct sym_tcb, uval));
10100 	}
10101 
10102 #ifdef SYM_CONF_IARB_SUPPORT
10103 	/*
10104 	 *    If user does not want to use IMMEDIATE ARBITRATION
10105 	 *    when we are reselected while attempting to arbitrate,
10106 	 *    patch the SCRIPTS accordingly with a SCRIPT NO_OP.
10107 	 */
10108 	if (!SYM_CONF_SET_IARB_ON_ARB_LOST)
10109 		np->script0->ungetjob[0] = cpu_to_scr(SCR_NO_OP);
10110 
10111 	/*
10112 	 *    If user wants IARB to be set when we win arbitration
10113 	 *    and have other jobs, compute the max number of consecutive
10114 	 *    settings of IARB hints before we leave devices a chance to
10115 	 *    arbitrate for reselection.
10116 	 */
10117 #ifdef	SYM_SETUP_IARB_MAX
10118 	np->iarb_max = SYM_SETUP_IARB_MAX;
10119 #else
10120 	np->iarb_max = 4;
10121 #endif
10122 #endif
10123 
10124 	/*
10125 	 *  Prepare the idle and invalid task actions.
10126 	 */
10127 	np->idletask.start	= cpu_to_scr(SCRIPT_BA(np, idle));
10128 	np->idletask.restart	= cpu_to_scr(SCRIPTH_BA(np, bad_i_t_l));
10129 	np->idletask_ba		= vtobus(&np->idletask);
10130 
10131 	np->notask.start	= cpu_to_scr(SCRIPT_BA(np, idle));
10132 	np->notask.restart	= cpu_to_scr(SCRIPTH_BA(np, bad_i_t_l));
10133 	np->notask_ba		= vtobus(&np->notask);
10134 
10135 	np->bad_itl.start	= cpu_to_scr(SCRIPT_BA(np, idle));
10136 	np->bad_itl.restart	= cpu_to_scr(SCRIPTH_BA(np, bad_i_t_l));
10137 	np->bad_itl_ba		= vtobus(&np->bad_itl);
10138 
10139 	np->bad_itlq.start	= cpu_to_scr(SCRIPT_BA(np, idle));
10140 	np->bad_itlq.restart	= cpu_to_scr(SCRIPTH_BA (np,bad_i_t_l_q));
10141 	np->bad_itlq_ba		= vtobus(&np->bad_itlq);
10142 
10143 	/*
10144 	 *  Allocate and prepare the lun JUMP table that is used
10145 	 *  for a target prior the probing of devices (bad lun table).
10146 	 *  A private table will be allocated for the target on the
10147 	 *  first INQUIRY response received.
10148 	 */
10149 	np->badluntbl = sym_calloc(256, "BADLUNTBL");
10150 	if (!np->badluntbl)
10151 		goto attach_failed;
10152 
10153 	np->badlun_sa = cpu_to_scr(SCRIPTH_BA(np, resel_bad_lun));
10154 	for (i = 0 ; i < 64 ; i++)	/* 64 luns/target, no less */
10155 		np->badluntbl[i] = cpu_to_scr(vtobus(&np->badlun_sa));
10156 
10157 	/*
10158 	 *  Prepare the bus address array that contains the bus
10159 	 *  address of each target control bloc.
10160 	 *  For now, assume all logical unit are wrong. :)
10161 	 */
10162 	np->scripth0->targtbl[0] = cpu_to_scr(vtobus(np->targtbl));
10163 	for (i = 0 ; i < SYM_CONF_MAX_TARGET ; i++) {
10164 		np->targtbl[i] = cpu_to_scr(vtobus(&np->target[i]));
10165 		np->target[i].luntbl_sa = cpu_to_scr(vtobus(np->badluntbl));
10166 		np->target[i].lun0_sa = cpu_to_scr(vtobus(&np->badlun_sa));
10167 	}
10168 
10169 	/*
10170 	 *  Now check the cache handling of the pci chipset.
10171 	 */
10172 	if (sym_snooptest (np)) {
10173 #ifdef FreeBSD_4_Bus
10174 		device_printf(dev, "CACHE INCORRECTLY CONFIGURED.\n");
10175 #else
10176 		printf("%s: CACHE INCORRECTLY CONFIGURED.\n", sym_name(np));
10177 #endif
10178 		goto attach_failed;
10179 	};
10180 
10181 	/*
10182 	 *  Now deal with CAM.
10183 	 *  Hopefully, we will succeed with that one.:)
10184 	 */
10185 	if (!sym_cam_attach(np))
10186 		goto attach_failed;
10187 
10188 	/*
10189 	 *  Sigh! we are done.
10190 	 */
10191 	return 0;
10192 
10193 	/*
10194 	 *  We have failed.
10195 	 *  We will try to free all the resources we have
10196 	 *  allocated, but if we are a boot device, this
10197 	 *  will not help that much.;)
10198 	 */
10199 attach_failed:
10200 	if (np)
10201 		sym_pci_free(np);
10202 	return ENXIO;
10203 }
10204 
10205 /*
10206  *  Free everything that have been allocated for this device.
10207  */
10208 static void sym_pci_free(hcb_p np)
10209 {
10210 	SYM_QUEHEAD *qp;
10211 	ccb_p cp;
10212 	tcb_p tp;
10213 	lcb_p lp;
10214 	int target, lun;
10215 	int s;
10216 
10217 	/*
10218 	 *  First free CAM resources.
10219 	 */
10220 	s = splcam();
10221 	sym_cam_free(np);
10222 	splx(s);
10223 
10224 	/*
10225 	 *  Now every should be quiet for us to
10226 	 *  free other resources.
10227 	 */
10228 #ifdef FreeBSD_4_Bus
10229 	if (np->ram_res)
10230 		bus_release_resource(np->device, SYS_RES_MEMORY,
10231 				     np->ram_id, np->ram_res);
10232 	if (np->mmio_res)
10233 		bus_release_resource(np->device, SYS_RES_MEMORY,
10234 				     SYM_PCI_MMIO, np->mmio_res);
10235 	if (np->io_res)
10236 		bus_release_resource(np->device, SYS_RES_IOPORT,
10237 				     SYM_PCI_IO, np->io_res);
10238 	if (np->irq_res)
10239 		bus_release_resource(np->device, SYS_RES_IRQ,
10240 				     0, np->irq_res);
10241 #else
10242 	/*
10243 	 *  YEAH!!!
10244 	 *  It seems there is no means to free MMIO resources.
10245 	 */
10246 #endif
10247 
10248 	if (np->scripth0)
10249 		sym_mfree(np->scripth0, sizeof(struct sym_scrh), "SCRIPTH0");
10250 	if (np->script0)
10251 		sym_mfree(np->script0, sizeof(struct sym_scr), "SCRIPT0");
10252 	if (np->squeue)
10253 		sym_mfree(np->squeue, sizeof(u32)*(MAX_QUEUE*2), "SQUEUE");
10254 	if (np->dqueue)
10255 		sym_mfree(np->dqueue, sizeof(u32)*(MAX_QUEUE*2), "DQUEUE");
10256 
10257 	while ((qp = sym_remque_head(&np->free_ccbq)) != 0) {
10258 		cp = sym_que_entry(qp, struct sym_ccb, link_ccbq);
10259 		sym_mfree(cp, sizeof(*cp), "CCB");
10260 	}
10261 
10262 	if (np->badluntbl)
10263 		sym_mfree(np->badluntbl, 256,"BADLUNTBL");
10264 
10265 	for (target = 0; target < SYM_CONF_MAX_TARGET ; target++) {
10266 		tp = &np->target[target];
10267 		for (lun = 0 ; lun < SYM_CONF_MAX_LUN ; lun++) {
10268 			lp = sym_lp(np, tp, lun);
10269 			if (!lp)
10270 				continue;
10271 			if (lp->itlq_tbl)
10272 				sym_mfree(lp->itlq_tbl, SYM_CONF_MAX_TASK*4,
10273 				       "ITLQ_TBL");
10274 			if (lp->cb_tags)
10275 				sym_mfree(lp->cb_tags, SYM_CONF_MAX_TASK,
10276 				       "CB_TAGS");
10277 			sym_mfree(lp, sizeof(*lp), "LCB");
10278 		}
10279 #if SYM_CONF_MAX_LUN > 1
10280 		if (tp->lunmp)
10281 			sym_mfree(tp->lunmp, SYM_CONF_MAX_LUN*sizeof(lcb_p),
10282 			       "LUNMP");
10283 #endif
10284 	}
10285 
10286 	sym_mfree(np, sizeof(*np), "HCB");
10287 }
10288 
10289 /*
10290  *  Allocate CAM resources and register a bus to CAM.
10291  */
10292 int sym_cam_attach(hcb_p np)
10293 {
10294 	struct cam_devq *devq = 0;
10295 	struct cam_sim *sim = 0;
10296 	struct cam_path *path = 0;
10297 	int err, s;
10298 
10299 	s = splcam();
10300 
10301 	/*
10302 	 *  Establish our interrupt handler.
10303 	 */
10304 #ifdef FreeBSD_4_Bus
10305 	err = bus_setup_intr(np->device, np->irq_res, INTR_TYPE_CAM,
10306 			     sym_intr, np, &np->intr);
10307 	if (err) {
10308 		device_printf(np->device, "bus_setup_intr() failed: %d\n",
10309 			      err);
10310 		goto fail;
10311 	}
10312 #else
10313 	if (!pci_map_int (np->pci_tag, sym_intr, np, &cam_imask)) {
10314 		printf("%s: failed to map interrupt\n", sym_name(np));
10315 		goto fail;
10316 	}
10317 #endif
10318 
10319 	/*
10320 	 *  Create the device queue for our sym SIM.
10321 	 */
10322 	devq = cam_simq_alloc(SYM_CONF_MAX_START);
10323 	if (!devq)
10324 		goto fail;
10325 
10326 	/*
10327 	 *  Construct our SIM entry.
10328 	 */
10329 	sim = cam_sim_alloc(sym_action, sym_poll, "sym", np, np->unit,
10330 			    1, SYM_SETUP_MAX_TAG, devq);
10331 	if (!sim)
10332 		goto fail;
10333 	devq = 0;
10334 
10335 	if (xpt_bus_register(sim, 0) != CAM_SUCCESS)
10336 		goto fail;
10337 	np->sim = sim;
10338 	sim = 0;
10339 
10340 	if (xpt_create_path(&path, 0,
10341 			    cam_sim_path(np->sim), CAM_TARGET_WILDCARD,
10342 			    CAM_LUN_WILDCARD) != CAM_REQ_CMP) {
10343 		goto fail;
10344 	}
10345 	np->path = path;
10346 
10347 	/*
10348 	 *  Hmmm... This should be useful, but I donnot want to
10349 	 *  know about.
10350 	 */
10351 #if 	__FreeBSD_version < 400000
10352 #ifdef	__alpha__
10353 #ifdef	FreeBSD_4_Bus
10354 	alpha_register_pci_scsi(pci_get_bus(np->device),
10355 				pci_get_slot(np->device), np->sim);
10356 #else
10357 	alpha_register_pci_scsi(pci_tag->bus, pci_tag->slot, np->sim);
10358 #endif
10359 #endif
10360 #endif
10361 
10362 #if 0
10363 	/*
10364 	 *  Establish our async notification handler.
10365 	 */
10366 	{
10367 	struct ccb_setasync csa;
10368 	xpt_setup_ccb(&csa.ccb_h, np->path, 5);
10369 	csa.ccb_h.func_code = XPT_SASYNC_CB;
10370 	csa.event_enable    = AC_LOST_DEVICE;
10371 	csa.callback	    = sym_async;
10372 	csa.callback_arg    = np->sim;
10373 	xpt_action((union ccb *)&csa);
10374 	}
10375 #endif
10376 	/*
10377 	 *  Start the chip now, without resetting the BUS, since
10378 	 *  it seems that this must stay under control of CAM.
10379 	 *  With LVD/SE capable chips and BUS in SE mode, we may
10380 	 *  get a spurious SMBC interrupt.
10381 	 */
10382 	sym_init (np, 0);
10383 
10384 	splx(s);
10385 	return 1;
10386 fail:
10387 	if (sim)
10388 		cam_sim_free(sim, FALSE);
10389 	if (devq)
10390 		cam_simq_free(devq);
10391 
10392 	sym_cam_free(np);
10393 
10394 	splx(s);
10395 	return 0;
10396 }
10397 
10398 /*
10399  *  Free everything that deals with CAM.
10400  */
10401 void sym_cam_free(hcb_p np)
10402 {
10403 #ifdef FreeBSD_4_Bus
10404 	if (np->intr)
10405 		bus_teardown_intr(np->device, np->irq_res, np->intr);
10406 #else
10407 	/* pci_unmap_int(np->pci_tag); */	/* Does nothing */
10408 #endif
10409 
10410 	if (np->sim) {
10411 		xpt_bus_deregister(cam_sim_path(np->sim));
10412 		cam_sim_free(np->sim, /*free_devq*/ TRUE);
10413 	}
10414 	if (np->path)
10415 		xpt_free_path(np->path);
10416 }
10417 
10418 /*============ OPTIONNAL NVRAM SUPPORT =================*/
10419 
10420 /*
10421  *  Get host setup from NVRAM.
10422  */
10423 static void sym_nvram_setup_host (hcb_p np, struct sym_nvram *nvram)
10424 {
10425 #ifdef SYM_CONF_NVRAM_SUPPORT
10426 	/*
10427 	 *  Get parity checking, host ID, verbose mode
10428 	 *  and miscellaneous host flags from NVRAM.
10429 	 */
10430 	switch(nvram->type) {
10431 	case SYM_SYMBIOS_NVRAM:
10432 		if (!(nvram->data.Symbios.flags & SYMBIOS_PARITY_ENABLE))
10433 			np->rv_scntl0  &= ~0x0a;
10434 		np->myaddr = nvram->data.Symbios.host_id & 0x0f;
10435 		if (nvram->data.Symbios.flags & SYMBIOS_VERBOSE_MSGS)
10436 			np->verbose += 1;
10437 		if (nvram->data.Symbios.flags1 & SYMBIOS_SCAN_HI_LO)
10438 			np->usrflags |= SYM_SCAN_TARGETS_HILO;
10439 		if (nvram->data.Symbios.flags2 & SYMBIOS_AVOID_BUS_RESET)
10440 			np->usrflags |= SYM_AVOID_BUS_RESET;
10441 		break;
10442 	case SYM_TEKRAM_NVRAM:
10443 		np->myaddr = nvram->data.Tekram.host_id & 0x0f;
10444 		break;
10445 	default:
10446 		break;
10447 	}
10448 #endif
10449 }
10450 
10451 /*
10452  *  Get target setup from NVRAM.
10453  */
10454 #ifdef SYM_CONF_NVRAM_SUPPORT
10455 static void sym_Symbios_setup_target(hcb_p np,int target, Symbios_nvram *nvram);
10456 static void sym_Tekram_setup_target(hcb_p np,int target, Tekram_nvram *nvram);
10457 #endif
10458 
10459 static void
10460 sym_nvram_setup_target (hcb_p np, int target, struct sym_nvram *nvp)
10461 {
10462 #ifdef SYM_CONF_NVRAM_SUPPORT
10463 	switch(nvp->type) {
10464 	case SYM_SYMBIOS_NVRAM:
10465 		sym_Symbios_setup_target (np, target, &nvp->data.Symbios);
10466 		break;
10467 	case SYM_TEKRAM_NVRAM:
10468 		sym_Tekram_setup_target (np, target, &nvp->data.Tekram);
10469 		break;
10470 	default:
10471 		break;
10472 	}
10473 #endif
10474 }
10475 
10476 #ifdef SYM_CONF_NVRAM_SUPPORT
10477 /*
10478  *  Get target set-up from Symbios format NVRAM.
10479  */
10480 static void
10481 sym_Symbios_setup_target(hcb_p np, int target, Symbios_nvram *nvram)
10482 {
10483 	tcb_p tp = &np->target[target];
10484 	Symbios_target *tn = &nvram->target[target];
10485 
10486 	tp->tinfo.user.period = tn->sync_period ? (tn->sync_period + 3) / 4 : 0;
10487 	tp->tinfo.user.width  = tn->bus_width == 0x10 ? BUS_16_BIT : BUS_8_BIT;
10488 	tp->usrtags =
10489 		(tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? SYM_SETUP_MAX_TAG : 0;
10490 
10491 	if (!(tn->flags & SYMBIOS_DISCONNECT_ENABLE))
10492 		tp->usrflags &= ~SYM_DISC_ENABLED;
10493 	if (!(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME))
10494 		tp->usrflags |= SYM_SCAN_BOOT_DISABLED;
10495 	if (!(tn->flags & SYMBIOS_SCAN_LUNS))
10496 		tp->usrflags |= SYM_SCAN_LUNS_DISABLED;
10497 }
10498 
10499 /*
10500  *  Get target set-up from Tekram format NVRAM.
10501  */
10502 static void
10503 sym_Tekram_setup_target(hcb_p np, int target, Tekram_nvram *nvram)
10504 {
10505 	tcb_p tp = &np->target[target];
10506 	struct Tekram_target *tn = &nvram->target[target];
10507 	int i;
10508 
10509 	if (tn->flags & TEKRAM_SYNC_NEGO) {
10510 		i = tn->sync_index & 0xf;
10511 		tp->tinfo.user.period = Tekram_sync[i];
10512 	}
10513 
10514 	tp->tinfo.user.width =
10515 		(tn->flags & TEKRAM_WIDE_NEGO) ? BUS_16_BIT : BUS_8_BIT;
10516 
10517 	if (tn->flags & TEKRAM_TAGGED_COMMANDS) {
10518 		tp->usrtags = 2 << nvram->max_tags_index;
10519 	}
10520 
10521 	if (tn->flags & TEKRAM_DISCONNECT_ENABLE)
10522 		tp->usrflags |= SYM_DISC_ENABLED;
10523 
10524 	/* If any device does not support parity, we will not use this option */
10525 	if (!(tn->flags & TEKRAM_PARITY_CHECK))
10526 		np->rv_scntl0  &= ~0x0a; /* SCSI parity checking disabled */
10527 }
10528 
10529 #ifdef	SYM_CONF_DEBUG_NVRAM
10530 /*
10531  *  Dump Symbios format NVRAM for debugging purpose.
10532  */
10533 void sym_display_Symbios_nvram(hcb_p np, Symbios_nvram *nvram)
10534 {
10535 	int i;
10536 
10537 	/* display Symbios nvram host data */
10538 	printf("%s: HOST ID=%d%s%s%s%s%s%s\n",
10539 		sym_name(np), nvram->host_id & 0x0f,
10540 		(nvram->flags  & SYMBIOS_SCAM_ENABLE)	? " SCAM"	:"",
10541 		(nvram->flags  & SYMBIOS_PARITY_ENABLE)	? " PARITY"	:"",
10542 		(nvram->flags  & SYMBIOS_VERBOSE_MSGS)	? " VERBOSE"	:"",
10543 		(nvram->flags  & SYMBIOS_CHS_MAPPING)	? " CHS_ALT"	:"",
10544 		(nvram->flags2 & SYMBIOS_AVOID_BUS_RESET)?" NO_RESET"	:"",
10545 		(nvram->flags1 & SYMBIOS_SCAN_HI_LO)	? " HI_LO"	:"");
10546 
10547 	/* display Symbios nvram drive data */
10548 	for (i = 0 ; i < 15 ; i++) {
10549 		struct Symbios_target *tn = &nvram->target[i];
10550 		printf("%s-%d:%s%s%s%s WIDTH=%d SYNC=%d TMO=%d\n",
10551 		sym_name(np), i,
10552 		(tn->flags & SYMBIOS_DISCONNECT_ENABLE)	? " DISC"	: "",
10553 		(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME)	? " SCAN_BOOT"	: "",
10554 		(tn->flags & SYMBIOS_SCAN_LUNS)		? " SCAN_LUNS"	: "",
10555 		(tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? " TCQ"	: "",
10556 		tn->bus_width,
10557 		tn->sync_period / 4,
10558 		tn->timeout);
10559 	}
10560 }
10561 
10562 /*
10563  *  Dump TEKRAM format NVRAM for debugging purpose.
10564  */
10565 static u_char Tekram_boot_delay[7] __initdata = {3, 5, 10, 20, 30, 60, 120};
10566 void sym_display_Tekram_nvram(hcb_p np, Tekram_nvram *nvram)
10567 {
10568 	int i, tags, boot_delay;
10569 	char *rem;
10570 
10571 	/* display Tekram nvram host data */
10572 	tags = 2 << nvram->max_tags_index;
10573 	boot_delay = 0;
10574 	if (nvram->boot_delay_index < 6)
10575 		boot_delay = Tekram_boot_delay[nvram->boot_delay_index];
10576 	switch((nvram->flags & TEKRAM_REMOVABLE_FLAGS) >> 6) {
10577 	default:
10578 	case 0:	rem = "";			break;
10579 	case 1: rem = " REMOVABLE=boot device";	break;
10580 	case 2: rem = " REMOVABLE=all";		break;
10581 	}
10582 
10583 	printf("%s: HOST ID=%d%s%s%s%s%s%s%s%s%s BOOT DELAY=%d tags=%d\n",
10584 		sym_name(np), nvram->host_id & 0x0f,
10585 		(nvram->flags1 & SYMBIOS_SCAM_ENABLE)	? " SCAM"	:"",
10586 		(nvram->flags & TEKRAM_MORE_THAN_2_DRIVES) ? " >2DRIVES"	:"",
10587 		(nvram->flags & TEKRAM_DRIVES_SUP_1GB)	? " >1GB"	:"",
10588 		(nvram->flags & TEKRAM_RESET_ON_POWER_ON) ? " RESET"	:"",
10589 		(nvram->flags & TEKRAM_ACTIVE_NEGATION)	? " ACT_NEG"	:"",
10590 		(nvram->flags & TEKRAM_IMMEDIATE_SEEK)	? " IMM_SEEK"	:"",
10591 		(nvram->flags & TEKRAM_SCAN_LUNS)	? " SCAN_LUNS"	:"",
10592 		(nvram->flags1 & TEKRAM_F2_F6_ENABLED)	? " F2_F6"	:"",
10593 		rem, boot_delay, tags);
10594 
10595 	/* display Tekram nvram drive data */
10596 	for (i = 0; i <= 15; i++) {
10597 		int sync, j;
10598 		struct Tekram_target *tn = &nvram->target[i];
10599 		j = tn->sync_index & 0xf;
10600 		sync = Tekram_sync[j];
10601 		printf("%s-%d:%s%s%s%s%s%s PERIOD=%d\n",
10602 		sym_name(np), i,
10603 		(tn->flags & TEKRAM_PARITY_CHECK)	? " PARITY"	: "",
10604 		(tn->flags & TEKRAM_SYNC_NEGO)		? " SYNC"	: "",
10605 		(tn->flags & TEKRAM_DISCONNECT_ENABLE)	? " DISC"	: "",
10606 		(tn->flags & TEKRAM_START_CMD)		? " START"	: "",
10607 		(tn->flags & TEKRAM_TAGGED_COMMANDS)	? " TCQ"	: "",
10608 		(tn->flags & TEKRAM_WIDE_NEGO)		? " WIDE"	: "",
10609 		sync);
10610 	}
10611 }
10612 #endif	/* SYM_CONF_DEBUG_NVRAM */
10613 #endif	/* SYM_CONF_NVRAM_SUPPORT */
10614 
10615 
10616 /*
10617  *  Try reading Symbios or Tekram NVRAM
10618  */
10619 #ifdef SYM_CONF_NVRAM_SUPPORT
10620 static int sym_read_Symbios_nvram (hcb_p np, Symbios_nvram *nvram);
10621 static int sym_read_Tekram_nvram  (hcb_p np, Tekram_nvram *nvram);
10622 #endif
10623 
10624 int sym_read_nvram(hcb_p np, struct sym_nvram *nvp)
10625 {
10626 #ifdef SYM_CONF_NVRAM_SUPPORT
10627 	/*
10628 	 *  Try to read SYMBIOS nvram.
10629 	 *  Try to read TEKRAM nvram if Symbios nvram not found.
10630 	 */
10631 	if	(SYM_SETUP_SYMBIOS_NVRAM &&
10632 		 !sym_read_Symbios_nvram (np, &nvp->data.Symbios))
10633 		nvp->type = SYM_SYMBIOS_NVRAM;
10634 	else if	(SYM_SETUP_TEKRAM_NVRAM &&
10635 		 !sym_read_Tekram_nvram (np, &nvp->data.Tekram))
10636 		nvp->type = SYM_TEKRAM_NVRAM;
10637 	else
10638 		nvp->type = 0;
10639 #else
10640 	nvp->type = 0;
10641 #endif
10642 	return nvp->type;
10643 }
10644 
10645 
10646 #ifdef SYM_CONF_NVRAM_SUPPORT
10647 /*
10648  *  24C16 EEPROM reading.
10649  *
10650  *  GPOI0 - data in/data out
10651  *  GPIO1 - clock
10652  *  Symbios NVRAM wiring now also used by Tekram.
10653  */
10654 
10655 #define SET_BIT 0
10656 #define CLR_BIT 1
10657 #define SET_CLK 2
10658 #define CLR_CLK 3
10659 
10660 /*
10661  *  Set/clear data/clock bit in GPIO0
10662  */
10663 static void S24C16_set_bit(hcb_p np, u_char write_bit, u_char *gpreg,
10664 			  int bit_mode)
10665 {
10666 	UDELAY (5);
10667 	switch (bit_mode){
10668 	case SET_BIT:
10669 		*gpreg |= write_bit;
10670 		break;
10671 	case CLR_BIT:
10672 		*gpreg &= 0xfe;
10673 		break;
10674 	case SET_CLK:
10675 		*gpreg |= 0x02;
10676 		break;
10677 	case CLR_CLK:
10678 		*gpreg &= 0xfd;
10679 		break;
10680 
10681 	}
10682 	OUTB (nc_gpreg, *gpreg);
10683 	UDELAY (5);
10684 }
10685 
10686 /*
10687  *  Send START condition to NVRAM to wake it up.
10688  */
10689 static void S24C16_start(hcb_p np, u_char *gpreg)
10690 {
10691 	S24C16_set_bit(np, 1, gpreg, SET_BIT);
10692 	S24C16_set_bit(np, 0, gpreg, SET_CLK);
10693 	S24C16_set_bit(np, 0, gpreg, CLR_BIT);
10694 	S24C16_set_bit(np, 0, gpreg, CLR_CLK);
10695 }
10696 
10697 /*
10698  *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZzzzz!!
10699  */
10700 static void S24C16_stop(hcb_p np, u_char *gpreg)
10701 {
10702 	S24C16_set_bit(np, 0, gpreg, SET_CLK);
10703 	S24C16_set_bit(np, 1, gpreg, SET_BIT);
10704 }
10705 
10706 /*
10707  *  Read or write a bit to the NVRAM,
10708  *  read if GPIO0 input else write if GPIO0 output
10709  */
10710 static void S24C16_do_bit(hcb_p np, u_char *read_bit, u_char write_bit,
10711 			 u_char *gpreg)
10712 {
10713 	S24C16_set_bit(np, write_bit, gpreg, SET_BIT);
10714 	S24C16_set_bit(np, 0, gpreg, SET_CLK);
10715 	if (read_bit)
10716 		*read_bit = INB (nc_gpreg);
10717 	S24C16_set_bit(np, 0, gpreg, CLR_CLK);
10718 	S24C16_set_bit(np, 0, gpreg, CLR_BIT);
10719 }
10720 
10721 /*
10722  *  Output an ACK to the NVRAM after reading,
10723  *  change GPIO0 to output and when done back to an input
10724  */
10725 static void S24C16_write_ack(hcb_p np, u_char write_bit, u_char *gpreg,
10726 			    u_char *gpcntl)
10727 {
10728 	OUTB (nc_gpcntl, *gpcntl & 0xfe);
10729 	S24C16_do_bit(np, 0, write_bit, gpreg);
10730 	OUTB (nc_gpcntl, *gpcntl);
10731 }
10732 
10733 /*
10734  *  Input an ACK from NVRAM after writing,
10735  *  change GPIO0 to input and when done back to an output
10736  */
10737 static void S24C16_read_ack(hcb_p np, u_char *read_bit, u_char *gpreg,
10738 			   u_char *gpcntl)
10739 {
10740 	OUTB (nc_gpcntl, *gpcntl | 0x01);
10741 	S24C16_do_bit(np, read_bit, 1, gpreg);
10742 	OUTB (nc_gpcntl, *gpcntl);
10743 }
10744 
10745 /*
10746  *  WRITE a byte to the NVRAM and then get an ACK to see it was accepted OK,
10747  *  GPIO0 must already be set as an output
10748  */
10749 static void S24C16_write_byte(hcb_p np, u_char *ack_data, u_char write_data,
10750 			     u_char *gpreg, u_char *gpcntl)
10751 {
10752 	int x;
10753 
10754 	for (x = 0; x < 8; x++)
10755 		S24C16_do_bit(np, 0, (write_data >> (7 - x)) & 0x01, gpreg);
10756 
10757 	S24C16_read_ack(np, ack_data, gpreg, gpcntl);
10758 }
10759 
10760 /*
10761  *  READ a byte from the NVRAM and then send an ACK to say we have got it,
10762  *  GPIO0 must already be set as an input
10763  */
10764 static void S24C16_read_byte(hcb_p np, u_char *read_data, u_char ack_data,
10765 			    u_char *gpreg, u_char *gpcntl)
10766 {
10767 	int x;
10768 	u_char read_bit;
10769 
10770 	*read_data = 0;
10771 	for (x = 0; x < 8; x++) {
10772 		S24C16_do_bit(np, &read_bit, 1, gpreg);
10773 		*read_data |= ((read_bit & 0x01) << (7 - x));
10774 	}
10775 
10776 	S24C16_write_ack(np, ack_data, gpreg, gpcntl);
10777 }
10778 
10779 /*
10780  *  Read 'len' bytes starting at 'offset'.
10781  */
10782 static int sym_read_S24C16_nvram (hcb_p np, int offset, u_char *data, int len)
10783 {
10784 	u_char	gpcntl, gpreg;
10785 	u_char	old_gpcntl, old_gpreg;
10786 	u_char	ack_data;
10787 	int	retv = 1;
10788 	int	x;
10789 
10790 	/* save current state of GPCNTL and GPREG */
10791 	old_gpreg	= INB (nc_gpreg);
10792 	old_gpcntl	= INB (nc_gpcntl);
10793 	gpcntl		= old_gpcntl & 0xfc;
10794 
10795 	/* set up GPREG & GPCNTL to set GPIO0 and GPIO1 in to known state */
10796 	OUTB (nc_gpreg,  old_gpreg);
10797 	OUTB (nc_gpcntl, gpcntl);
10798 
10799 	/* this is to set NVRAM into a known state with GPIO0/1 both low */
10800 	gpreg = old_gpreg;
10801 	S24C16_set_bit(np, 0, &gpreg, CLR_CLK);
10802 	S24C16_set_bit(np, 0, &gpreg, CLR_BIT);
10803 
10804 	/* now set NVRAM inactive with GPIO0/1 both high */
10805 	S24C16_stop(np, &gpreg);
10806 
10807 	/* activate NVRAM */
10808 	S24C16_start(np, &gpreg);
10809 
10810 	/* write device code and random address MSB */
10811 	S24C16_write_byte(np, &ack_data,
10812 		0xa0 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
10813 	if (ack_data & 0x01)
10814 		goto out;
10815 
10816 	/* write random address LSB */
10817 	S24C16_write_byte(np, &ack_data,
10818 		offset & 0xff, &gpreg, &gpcntl);
10819 	if (ack_data & 0x01)
10820 		goto out;
10821 
10822 	/* regenerate START state to set up for reading */
10823 	S24C16_start(np, &gpreg);
10824 
10825 	/* rewrite device code and address MSB with read bit set (lsb = 0x01) */
10826 	S24C16_write_byte(np, &ack_data,
10827 		0xa1 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
10828 	if (ack_data & 0x01)
10829 		goto out;
10830 
10831 	/* now set up GPIO0 for inputting data */
10832 	gpcntl |= 0x01;
10833 	OUTB (nc_gpcntl, gpcntl);
10834 
10835 	/* input all requested data - only part of total NVRAM */
10836 	for (x = 0; x < len; x++)
10837 		S24C16_read_byte(np, &data[x], (x == (len-1)), &gpreg, &gpcntl);
10838 
10839 	/* finally put NVRAM back in inactive mode */
10840 	gpcntl &= 0xfe;
10841 	OUTB (nc_gpcntl, gpcntl);
10842 	S24C16_stop(np, &gpreg);
10843 	retv = 0;
10844 out:
10845 	/* return GPIO0/1 to original states after having accessed NVRAM */
10846 	OUTB (nc_gpcntl, old_gpcntl);
10847 	OUTB (nc_gpreg,  old_gpreg);
10848 
10849 	return retv;
10850 }
10851 
10852 #undef SET_BIT 0
10853 #undef CLR_BIT 1
10854 #undef SET_CLK 2
10855 #undef CLR_CLK 3
10856 
10857 /*
10858  *  Try reading Symbios NVRAM.
10859  *  Return 0 if OK.
10860  */
10861 static int sym_read_Symbios_nvram (hcb_p np, Symbios_nvram *nvram)
10862 {
10863 	static u_char Symbios_trailer[6] = {0xfe, 0xfe, 0, 0, 0, 0};
10864 	u_char *data = (u_char *) nvram;
10865 	int len  = sizeof(*nvram);
10866 	u_short	csum;
10867 	int x;
10868 
10869 	/* probe the 24c16 and read the SYMBIOS 24c16 area */
10870 	if (sym_read_S24C16_nvram (np, SYMBIOS_NVRAM_ADDRESS, data, len))
10871 		return 1;
10872 
10873 	/* check valid NVRAM signature, verify byte count and checksum */
10874 	if (nvram->type != 0 ||
10875 	    bcmp(nvram->trailer, Symbios_trailer, 6) ||
10876 	    nvram->byte_count != len - 12)
10877 		return 1;
10878 
10879 	/* verify checksum */
10880 	for (x = 6, csum = 0; x < len - 6; x++)
10881 		csum += data[x];
10882 	if (csum != nvram->checksum)
10883 		return 1;
10884 
10885 	return 0;
10886 }
10887 
10888 /*
10889  *  93C46 EEPROM reading.
10890  *
10891  *  GPOI0 - data in
10892  *  GPIO1 - data out
10893  *  GPIO2 - clock
10894  *  GPIO4 - chip select
10895  *
10896  *  Used by Tekram.
10897  */
10898 
10899 /*
10900  *  Pulse clock bit in GPIO0
10901  */
10902 static void T93C46_Clk(hcb_p np, u_char *gpreg)
10903 {
10904 	OUTB (nc_gpreg, *gpreg | 0x04);
10905 	UDELAY (2);
10906 	OUTB (nc_gpreg, *gpreg);
10907 }
10908 
10909 /*
10910  *  Read bit from NVRAM
10911  */
10912 static void T93C46_Read_Bit(hcb_p np, u_char *read_bit, u_char *gpreg)
10913 {
10914 	UDELAY (2);
10915 	T93C46_Clk(np, gpreg);
10916 	*read_bit = INB (nc_gpreg);
10917 }
10918 
10919 /*
10920  *  Write bit to GPIO0
10921  */
10922 static void T93C46_Write_Bit(hcb_p np, u_char write_bit, u_char *gpreg)
10923 {
10924 	if (write_bit & 0x01)
10925 		*gpreg |= 0x02;
10926 	else
10927 		*gpreg &= 0xfd;
10928 
10929 	*gpreg |= 0x10;
10930 
10931 	OUTB (nc_gpreg, *gpreg);
10932 	UDELAY (2);
10933 
10934 	T93C46_Clk(np, gpreg);
10935 }
10936 
10937 /*
10938  *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZZzzz!!
10939  */
10940 static void T93C46_Stop(hcb_p np, u_char *gpreg)
10941 {
10942 	*gpreg &= 0xef;
10943 	OUTB (nc_gpreg, *gpreg);
10944 	UDELAY (2);
10945 
10946 	T93C46_Clk(np, gpreg);
10947 }
10948 
10949 /*
10950  *  Send read command and address to NVRAM
10951  */
10952 static void T93C46_Send_Command(hcb_p np, u_short write_data,
10953 				u_char *read_bit, u_char *gpreg)
10954 {
10955 	int x;
10956 
10957 	/* send 9 bits, start bit (1), command (2), address (6)  */
10958 	for (x = 0; x < 9; x++)
10959 		T93C46_Write_Bit(np, (u_char) (write_data >> (8 - x)), gpreg);
10960 
10961 	*read_bit = INB (nc_gpreg);
10962 }
10963 
10964 /*
10965  *  READ 2 bytes from the NVRAM
10966  */
10967 static void T93C46_Read_Word(hcb_p np, u_short *nvram_data, u_char *gpreg)
10968 {
10969 	int x;
10970 	u_char read_bit;
10971 
10972 	*nvram_data = 0;
10973 	for (x = 0; x < 16; x++) {
10974 		T93C46_Read_Bit(np, &read_bit, gpreg);
10975 
10976 		if (read_bit & 0x01)
10977 			*nvram_data |=  (0x01 << (15 - x));
10978 		else
10979 			*nvram_data &= ~(0x01 << (15 - x));
10980 	}
10981 }
10982 
10983 /*
10984  *  Read Tekram NvRAM data.
10985  */
10986 static int T93C46_Read_Data(hcb_p np, u_short *data,int len,u_char *gpreg)
10987 {
10988 	u_char	read_bit;
10989 	int	x;
10990 
10991 	for (x = 0; x < len; x++)  {
10992 
10993 		/* output read command and address */
10994 		T93C46_Send_Command(np, 0x180 | x, &read_bit, gpreg);
10995 		if (read_bit & 0x01)
10996 			return 1; /* Bad */
10997 		T93C46_Read_Word(np, &data[x], gpreg);
10998 		T93C46_Stop(np, gpreg);
10999 	}
11000 
11001 	return 0;
11002 }
11003 
11004 /*
11005  *  Try reading 93C46 Tekram NVRAM.
11006  */
11007 static int sym_read_T93C46_nvram (hcb_p np, Tekram_nvram *nvram)
11008 {
11009 	u_char gpcntl, gpreg;
11010 	u_char old_gpcntl, old_gpreg;
11011 	int retv = 1;
11012 
11013 	/* save current state of GPCNTL and GPREG */
11014 	old_gpreg	= INB (nc_gpreg);
11015 	old_gpcntl	= INB (nc_gpcntl);
11016 
11017 	/* set up GPREG & GPCNTL to set GPIO0/1/2/4 in to known state, 0 in,
11018 	   1/2/4 out */
11019 	gpreg = old_gpreg & 0xe9;
11020 	OUTB (nc_gpreg, gpreg);
11021 	gpcntl = (old_gpcntl & 0xe9) | 0x09;
11022 	OUTB (nc_gpcntl, gpcntl);
11023 
11024 	/* input all of NVRAM, 64 words */
11025 	retv = T93C46_Read_Data(np, (u_short *) nvram,
11026 				sizeof(*nvram) / sizeof(short), &gpreg);
11027 
11028 	/* return GPIO0/1/2/4 to original states after having accessed NVRAM */
11029 	OUTB (nc_gpcntl, old_gpcntl);
11030 	OUTB (nc_gpreg,  old_gpreg);
11031 
11032 	return retv;
11033 }
11034 
11035 /*
11036  *  Try reading Tekram NVRAM.
11037  *  Return 0 if OK.
11038  */
11039 static int sym_read_Tekram_nvram (hcb_p np, Tekram_nvram *nvram)
11040 {
11041 	u_char *data = (u_char *) nvram;
11042 	int len = sizeof(*nvram);
11043 	u_short	csum;
11044 	int x;
11045 
11046 	switch (np->device_id) {
11047 	case PCI_ID_SYM53C885:
11048 	case PCI_ID_SYM53C895:
11049 	case PCI_ID_SYM53C896:
11050 		x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
11051 					  data, len);
11052 		break;
11053 	case PCI_ID_SYM53C875:
11054 		x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
11055 					  data, len);
11056 		if (!x)
11057 			break;
11058 	default:
11059 		x = sym_read_T93C46_nvram(np, nvram);
11060 		break;
11061 	}
11062 	if (x)
11063 		return 1;
11064 
11065 	/* verify checksum */
11066 	for (x = 0, csum = 0; x < len - 1; x += 2)
11067 		csum += data[x] + (data[x+1] << 8);
11068 	if (csum != 0x1234)
11069 		return 1;
11070 
11071 	return 0;
11072 }
11073 
11074 #endif	/* SYM_CONF_NVRAM_SUPPORT */
11075