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