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