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