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