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