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