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