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