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