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