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