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