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