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