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