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