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