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