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