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