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