xref: /openbmc/linux/drivers/scsi/ncr53c8xx.c (revision dacef016)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /******************************************************************************
3 **  Device driver for the PCI-SCSI NCR538XX controller family.
4 **
5 **  Copyright (C) 1994  Wolfgang Stanglmeier
6 **
7 **
8 **-----------------------------------------------------------------------------
9 **
10 **  This driver has been ported to Linux from the FreeBSD NCR53C8XX driver
11 **  and is currently maintained by
12 **
13 **          Gerard Roudier              <groudier@free.fr>
14 **
15 **  Being given that this driver originates from the FreeBSD version, and
16 **  in order to keep synergy on both, any suggested enhancements and corrections
17 **  received on Linux are automatically a potential candidate for the FreeBSD
18 **  version.
19 **
20 **  The original driver has been written for 386bsd and FreeBSD by
21 **          Wolfgang Stanglmeier        <wolf@cologne.de>
22 **          Stefan Esser                <se@mi.Uni-Koeln.de>
23 **
24 **  And has been ported to NetBSD by
25 **          Charles M. Hannum           <mycroft@gnu.ai.mit.edu>
26 **
27 **-----------------------------------------------------------------------------
28 **
29 **                     Brief history
30 **
31 **  December 10 1995 by Gerard Roudier:
32 **     Initial port to Linux.
33 **
34 **  June 23 1996 by Gerard Roudier:
35 **     Support for 64 bits architectures (Alpha).
36 **
37 **  November 30 1996 by Gerard Roudier:
38 **     Support for Fast-20 scsi.
39 **     Support for large DMA fifo and 128 dwords bursting.
40 **
41 **  February 27 1997 by Gerard Roudier:
42 **     Support for Fast-40 scsi.
43 **     Support for on-Board RAM.
44 **
45 **  May 3 1997 by Gerard Roudier:
46 **     Full support for scsi scripts instructions pre-fetching.
47 **
48 **  May 19 1997 by Richard Waltham <dormouse@farsrobt.demon.co.uk>:
49 **     Support for NvRAM detection and reading.
50 **
51 **  August 18 1997 by Cort <cort@cs.nmt.edu>:
52 **     Support for Power/PC (Big Endian).
53 **
54 **  June 20 1998 by Gerard Roudier
55 **     Support for up to 64 tags per lun.
56 **     O(1) everywhere (C and SCRIPTS) for normal cases.
57 **     Low PCI traffic for command handling when on-chip RAM is present.
58 **     Aggressive SCSI SCRIPTS optimizations.
59 **
60 **  2005 by Matthew Wilcox and James Bottomley
61 **     PCI-ectomy.  This driver now supports only the 720 chip (see the
62 **     NCR_Q720 and zalon drivers for the bus probe logic).
63 **
64 *******************************************************************************
65 */
66 
67 /*
68 **	Supported SCSI-II features:
69 **	    Synchronous negotiation
70 **	    Wide negotiation        (depends on the NCR Chip)
71 **	    Enable disconnection
72 **	    Tagged command queuing
73 **	    Parity checking
74 **	    Etc...
75 **
76 **	Supported NCR/SYMBIOS chips:
77 **		53C720		(Wide,   Fast SCSI-2, intfly problems)
78 */
79 
80 /* Name and version of the driver */
81 #define SCSI_NCR_DRIVER_NAME	"ncr53c8xx-3.4.3g"
82 
83 #define SCSI_NCR_DEBUG_FLAGS	(0)
84 
85 #include <linux/blkdev.h>
86 #include <linux/delay.h>
87 #include <linux/dma-mapping.h>
88 #include <linux/errno.h>
89 #include <linux/gfp.h>
90 #include <linux/init.h>
91 #include <linux/interrupt.h>
92 #include <linux/ioport.h>
93 #include <linux/mm.h>
94 #include <linux/module.h>
95 #include <linux/sched.h>
96 #include <linux/signal.h>
97 #include <linux/spinlock.h>
98 #include <linux/stat.h>
99 #include <linux/string.h>
100 #include <linux/time.h>
101 #include <linux/timer.h>
102 #include <linux/types.h>
103 
104 #include <asm/dma.h>
105 #include <asm/io.h>
106 
107 #include <scsi/scsi.h>
108 #include <scsi/scsi_cmnd.h>
109 #include <scsi/scsi_dbg.h>
110 #include <scsi/scsi_device.h>
111 #include <scsi/scsi_tcq.h>
112 #include <scsi/scsi_transport.h>
113 #include <scsi/scsi_transport_spi.h>
114 
115 #include "ncr53c8xx.h"
116 
117 #define NAME53C8XX		"ncr53c8xx"
118 
119 /*==========================================================
120 **
121 **	Debugging tags
122 **
123 **==========================================================
124 */
125 
126 #define DEBUG_ALLOC    (0x0001)
127 #define DEBUG_PHASE    (0x0002)
128 #define DEBUG_QUEUE    (0x0008)
129 #define DEBUG_RESULT   (0x0010)
130 #define DEBUG_POINTER  (0x0020)
131 #define DEBUG_SCRIPT   (0x0040)
132 #define DEBUG_TINY     (0x0080)
133 #define DEBUG_TIMING   (0x0100)
134 #define DEBUG_NEGO     (0x0200)
135 #define DEBUG_TAGS     (0x0400)
136 #define DEBUG_SCATTER  (0x0800)
137 #define DEBUG_IC        (0x1000)
138 
139 /*
140 **    Enable/Disable debug messages.
141 **    Can be changed at runtime too.
142 */
143 
144 #ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
145 static int ncr_debug = SCSI_NCR_DEBUG_FLAGS;
146 	#define DEBUG_FLAGS ncr_debug
147 #else
148 	#define DEBUG_FLAGS	SCSI_NCR_DEBUG_FLAGS
149 #endif
150 
151 /*
152  * Locally used status flag
153  */
154 #define SAM_STAT_ILLEGAL	0xff
155 
156 static inline struct list_head *ncr_list_pop(struct list_head *head)
157 {
158 	if (!list_empty(head)) {
159 		struct list_head *elem = head->next;
160 
161 		list_del(elem);
162 		return elem;
163 	}
164 
165 	return NULL;
166 }
167 
168 /*==========================================================
169 **
170 **	Simple power of two buddy-like allocator.
171 **
172 **	This simple code is not intended to be fast, but to
173 **	provide power of 2 aligned memory allocations.
174 **	Since the SCRIPTS processor only supplies 8 bit
175 **	arithmetic, this allocator allows simple and fast
176 **	address calculations  from the SCRIPTS code.
177 **	In addition, cache line alignment is guaranteed for
178 **	power of 2 cache line size.
179 **	Enhanced in linux-2.3.44 to provide a memory pool
180 **	per pcidev to support dynamic dma mapping. (I would
181 **	have preferred a real bus abstraction, btw).
182 **
183 **==========================================================
184 */
185 
186 #define MEMO_SHIFT	4	/* 16 bytes minimum memory chunk */
187 #if PAGE_SIZE >= 8192
188 #define MEMO_PAGE_ORDER	0	/* 1 PAGE  maximum */
189 #else
190 #define MEMO_PAGE_ORDER	1	/* 2 PAGES maximum */
191 #endif
192 #define MEMO_FREE_UNUSED	/* Free unused pages immediately */
193 #define MEMO_WARN	1
194 #define MEMO_GFP_FLAGS	GFP_ATOMIC
195 #define MEMO_CLUSTER_SHIFT	(PAGE_SHIFT+MEMO_PAGE_ORDER)
196 #define MEMO_CLUSTER_SIZE	(1UL << MEMO_CLUSTER_SHIFT)
197 #define MEMO_CLUSTER_MASK	(MEMO_CLUSTER_SIZE-1)
198 
199 typedef u_long m_addr_t;	/* Enough bits to bit-hack addresses */
200 typedef struct device *m_bush_t;	/* Something that addresses DMAable */
201 
202 typedef struct m_link {		/* Link between free memory chunks */
203 	struct m_link *next;
204 } m_link_s;
205 
206 typedef struct m_vtob {		/* Virtual to Bus address translation */
207 	struct m_vtob *next;
208 	m_addr_t vaddr;
209 	m_addr_t baddr;
210 } m_vtob_s;
211 #define VTOB_HASH_SHIFT		5
212 #define VTOB_HASH_SIZE		(1UL << VTOB_HASH_SHIFT)
213 #define VTOB_HASH_MASK		(VTOB_HASH_SIZE-1)
214 #define VTOB_HASH_CODE(m)	\
215 	((((m_addr_t) (m)) >> MEMO_CLUSTER_SHIFT) & VTOB_HASH_MASK)
216 
217 typedef struct m_pool {		/* Memory pool of a given kind */
218 	m_bush_t bush;
219 	m_addr_t (*getp)(struct m_pool *);
220 	void (*freep)(struct m_pool *, m_addr_t);
221 	int nump;
222 	m_vtob_s *(vtob[VTOB_HASH_SIZE]);
223 	struct m_pool *next;
224 	struct m_link h[PAGE_SHIFT-MEMO_SHIFT+MEMO_PAGE_ORDER+1];
225 } m_pool_s;
226 
227 static void *___m_alloc(m_pool_s *mp, int size)
228 {
229 	int i = 0;
230 	int s = (1 << MEMO_SHIFT);
231 	int j;
232 	m_addr_t a;
233 	m_link_s *h = mp->h;
234 
235 	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
236 		return NULL;
237 
238 	while (size > s) {
239 		s <<= 1;
240 		++i;
241 	}
242 
243 	j = i;
244 	while (!h[j].next) {
245 		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
246 			h[j].next = (m_link_s *)mp->getp(mp);
247 			if (h[j].next)
248 				h[j].next->next = NULL;
249 			break;
250 		}
251 		++j;
252 		s <<= 1;
253 	}
254 	a = (m_addr_t) h[j].next;
255 	if (a) {
256 		h[j].next = h[j].next->next;
257 		while (j > i) {
258 			j -= 1;
259 			s >>= 1;
260 			h[j].next = (m_link_s *) (a+s);
261 			h[j].next->next = NULL;
262 		}
263 	}
264 #ifdef DEBUG
265 	printk("___m_alloc(%d) = %p\n", size, (void *) a);
266 #endif
267 	return (void *) a;
268 }
269 
270 static void ___m_free(m_pool_s *mp, void *ptr, int size)
271 {
272 	int i = 0;
273 	int s = (1 << MEMO_SHIFT);
274 	m_link_s *q;
275 	m_addr_t a, b;
276 	m_link_s *h = mp->h;
277 
278 #ifdef DEBUG
279 	printk("___m_free(%p, %d)\n", ptr, size);
280 #endif
281 
282 	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
283 		return;
284 
285 	while (size > s) {
286 		s <<= 1;
287 		++i;
288 	}
289 
290 	a = (m_addr_t) ptr;
291 
292 	while (1) {
293 #ifdef MEMO_FREE_UNUSED
294 		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
295 			mp->freep(mp, a);
296 			break;
297 		}
298 #endif
299 		b = a ^ s;
300 		q = &h[i];
301 		while (q->next && q->next != (m_link_s *) b) {
302 			q = q->next;
303 		}
304 		if (!q->next) {
305 			((m_link_s *) a)->next = h[i].next;
306 			h[i].next = (m_link_s *) a;
307 			break;
308 		}
309 		q->next = q->next->next;
310 		a = a & b;
311 		s <<= 1;
312 		++i;
313 	}
314 }
315 
316 static DEFINE_SPINLOCK(ncr53c8xx_lock);
317 
318 static void *__m_calloc2(m_pool_s *mp, int size, char *name, int uflags)
319 {
320 	void *p;
321 
322 	p = ___m_alloc(mp, size);
323 
324 	if (DEBUG_FLAGS & DEBUG_ALLOC)
325 		printk ("new %-10s[%4d] @%p.\n", name, size, p);
326 
327 	if (p)
328 		memset(p, 0, size);
329 	else if (uflags & MEMO_WARN)
330 		printk (NAME53C8XX ": failed to allocate %s[%d]\n", name, size);
331 
332 	return p;
333 }
334 
335 #define __m_calloc(mp, s, n)	__m_calloc2(mp, s, n, MEMO_WARN)
336 
337 static void __m_free(m_pool_s *mp, void *ptr, int size, char *name)
338 {
339 	if (DEBUG_FLAGS & DEBUG_ALLOC)
340 		printk ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
341 
342 	___m_free(mp, ptr, size);
343 
344 }
345 
346 /*
347  * With pci bus iommu support, we use a default pool of unmapped memory
348  * for memory we donnot need to DMA from/to and one pool per pcidev for
349  * memory accessed by the PCI chip. `mp0' is the default not DMAable pool.
350  */
351 
352 static m_addr_t ___mp0_getp(m_pool_s *mp)
353 {
354 	m_addr_t m = __get_free_pages(MEMO_GFP_FLAGS, MEMO_PAGE_ORDER);
355 	if (m)
356 		++mp->nump;
357 	return m;
358 }
359 
360 static void ___mp0_freep(m_pool_s *mp, m_addr_t m)
361 {
362 	free_pages(m, MEMO_PAGE_ORDER);
363 	--mp->nump;
364 }
365 
366 static m_pool_s mp0 = {NULL, ___mp0_getp, ___mp0_freep};
367 
368 /*
369  * DMAable pools.
370  */
371 
372 /*
373  * With pci bus iommu support, we maintain one pool per pcidev and a
374  * hashed reverse table for virtual to bus physical address translations.
375  */
376 static m_addr_t ___dma_getp(m_pool_s *mp)
377 {
378 	m_addr_t vp;
379 	m_vtob_s *vbp;
380 
381 	vbp = __m_calloc(&mp0, sizeof(*vbp), "VTOB");
382 	if (vbp) {
383 		dma_addr_t daddr;
384 		vp = (m_addr_t) dma_alloc_coherent(mp->bush,
385 						PAGE_SIZE<<MEMO_PAGE_ORDER,
386 						&daddr, GFP_ATOMIC);
387 		if (vp) {
388 			int hc = VTOB_HASH_CODE(vp);
389 			vbp->vaddr = vp;
390 			vbp->baddr = daddr;
391 			vbp->next = mp->vtob[hc];
392 			mp->vtob[hc] = vbp;
393 			++mp->nump;
394 			return vp;
395 		}
396 	}
397 	if (vbp)
398 		__m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
399 	return 0;
400 }
401 
402 static void ___dma_freep(m_pool_s *mp, m_addr_t m)
403 {
404 	m_vtob_s **vbpp, *vbp;
405 	int hc = VTOB_HASH_CODE(m);
406 
407 	vbpp = &mp->vtob[hc];
408 	while (*vbpp && (*vbpp)->vaddr != m)
409 		vbpp = &(*vbpp)->next;
410 	if (*vbpp) {
411 		vbp = *vbpp;
412 		*vbpp = (*vbpp)->next;
413 		dma_free_coherent(mp->bush, PAGE_SIZE<<MEMO_PAGE_ORDER,
414 				  (void *)vbp->vaddr, (dma_addr_t)vbp->baddr);
415 		__m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
416 		--mp->nump;
417 	}
418 }
419 
420 static inline m_pool_s *___get_dma_pool(m_bush_t bush)
421 {
422 	m_pool_s *mp;
423 	for (mp = mp0.next; mp && mp->bush != bush; mp = mp->next);
424 	return mp;
425 }
426 
427 static m_pool_s *___cre_dma_pool(m_bush_t bush)
428 {
429 	m_pool_s *mp;
430 	mp = __m_calloc(&mp0, sizeof(*mp), "MPOOL");
431 	if (mp) {
432 		memset(mp, 0, sizeof(*mp));
433 		mp->bush = bush;
434 		mp->getp = ___dma_getp;
435 		mp->freep = ___dma_freep;
436 		mp->next = mp0.next;
437 		mp0.next = mp;
438 	}
439 	return mp;
440 }
441 
442 static void ___del_dma_pool(m_pool_s *p)
443 {
444 	struct m_pool **pp = &mp0.next;
445 
446 	while (*pp && *pp != p)
447 		pp = &(*pp)->next;
448 	if (*pp) {
449 		*pp = (*pp)->next;
450 		__m_free(&mp0, p, sizeof(*p), "MPOOL");
451 	}
452 }
453 
454 static void *__m_calloc_dma(m_bush_t bush, int size, char *name)
455 {
456 	u_long flags;
457 	struct m_pool *mp;
458 	void *m = NULL;
459 
460 	spin_lock_irqsave(&ncr53c8xx_lock, flags);
461 	mp = ___get_dma_pool(bush);
462 	if (!mp)
463 		mp = ___cre_dma_pool(bush);
464 	if (mp)
465 		m = __m_calloc(mp, size, name);
466 	if (mp && !mp->nump)
467 		___del_dma_pool(mp);
468 	spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
469 
470 	return m;
471 }
472 
473 static void __m_free_dma(m_bush_t bush, void *m, int size, char *name)
474 {
475 	u_long flags;
476 	struct m_pool *mp;
477 
478 	spin_lock_irqsave(&ncr53c8xx_lock, flags);
479 	mp = ___get_dma_pool(bush);
480 	if (mp)
481 		__m_free(mp, m, size, name);
482 	if (mp && !mp->nump)
483 		___del_dma_pool(mp);
484 	spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
485 }
486 
487 static m_addr_t __vtobus(m_bush_t bush, void *m)
488 {
489 	u_long flags;
490 	m_pool_s *mp;
491 	int hc = VTOB_HASH_CODE(m);
492 	m_vtob_s *vp = NULL;
493 	m_addr_t a = ((m_addr_t) m) & ~MEMO_CLUSTER_MASK;
494 
495 	spin_lock_irqsave(&ncr53c8xx_lock, flags);
496 	mp = ___get_dma_pool(bush);
497 	if (mp) {
498 		vp = mp->vtob[hc];
499 		while (vp && (m_addr_t) vp->vaddr != a)
500 			vp = vp->next;
501 	}
502 	spin_unlock_irqrestore(&ncr53c8xx_lock, flags);
503 	return vp ? vp->baddr + (((m_addr_t) m) - a) : 0;
504 }
505 
506 #define _m_calloc_dma(np, s, n)		__m_calloc_dma(np->dev, s, n)
507 #define _m_free_dma(np, p, s, n)	__m_free_dma(np->dev, p, s, n)
508 #define m_calloc_dma(s, n)		_m_calloc_dma(np, s, n)
509 #define m_free_dma(p, s, n)		_m_free_dma(np, p, s, n)
510 #define _vtobus(np, p)			__vtobus(np->dev, p)
511 #define vtobus(p)			_vtobus(np, p)
512 
513 /*
514  *  Deal with DMA mapping/unmapping.
515  */
516 
517 /* To keep track of the dma mapping (sg/single) that has been set */
518 #define __data_mapped	SCp.phase
519 #define __data_mapping	SCp.have_data_in
520 
521 static void __unmap_scsi_data(struct device *dev, struct scsi_cmnd *cmd)
522 {
523 	switch(cmd->__data_mapped) {
524 	case 2:
525 		scsi_dma_unmap(cmd);
526 		break;
527 	}
528 	cmd->__data_mapped = 0;
529 }
530 
531 static int __map_scsi_sg_data(struct device *dev, struct scsi_cmnd *cmd)
532 {
533 	int use_sg;
534 
535 	use_sg = scsi_dma_map(cmd);
536 	if (!use_sg)
537 		return 0;
538 
539 	cmd->__data_mapped = 2;
540 	cmd->__data_mapping = use_sg;
541 
542 	return use_sg;
543 }
544 
545 #define unmap_scsi_data(np, cmd)	__unmap_scsi_data(np->dev, cmd)
546 #define map_scsi_sg_data(np, cmd)	__map_scsi_sg_data(np->dev, cmd)
547 
548 /*==========================================================
549 **
550 **	Driver setup.
551 **
552 **	This structure is initialized from linux config
553 **	options. It can be overridden at boot-up by the boot
554 **	command line.
555 **
556 **==========================================================
557 */
558 static struct ncr_driver_setup
559 	driver_setup			= SCSI_NCR_DRIVER_SETUP;
560 
561 #ifndef MODULE
562 #ifdef	SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
563 static struct ncr_driver_setup
564 	driver_safe_setup __initdata	= SCSI_NCR_DRIVER_SAFE_SETUP;
565 #endif
566 #endif /* !MODULE */
567 
568 #define initverbose (driver_setup.verbose)
569 #define bootverbose (np->verbose)
570 
571 
572 /*===================================================================
573 **
574 **	Driver setup from the boot command line
575 **
576 **===================================================================
577 */
578 
579 #ifdef MODULE
580 #define	ARG_SEP	' '
581 #else
582 #define	ARG_SEP	','
583 #endif
584 
585 #define OPT_TAGS		1
586 #define OPT_MASTER_PARITY	2
587 #define OPT_SCSI_PARITY		3
588 #define OPT_DISCONNECTION	4
589 #define OPT_SPECIAL_FEATURES	5
590 #define OPT_UNUSED_1		6
591 #define OPT_FORCE_SYNC_NEGO	7
592 #define OPT_REVERSE_PROBE	8
593 #define OPT_DEFAULT_SYNC	9
594 #define OPT_VERBOSE		10
595 #define OPT_DEBUG		11
596 #define OPT_BURST_MAX		12
597 #define OPT_LED_PIN		13
598 #define OPT_MAX_WIDE		14
599 #define OPT_SETTLE_DELAY	15
600 #define OPT_DIFF_SUPPORT	16
601 #define OPT_IRQM		17
602 #define OPT_PCI_FIX_UP		18
603 #define OPT_BUS_CHECK		19
604 #define OPT_OPTIMIZE		20
605 #define OPT_RECOVERY		21
606 #define OPT_SAFE_SETUP		22
607 #define OPT_USE_NVRAM		23
608 #define OPT_EXCLUDE		24
609 #define OPT_HOST_ID		25
610 
611 #ifdef SCSI_NCR_IARB_SUPPORT
612 #define OPT_IARB		26
613 #endif
614 
615 #ifdef MODULE
616 #define	ARG_SEP	' '
617 #else
618 #define	ARG_SEP	','
619 #endif
620 
621 #ifndef MODULE
622 static char setup_token[] __initdata =
623 	"tags:"   "mpar:"
624 	"spar:"   "disc:"
625 	"specf:"  "ultra:"
626 	"fsn:"    "revprob:"
627 	"sync:"   "verb:"
628 	"debug:"  "burst:"
629 	"led:"    "wide:"
630 	"settle:" "diff:"
631 	"irqm:"   "pcifix:"
632 	"buschk:" "optim:"
633 	"recovery:"
634 	"safe:"   "nvram:"
635 	"excl:"   "hostid:"
636 #ifdef SCSI_NCR_IARB_SUPPORT
637 	"iarb:"
638 #endif
639 	;	/* DONNOT REMOVE THIS ';' */
640 
641 static int __init get_setup_token(char *p)
642 {
643 	char *cur = setup_token;
644 	char *pc;
645 	int i = 0;
646 
647 	while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
648 		++pc;
649 		++i;
650 		if (!strncmp(p, cur, pc - cur))
651 			return i;
652 		cur = pc;
653 	}
654 	return 0;
655 }
656 
657 static int __init sym53c8xx__setup(char *str)
658 {
659 #ifdef SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
660 	char *cur = str;
661 	char *pc, *pv;
662 	int i, val, c;
663 	int xi = 0;
664 
665 	while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
666 		char *pe;
667 
668 		val = 0;
669 		pv = pc;
670 		c = *++pv;
671 
672 		if	(c == 'n')
673 			val = 0;
674 		else if	(c == 'y')
675 			val = 1;
676 		else
677 			val = (int) simple_strtoul(pv, &pe, 0);
678 
679 		switch (get_setup_token(cur)) {
680 		case OPT_TAGS:
681 			driver_setup.default_tags = val;
682 			if (pe && *pe == '/') {
683 				i = 0;
684 				while (*pe && *pe != ARG_SEP &&
685 					i < sizeof(driver_setup.tag_ctrl)-1) {
686 					driver_setup.tag_ctrl[i++] = *pe++;
687 				}
688 				driver_setup.tag_ctrl[i] = '\0';
689 			}
690 			break;
691 		case OPT_MASTER_PARITY:
692 			driver_setup.master_parity = val;
693 			break;
694 		case OPT_SCSI_PARITY:
695 			driver_setup.scsi_parity = val;
696 			break;
697 		case OPT_DISCONNECTION:
698 			driver_setup.disconnection = val;
699 			break;
700 		case OPT_SPECIAL_FEATURES:
701 			driver_setup.special_features = val;
702 			break;
703 		case OPT_FORCE_SYNC_NEGO:
704 			driver_setup.force_sync_nego = val;
705 			break;
706 		case OPT_REVERSE_PROBE:
707 			driver_setup.reverse_probe = val;
708 			break;
709 		case OPT_DEFAULT_SYNC:
710 			driver_setup.default_sync = val;
711 			break;
712 		case OPT_VERBOSE:
713 			driver_setup.verbose = val;
714 			break;
715 		case OPT_DEBUG:
716 			driver_setup.debug = val;
717 			break;
718 		case OPT_BURST_MAX:
719 			driver_setup.burst_max = val;
720 			break;
721 		case OPT_LED_PIN:
722 			driver_setup.led_pin = val;
723 			break;
724 		case OPT_MAX_WIDE:
725 			driver_setup.max_wide = val? 1:0;
726 			break;
727 		case OPT_SETTLE_DELAY:
728 			driver_setup.settle_delay = val;
729 			break;
730 		case OPT_DIFF_SUPPORT:
731 			driver_setup.diff_support = val;
732 			break;
733 		case OPT_IRQM:
734 			driver_setup.irqm = val;
735 			break;
736 		case OPT_PCI_FIX_UP:
737 			driver_setup.pci_fix_up	= val;
738 			break;
739 		case OPT_BUS_CHECK:
740 			driver_setup.bus_check = val;
741 			break;
742 		case OPT_OPTIMIZE:
743 			driver_setup.optimize = val;
744 			break;
745 		case OPT_RECOVERY:
746 			driver_setup.recovery = val;
747 			break;
748 		case OPT_USE_NVRAM:
749 			driver_setup.use_nvram = val;
750 			break;
751 		case OPT_SAFE_SETUP:
752 			memcpy(&driver_setup, &driver_safe_setup,
753 				sizeof(driver_setup));
754 			break;
755 		case OPT_EXCLUDE:
756 			if (xi < SCSI_NCR_MAX_EXCLUDES)
757 				driver_setup.excludes[xi++] = val;
758 			break;
759 		case OPT_HOST_ID:
760 			driver_setup.host_id = val;
761 			break;
762 #ifdef SCSI_NCR_IARB_SUPPORT
763 		case OPT_IARB:
764 			driver_setup.iarb = val;
765 			break;
766 #endif
767 		default:
768 			printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
769 			break;
770 		}
771 
772 		if ((cur = strchr(cur, ARG_SEP)) != NULL)
773 			++cur;
774 	}
775 #endif /* SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT */
776 	return 1;
777 }
778 #endif /* !MODULE */
779 
780 /*===================================================================
781 **
782 **	Get device queue depth from boot command line.
783 **
784 **===================================================================
785 */
786 #define DEF_DEPTH	(driver_setup.default_tags)
787 #define ALL_TARGETS	-2
788 #define NO_TARGET	-1
789 #define ALL_LUNS	-2
790 #define NO_LUN		-1
791 
792 static int device_queue_depth(int unit, int target, int lun)
793 {
794 	int c, h, t, u, v;
795 	char *p = driver_setup.tag_ctrl;
796 	char *ep;
797 
798 	h = -1;
799 	t = NO_TARGET;
800 	u = NO_LUN;
801 	while ((c = *p++) != 0) {
802 		v = simple_strtoul(p, &ep, 0);
803 		switch(c) {
804 		case '/':
805 			++h;
806 			t = ALL_TARGETS;
807 			u = ALL_LUNS;
808 			break;
809 		case 't':
810 			if (t != target)
811 				t = (target == v) ? v : NO_TARGET;
812 			u = ALL_LUNS;
813 			break;
814 		case 'u':
815 			if (u != lun)
816 				u = (lun == v) ? v : NO_LUN;
817 			break;
818 		case 'q':
819 			if (h == unit &&
820 				(t == ALL_TARGETS || t == target) &&
821 				(u == ALL_LUNS    || u == lun))
822 				return v;
823 			break;
824 		case '-':
825 			t = ALL_TARGETS;
826 			u = ALL_LUNS;
827 			break;
828 		default:
829 			break;
830 		}
831 		p = ep;
832 	}
833 	return DEF_DEPTH;
834 }
835 
836 
837 /*==========================================================
838 **
839 **	The CCB done queue uses an array of CCB virtual
840 **	addresses. Empty entries are flagged using the bogus
841 **	virtual address 0xffffffff.
842 **
843 **	Since PCI ensures that only aligned DWORDs are accessed
844 **	atomically, 64 bit little-endian architecture requires
845 **	to test the high order DWORD of the entry to determine
846 **	if it is empty or valid.
847 **
848 **	BTW, I will make things differently as soon as I will
849 **	have a better idea, but this is simple and should work.
850 **
851 **==========================================================
852 */
853 
854 #define SCSI_NCR_CCB_DONE_SUPPORT
855 #ifdef  SCSI_NCR_CCB_DONE_SUPPORT
856 
857 #define MAX_DONE 24
858 #define CCB_DONE_EMPTY 0xffffffffUL
859 
860 /* All 32 bit architectures */
861 #if BITS_PER_LONG == 32
862 #define CCB_DONE_VALID(cp)  (((u_long) cp) != CCB_DONE_EMPTY)
863 
864 /* All > 32 bit (64 bit) architectures regardless endian-ness */
865 #else
866 #define CCB_DONE_VALID(cp)  \
867 	((((u_long) cp) & 0xffffffff00000000ul) && 	\
868 	 (((u_long) cp) & 0xfffffffful) != CCB_DONE_EMPTY)
869 #endif
870 
871 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
872 
873 /*==========================================================
874 **
875 **	Configuration and Debugging
876 **
877 **==========================================================
878 */
879 
880 /*
881 **    SCSI address of this device.
882 **    The boot routines should have set it.
883 **    If not, use this.
884 */
885 
886 #ifndef SCSI_NCR_MYADDR
887 #define SCSI_NCR_MYADDR      (7)
888 #endif
889 
890 /*
891 **    The maximum number of tags per logic unit.
892 **    Used only for disk devices that support tags.
893 */
894 
895 #ifndef SCSI_NCR_MAX_TAGS
896 #define SCSI_NCR_MAX_TAGS    (8)
897 #endif
898 
899 /*
900 **    TAGS are actually limited to 64 tags/lun.
901 **    We need to deal with power of 2, for alignment constraints.
902 */
903 #if	SCSI_NCR_MAX_TAGS > 64
904 #define	MAX_TAGS (64)
905 #else
906 #define	MAX_TAGS SCSI_NCR_MAX_TAGS
907 #endif
908 
909 #define NO_TAG	(255)
910 
911 /*
912 **	Choose appropriate type for tag bitmap.
913 */
914 #if	MAX_TAGS > 32
915 typedef u64 tagmap_t;
916 #else
917 typedef u32 tagmap_t;
918 #endif
919 
920 /*
921 **    Number of targets supported by the driver.
922 **    n permits target numbers 0..n-1.
923 **    Default is 16, meaning targets #0..#15.
924 **    #7 .. is myself.
925 */
926 
927 #ifdef SCSI_NCR_MAX_TARGET
928 #define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
929 #else
930 #define MAX_TARGET  (16)
931 #endif
932 
933 /*
934 **    Number of logic units supported by the driver.
935 **    n enables logic unit numbers 0..n-1.
936 **    The common SCSI devices require only
937 **    one lun, so take 1 as the default.
938 */
939 
940 #ifdef SCSI_NCR_MAX_LUN
941 #define MAX_LUN    SCSI_NCR_MAX_LUN
942 #else
943 #define MAX_LUN    (1)
944 #endif
945 
946 /*
947 **    Asynchronous pre-scaler (ns). Shall be 40
948 */
949 
950 #ifndef SCSI_NCR_MIN_ASYNC
951 #define SCSI_NCR_MIN_ASYNC (40)
952 #endif
953 
954 /*
955 **    The maximum number of jobs scheduled for starting.
956 **    There should be one slot per target, and one slot
957 **    for each tag of each target in use.
958 **    The calculation below is actually quite silly ...
959 */
960 
961 #ifdef SCSI_NCR_CAN_QUEUE
962 #define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
963 #else
964 #define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
965 #endif
966 
967 /*
968 **   We limit the max number of pending IO to 250.
969 **   since we donnot want to allocate more than 1
970 **   PAGE for 'scripth'.
971 */
972 #if	MAX_START > 250
973 #undef	MAX_START
974 #define	MAX_START 250
975 #endif
976 
977 /*
978 **    The maximum number of segments a transfer is split into.
979 **    We support up to 127 segments for both read and write.
980 **    The data scripts are broken into 2 sub-scripts.
981 **    80 (MAX_SCATTERL) segments are moved from a sub-script
982 **    in on-chip RAM. This makes data transfers shorter than
983 **    80k (assuming 1k fs) as fast as possible.
984 */
985 
986 #define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
987 
988 #if (MAX_SCATTER > 80)
989 #define MAX_SCATTERL	80
990 #define	MAX_SCATTERH	(MAX_SCATTER - MAX_SCATTERL)
991 #else
992 #define MAX_SCATTERL	(MAX_SCATTER-1)
993 #define	MAX_SCATTERH	1
994 #endif
995 
996 /*
997 **	other
998 */
999 
1000 #define NCR_SNOOP_TIMEOUT (1000000)
1001 
1002 /*
1003 **	Other definitions
1004 */
1005 
1006 #define initverbose (driver_setup.verbose)
1007 #define bootverbose (np->verbose)
1008 
1009 /*==========================================================
1010 **
1011 **	Command control block states.
1012 **
1013 **==========================================================
1014 */
1015 
1016 #define HS_IDLE		(0)
1017 #define HS_BUSY		(1)
1018 #define HS_NEGOTIATE	(2)	/* sync/wide data transfer*/
1019 #define HS_DISCONNECT	(3)	/* Disconnected by target */
1020 
1021 #define HS_DONEMASK	(0x80)
1022 #define HS_COMPLETE	(4|HS_DONEMASK)
1023 #define HS_SEL_TIMEOUT	(5|HS_DONEMASK)	/* Selection timeout      */
1024 #define HS_RESET	(6|HS_DONEMASK)	/* SCSI reset	          */
1025 #define HS_ABORTED	(7|HS_DONEMASK)	/* Transfer aborted       */
1026 #define HS_TIMEOUT	(8|HS_DONEMASK)	/* Software timeout       */
1027 #define HS_FAIL		(9|HS_DONEMASK)	/* SCSI or PCI bus errors */
1028 #define HS_UNEXPECTED	(10|HS_DONEMASK)/* Unexpected disconnect  */
1029 
1030 /*
1031 **	Invalid host status values used by the SCRIPTS processor
1032 **	when the nexus is not fully identified.
1033 **	Shall never appear in a CCB.
1034 */
1035 
1036 #define HS_INVALMASK	(0x40)
1037 #define	HS_SELECTING	(0|HS_INVALMASK)
1038 #define	HS_IN_RESELECT	(1|HS_INVALMASK)
1039 #define	HS_STARTING	(2|HS_INVALMASK)
1040 
1041 /*
1042 **	Flags set by the SCRIPT processor for commands
1043 **	that have been skipped.
1044 */
1045 #define HS_SKIPMASK	(0x20)
1046 
1047 /*==========================================================
1048 **
1049 **	Software Interrupt Codes
1050 **
1051 **==========================================================
1052 */
1053 
1054 #define	SIR_BAD_STATUS		(1)
1055 #define	SIR_XXXXXXXXXX		(2)
1056 #define	SIR_NEGO_SYNC		(3)
1057 #define	SIR_NEGO_WIDE		(4)
1058 #define	SIR_NEGO_FAILED		(5)
1059 #define	SIR_NEGO_PROTO		(6)
1060 #define	SIR_REJECT_RECEIVED	(7)
1061 #define	SIR_REJECT_SENT		(8)
1062 #define	SIR_IGN_RESIDUE		(9)
1063 #define	SIR_MISSING_SAVE	(10)
1064 #define	SIR_RESEL_NO_MSG_IN	(11)
1065 #define	SIR_RESEL_NO_IDENTIFY	(12)
1066 #define	SIR_RESEL_BAD_LUN	(13)
1067 #define	SIR_RESEL_BAD_TARGET	(14)
1068 #define	SIR_RESEL_BAD_I_T_L	(15)
1069 #define	SIR_RESEL_BAD_I_T_L_Q	(16)
1070 #define	SIR_DONE_OVERFLOW	(17)
1071 #define	SIR_INTFLY		(18)
1072 #define	SIR_MAX			(18)
1073 
1074 /*==========================================================
1075 **
1076 **	Extended error codes.
1077 **	xerr_status field of struct ccb.
1078 **
1079 **==========================================================
1080 */
1081 
1082 #define	XE_OK		(0)
1083 #define	XE_EXTRA_DATA	(1)	/* unexpected data phase */
1084 #define	XE_BAD_PHASE	(2)	/* illegal phase (4/5)   */
1085 
1086 /*==========================================================
1087 **
1088 **	Negotiation status.
1089 **	nego_status field	of struct ccb.
1090 **
1091 **==========================================================
1092 */
1093 
1094 #define NS_NOCHANGE	(0)
1095 #define NS_SYNC		(1)
1096 #define NS_WIDE		(2)
1097 #define NS_PPR		(4)
1098 
1099 /*==========================================================
1100 **
1101 **	Misc.
1102 **
1103 **==========================================================
1104 */
1105 
1106 #define CCB_MAGIC	(0xf2691ad2)
1107 
1108 /*==========================================================
1109 **
1110 **	Declaration of structs.
1111 **
1112 **==========================================================
1113 */
1114 
1115 static struct scsi_transport_template *ncr53c8xx_transport_template = NULL;
1116 
1117 struct tcb;
1118 struct lcb;
1119 struct ccb;
1120 struct ncb;
1121 struct script;
1122 
1123 struct link {
1124 	ncrcmd	l_cmd;
1125 	ncrcmd	l_paddr;
1126 };
1127 
1128 struct	usrcmd {
1129 	u_long	target;
1130 	u_long	lun;
1131 	u_long	data;
1132 	u_long	cmd;
1133 };
1134 
1135 #define UC_SETSYNC      10
1136 #define UC_SETTAGS	11
1137 #define UC_SETDEBUG	12
1138 #define UC_SETORDER	13
1139 #define UC_SETWIDE	14
1140 #define UC_SETFLAG	15
1141 #define UC_SETVERBOSE	17
1142 
1143 #define	UF_TRACE	(0x01)
1144 #define	UF_NODISC	(0x02)
1145 #define	UF_NOSCAN	(0x04)
1146 
1147 /*========================================================================
1148 **
1149 **	Declaration of structs:		target control block
1150 **
1151 **========================================================================
1152 */
1153 struct tcb {
1154 	/*----------------------------------------------------------------
1155 	**	During reselection the ncr jumps to this point with SFBR
1156 	**	set to the encoded target number with bit 7 set.
1157 	**	if it's not this target, jump to the next.
1158 	**
1159 	**	JUMP  IF (SFBR != #target#), @(next tcb)
1160 	**----------------------------------------------------------------
1161 	*/
1162 	struct link   jump_tcb;
1163 
1164 	/*----------------------------------------------------------------
1165 	**	Load the actual values for the sxfer and the scntl3
1166 	**	register (sync/wide mode).
1167 	**
1168 	**	SCR_COPY (1), @(sval field of this tcb), @(sxfer  register)
1169 	**	SCR_COPY (1), @(wval field of this tcb), @(scntl3 register)
1170 	**----------------------------------------------------------------
1171 	*/
1172 	ncrcmd	getscr[6];
1173 
1174 	/*----------------------------------------------------------------
1175 	**	Get the IDENTIFY message and load the LUN to SFBR.
1176 	**
1177 	**	CALL, <RESEL_LUN>
1178 	**----------------------------------------------------------------
1179 	*/
1180 	struct link   call_lun;
1181 
1182 	/*----------------------------------------------------------------
1183 	**	Now look for the right lun.
1184 	**
1185 	**	For i = 0 to 3
1186 	**		SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(first lcb mod. i)
1187 	**
1188 	**	Recent chips will prefetch the 4 JUMPS using only 1 burst.
1189 	**	It is kind of hashcoding.
1190 	**----------------------------------------------------------------
1191 	*/
1192 	struct link     jump_lcb[4];	/* JUMPs for reselection	*/
1193 	struct lcb *	lp[MAX_LUN];	/* The lcb's of this tcb	*/
1194 
1195 	/*----------------------------------------------------------------
1196 	**	Pointer to the ccb used for negotiation.
1197 	**	Prevent from starting a negotiation for all queued commands
1198 	**	when tagged command queuing is enabled.
1199 	**----------------------------------------------------------------
1200 	*/
1201 	struct ccb *   nego_cp;
1202 
1203 	/*----------------------------------------------------------------
1204 	**	statistical data
1205 	**----------------------------------------------------------------
1206 	*/
1207 	u_long	transfers;
1208 	u_long	bytes;
1209 
1210 	/*----------------------------------------------------------------
1211 	**	negotiation of wide and synch transfer and device quirks.
1212 	**----------------------------------------------------------------
1213 	*/
1214 #ifdef SCSI_NCR_BIG_ENDIAN
1215 /*0*/	u16	period;
1216 /*2*/	u_char	sval;
1217 /*3*/	u_char	minsync;
1218 /*0*/	u_char	wval;
1219 /*1*/	u_char	widedone;
1220 /*2*/	u_char	quirks;
1221 /*3*/	u_char	maxoffs;
1222 #else
1223 /*0*/	u_char	minsync;
1224 /*1*/	u_char	sval;
1225 /*2*/	u16	period;
1226 /*0*/	u_char	maxoffs;
1227 /*1*/	u_char	quirks;
1228 /*2*/	u_char	widedone;
1229 /*3*/	u_char	wval;
1230 #endif
1231 
1232 	/* User settable limits and options.  */
1233 	u_char	usrsync;
1234 	u_char	usrwide;
1235 	u_char	usrtags;
1236 	u_char	usrflag;
1237 	struct scsi_target *starget;
1238 };
1239 
1240 /*========================================================================
1241 **
1242 **	Declaration of structs:		lun control block
1243 **
1244 **========================================================================
1245 */
1246 struct lcb {
1247 	/*----------------------------------------------------------------
1248 	**	During reselection the ncr jumps to this point
1249 	**	with SFBR set to the "Identify" message.
1250 	**	if it's not this lun, jump to the next.
1251 	**
1252 	**	JUMP  IF (SFBR != #lun#), @(next lcb of this target)
1253 	**
1254 	**	It is this lun. Load TEMP with the nexus jumps table
1255 	**	address and jump to RESEL_TAG (or RESEL_NOTAG).
1256 	**
1257 	**		SCR_COPY (4), p_jump_ccb, TEMP,
1258 	**		SCR_JUMP, <RESEL_TAG>
1259 	**----------------------------------------------------------------
1260 	*/
1261 	struct link	jump_lcb;
1262 	ncrcmd		load_jump_ccb[3];
1263 	struct link	jump_tag;
1264 	ncrcmd		p_jump_ccb;	/* Jump table bus address	*/
1265 
1266 	/*----------------------------------------------------------------
1267 	**	Jump table used by the script processor to directly jump
1268 	**	to the CCB corresponding to the reselected nexus.
1269 	**	Address is allocated on 256 bytes boundary in order to
1270 	**	allow 8 bit calculation of the tag jump entry for up to
1271 	**	64 possible tags.
1272 	**----------------------------------------------------------------
1273 	*/
1274 	u32		jump_ccb_0;	/* Default table if no tags	*/
1275 	u32		*jump_ccb;	/* Virtual address		*/
1276 
1277 	/*----------------------------------------------------------------
1278 	**	CCB queue management.
1279 	**----------------------------------------------------------------
1280 	*/
1281 	struct list_head free_ccbq;	/* Queue of available CCBs	*/
1282 	struct list_head busy_ccbq;	/* Queue of busy CCBs		*/
1283 	struct list_head wait_ccbq;	/* Queue of waiting for IO CCBs	*/
1284 	struct list_head skip_ccbq;	/* Queue of skipped CCBs	*/
1285 	u_char		actccbs;	/* Number of allocated CCBs	*/
1286 	u_char		busyccbs;	/* CCBs busy for this lun	*/
1287 	u_char		queuedccbs;	/* CCBs queued to the controller*/
1288 	u_char		queuedepth;	/* Queue depth for this lun	*/
1289 	u_char		scdev_depth;	/* SCSI device queue depth	*/
1290 	u_char		maxnxs;		/* Max possible nexuses		*/
1291 
1292 	/*----------------------------------------------------------------
1293 	**	Control of tagged command queuing.
1294 	**	Tags allocation is performed using a circular buffer.
1295 	**	This avoids using a loop for tag allocation.
1296 	**----------------------------------------------------------------
1297 	*/
1298 	u_char		ia_tag;		/* Allocation index		*/
1299 	u_char		if_tag;		/* Freeing index		*/
1300 	u_char cb_tags[MAX_TAGS];	/* Circular tags buffer	*/
1301 	u_char		usetags;	/* Command queuing is active	*/
1302 	u_char		maxtags;	/* Max nr of tags asked by user	*/
1303 	u_char		numtags;	/* Current number of tags	*/
1304 
1305 	/*----------------------------------------------------------------
1306 	**	QUEUE FULL control and ORDERED tag control.
1307 	**----------------------------------------------------------------
1308 	*/
1309 	/*----------------------------------------------------------------
1310 	**	QUEUE FULL and ORDERED tag control.
1311 	**----------------------------------------------------------------
1312 	*/
1313 	u16		num_good;	/* Nr of GOOD since QUEUE FULL	*/
1314 	tagmap_t	tags_umap;	/* Used tags bitmap		*/
1315 	tagmap_t	tags_smap;	/* Tags in use at 'tag_stime'	*/
1316 	u_long		tags_stime;	/* Last time we set smap=umap	*/
1317 	struct ccb *	held_ccb;	/* CCB held for QUEUE FULL	*/
1318 };
1319 
1320 /*========================================================================
1321 **
1322 **      Declaration of structs:     the launch script.
1323 **
1324 **========================================================================
1325 **
1326 **	It is part of the CCB and is called by the scripts processor to
1327 **	start or restart the data structure (nexus).
1328 **	This 6 DWORDs mini script makes use of prefetching.
1329 **
1330 **------------------------------------------------------------------------
1331 */
1332 struct launch {
1333 	/*----------------------------------------------------------------
1334 	**	SCR_COPY(4),	@(p_phys), @(dsa register)
1335 	**	SCR_JUMP,	@(scheduler_point)
1336 	**----------------------------------------------------------------
1337 	*/
1338 	ncrcmd		setup_dsa[3];	/* Copy 'phys' address to dsa	*/
1339 	struct link	schedule;	/* Jump to scheduler point	*/
1340 	ncrcmd		p_phys;		/* 'phys' header bus address	*/
1341 };
1342 
1343 /*========================================================================
1344 **
1345 **      Declaration of structs:     global HEADER.
1346 **
1347 **========================================================================
1348 **
1349 **	This substructure is copied from the ccb to a global address after
1350 **	selection (or reselection) and copied back before disconnect.
1351 **
1352 **	These fields are accessible to the script processor.
1353 **
1354 **------------------------------------------------------------------------
1355 */
1356 
1357 struct head {
1358 	/*----------------------------------------------------------------
1359 	**	Saved data pointer.
1360 	**	Points to the position in the script responsible for the
1361 	**	actual transfer transfer of data.
1362 	**	It's written after reception of a SAVE_DATA_POINTER message.
1363 	**	The goalpointer points after the last transfer command.
1364 	**----------------------------------------------------------------
1365 	*/
1366 	u32		savep;
1367 	u32		lastp;
1368 	u32		goalp;
1369 
1370 	/*----------------------------------------------------------------
1371 	**	Alternate data pointer.
1372 	**	They are copied back to savep/lastp/goalp by the SCRIPTS
1373 	**	when the direction is unknown and the device claims data out.
1374 	**----------------------------------------------------------------
1375 	*/
1376 	u32		wlastp;
1377 	u32		wgoalp;
1378 
1379 	/*----------------------------------------------------------------
1380 	**	The virtual address of the ccb containing this header.
1381 	**----------------------------------------------------------------
1382 	*/
1383 	struct ccb *	cp;
1384 
1385 	/*----------------------------------------------------------------
1386 	**	Status fields.
1387 	**----------------------------------------------------------------
1388 	*/
1389 	u_char		scr_st[4];	/* script status		*/
1390 	u_char		status[4];	/* host status. must be the 	*/
1391 					/*  last DWORD of the header.	*/
1392 };
1393 
1394 /*
1395 **	The status bytes are used by the host and the script processor.
1396 **
1397 **	The byte corresponding to the host_status must be stored in the
1398 **	last DWORD of the CCB header since it is used for command
1399 **	completion (ncr_wakeup()). Doing so, we are sure that the header
1400 **	has been entirely copied back to the CCB when the host_status is
1401 **	seen complete by the CPU.
1402 **
1403 **	The last four bytes (status[4]) are copied to the scratchb register
1404 **	(declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
1405 **	and copied back just after disconnecting.
1406 **	Inside the script the XX_REG are used.
1407 **
1408 **	The first four bytes (scr_st[4]) are used inside the script by
1409 **	"COPY" commands.
1410 **	Because source and destination must have the same alignment
1411 **	in a DWORD, the fields HAVE to be at the chosen offsets.
1412 **		xerr_st		0	(0x34)	scratcha
1413 **		sync_st		1	(0x05)	sxfer
1414 **		wide_st		3	(0x03)	scntl3
1415 */
1416 
1417 /*
1418 **	Last four bytes (script)
1419 */
1420 #define  QU_REG	scr0
1421 #define  HS_REG	scr1
1422 #define  HS_PRT	nc_scr1
1423 #define  SS_REG	scr2
1424 #define  SS_PRT	nc_scr2
1425 #define  PS_REG	scr3
1426 
1427 /*
1428 **	Last four bytes (host)
1429 */
1430 #ifdef SCSI_NCR_BIG_ENDIAN
1431 #define  actualquirks  phys.header.status[3]
1432 #define  host_status   phys.header.status[2]
1433 #define  scsi_status   phys.header.status[1]
1434 #define  parity_status phys.header.status[0]
1435 #else
1436 #define  actualquirks  phys.header.status[0]
1437 #define  host_status   phys.header.status[1]
1438 #define  scsi_status   phys.header.status[2]
1439 #define  parity_status phys.header.status[3]
1440 #endif
1441 
1442 /*
1443 **	First four bytes (script)
1444 */
1445 #define  xerr_st       header.scr_st[0]
1446 #define  sync_st       header.scr_st[1]
1447 #define  nego_st       header.scr_st[2]
1448 #define  wide_st       header.scr_st[3]
1449 
1450 /*
1451 **	First four bytes (host)
1452 */
1453 #define  xerr_status   phys.xerr_st
1454 #define  nego_status   phys.nego_st
1455 
1456 /*==========================================================
1457 **
1458 **      Declaration of structs:     Data structure block
1459 **
1460 **==========================================================
1461 **
1462 **	During execution of a ccb by the script processor,
1463 **	the DSA (data structure address) register points
1464 **	to this substructure of the ccb.
1465 **	This substructure contains the header with
1466 **	the script-processor-changeable data and
1467 **	data blocks for the indirect move commands.
1468 **
1469 **----------------------------------------------------------
1470 */
1471 
1472 struct dsb {
1473 
1474 	/*
1475 	**	Header.
1476 	*/
1477 
1478 	struct head	header;
1479 
1480 	/*
1481 	**	Table data for Script
1482 	*/
1483 
1484 	struct scr_tblsel  select;
1485 	struct scr_tblmove smsg  ;
1486 	struct scr_tblmove cmd   ;
1487 	struct scr_tblmove sense ;
1488 	struct scr_tblmove data[MAX_SCATTER];
1489 };
1490 
1491 
1492 /*========================================================================
1493 **
1494 **      Declaration of structs:     Command control block.
1495 **
1496 **========================================================================
1497 */
1498 struct ccb {
1499 	/*----------------------------------------------------------------
1500 	**	This is the data structure which is pointed by the DSA
1501 	**	register when it is executed by the script processor.
1502 	**	It must be the first entry because it contains the header
1503 	**	as first entry that must be cache line aligned.
1504 	**----------------------------------------------------------------
1505 	*/
1506 	struct dsb	phys;
1507 
1508 	/*----------------------------------------------------------------
1509 	**	Mini-script used at CCB execution start-up.
1510 	**	Load the DSA with the data structure address (phys) and
1511 	**	jump to SELECT. Jump to CANCEL if CCB is to be canceled.
1512 	**----------------------------------------------------------------
1513 	*/
1514 	struct launch	start;
1515 
1516 	/*----------------------------------------------------------------
1517 	**	Mini-script used at CCB relection to restart the nexus.
1518 	**	Load the DSA with the data structure address (phys) and
1519 	**	jump to RESEL_DSA. Jump to ABORT if CCB is to be aborted.
1520 	**----------------------------------------------------------------
1521 	*/
1522 	struct launch	restart;
1523 
1524 	/*----------------------------------------------------------------
1525 	**	If a data transfer phase is terminated too early
1526 	**	(after reception of a message (i.e. DISCONNECT)),
1527 	**	we have to prepare a mini script to transfer
1528 	**	the rest of the data.
1529 	**----------------------------------------------------------------
1530 	*/
1531 	ncrcmd		patch[8];
1532 
1533 	/*----------------------------------------------------------------
1534 	**	The general SCSI driver provides a
1535 	**	pointer to a control block.
1536 	**----------------------------------------------------------------
1537 	*/
1538 	struct scsi_cmnd	*cmd;		/* SCSI command 		*/
1539 	u_char		cdb_buf[16];	/* Copy of CDB			*/
1540 	u_char		sense_buf[64];
1541 	int		data_len;	/* Total data length		*/
1542 
1543 	/*----------------------------------------------------------------
1544 	**	Message areas.
1545 	**	We prepare a message to be sent after selection.
1546 	**	We may use a second one if the command is rescheduled
1547 	**	due to GETCC or QFULL.
1548 	**      Contents are IDENTIFY and SIMPLE_TAG.
1549 	**	While negotiating sync or wide transfer,
1550 	**	a SDTR or WDTR message is appended.
1551 	**----------------------------------------------------------------
1552 	*/
1553 	u_char		scsi_smsg [8];
1554 	u_char		scsi_smsg2[8];
1555 
1556 	/*----------------------------------------------------------------
1557 	**	Other fields.
1558 	**----------------------------------------------------------------
1559 	*/
1560 	u_long		p_ccb;		/* BUS address of this CCB	*/
1561 	u_char		sensecmd[6];	/* Sense command		*/
1562 	u_char		tag;		/* Tag for this transfer	*/
1563 					/*  255 means no tag		*/
1564 	u_char		target;
1565 	u_char		lun;
1566 	u_char		queued;
1567 	u_char		auto_sense;
1568 	struct ccb *	link_ccb;	/* Host adapter CCB chain	*/
1569 	struct list_head link_ccbq;	/* Link to unit CCB queue	*/
1570 	u32		startp;		/* Initial data pointer		*/
1571 	u_long		magic;		/* Free / busy  CCB flag	*/
1572 };
1573 
1574 #define CCB_PHYS(cp,lbl)	(cp->p_ccb + offsetof(struct ccb, lbl))
1575 
1576 
1577 /*========================================================================
1578 **
1579 **      Declaration of structs:     NCR device descriptor
1580 **
1581 **========================================================================
1582 */
1583 struct ncb {
1584 	/*----------------------------------------------------------------
1585 	**	The global header.
1586 	**	It is accessible to both the host and the script processor.
1587 	**	Must be cache line size aligned (32 for x86) in order to
1588 	**	allow cache line bursting when it is copied to/from CCB.
1589 	**----------------------------------------------------------------
1590 	*/
1591 	struct head     header;
1592 
1593 	/*----------------------------------------------------------------
1594 	**	CCBs management queues.
1595 	**----------------------------------------------------------------
1596 	*/
1597 	struct scsi_cmnd	*waiting_list;	/* Commands waiting for a CCB	*/
1598 					/*  when lcb is not allocated.	*/
1599 	struct scsi_cmnd	*done_list;	/* Commands waiting for done()  */
1600 					/* callback to be invoked.      */
1601 	spinlock_t	smp_lock;	/* Lock for SMP threading       */
1602 
1603 	/*----------------------------------------------------------------
1604 	**	Chip and controller identification.
1605 	**----------------------------------------------------------------
1606 	*/
1607 	int		unit;		/* Unit number			*/
1608 	char		inst_name[16];	/* ncb instance name		*/
1609 
1610 	/*----------------------------------------------------------------
1611 	**	Initial value of some IO register bits.
1612 	**	These values are assumed to have been set by BIOS, and may
1613 	**	be used for probing adapter implementation differences.
1614 	**----------------------------------------------------------------
1615 	*/
1616 	u_char	sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest0, sv_ctest3,
1617 		sv_ctest4, sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4;
1618 
1619 	/*----------------------------------------------------------------
1620 	**	Actual initial value of IO register bits used by the
1621 	**	driver. They are loaded at initialisation according to
1622 	**	features that are to be enabled.
1623 	**----------------------------------------------------------------
1624 	*/
1625 	u_char	rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest0, rv_ctest3,
1626 		rv_ctest4, rv_ctest5, rv_stest2;
1627 
1628 	/*----------------------------------------------------------------
1629 	**	Targets management.
1630 	**	During reselection the ncr jumps to jump_tcb.
1631 	**	The SFBR register is loaded with the encoded target id.
1632 	**	For i = 0 to 3
1633 	**		SCR_JUMP ^ IFTRUE(MASK(i, 3)), @(next tcb mod. i)
1634 	**
1635 	**	Recent chips will prefetch the 4 JUMPS using only 1 burst.
1636 	**	It is kind of hashcoding.
1637 	**----------------------------------------------------------------
1638 	*/
1639 	struct link     jump_tcb[4];	/* JUMPs for reselection	*/
1640 	struct tcb  target[MAX_TARGET];	/* Target data			*/
1641 
1642 	/*----------------------------------------------------------------
1643 	**	Virtual and physical bus addresses of the chip.
1644 	**----------------------------------------------------------------
1645 	*/
1646 	void __iomem *vaddr;		/* Virtual and bus address of	*/
1647 	unsigned long	paddr;		/*  chip's IO registers.	*/
1648 	unsigned long	paddr2;		/* On-chip RAM bus address.	*/
1649 	volatile			/* Pointer to volatile for 	*/
1650 	struct ncr_reg	__iomem *reg;	/*  memory mapped IO.		*/
1651 
1652 	/*----------------------------------------------------------------
1653 	**	SCRIPTS virtual and physical bus addresses.
1654 	**	'script'  is loaded in the on-chip RAM if present.
1655 	**	'scripth' stays in main memory.
1656 	**----------------------------------------------------------------
1657 	*/
1658 	struct script	*script0;	/* Copies of script and scripth	*/
1659 	struct scripth	*scripth0;	/*  relocated for this ncb.	*/
1660 	struct scripth	*scripth;	/* Actual scripth virt. address	*/
1661 	u_long		p_script;	/* Actual script and scripth	*/
1662 	u_long		p_scripth;	/*  bus addresses.		*/
1663 
1664 	/*----------------------------------------------------------------
1665 	**	General controller parameters and configuration.
1666 	**----------------------------------------------------------------
1667 	*/
1668 	struct device	*dev;
1669 	u_char		revision_id;	/* PCI device revision id	*/
1670 	u32		irq;		/* IRQ level			*/
1671 	u32		features;	/* Chip features map		*/
1672 	u_char		myaddr;		/* SCSI id of the adapter	*/
1673 	u_char		maxburst;	/* log base 2 of dwords burst	*/
1674 	u_char		maxwide;	/* Maximum transfer width	*/
1675 	u_char		minsync;	/* Minimum sync period factor	*/
1676 	u_char		maxsync;	/* Maximum sync period factor	*/
1677 	u_char		maxoffs;	/* Max scsi offset		*/
1678 	u_char		multiplier;	/* Clock multiplier (1,2,4)	*/
1679 	u_char		clock_divn;	/* Number of clock divisors	*/
1680 	u_long		clock_khz;	/* SCSI clock frequency in KHz	*/
1681 
1682 	/*----------------------------------------------------------------
1683 	**	Start queue management.
1684 	**	It is filled up by the host processor and accessed by the
1685 	**	SCRIPTS processor in order to start SCSI commands.
1686 	**----------------------------------------------------------------
1687 	*/
1688 	u16		squeueput;	/* Next free slot of the queue	*/
1689 	u16		actccbs;	/* Number of allocated CCBs	*/
1690 	u16		queuedccbs;	/* Number of CCBs in start queue*/
1691 	u16		queuedepth;	/* Start queue depth		*/
1692 
1693 	/*----------------------------------------------------------------
1694 	**	Timeout handler.
1695 	**----------------------------------------------------------------
1696 	*/
1697 	struct timer_list timer;	/* Timer handler link header	*/
1698 	u_long		lasttime;
1699 	u_long		settle_time;	/* Resetting the SCSI BUS	*/
1700 
1701 	/*----------------------------------------------------------------
1702 	**	Debugging and profiling.
1703 	**----------------------------------------------------------------
1704 	*/
1705 	struct ncr_reg	regdump;	/* Register dump		*/
1706 	u_long		regtime;	/* Time it has been done	*/
1707 
1708 	/*----------------------------------------------------------------
1709 	**	Miscellaneous buffers accessed by the scripts-processor.
1710 	**	They shall be DWORD aligned, because they may be read or
1711 	**	written with a SCR_COPY script command.
1712 	**----------------------------------------------------------------
1713 	*/
1714 	u_char		msgout[8];	/* Buffer for MESSAGE OUT 	*/
1715 	u_char		msgin [8];	/* Buffer for MESSAGE IN	*/
1716 	u32		lastmsg;	/* Last SCSI message sent	*/
1717 	u_char		scratch;	/* Scratch for SCSI receive	*/
1718 
1719 	/*----------------------------------------------------------------
1720 	**	Miscellaneous configuration and status parameters.
1721 	**----------------------------------------------------------------
1722 	*/
1723 	u_char		disc;		/* Disconnection allowed	*/
1724 	u_char		scsi_mode;	/* Current SCSI BUS mode	*/
1725 	u_char		order;		/* Tag order to use		*/
1726 	u_char		verbose;	/* Verbosity for this controller*/
1727 	int		ncr_cache;	/* Used for cache test at init.	*/
1728 	u_long		p_ncb;		/* BUS address of this NCB	*/
1729 
1730 	/*----------------------------------------------------------------
1731 	**	Command completion handling.
1732 	**----------------------------------------------------------------
1733 	*/
1734 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1735 	struct ccb	*(ccb_done[MAX_DONE]);
1736 	int		ccb_done_ic;
1737 #endif
1738 	/*----------------------------------------------------------------
1739 	**	Fields that should be removed or changed.
1740 	**----------------------------------------------------------------
1741 	*/
1742 	struct ccb	*ccb;		/* Global CCB			*/
1743 	struct usrcmd	user;		/* Command from user		*/
1744 	volatile u_char	release_stage;	/* Synchronisation stage on release  */
1745 };
1746 
1747 #define NCB_SCRIPT_PHYS(np,lbl)	 (np->p_script  + offsetof (struct script, lbl))
1748 #define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
1749 
1750 /*==========================================================
1751 **
1752 **
1753 **      Script for NCR-Processor.
1754 **
1755 **	Use ncr_script_fill() to create the variable parts.
1756 **	Use ncr_script_copy_and_bind() to make a copy and
1757 **	bind to physical addresses.
1758 **
1759 **
1760 **==========================================================
1761 **
1762 **	We have to know the offsets of all labels before
1763 **	we reach them (for forward jumps).
1764 **	Therefore we declare a struct here.
1765 **	If you make changes inside the script,
1766 **	DONT FORGET TO CHANGE THE LENGTHS HERE!
1767 **
1768 **----------------------------------------------------------
1769 */
1770 
1771 /*
1772 **	For HP Zalon/53c720 systems, the Zalon interface
1773 **	between CPU and 53c720 does prefetches, which causes
1774 **	problems with self modifying scripts.  The problem
1775 **	is overcome by calling a dummy subroutine after each
1776 **	modification, to force a refetch of the script on
1777 **	return from the subroutine.
1778 */
1779 
1780 #ifdef CONFIG_NCR53C8XX_PREFETCH
1781 #define PREFETCH_FLUSH_CNT	2
1782 #define PREFETCH_FLUSH		SCR_CALL, PADDRH (wait_dma),
1783 #else
1784 #define PREFETCH_FLUSH_CNT	0
1785 #define PREFETCH_FLUSH
1786 #endif
1787 
1788 /*
1789 **	Script fragments which are loaded into the on-chip RAM
1790 **	of 825A, 875 and 895 chips.
1791 */
1792 struct script {
1793 	ncrcmd	start		[  5];
1794 	ncrcmd  startpos	[  1];
1795 	ncrcmd	select		[  6];
1796 	ncrcmd	select2		[  9 + PREFETCH_FLUSH_CNT];
1797 	ncrcmd	loadpos		[  4];
1798 	ncrcmd	send_ident	[  9];
1799 	ncrcmd	prepare		[  6];
1800 	ncrcmd	prepare2	[  7];
1801 	ncrcmd  command		[  6];
1802 	ncrcmd  dispatch	[ 32];
1803 	ncrcmd  clrack		[  4];
1804 	ncrcmd	no_data		[ 17];
1805 	ncrcmd  status		[  8];
1806 	ncrcmd  msg_in		[  2];
1807 	ncrcmd  msg_in2		[ 16];
1808 	ncrcmd  msg_bad		[  4];
1809 	ncrcmd	setmsg		[  7];
1810 	ncrcmd	cleanup		[  6];
1811 	ncrcmd  complete	[  9];
1812 	ncrcmd	cleanup_ok	[  8 + PREFETCH_FLUSH_CNT];
1813 	ncrcmd	cleanup0	[  1];
1814 #ifndef SCSI_NCR_CCB_DONE_SUPPORT
1815 	ncrcmd	signal		[ 12];
1816 #else
1817 	ncrcmd	signal		[  9];
1818 	ncrcmd	done_pos	[  1];
1819 	ncrcmd	done_plug	[  2];
1820 	ncrcmd	done_end	[  7];
1821 #endif
1822 	ncrcmd  save_dp		[  7];
1823 	ncrcmd  restore_dp	[  5];
1824 	ncrcmd  disconnect	[ 10];
1825 	ncrcmd	msg_out		[  9];
1826 	ncrcmd	msg_out_done	[  7];
1827 	ncrcmd  idle		[  2];
1828 	ncrcmd	reselect	[  8];
1829 	ncrcmd	reselected	[  8];
1830 	ncrcmd	resel_dsa	[  6 + PREFETCH_FLUSH_CNT];
1831 	ncrcmd	loadpos1	[  4];
1832 	ncrcmd  resel_lun	[  6];
1833 	ncrcmd	resel_tag	[  6];
1834 	ncrcmd	jump_to_nexus	[  4 + PREFETCH_FLUSH_CNT];
1835 	ncrcmd	nexus_indirect	[  4];
1836 	ncrcmd	resel_notag	[  4];
1837 	ncrcmd  data_in		[MAX_SCATTERL * 4];
1838 	ncrcmd  data_in2	[  4];
1839 	ncrcmd  data_out	[MAX_SCATTERL * 4];
1840 	ncrcmd  data_out2	[  4];
1841 };
1842 
1843 /*
1844 **	Script fragments which stay in main memory for all chips.
1845 */
1846 struct scripth {
1847 	ncrcmd  tryloop		[MAX_START*2];
1848 	ncrcmd  tryloop2	[  2];
1849 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
1850 	ncrcmd  done_queue	[MAX_DONE*5];
1851 	ncrcmd  done_queue2	[  2];
1852 #endif
1853 	ncrcmd	select_no_atn	[  8];
1854 	ncrcmd	cancel		[  4];
1855 	ncrcmd	skip		[  9 + PREFETCH_FLUSH_CNT];
1856 	ncrcmd	skip2		[ 19];
1857 	ncrcmd	par_err_data_in	[  6];
1858 	ncrcmd	par_err_other	[  4];
1859 	ncrcmd	msg_reject	[  8];
1860 	ncrcmd	msg_ign_residue	[ 24];
1861 	ncrcmd  msg_extended	[ 10];
1862 	ncrcmd  msg_ext_2	[ 10];
1863 	ncrcmd	msg_wdtr	[ 14];
1864 	ncrcmd	send_wdtr	[  7];
1865 	ncrcmd  msg_ext_3	[ 10];
1866 	ncrcmd	msg_sdtr	[ 14];
1867 	ncrcmd	send_sdtr	[  7];
1868 	ncrcmd	nego_bad_phase	[  4];
1869 	ncrcmd	msg_out_abort	[ 10];
1870 	ncrcmd  hdata_in	[MAX_SCATTERH * 4];
1871 	ncrcmd  hdata_in2	[  2];
1872 	ncrcmd  hdata_out	[MAX_SCATTERH * 4];
1873 	ncrcmd  hdata_out2	[  2];
1874 	ncrcmd	reset		[  4];
1875 	ncrcmd	aborttag	[  4];
1876 	ncrcmd	abort		[  2];
1877 	ncrcmd	abort_resel	[ 20];
1878 	ncrcmd	resend_ident	[  4];
1879 	ncrcmd	clratn_go_on	[  3];
1880 	ncrcmd	nxtdsp_go_on	[  1];
1881 	ncrcmd	sdata_in	[  8];
1882 	ncrcmd  data_io		[ 18];
1883 	ncrcmd	bad_identify	[ 12];
1884 	ncrcmd	bad_i_t_l	[  4];
1885 	ncrcmd	bad_i_t_l_q	[  4];
1886 	ncrcmd	bad_target	[  8];
1887 	ncrcmd	bad_status	[  8];
1888 	ncrcmd	start_ram	[  4 + PREFETCH_FLUSH_CNT];
1889 	ncrcmd	start_ram0	[  4];
1890 	ncrcmd	sto_restart	[  5];
1891 	ncrcmd	wait_dma	[  2];
1892 	ncrcmd	snooptest	[  9];
1893 	ncrcmd	snoopend	[  2];
1894 };
1895 
1896 /*==========================================================
1897 **
1898 **
1899 **      Function headers.
1900 **
1901 **
1902 **==========================================================
1903 */
1904 
1905 static	void	ncr_alloc_ccb	(struct ncb *np, u_char tn, u_char ln);
1906 static	void	ncr_complete	(struct ncb *np, struct ccb *cp);
1907 static	void	ncr_exception	(struct ncb *np);
1908 static	void	ncr_free_ccb	(struct ncb *np, struct ccb *cp);
1909 static	void	ncr_init_ccb	(struct ncb *np, struct ccb *cp);
1910 static	void	ncr_init_tcb	(struct ncb *np, u_char tn);
1911 static	struct lcb *	ncr_alloc_lcb	(struct ncb *np, u_char tn, u_char ln);
1912 static	struct lcb *	ncr_setup_lcb	(struct ncb *np, struct scsi_device *sdev);
1913 static	void	ncr_getclock	(struct ncb *np, int mult);
1914 static	void	ncr_selectclock	(struct ncb *np, u_char scntl3);
1915 static	struct ccb *ncr_get_ccb	(struct ncb *np, struct scsi_cmnd *cmd);
1916 static	void	ncr_chip_reset	(struct ncb *np, int delay);
1917 static	void	ncr_init	(struct ncb *np, int reset, char * msg, u_long code);
1918 static	int	ncr_int_sbmc	(struct ncb *np);
1919 static	int	ncr_int_par	(struct ncb *np);
1920 static	void	ncr_int_ma	(struct ncb *np);
1921 static	void	ncr_int_sir	(struct ncb *np);
1922 static  void    ncr_int_sto     (struct ncb *np);
1923 static	void	ncr_negotiate	(struct ncb* np, struct tcb* tp);
1924 static	int	ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr);
1925 
1926 static	void	ncr_script_copy_and_bind
1927 				(struct ncb *np, ncrcmd *src, ncrcmd *dst, int len);
1928 static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
1929 static	int	ncr_scatter	(struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd);
1930 static	void	ncr_getsync	(struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p);
1931 static	void	ncr_setsync	(struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer);
1932 static	void	ncr_setup_tags	(struct ncb *np, struct scsi_device *sdev);
1933 static	void	ncr_setwide	(struct ncb *np, struct ccb *cp, u_char wide, u_char ack);
1934 static	int	ncr_snooptest	(struct ncb *np);
1935 static	void	ncr_timeout	(struct ncb *np);
1936 static  void    ncr_wakeup      (struct ncb *np, u_long code);
1937 static  void    ncr_wakeup_done (struct ncb *np);
1938 static	void	ncr_start_next_ccb (struct ncb *np, struct lcb * lp, int maxn);
1939 static	void	ncr_put_start_queue(struct ncb *np, struct ccb *cp);
1940 
1941 static void insert_into_waiting_list(struct ncb *np, struct scsi_cmnd *cmd);
1942 static void process_waiting_list(struct ncb *np, int sts);
1943 
1944 #define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
1945 #define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
1946 
1947 static inline char *ncr_name (struct ncb *np)
1948 {
1949 	return np->inst_name;
1950 }
1951 
1952 
1953 /*==========================================================
1954 **
1955 **
1956 **      Scripts for NCR-Processor.
1957 **
1958 **      Use ncr_script_bind for binding to physical addresses.
1959 **
1960 **
1961 **==========================================================
1962 **
1963 **	NADDR generates a reference to a field of the controller data.
1964 **	PADDR generates a reference to another part of the script.
1965 **	RADDR generates a reference to a script processor register.
1966 **	FADDR generates a reference to a script processor register
1967 **		with offset.
1968 **
1969 **----------------------------------------------------------
1970 */
1971 
1972 #define	RELOC_SOFTC	0x40000000
1973 #define	RELOC_LABEL	0x50000000
1974 #define	RELOC_REGISTER	0x60000000
1975 #define	RELOC_LABELH	0x80000000
1976 #define	RELOC_MASK	0xf0000000
1977 
1978 #define	NADDR(label)	(RELOC_SOFTC | offsetof(struct ncb, label))
1979 #define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
1980 #define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
1981 #define	RADDR(label)	(RELOC_REGISTER | REG(label))
1982 #define	FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
1983 
1984 
1985 static	struct script script0 __initdata = {
1986 /*--------------------------< START >-----------------------*/ {
1987 	/*
1988 	**	This NOP will be patched with LED ON
1989 	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
1990 	*/
1991 	SCR_NO_OP,
1992 		0,
1993 	/*
1994 	**      Clear SIGP.
1995 	*/
1996 	SCR_FROM_REG (ctest2),
1997 		0,
1998 	/*
1999 	**	Then jump to a certain point in tryloop.
2000 	**	Due to the lack of indirect addressing the code
2001 	**	is self modifying here.
2002 	*/
2003 	SCR_JUMP,
2004 }/*-------------------------< STARTPOS >--------------------*/,{
2005 		PADDRH(tryloop),
2006 
2007 }/*-------------------------< SELECT >----------------------*/,{
2008 	/*
2009 	**	DSA	contains the address of a scheduled
2010 	**		data structure.
2011 	**
2012 	**	SCRATCHA contains the address of the script,
2013 	**		which starts the next entry.
2014 	**
2015 	**	Set Initiator mode.
2016 	**
2017 	**	(Target mode is left as an exercise for the reader)
2018 	*/
2019 
2020 	SCR_CLR (SCR_TRG),
2021 		0,
2022 	SCR_LOAD_REG (HS_REG, HS_SELECTING),
2023 		0,
2024 
2025 	/*
2026 	**      And try to select this target.
2027 	*/
2028 	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2029 		PADDR (reselect),
2030 
2031 }/*-------------------------< SELECT2 >----------------------*/,{
2032 	/*
2033 	**	Now there are 4 possibilities:
2034 	**
2035 	**	(1) The ncr loses arbitration.
2036 	**	This is ok, because it will try again,
2037 	**	when the bus becomes idle.
2038 	**	(But beware of the timeout function!)
2039 	**
2040 	**	(2) The ncr is reselected.
2041 	**	Then the script processor takes the jump
2042 	**	to the RESELECT label.
2043 	**
2044 	**	(3) The ncr wins arbitration.
2045 	**	Then it will execute SCRIPTS instruction until
2046 	**	the next instruction that checks SCSI phase.
2047 	**	Then will stop and wait for selection to be
2048 	**	complete or selection time-out to occur.
2049 	**	As a result the SCRIPTS instructions until
2050 	**	LOADPOS + 2 should be executed in parallel with
2051 	**	the SCSI core performing selection.
2052 	*/
2053 
2054 	/*
2055 	**	The MESSAGE_REJECT problem seems to be due to a selection
2056 	**	timing problem.
2057 	**	Wait immediately for the selection to complete.
2058 	**	(2.5x behaves so)
2059 	*/
2060 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2061 		0,
2062 
2063 	/*
2064 	**	Next time use the next slot.
2065 	*/
2066 	SCR_COPY (4),
2067 		RADDR (temp),
2068 		PADDR (startpos),
2069 	/*
2070 	**      The ncr doesn't have an indirect load
2071 	**	or store command. So we have to
2072 	**	copy part of the control block to a
2073 	**	fixed place, where we can access it.
2074 	**
2075 	**	We patch the address part of a
2076 	**	COPY command with the DSA-register.
2077 	*/
2078 	SCR_COPY_F (4),
2079 		RADDR (dsa),
2080 		PADDR (loadpos),
2081 	/*
2082 	**	Flush script prefetch if required
2083 	*/
2084 	PREFETCH_FLUSH
2085 	/*
2086 	**	then we do the actual copy.
2087 	*/
2088 	SCR_COPY (sizeof (struct head)),
2089 	/*
2090 	**	continued after the next label ...
2091 	*/
2092 }/*-------------------------< LOADPOS >---------------------*/,{
2093 		0,
2094 		NADDR (header),
2095 	/*
2096 	**	Wait for the next phase or the selection
2097 	**	to complete or time-out.
2098 	*/
2099 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2100 		PADDR (prepare),
2101 
2102 }/*-------------------------< SEND_IDENT >----------------------*/,{
2103 	/*
2104 	**	Selection complete.
2105 	**	Send the IDENTIFY and SIMPLE_TAG messages
2106 	**	(and the EXTENDED_SDTR message)
2107 	*/
2108 	SCR_MOVE_TBL ^ SCR_MSG_OUT,
2109 		offsetof (struct dsb, smsg),
2110 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2111 		PADDRH (resend_ident),
2112 	SCR_LOAD_REG (scratcha, 0x80),
2113 		0,
2114 	SCR_COPY (1),
2115 		RADDR (scratcha),
2116 		NADDR (lastmsg),
2117 }/*-------------------------< PREPARE >----------------------*/,{
2118 	/*
2119 	**      load the savep (saved pointer) into
2120 	**      the TEMP register (actual pointer)
2121 	*/
2122 	SCR_COPY (4),
2123 		NADDR (header.savep),
2124 		RADDR (temp),
2125 	/*
2126 	**      Initialize the status registers
2127 	*/
2128 	SCR_COPY (4),
2129 		NADDR (header.status),
2130 		RADDR (scr0),
2131 }/*-------------------------< PREPARE2 >---------------------*/,{
2132 	/*
2133 	**	Initialize the msgout buffer with a NOOP message.
2134 	*/
2135 	SCR_LOAD_REG (scratcha, NOP),
2136 		0,
2137 	SCR_COPY (1),
2138 		RADDR (scratcha),
2139 		NADDR (msgout),
2140 	/*
2141 	**	Anticipate the COMMAND phase.
2142 	**	This is the normal case for initial selection.
2143 	*/
2144 	SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
2145 		PADDR (dispatch),
2146 
2147 }/*-------------------------< COMMAND >--------------------*/,{
2148 	/*
2149 	**	... and send the command
2150 	*/
2151 	SCR_MOVE_TBL ^ SCR_COMMAND,
2152 		offsetof (struct dsb, cmd),
2153 	/*
2154 	**	If status is still HS_NEGOTIATE, negotiation failed.
2155 	**	We check this here, since we want to do that
2156 	**	only once.
2157 	*/
2158 	SCR_FROM_REG (HS_REG),
2159 		0,
2160 	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2161 		SIR_NEGO_FAILED,
2162 
2163 }/*-----------------------< DISPATCH >----------------------*/,{
2164 	/*
2165 	**	MSG_IN is the only phase that shall be
2166 	**	entered at least once for each (re)selection.
2167 	**	So we test it first.
2168 	*/
2169 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2170 		PADDR (msg_in),
2171 
2172 	SCR_RETURN ^ IFTRUE (IF (SCR_DATA_OUT)),
2173 		0,
2174 	/*
2175 	**	DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 4.
2176 	**	Possible data corruption during Memory Write and Invalidate.
2177 	**	This work-around resets the addressing logic prior to the
2178 	**	start of the first MOVE of a DATA IN phase.
2179 	**	(See Documentation/scsi/ncr53c8xx.rst for more information)
2180 	*/
2181 	SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2182 		20,
2183 	SCR_COPY (4),
2184 		RADDR (scratcha),
2185 		RADDR (scratcha),
2186 	SCR_RETURN,
2187  		0,
2188 	SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
2189 		PADDR (status),
2190 	SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
2191 		PADDR (command),
2192 	SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
2193 		PADDR (msg_out),
2194 	/*
2195 	**      Discard one illegal phase byte, if required.
2196 	*/
2197 	SCR_LOAD_REG (scratcha, XE_BAD_PHASE),
2198 		0,
2199 	SCR_COPY (1),
2200 		RADDR (scratcha),
2201 		NADDR (xerr_st),
2202 	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_OUT)),
2203 		8,
2204 	SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
2205 		NADDR (scratch),
2206 	SCR_JUMPR ^ IFFALSE (IF (SCR_ILG_IN)),
2207 		8,
2208 	SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
2209 		NADDR (scratch),
2210 	SCR_JUMP,
2211 		PADDR (dispatch),
2212 
2213 }/*-------------------------< CLRACK >----------------------*/,{
2214 	/*
2215 	**	Terminate possible pending message phase.
2216 	*/
2217 	SCR_CLR (SCR_ACK),
2218 		0,
2219 	SCR_JUMP,
2220 		PADDR (dispatch),
2221 
2222 }/*-------------------------< NO_DATA >--------------------*/,{
2223 	/*
2224 	**	The target wants to tranfer too much data
2225 	**	or in the wrong direction.
2226 	**      Remember that in extended error.
2227 	*/
2228 	SCR_LOAD_REG (scratcha, XE_EXTRA_DATA),
2229 		0,
2230 	SCR_COPY (1),
2231 		RADDR (scratcha),
2232 		NADDR (xerr_st),
2233 	/*
2234 	**      Discard one data byte, if required.
2235 	*/
2236 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2237 		8,
2238 	SCR_MOVE_ABS (1) ^ SCR_DATA_OUT,
2239 		NADDR (scratch),
2240 	SCR_JUMPR ^ IFFALSE (IF (SCR_DATA_IN)),
2241 		8,
2242 	SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2243 		NADDR (scratch),
2244 	/*
2245 	**      .. and repeat as required.
2246 	*/
2247 	SCR_CALL,
2248 		PADDR (dispatch),
2249 	SCR_JUMP,
2250 		PADDR (no_data),
2251 
2252 }/*-------------------------< STATUS >--------------------*/,{
2253 	/*
2254 	**	get the status
2255 	*/
2256 	SCR_MOVE_ABS (1) ^ SCR_STATUS,
2257 		NADDR (scratch),
2258 	/*
2259 	**	save status to scsi_status.
2260 	**	mark as complete.
2261 	*/
2262 	SCR_TO_REG (SS_REG),
2263 		0,
2264 	SCR_LOAD_REG (HS_REG, HS_COMPLETE),
2265 		0,
2266 	SCR_JUMP,
2267 		PADDR (dispatch),
2268 }/*-------------------------< MSG_IN >--------------------*/,{
2269 	/*
2270 	**	Get the first byte of the message
2271 	**	and save it to SCRATCHA.
2272 	**
2273 	**	The script processor doesn't negate the
2274 	**	ACK signal after this transfer.
2275 	*/
2276 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2277 		NADDR (msgin[0]),
2278 }/*-------------------------< MSG_IN2 >--------------------*/,{
2279 	/*
2280 	**	Handle this message.
2281 	*/
2282 	SCR_JUMP ^ IFTRUE (DATA (COMMAND_COMPLETE)),
2283 		PADDR (complete),
2284 	SCR_JUMP ^ IFTRUE (DATA (DISCONNECT)),
2285 		PADDR (disconnect),
2286 	SCR_JUMP ^ IFTRUE (DATA (SAVE_POINTERS)),
2287 		PADDR (save_dp),
2288 	SCR_JUMP ^ IFTRUE (DATA (RESTORE_POINTERS)),
2289 		PADDR (restore_dp),
2290 	SCR_JUMP ^ IFTRUE (DATA (EXTENDED_MESSAGE)),
2291 		PADDRH (msg_extended),
2292 	SCR_JUMP ^ IFTRUE (DATA (NOP)),
2293 		PADDR (clrack),
2294 	SCR_JUMP ^ IFTRUE (DATA (MESSAGE_REJECT)),
2295 		PADDRH (msg_reject),
2296 	SCR_JUMP ^ IFTRUE (DATA (IGNORE_WIDE_RESIDUE)),
2297 		PADDRH (msg_ign_residue),
2298 	/*
2299 	**	Rest of the messages left as
2300 	**	an exercise ...
2301 	**
2302 	**	Unimplemented messages:
2303 	**	fall through to MSG_BAD.
2304 	*/
2305 }/*-------------------------< MSG_BAD >------------------*/,{
2306 	/*
2307 	**	unimplemented message - reject it.
2308 	*/
2309 	SCR_INT,
2310 		SIR_REJECT_SENT,
2311 	SCR_LOAD_REG (scratcha, MESSAGE_REJECT),
2312 		0,
2313 }/*-------------------------< SETMSG >----------------------*/,{
2314 	SCR_COPY (1),
2315 		RADDR (scratcha),
2316 		NADDR (msgout),
2317 	SCR_SET (SCR_ATN),
2318 		0,
2319 	SCR_JUMP,
2320 		PADDR (clrack),
2321 }/*-------------------------< CLEANUP >-------------------*/,{
2322 	/*
2323 	**      dsa:    Pointer to ccb
2324 	**	      or xxxxxxFF (no ccb)
2325 	**
2326 	**      HS_REG:   Host-Status (<>0!)
2327 	*/
2328 	SCR_FROM_REG (dsa),
2329 		0,
2330 	SCR_JUMP ^ IFTRUE (DATA (0xff)),
2331 		PADDR (start),
2332 	/*
2333 	**      dsa is valid.
2334 	**	complete the cleanup.
2335 	*/
2336 	SCR_JUMP,
2337 		PADDR (cleanup_ok),
2338 
2339 }/*-------------------------< COMPLETE >-----------------*/,{
2340 	/*
2341 	**	Complete message.
2342 	**
2343 	**	Copy TEMP register to LASTP in header.
2344 	*/
2345 	SCR_COPY (4),
2346 		RADDR (temp),
2347 		NADDR (header.lastp),
2348 	/*
2349 	**	When we terminate the cycle by clearing ACK,
2350 	**	the target may disconnect immediately.
2351 	**
2352 	**	We don't want to be told of an
2353 	**	"unexpected disconnect",
2354 	**	so we disable this feature.
2355 	*/
2356 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2357 		0,
2358 	/*
2359 	**	Terminate cycle ...
2360 	*/
2361 	SCR_CLR (SCR_ACK|SCR_ATN),
2362 		0,
2363 	/*
2364 	**	... and wait for the disconnect.
2365 	*/
2366 	SCR_WAIT_DISC,
2367 		0,
2368 }/*-------------------------< CLEANUP_OK >----------------*/,{
2369 	/*
2370 	**	Save host status to header.
2371 	*/
2372 	SCR_COPY (4),
2373 		RADDR (scr0),
2374 		NADDR (header.status),
2375 	/*
2376 	**	and copy back the header to the ccb.
2377 	*/
2378 	SCR_COPY_F (4),
2379 		RADDR (dsa),
2380 		PADDR (cleanup0),
2381 	/*
2382 	**	Flush script prefetch if required
2383 	*/
2384 	PREFETCH_FLUSH
2385 	SCR_COPY (sizeof (struct head)),
2386 		NADDR (header),
2387 }/*-------------------------< CLEANUP0 >--------------------*/,{
2388 		0,
2389 }/*-------------------------< SIGNAL >----------------------*/,{
2390 	/*
2391 	**	if job not completed ...
2392 	*/
2393 	SCR_FROM_REG (HS_REG),
2394 		0,
2395 	/*
2396 	**	... start the next command.
2397 	*/
2398 	SCR_JUMP ^ IFTRUE (MASK (0, (HS_DONEMASK|HS_SKIPMASK))),
2399 		PADDR(start),
2400 	/*
2401 	**	If command resulted in not GOOD status,
2402 	**	call the C code if needed.
2403 	*/
2404 	SCR_FROM_REG (SS_REG),
2405 		0,
2406 	SCR_CALL ^ IFFALSE (DATA (SAM_STAT_GOOD)),
2407 		PADDRH (bad_status),
2408 
2409 #ifndef	SCSI_NCR_CCB_DONE_SUPPORT
2410 
2411 	/*
2412 	**	... signal completion to the host
2413 	*/
2414 	SCR_INT,
2415 		SIR_INTFLY,
2416 	/*
2417 	**	Auf zu neuen Schandtaten!
2418 	*/
2419 	SCR_JUMP,
2420 		PADDR(start),
2421 
2422 #else	/* defined SCSI_NCR_CCB_DONE_SUPPORT */
2423 
2424 	/*
2425 	**	... signal completion to the host
2426 	*/
2427 	SCR_JUMP,
2428 }/*------------------------< DONE_POS >---------------------*/,{
2429 		PADDRH (done_queue),
2430 }/*------------------------< DONE_PLUG >--------------------*/,{
2431 	SCR_INT,
2432 		SIR_DONE_OVERFLOW,
2433 }/*------------------------< DONE_END >---------------------*/,{
2434 	SCR_INT,
2435 		SIR_INTFLY,
2436 	SCR_COPY (4),
2437 		RADDR (temp),
2438 		PADDR (done_pos),
2439 	SCR_JUMP,
2440 		PADDR (start),
2441 
2442 #endif	/* SCSI_NCR_CCB_DONE_SUPPORT */
2443 
2444 }/*-------------------------< SAVE_DP >------------------*/,{
2445 	/*
2446 	**	SAVE_DP message:
2447 	**	Copy TEMP register to SAVEP in header.
2448 	*/
2449 	SCR_COPY (4),
2450 		RADDR (temp),
2451 		NADDR (header.savep),
2452 	SCR_CLR (SCR_ACK),
2453 		0,
2454 	SCR_JUMP,
2455 		PADDR (dispatch),
2456 }/*-------------------------< RESTORE_DP >---------------*/,{
2457 	/*
2458 	**	RESTORE_DP message:
2459 	**	Copy SAVEP in header to TEMP register.
2460 	*/
2461 	SCR_COPY (4),
2462 		NADDR (header.savep),
2463 		RADDR (temp),
2464 	SCR_JUMP,
2465 		PADDR (clrack),
2466 
2467 }/*-------------------------< DISCONNECT >---------------*/,{
2468 	/*
2469 	**	DISCONNECTing  ...
2470 	**
2471 	**	disable the "unexpected disconnect" feature,
2472 	**	and remove the ACK signal.
2473 	*/
2474 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
2475 		0,
2476 	SCR_CLR (SCR_ACK|SCR_ATN),
2477 		0,
2478 	/*
2479 	**	Wait for the disconnect.
2480 	*/
2481 	SCR_WAIT_DISC,
2482 		0,
2483 	/*
2484 	**	Status is: DISCONNECTED.
2485 	*/
2486 	SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
2487 		0,
2488 	SCR_JUMP,
2489 		PADDR (cleanup_ok),
2490 
2491 }/*-------------------------< MSG_OUT >-------------------*/,{
2492 	/*
2493 	**	The target requests a message.
2494 	*/
2495 	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
2496 		NADDR (msgout),
2497 	SCR_COPY (1),
2498 		NADDR (msgout),
2499 		NADDR (lastmsg),
2500 	/*
2501 	**	If it was no ABORT message ...
2502 	*/
2503 	SCR_JUMP ^ IFTRUE (DATA (ABORT_TASK_SET)),
2504 		PADDRH (msg_out_abort),
2505 	/*
2506 	**	... wait for the next phase
2507 	**	if it's a message out, send it again, ...
2508 	*/
2509 	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2510 		PADDR (msg_out),
2511 }/*-------------------------< MSG_OUT_DONE >--------------*/,{
2512 	/*
2513 	**	... else clear the message ...
2514 	*/
2515 	SCR_LOAD_REG (scratcha, NOP),
2516 		0,
2517 	SCR_COPY (4),
2518 		RADDR (scratcha),
2519 		NADDR (msgout),
2520 	/*
2521 	**	... and process the next phase
2522 	*/
2523 	SCR_JUMP,
2524 		PADDR (dispatch),
2525 }/*-------------------------< IDLE >------------------------*/,{
2526 	/*
2527 	**	Nothing to do?
2528 	**	Wait for reselect.
2529 	**	This NOP will be patched with LED OFF
2530 	**	SCR_REG_REG (gpreg, SCR_OR, 0x01)
2531 	*/
2532 	SCR_NO_OP,
2533 		0,
2534 }/*-------------------------< RESELECT >--------------------*/,{
2535 	/*
2536 	**	make the DSA invalid.
2537 	*/
2538 	SCR_LOAD_REG (dsa, 0xff),
2539 		0,
2540 	SCR_CLR (SCR_TRG),
2541 		0,
2542 	SCR_LOAD_REG (HS_REG, HS_IN_RESELECT),
2543 		0,
2544 	/*
2545 	**	Sleep waiting for a reselection.
2546 	**	If SIGP is set, special treatment.
2547 	**
2548 	**	Zu allem bereit ..
2549 	*/
2550 	SCR_WAIT_RESEL,
2551 		PADDR(start),
2552 }/*-------------------------< RESELECTED >------------------*/,{
2553 	/*
2554 	**	This NOP will be patched with LED ON
2555 	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2556 	*/
2557 	SCR_NO_OP,
2558 		0,
2559 	/*
2560 	**	... zu nichts zu gebrauchen ?
2561 	**
2562 	**      load the target id into the SFBR
2563 	**	and jump to the control block.
2564 	**
2565 	**	Look at the declarations of
2566 	**	- struct ncb
2567 	**	- struct tcb
2568 	**	- struct lcb
2569 	**	- struct ccb
2570 	**	to understand what's going on.
2571 	*/
2572 	SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
2573 		0,
2574 	SCR_TO_REG (sdid),
2575 		0,
2576 	SCR_JUMP,
2577 		NADDR (jump_tcb),
2578 
2579 }/*-------------------------< RESEL_DSA >-------------------*/,{
2580 	/*
2581 	**	Ack the IDENTIFY or TAG previously received.
2582 	*/
2583 	SCR_CLR (SCR_ACK),
2584 		0,
2585 	/*
2586 	**      The ncr doesn't have an indirect load
2587 	**	or store command. So we have to
2588 	**	copy part of the control block to a
2589 	**	fixed place, where we can access it.
2590 	**
2591 	**	We patch the address part of a
2592 	**	COPY command with the DSA-register.
2593 	*/
2594 	SCR_COPY_F (4),
2595 		RADDR (dsa),
2596 		PADDR (loadpos1),
2597 	/*
2598 	**	Flush script prefetch if required
2599 	*/
2600 	PREFETCH_FLUSH
2601 	/*
2602 	**	then we do the actual copy.
2603 	*/
2604 	SCR_COPY (sizeof (struct head)),
2605 	/*
2606 	**	continued after the next label ...
2607 	*/
2608 
2609 }/*-------------------------< LOADPOS1 >-------------------*/,{
2610 		0,
2611 		NADDR (header),
2612 	/*
2613 	**	The DSA contains the data structure address.
2614 	*/
2615 	SCR_JUMP,
2616 		PADDR (prepare),
2617 
2618 }/*-------------------------< RESEL_LUN >-------------------*/,{
2619 	/*
2620 	**	come back to this point
2621 	**	to get an IDENTIFY message
2622 	**	Wait for a msg_in phase.
2623 	*/
2624 	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2625 		SIR_RESEL_NO_MSG_IN,
2626 	/*
2627 	**	message phase.
2628 	**	Read the data directly from the BUS DATA lines.
2629 	**	This helps to support very old SCSI devices that
2630 	**	may reselect without sending an IDENTIFY.
2631 	*/
2632 	SCR_FROM_REG (sbdl),
2633 		0,
2634 	/*
2635 	**	It should be an Identify message.
2636 	*/
2637 	SCR_RETURN,
2638 		0,
2639 }/*-------------------------< RESEL_TAG >-------------------*/,{
2640 	/*
2641 	**	Read IDENTIFY + SIMPLE + TAG using a single MOVE.
2642 	**	Aggressive optimization, is'nt it?
2643 	**	No need to test the SIMPLE TAG message, since the
2644 	**	driver only supports conformant devices for tags. ;-)
2645 	*/
2646 	SCR_MOVE_ABS (3) ^ SCR_MSG_IN,
2647 		NADDR (msgin),
2648 	/*
2649 	**	Read the TAG from the SIDL.
2650 	**	Still an aggressive optimization. ;-)
2651 	**	Compute the CCB indirect jump address which
2652 	**	is (#TAG*2 & 0xfc) due to tag numbering using
2653 	**	1,3,5..MAXTAGS*2+1 actual values.
2654 	*/
2655 	SCR_REG_SFBR (sidl, SCR_SHL, 0),
2656 		0,
2657 	SCR_SFBR_REG (temp, SCR_AND, 0xfc),
2658 		0,
2659 }/*-------------------------< JUMP_TO_NEXUS >-------------------*/,{
2660 	SCR_COPY_F (4),
2661 		RADDR (temp),
2662 		PADDR (nexus_indirect),
2663 	/*
2664 	**	Flush script prefetch if required
2665 	*/
2666 	PREFETCH_FLUSH
2667 	SCR_COPY (4),
2668 }/*-------------------------< NEXUS_INDIRECT >-------------------*/,{
2669 		0,
2670 		RADDR (temp),
2671 	SCR_RETURN,
2672 		0,
2673 }/*-------------------------< RESEL_NOTAG >-------------------*/,{
2674 	/*
2675 	**	No tag expected.
2676 	**	Read an throw away the IDENTIFY.
2677 	*/
2678 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2679 		NADDR (msgin),
2680 	SCR_JUMP,
2681 		PADDR (jump_to_nexus),
2682 }/*-------------------------< DATA_IN >--------------------*/,{
2683 /*
2684 **	Because the size depends on the
2685 **	#define MAX_SCATTERL parameter,
2686 **	it is filled in at runtime.
2687 **
2688 **  ##===========< i=0; i<MAX_SCATTERL >=========
2689 **  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
2690 **  ||		PADDR (dispatch),
2691 **  ||	SCR_MOVE_TBL ^ SCR_DATA_IN,
2692 **  ||		offsetof (struct dsb, data[ i]),
2693 **  ##==========================================
2694 **
2695 **---------------------------------------------------------
2696 */
2697 0
2698 }/*-------------------------< DATA_IN2 >-------------------*/,{
2699 	SCR_CALL,
2700 		PADDR (dispatch),
2701 	SCR_JUMP,
2702 		PADDR (no_data),
2703 }/*-------------------------< DATA_OUT >--------------------*/,{
2704 /*
2705 **	Because the size depends on the
2706 **	#define MAX_SCATTERL parameter,
2707 **	it is filled in at runtime.
2708 **
2709 **  ##===========< i=0; i<MAX_SCATTERL >=========
2710 **  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
2711 **  ||		PADDR (dispatch),
2712 **  ||	SCR_MOVE_TBL ^ SCR_DATA_OUT,
2713 **  ||		offsetof (struct dsb, data[ i]),
2714 **  ##==========================================
2715 **
2716 **---------------------------------------------------------
2717 */
2718 0
2719 }/*-------------------------< DATA_OUT2 >-------------------*/,{
2720 	SCR_CALL,
2721 		PADDR (dispatch),
2722 	SCR_JUMP,
2723 		PADDR (no_data),
2724 }/*--------------------------------------------------------*/
2725 };
2726 
2727 static	struct scripth scripth0 __initdata = {
2728 /*-------------------------< TRYLOOP >---------------------*/{
2729 /*
2730 **	Start the next entry.
2731 **	Called addresses point to the launch script in the CCB.
2732 **	They are patched by the main processor.
2733 **
2734 **	Because the size depends on the
2735 **	#define MAX_START parameter, it is filled
2736 **	in at runtime.
2737 **
2738 **-----------------------------------------------------------
2739 **
2740 **  ##===========< I=0; i<MAX_START >===========
2741 **  ||	SCR_CALL,
2742 **  ||		PADDR (idle),
2743 **  ##==========================================
2744 **
2745 **-----------------------------------------------------------
2746 */
2747 0
2748 }/*------------------------< TRYLOOP2 >---------------------*/,{
2749 	SCR_JUMP,
2750 		PADDRH(tryloop),
2751 
2752 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
2753 
2754 }/*------------------------< DONE_QUEUE >-------------------*/,{
2755 /*
2756 **	Copy the CCB address to the next done entry.
2757 **	Because the size depends on the
2758 **	#define MAX_DONE parameter, it is filled
2759 **	in at runtime.
2760 **
2761 **-----------------------------------------------------------
2762 **
2763 **  ##===========< I=0; i<MAX_DONE >===========
2764 **  ||	SCR_COPY (sizeof(struct ccb *),
2765 **  ||		NADDR (header.cp),
2766 **  ||		NADDR (ccb_done[i]),
2767 **  ||	SCR_CALL,
2768 **  ||		PADDR (done_end),
2769 **  ##==========================================
2770 **
2771 **-----------------------------------------------------------
2772 */
2773 0
2774 }/*------------------------< DONE_QUEUE2 >------------------*/,{
2775 	SCR_JUMP,
2776 		PADDRH (done_queue),
2777 
2778 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
2779 }/*------------------------< SELECT_NO_ATN >-----------------*/,{
2780 	/*
2781 	**	Set Initiator mode.
2782 	**      And try to select this target without ATN.
2783 	*/
2784 
2785 	SCR_CLR (SCR_TRG),
2786 		0,
2787 	SCR_LOAD_REG (HS_REG, HS_SELECTING),
2788 		0,
2789 	SCR_SEL_TBL ^ offsetof (struct dsb, select),
2790 		PADDR (reselect),
2791 	SCR_JUMP,
2792 		PADDR (select2),
2793 
2794 }/*-------------------------< CANCEL >------------------------*/,{
2795 
2796 	SCR_LOAD_REG (scratcha, HS_ABORTED),
2797 		0,
2798 	SCR_JUMPR,
2799 		8,
2800 }/*-------------------------< SKIP >------------------------*/,{
2801 	SCR_LOAD_REG (scratcha, 0),
2802 		0,
2803 	/*
2804 	**	This entry has been canceled.
2805 	**	Next time use the next slot.
2806 	*/
2807 	SCR_COPY (4),
2808 		RADDR (temp),
2809 		PADDR (startpos),
2810 	/*
2811 	**      The ncr doesn't have an indirect load
2812 	**	or store command. So we have to
2813 	**	copy part of the control block to a
2814 	**	fixed place, where we can access it.
2815 	**
2816 	**	We patch the address part of a
2817 	**	COPY command with the DSA-register.
2818 	*/
2819 	SCR_COPY_F (4),
2820 		RADDR (dsa),
2821 		PADDRH (skip2),
2822 	/*
2823 	**	Flush script prefetch if required
2824 	*/
2825 	PREFETCH_FLUSH
2826 	/*
2827 	**	then we do the actual copy.
2828 	*/
2829 	SCR_COPY (sizeof (struct head)),
2830 	/*
2831 	**	continued after the next label ...
2832 	*/
2833 }/*-------------------------< SKIP2 >---------------------*/,{
2834 		0,
2835 		NADDR (header),
2836 	/*
2837 	**      Initialize the status registers
2838 	*/
2839 	SCR_COPY (4),
2840 		NADDR (header.status),
2841 		RADDR (scr0),
2842 	/*
2843 	**	Force host status.
2844 	*/
2845 	SCR_FROM_REG (scratcha),
2846 		0,
2847 	SCR_JUMPR ^ IFFALSE (MASK (0, HS_DONEMASK)),
2848 		16,
2849 	SCR_REG_REG (HS_REG, SCR_OR, HS_SKIPMASK),
2850 		0,
2851 	SCR_JUMPR,
2852 		8,
2853 	SCR_TO_REG (HS_REG),
2854 		0,
2855 	SCR_LOAD_REG (SS_REG, SAM_STAT_GOOD),
2856 		0,
2857 	SCR_JUMP,
2858 		PADDR (cleanup_ok),
2859 
2860 },/*-------------------------< PAR_ERR_DATA_IN >---------------*/{
2861 	/*
2862 	**	Ignore all data in byte, until next phase
2863 	*/
2864 	SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
2865 		PADDRH (par_err_other),
2866 	SCR_MOVE_ABS (1) ^ SCR_DATA_IN,
2867 		NADDR (scratch),
2868 	SCR_JUMPR,
2869 		-24,
2870 },/*-------------------------< PAR_ERR_OTHER >------------------*/{
2871 	/*
2872 	**	count it.
2873 	*/
2874 	SCR_REG_REG (PS_REG, SCR_ADD, 0x01),
2875 		0,
2876 	/*
2877 	**	jump to dispatcher.
2878 	*/
2879 	SCR_JUMP,
2880 		PADDR (dispatch),
2881 }/*-------------------------< MSG_REJECT >---------------*/,{
2882 	/*
2883 	**	If a negotiation was in progress,
2884 	**	negotiation failed.
2885 	**	Otherwise, let the C code print
2886 	**	some message.
2887 	*/
2888 	SCR_FROM_REG (HS_REG),
2889 		0,
2890 	SCR_INT ^ IFFALSE (DATA (HS_NEGOTIATE)),
2891 		SIR_REJECT_RECEIVED,
2892 	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2893 		SIR_NEGO_FAILED,
2894 	SCR_JUMP,
2895 		PADDR (clrack),
2896 
2897 }/*-------------------------< MSG_IGN_RESIDUE >----------*/,{
2898 	/*
2899 	**	Terminate cycle
2900 	*/
2901 	SCR_CLR (SCR_ACK),
2902 		0,
2903 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2904 		PADDR (dispatch),
2905 	/*
2906 	**	get residue size.
2907 	*/
2908 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2909 		NADDR (msgin[1]),
2910 	/*
2911 	**	Size is 0 .. ignore message.
2912 	*/
2913 	SCR_JUMP ^ IFTRUE (DATA (0)),
2914 		PADDR (clrack),
2915 	/*
2916 	**	Size is not 1 .. have to interrupt.
2917 	*/
2918 	SCR_JUMPR ^ IFFALSE (DATA (1)),
2919 		40,
2920 	/*
2921 	**	Check for residue byte in swide register
2922 	*/
2923 	SCR_FROM_REG (scntl2),
2924 		0,
2925 	SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
2926 		16,
2927 	/*
2928 	**	There IS data in the swide register.
2929 	**	Discard it.
2930 	*/
2931 	SCR_REG_REG (scntl2, SCR_OR, WSR),
2932 		0,
2933 	SCR_JUMP,
2934 		PADDR (clrack),
2935 	/*
2936 	**	Load again the size to the sfbr register.
2937 	*/
2938 	SCR_FROM_REG (scratcha),
2939 		0,
2940 	SCR_INT,
2941 		SIR_IGN_RESIDUE,
2942 	SCR_JUMP,
2943 		PADDR (clrack),
2944 
2945 }/*-------------------------< MSG_EXTENDED >-------------*/,{
2946 	/*
2947 	**	Terminate cycle
2948 	*/
2949 	SCR_CLR (SCR_ACK),
2950 		0,
2951 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2952 		PADDR (dispatch),
2953 	/*
2954 	**	get length.
2955 	*/
2956 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2957 		NADDR (msgin[1]),
2958 	/*
2959 	*/
2960 	SCR_JUMP ^ IFTRUE (DATA (3)),
2961 		PADDRH (msg_ext_3),
2962 	SCR_JUMP ^ IFFALSE (DATA (2)),
2963 		PADDR (msg_bad),
2964 }/*-------------------------< MSG_EXT_2 >----------------*/,{
2965 	SCR_CLR (SCR_ACK),
2966 		0,
2967 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2968 		PADDR (dispatch),
2969 	/*
2970 	**	get extended message code.
2971 	*/
2972 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2973 		NADDR (msgin[2]),
2974 	SCR_JUMP ^ IFTRUE (DATA (EXTENDED_WDTR)),
2975 		PADDRH (msg_wdtr),
2976 	/*
2977 	**	unknown extended message
2978 	*/
2979 	SCR_JUMP,
2980 		PADDR (msg_bad)
2981 }/*-------------------------< MSG_WDTR >-----------------*/,{
2982 	SCR_CLR (SCR_ACK),
2983 		0,
2984 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2985 		PADDR (dispatch),
2986 	/*
2987 	**	get data bus width
2988 	*/
2989 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2990 		NADDR (msgin[3]),
2991 	/*
2992 	**	let the host do the real work.
2993 	*/
2994 	SCR_INT,
2995 		SIR_NEGO_WIDE,
2996 	/*
2997 	**	let the target fetch our answer.
2998 	*/
2999 	SCR_SET (SCR_ATN),
3000 		0,
3001 	SCR_CLR (SCR_ACK),
3002 		0,
3003 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3004 		PADDRH (nego_bad_phase),
3005 
3006 }/*-------------------------< SEND_WDTR >----------------*/,{
3007 	/*
3008 	**	Send the EXTENDED_WDTR
3009 	*/
3010 	SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
3011 		NADDR (msgout),
3012 	SCR_COPY (1),
3013 		NADDR (msgout),
3014 		NADDR (lastmsg),
3015 	SCR_JUMP,
3016 		PADDR (msg_out_done),
3017 
3018 }/*-------------------------< MSG_EXT_3 >----------------*/,{
3019 	SCR_CLR (SCR_ACK),
3020 		0,
3021 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3022 		PADDR (dispatch),
3023 	/*
3024 	**	get extended message code.
3025 	*/
3026 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3027 		NADDR (msgin[2]),
3028 	SCR_JUMP ^ IFTRUE (DATA (EXTENDED_SDTR)),
3029 		PADDRH (msg_sdtr),
3030 	/*
3031 	**	unknown extended message
3032 	*/
3033 	SCR_JUMP,
3034 		PADDR (msg_bad)
3035 
3036 }/*-------------------------< MSG_SDTR >-----------------*/,{
3037 	SCR_CLR (SCR_ACK),
3038 		0,
3039 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3040 		PADDR (dispatch),
3041 	/*
3042 	**	get period and offset
3043 	*/
3044 	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
3045 		NADDR (msgin[3]),
3046 	/*
3047 	**	let the host do the real work.
3048 	*/
3049 	SCR_INT,
3050 		SIR_NEGO_SYNC,
3051 	/*
3052 	**	let the target fetch our answer.
3053 	*/
3054 	SCR_SET (SCR_ATN),
3055 		0,
3056 	SCR_CLR (SCR_ACK),
3057 		0,
3058 	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3059 		PADDRH (nego_bad_phase),
3060 
3061 }/*-------------------------< SEND_SDTR >-------------*/,{
3062 	/*
3063 	**	Send the EXTENDED_SDTR
3064 	*/
3065 	SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
3066 		NADDR (msgout),
3067 	SCR_COPY (1),
3068 		NADDR (msgout),
3069 		NADDR (lastmsg),
3070 	SCR_JUMP,
3071 		PADDR (msg_out_done),
3072 
3073 }/*-------------------------< NEGO_BAD_PHASE >------------*/,{
3074 	SCR_INT,
3075 		SIR_NEGO_PROTO,
3076 	SCR_JUMP,
3077 		PADDR (dispatch),
3078 
3079 }/*-------------------------< MSG_OUT_ABORT >-------------*/,{
3080 	/*
3081 	**	After ABORT message,
3082 	**
3083 	**	expect an immediate disconnect, ...
3084 	*/
3085 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3086 		0,
3087 	SCR_CLR (SCR_ACK|SCR_ATN),
3088 		0,
3089 	SCR_WAIT_DISC,
3090 		0,
3091 	/*
3092 	**	... and set the status to "ABORTED"
3093 	*/
3094 	SCR_LOAD_REG (HS_REG, HS_ABORTED),
3095 		0,
3096 	SCR_JUMP,
3097 		PADDR (cleanup),
3098 
3099 }/*-------------------------< HDATA_IN >-------------------*/,{
3100 /*
3101 **	Because the size depends on the
3102 **	#define MAX_SCATTERH parameter,
3103 **	it is filled in at runtime.
3104 **
3105 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3106 **  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3107 **  ||		PADDR (dispatch),
3108 **  ||	SCR_MOVE_TBL ^ SCR_DATA_IN,
3109 **  ||		offsetof (struct dsb, data[ i]),
3110 **  ##===================================================
3111 **
3112 **---------------------------------------------------------
3113 */
3114 0
3115 }/*-------------------------< HDATA_IN2 >------------------*/,{
3116 	SCR_JUMP,
3117 		PADDR (data_in),
3118 
3119 }/*-------------------------< HDATA_OUT >-------------------*/,{
3120 /*
3121 **	Because the size depends on the
3122 **	#define MAX_SCATTERH parameter,
3123 **	it is filled in at runtime.
3124 **
3125 **  ##==< i=MAX_SCATTERL; i<MAX_SCATTERL+MAX_SCATTERH >==
3126 **  ||	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT)),
3127 **  ||		PADDR (dispatch),
3128 **  ||	SCR_MOVE_TBL ^ SCR_DATA_OUT,
3129 **  ||		offsetof (struct dsb, data[ i]),
3130 **  ##===================================================
3131 **
3132 **---------------------------------------------------------
3133 */
3134 0
3135 }/*-------------------------< HDATA_OUT2 >------------------*/,{
3136 	SCR_JUMP,
3137 		PADDR (data_out),
3138 
3139 }/*-------------------------< RESET >----------------------*/,{
3140 	/*
3141 	**      Send a TARGET_RESET message if bad IDENTIFY
3142 	**	received on reselection.
3143 	*/
3144 	SCR_LOAD_REG (scratcha, ABORT_TASK),
3145 		0,
3146 	SCR_JUMP,
3147 		PADDRH (abort_resel),
3148 }/*-------------------------< ABORTTAG >-------------------*/,{
3149 	/*
3150 	**      Abort a wrong tag received on reselection.
3151 	*/
3152 	SCR_LOAD_REG (scratcha, ABORT_TASK),
3153 		0,
3154 	SCR_JUMP,
3155 		PADDRH (abort_resel),
3156 }/*-------------------------< ABORT >----------------------*/,{
3157 	/*
3158 	**      Abort a reselection when no active CCB.
3159 	*/
3160 	SCR_LOAD_REG (scratcha, ABORT_TASK_SET),
3161 		0,
3162 }/*-------------------------< ABORT_RESEL >----------------*/,{
3163 	SCR_COPY (1),
3164 		RADDR (scratcha),
3165 		NADDR (msgout),
3166 	SCR_SET (SCR_ATN),
3167 		0,
3168 	SCR_CLR (SCR_ACK),
3169 		0,
3170 	/*
3171 	**	and send it.
3172 	**	we expect an immediate disconnect
3173 	*/
3174 	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3175 		0,
3176 	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
3177 		NADDR (msgout),
3178 	SCR_COPY (1),
3179 		NADDR (msgout),
3180 		NADDR (lastmsg),
3181 	SCR_CLR (SCR_ACK|SCR_ATN),
3182 		0,
3183 	SCR_WAIT_DISC,
3184 		0,
3185 	SCR_JUMP,
3186 		PADDR (start),
3187 }/*-------------------------< RESEND_IDENT >-------------------*/,{
3188 	/*
3189 	**	The target stays in MSG OUT phase after having acked
3190 	**	Identify [+ Tag [+ Extended message ]]. Targets shall
3191 	**	behave this way on parity error.
3192 	**	We must send it again all the messages.
3193 	*/
3194 	SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
3195 		0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
3196 	SCR_JUMP,
3197 		PADDR (send_ident),
3198 }/*-------------------------< CLRATN_GO_ON >-------------------*/,{
3199 	SCR_CLR (SCR_ATN),
3200 		0,
3201 	SCR_JUMP,
3202 }/*-------------------------< NXTDSP_GO_ON >-------------------*/,{
3203 		0,
3204 }/*-------------------------< SDATA_IN >-------------------*/,{
3205 	SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN)),
3206 		PADDR (dispatch),
3207 	SCR_MOVE_TBL ^ SCR_DATA_IN,
3208 		offsetof (struct dsb, sense),
3209 	SCR_CALL,
3210 		PADDR (dispatch),
3211 	SCR_JUMP,
3212 		PADDR (no_data),
3213 }/*-------------------------< DATA_IO >--------------------*/,{
3214 	/*
3215 	**	We jump here if the data direction was unknown at the
3216 	**	time we had to queue the command to the scripts processor.
3217 	**	Pointers had been set as follow in this situation:
3218 	**	  savep   -->   DATA_IO
3219 	**	  lastp   -->   start pointer when DATA_IN
3220 	**	  goalp   -->   goal  pointer when DATA_IN
3221 	**	  wlastp  -->   start pointer when DATA_OUT
3222 	**	  wgoalp  -->   goal  pointer when DATA_OUT
3223 	**	This script sets savep/lastp/goalp according to the
3224 	**	direction chosen by the target.
3225 	*/
3226 	SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_OUT)),
3227 		32,
3228 	/*
3229 	**	Direction is DATA IN.
3230 	**	Warning: we jump here, even when phase is DATA OUT.
3231 	*/
3232 	SCR_COPY (4),
3233 		NADDR (header.lastp),
3234 		NADDR (header.savep),
3235 
3236 	/*
3237 	**	Jump to the SCRIPTS according to actual direction.
3238 	*/
3239 	SCR_COPY (4),
3240 		NADDR (header.savep),
3241 		RADDR (temp),
3242 	SCR_RETURN,
3243 		0,
3244 	/*
3245 	**	Direction is DATA OUT.
3246 	*/
3247 	SCR_COPY (4),
3248 		NADDR (header.wlastp),
3249 		NADDR (header.lastp),
3250 	SCR_COPY (4),
3251 		NADDR (header.wgoalp),
3252 		NADDR (header.goalp),
3253 	SCR_JUMPR,
3254 		-64,
3255 }/*-------------------------< BAD_IDENTIFY >---------------*/,{
3256 	/*
3257 	**	If message phase but not an IDENTIFY,
3258 	**	get some help from the C code.
3259 	**	Old SCSI device may behave so.
3260 	*/
3261 	SCR_JUMPR ^ IFTRUE (MASK (0x80, 0x80)),
3262 		16,
3263 	SCR_INT,
3264 		SIR_RESEL_NO_IDENTIFY,
3265 	SCR_JUMP,
3266 		PADDRH (reset),
3267 	/*
3268 	**	Message is an IDENTIFY, but lun is unknown.
3269 	**	Read the message, since we got it directly
3270 	**	from the SCSI BUS data lines.
3271 	**	Signal problem to C code for logging the event.
3272 	**	Send an ABORT_TASK_SET to clear all pending tasks.
3273 	*/
3274 	SCR_INT,
3275 		SIR_RESEL_BAD_LUN,
3276 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3277 		NADDR (msgin),
3278 	SCR_JUMP,
3279 		PADDRH (abort),
3280 }/*-------------------------< BAD_I_T_L >------------------*/,{
3281 	/*
3282 	**	We donnot have a task for that I_T_L.
3283 	**	Signal problem to C code for logging the event.
3284 	**	Send an ABORT_TASK_SET message.
3285 	*/
3286 	SCR_INT,
3287 		SIR_RESEL_BAD_I_T_L,
3288 	SCR_JUMP,
3289 		PADDRH (abort),
3290 }/*-------------------------< BAD_I_T_L_Q >----------------*/,{
3291 	/*
3292 	**	We donnot have a task that matches the tag.
3293 	**	Signal problem to C code for logging the event.
3294 	**	Send an ABORT_TASK message.
3295 	*/
3296 	SCR_INT,
3297 		SIR_RESEL_BAD_I_T_L_Q,
3298 	SCR_JUMP,
3299 		PADDRH (aborttag),
3300 }/*-------------------------< BAD_TARGET >-----------------*/,{
3301 	/*
3302 	**	We donnot know the target that reselected us.
3303 	**	Grab the first message if any (IDENTIFY).
3304 	**	Signal problem to C code for logging the event.
3305 	**	TARGET_RESET message.
3306 	*/
3307 	SCR_INT,
3308 		SIR_RESEL_BAD_TARGET,
3309 	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_IN)),
3310 		8,
3311 	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3312 		NADDR (msgin),
3313 	SCR_JUMP,
3314 		PADDRH (reset),
3315 }/*-------------------------< BAD_STATUS >-----------------*/,{
3316 	/*
3317 	**	If command resulted in either TASK_SET FULL,
3318 	**	CHECK CONDITION or COMMAND TERMINATED,
3319 	**	call the C code.
3320 	*/
3321 	SCR_INT ^ IFTRUE (DATA (SAM_STAT_TASK_SET_FULL)),
3322 		SIR_BAD_STATUS,
3323 	SCR_INT ^ IFTRUE (DATA (SAM_STAT_CHECK_CONDITION)),
3324 		SIR_BAD_STATUS,
3325 	SCR_INT ^ IFTRUE (DATA (SAM_STAT_COMMAND_TERMINATED)),
3326 		SIR_BAD_STATUS,
3327 	SCR_RETURN,
3328 		0,
3329 }/*-------------------------< START_RAM >-------------------*/,{
3330 	/*
3331 	**	Load the script into on-chip RAM,
3332 	**	and jump to start point.
3333 	*/
3334 	SCR_COPY_F (4),
3335 		RADDR (scratcha),
3336 		PADDRH (start_ram0),
3337 	/*
3338 	**	Flush script prefetch if required
3339 	*/
3340 	PREFETCH_FLUSH
3341 	SCR_COPY (sizeof (struct script)),
3342 }/*-------------------------< START_RAM0 >--------------------*/,{
3343 		0,
3344 		PADDR (start),
3345 	SCR_JUMP,
3346 		PADDR (start),
3347 }/*-------------------------< STO_RESTART >-------------------*/,{
3348 	/*
3349 	**
3350 	**	Repair start queue (e.g. next time use the next slot)
3351 	**	and jump to start point.
3352 	*/
3353 	SCR_COPY (4),
3354 		RADDR (temp),
3355 		PADDR (startpos),
3356 	SCR_JUMP,
3357 		PADDR (start),
3358 }/*-------------------------< WAIT_DMA >-------------------*/,{
3359 	/*
3360 	**	For HP Zalon/53c720 systems, the Zalon interface
3361 	**	between CPU and 53c720 does prefetches, which causes
3362 	**	problems with self modifying scripts.  The problem
3363 	**	is overcome by calling a dummy subroutine after each
3364 	**	modification, to force a refetch of the script on
3365 	**	return from the subroutine.
3366 	*/
3367 	SCR_RETURN,
3368 		0,
3369 }/*-------------------------< SNOOPTEST >-------------------*/,{
3370 	/*
3371 	**	Read the variable.
3372 	*/
3373 	SCR_COPY (4),
3374 		NADDR(ncr_cache),
3375 		RADDR (scratcha),
3376 	/*
3377 	**	Write the variable.
3378 	*/
3379 	SCR_COPY (4),
3380 		RADDR (temp),
3381 		NADDR(ncr_cache),
3382 	/*
3383 	**	Read back the variable.
3384 	*/
3385 	SCR_COPY (4),
3386 		NADDR(ncr_cache),
3387 		RADDR (temp),
3388 }/*-------------------------< SNOOPEND >-------------------*/,{
3389 	/*
3390 	**	And stop.
3391 	*/
3392 	SCR_INT,
3393 		99,
3394 }/*--------------------------------------------------------*/
3395 };
3396 
3397 /*==========================================================
3398 **
3399 **
3400 **	Fill in #define dependent parts of the script
3401 **
3402 **
3403 **==========================================================
3404 */
3405 
3406 void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
3407 {
3408 	int	i;
3409 	ncrcmd	*p;
3410 
3411 	p = scrh->tryloop;
3412 	for (i=0; i<MAX_START; i++) {
3413 		*p++ =SCR_CALL;
3414 		*p++ =PADDR (idle);
3415 	}
3416 
3417 	BUG_ON((u_long)p != (u_long)&scrh->tryloop + sizeof (scrh->tryloop));
3418 
3419 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
3420 
3421 	p = scrh->done_queue;
3422 	for (i = 0; i<MAX_DONE; i++) {
3423 		*p++ =SCR_COPY (sizeof(struct ccb *));
3424 		*p++ =NADDR (header.cp);
3425 		*p++ =NADDR (ccb_done[i]);
3426 		*p++ =SCR_CALL;
3427 		*p++ =PADDR (done_end);
3428 	}
3429 
3430 	BUG_ON((u_long)p != (u_long)&scrh->done_queue+sizeof(scrh->done_queue));
3431 
3432 #endif /* SCSI_NCR_CCB_DONE_SUPPORT */
3433 
3434 	p = scrh->hdata_in;
3435 	for (i=0; i<MAX_SCATTERH; i++) {
3436 		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3437 		*p++ =PADDR (dispatch);
3438 		*p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3439 		*p++ =offsetof (struct dsb, data[i]);
3440 	}
3441 
3442 	BUG_ON((u_long)p != (u_long)&scrh->hdata_in + sizeof (scrh->hdata_in));
3443 
3444 	p = scr->data_in;
3445 	for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3446 		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_IN));
3447 		*p++ =PADDR (dispatch);
3448 		*p++ =SCR_MOVE_TBL ^ SCR_DATA_IN;
3449 		*p++ =offsetof (struct dsb, data[i]);
3450 	}
3451 
3452 	BUG_ON((u_long)p != (u_long)&scr->data_in + sizeof (scr->data_in));
3453 
3454 	p = scrh->hdata_out;
3455 	for (i=0; i<MAX_SCATTERH; i++) {
3456 		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3457 		*p++ =PADDR (dispatch);
3458 		*p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3459 		*p++ =offsetof (struct dsb, data[i]);
3460 	}
3461 
3462 	BUG_ON((u_long)p != (u_long)&scrh->hdata_out + sizeof (scrh->hdata_out));
3463 
3464 	p = scr->data_out;
3465 	for (i=MAX_SCATTERH; i<MAX_SCATTERH+MAX_SCATTERL; i++) {
3466 		*p++ =SCR_CALL ^ IFFALSE (WHEN (SCR_DATA_OUT));
3467 		*p++ =PADDR (dispatch);
3468 		*p++ =SCR_MOVE_TBL ^ SCR_DATA_OUT;
3469 		*p++ =offsetof (struct dsb, data[i]);
3470 	}
3471 
3472 	BUG_ON((u_long) p != (u_long)&scr->data_out + sizeof (scr->data_out));
3473 }
3474 
3475 /*==========================================================
3476 **
3477 **
3478 **	Copy and rebind a script.
3479 **
3480 **
3481 **==========================================================
3482 */
3483 
3484 static void __init
3485 ncr_script_copy_and_bind (struct ncb *np, ncrcmd *src, ncrcmd *dst, int len)
3486 {
3487 	ncrcmd  opcode, new, old, tmp1, tmp2;
3488 	ncrcmd	*start, *end;
3489 	int relocs;
3490 	int opchanged = 0;
3491 
3492 	start = src;
3493 	end = src + len/4;
3494 
3495 	while (src < end) {
3496 
3497 		opcode = *src++;
3498 		*dst++ = cpu_to_scr(opcode);
3499 
3500 		/*
3501 		**	If we forget to change the length
3502 		**	in struct script, a field will be
3503 		**	padded with 0. This is an illegal
3504 		**	command.
3505 		*/
3506 
3507 		if (opcode == 0) {
3508 			printk (KERN_ERR "%s: ERROR0 IN SCRIPT at %d.\n",
3509 				ncr_name(np), (int) (src-start-1));
3510 			mdelay(1000);
3511 		}
3512 
3513 		if (DEBUG_FLAGS & DEBUG_SCRIPT)
3514 			printk (KERN_DEBUG "%p:  <%x>\n",
3515 				(src-1), (unsigned)opcode);
3516 
3517 		/*
3518 		**	We don't have to decode ALL commands
3519 		*/
3520 		switch (opcode >> 28) {
3521 
3522 		case 0xc:
3523 			/*
3524 			**	COPY has TWO arguments.
3525 			*/
3526 			relocs = 2;
3527 			tmp1 = src[0];
3528 #ifdef	RELOC_KVAR
3529 			if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
3530 				tmp1 = 0;
3531 #endif
3532 			tmp2 = src[1];
3533 #ifdef	RELOC_KVAR
3534 			if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
3535 				tmp2 = 0;
3536 #endif
3537 			if ((tmp1 ^ tmp2) & 3) {
3538 				printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
3539 					ncr_name(np), (int) (src-start-1));
3540 				mdelay(1000);
3541 			}
3542 			/*
3543 			**	If PREFETCH feature not enabled, remove
3544 			**	the NO FLUSH bit if present.
3545 			*/
3546 			if ((opcode & SCR_NO_FLUSH) && !(np->features & FE_PFEN)) {
3547 				dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
3548 				++opchanged;
3549 			}
3550 			break;
3551 
3552 		case 0x0:
3553 			/*
3554 			**	MOVE (absolute address)
3555 			*/
3556 			relocs = 1;
3557 			break;
3558 
3559 		case 0x8:
3560 			/*
3561 			**	JUMP / CALL
3562 			**	don't relocate if relative :-)
3563 			*/
3564 			if (opcode & 0x00800000)
3565 				relocs = 0;
3566 			else
3567 				relocs = 1;
3568 			break;
3569 
3570 		case 0x4:
3571 		case 0x5:
3572 		case 0x6:
3573 		case 0x7:
3574 			relocs = 1;
3575 			break;
3576 
3577 		default:
3578 			relocs = 0;
3579 			break;
3580 		}
3581 
3582 		if (relocs) {
3583 			while (relocs--) {
3584 				old = *src++;
3585 
3586 				switch (old & RELOC_MASK) {
3587 				case RELOC_REGISTER:
3588 					new = (old & ~RELOC_MASK) + np->paddr;
3589 					break;
3590 				case RELOC_LABEL:
3591 					new = (old & ~RELOC_MASK) + np->p_script;
3592 					break;
3593 				case RELOC_LABELH:
3594 					new = (old & ~RELOC_MASK) + np->p_scripth;
3595 					break;
3596 				case RELOC_SOFTC:
3597 					new = (old & ~RELOC_MASK) + np->p_ncb;
3598 					break;
3599 #ifdef	RELOC_KVAR
3600 				case RELOC_KVAR:
3601 					if (((old & ~RELOC_MASK) <
3602 					     SCRIPT_KVAR_FIRST) ||
3603 					    ((old & ~RELOC_MASK) >
3604 					     SCRIPT_KVAR_LAST))
3605 						panic("ncr KVAR out of range");
3606 					new = vtophys(script_kvars[old &
3607 					    ~RELOC_MASK]);
3608 					break;
3609 #endif
3610 				case 0:
3611 					/* Don't relocate a 0 address. */
3612 					if (old == 0) {
3613 						new = old;
3614 						break;
3615 					}
3616 					fallthrough;
3617 				default:
3618 					panic("ncr_script_copy_and_bind: weird relocation %x\n", old);
3619 					break;
3620 				}
3621 
3622 				*dst++ = cpu_to_scr(new);
3623 			}
3624 		} else
3625 			*dst++ = cpu_to_scr(*src++);
3626 
3627 	}
3628 }
3629 
3630 /*
3631 **	Linux host data structure
3632 */
3633 
3634 struct host_data {
3635      struct ncb *ncb;
3636 };
3637 
3638 #define PRINT_ADDR(cmd, arg...) dev_info(&cmd->device->sdev_gendev , ## arg)
3639 
3640 static void ncr_print_msg(struct ccb *cp, char *label, u_char *msg)
3641 {
3642 	PRINT_ADDR(cp->cmd, "%s: ", label);
3643 
3644 	spi_print_msg(msg);
3645 	printk("\n");
3646 }
3647 
3648 /*==========================================================
3649 **
3650 **	NCR chip clock divisor table.
3651 **	Divisors are multiplied by 10,000,000 in order to make
3652 **	calculations more simple.
3653 **
3654 **==========================================================
3655 */
3656 
3657 #define _5M 5000000
3658 static u_long div_10M[] =
3659 	{2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
3660 
3661 
3662 /*===============================================================
3663 **
3664 **	Prepare io register values used by ncr_init() according
3665 **	to selected and supported features.
3666 **
3667 **	NCR chips allow burst lengths of 2, 4, 8, 16, 32, 64, 128
3668 **	transfers. 32,64,128 are only supported by 875 and 895 chips.
3669 **	We use log base 2 (burst length) as internal code, with
3670 **	value 0 meaning "burst disabled".
3671 **
3672 **===============================================================
3673 */
3674 
3675 /*
3676  *	Burst length from burst code.
3677  */
3678 #define burst_length(bc) (!(bc))? 0 : 1 << (bc)
3679 
3680 /*
3681  *	Burst code from io register bits.  Burst enable is ctest0 for c720
3682  */
3683 #define burst_code(dmode, ctest0) \
3684 	(ctest0) & 0x80 ? 0 : (((dmode) & 0xc0) >> 6) + 1
3685 
3686 /*
3687  *	Set initial io register bits from burst code.
3688  */
3689 static inline void ncr_init_burst(struct ncb *np, u_char bc)
3690 {
3691 	u_char *be = &np->rv_ctest0;
3692 	*be		&= ~0x80;
3693 	np->rv_dmode	&= ~(0x3 << 6);
3694 	np->rv_ctest5	&= ~0x4;
3695 
3696 	if (!bc) {
3697 		*be		|= 0x80;
3698 	} else {
3699 		--bc;
3700 		np->rv_dmode	|= ((bc & 0x3) << 6);
3701 		np->rv_ctest5	|= (bc & 0x4);
3702 	}
3703 }
3704 
3705 static void __init ncr_prepare_setting(struct ncb *np)
3706 {
3707 	u_char	burst_max;
3708 	u_long	period;
3709 	int i;
3710 
3711 	/*
3712 	**	Save assumed BIOS setting
3713 	*/
3714 
3715 	np->sv_scntl0	= INB(nc_scntl0) & 0x0a;
3716 	np->sv_scntl3	= INB(nc_scntl3) & 0x07;
3717 	np->sv_dmode	= INB(nc_dmode)  & 0xce;
3718 	np->sv_dcntl	= INB(nc_dcntl)  & 0xa8;
3719 	np->sv_ctest0	= INB(nc_ctest0) & 0x84;
3720 	np->sv_ctest3	= INB(nc_ctest3) & 0x01;
3721 	np->sv_ctest4	= INB(nc_ctest4) & 0x80;
3722 	np->sv_ctest5	= INB(nc_ctest5) & 0x24;
3723 	np->sv_gpcntl	= INB(nc_gpcntl);
3724 	np->sv_stest2	= INB(nc_stest2) & 0x20;
3725 	np->sv_stest4	= INB(nc_stest4);
3726 
3727 	/*
3728 	**	Wide ?
3729 	*/
3730 
3731 	np->maxwide	= (np->features & FE_WIDE)? 1 : 0;
3732 
3733  	/*
3734 	 *  Guess the frequency of the chip's clock.
3735 	 */
3736 	if (np->features & FE_ULTRA)
3737 		np->clock_khz = 80000;
3738 	else
3739 		np->clock_khz = 40000;
3740 
3741 	/*
3742 	 *  Get the clock multiplier factor.
3743  	 */
3744 	if	(np->features & FE_QUAD)
3745 		np->multiplier	= 4;
3746 	else if	(np->features & FE_DBLR)
3747 		np->multiplier	= 2;
3748 	else
3749 		np->multiplier	= 1;
3750 
3751 	/*
3752 	 *  Measure SCSI clock frequency for chips
3753 	 *  it may vary from assumed one.
3754 	 */
3755 	if (np->features & FE_VARCLK)
3756 		ncr_getclock(np, np->multiplier);
3757 
3758 	/*
3759 	 * Divisor to be used for async (timer pre-scaler).
3760 	 */
3761 	i = np->clock_divn - 1;
3762 	while (--i >= 0) {
3763 		if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz > div_10M[i]) {
3764 			++i;
3765 			break;
3766 		}
3767 	}
3768 	np->rv_scntl3 = i+1;
3769 
3770 	/*
3771 	 * Minimum synchronous period factor supported by the chip.
3772 	 * Btw, 'period' is in tenths of nanoseconds.
3773 	 */
3774 
3775 	period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
3776 	if	(period <= 250)		np->minsync = 10;
3777 	else if	(period <= 303)		np->minsync = 11;
3778 	else if	(period <= 500)		np->minsync = 12;
3779 	else				np->minsync = (period + 40 - 1) / 40;
3780 
3781 	/*
3782 	 * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
3783 	 */
3784 
3785 	if	(np->minsync < 25 && !(np->features & FE_ULTRA))
3786 		np->minsync = 25;
3787 
3788 	/*
3789 	 * Maximum synchronous period factor supported by the chip.
3790 	 */
3791 
3792 	period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
3793 	np->maxsync = period > 2540 ? 254 : period / 10;
3794 
3795 	/*
3796 	**	Prepare initial value of other IO registers
3797 	*/
3798 #if defined SCSI_NCR_TRUST_BIOS_SETTING
3799 	np->rv_scntl0	= np->sv_scntl0;
3800 	np->rv_dmode	= np->sv_dmode;
3801 	np->rv_dcntl	= np->sv_dcntl;
3802 	np->rv_ctest0	= np->sv_ctest0;
3803 	np->rv_ctest3	= np->sv_ctest3;
3804 	np->rv_ctest4	= np->sv_ctest4;
3805 	np->rv_ctest5	= np->sv_ctest5;
3806 	burst_max	= burst_code(np->sv_dmode, np->sv_ctest0);
3807 #else
3808 
3809 	/*
3810 	**	Select burst length (dwords)
3811 	*/
3812 	burst_max	= driver_setup.burst_max;
3813 	if (burst_max == 255)
3814 		burst_max = burst_code(np->sv_dmode, np->sv_ctest0);
3815 	if (burst_max > 7)
3816 		burst_max = 7;
3817 	if (burst_max > np->maxburst)
3818 		burst_max = np->maxburst;
3819 
3820 	/*
3821 	**	Select all supported special features
3822 	*/
3823 	if (np->features & FE_ERL)
3824 		np->rv_dmode	|= ERL;		/* Enable Read Line */
3825 	if (np->features & FE_BOF)
3826 		np->rv_dmode	|= BOF;		/* Burst Opcode Fetch */
3827 	if (np->features & FE_ERMP)
3828 		np->rv_dmode	|= ERMP;	/* Enable Read Multiple */
3829 	if (np->features & FE_PFEN)
3830 		np->rv_dcntl	|= PFEN;	/* Prefetch Enable */
3831 	if (np->features & FE_CLSE)
3832 		np->rv_dcntl	|= CLSE;	/* Cache Line Size Enable */
3833 	if (np->features & FE_WRIE)
3834 		np->rv_ctest3	|= WRIE;	/* Write and Invalidate */
3835 	if (np->features & FE_DFS)
3836 		np->rv_ctest5	|= DFS;		/* Dma Fifo Size */
3837 	if (np->features & FE_MUX)
3838 		np->rv_ctest4	|= MUX;		/* Host bus multiplex mode */
3839 	if (np->features & FE_EA)
3840 		np->rv_dcntl	|= EA;		/* Enable ACK */
3841 	if (np->features & FE_EHP)
3842 		np->rv_ctest0	|= EHP;		/* Even host parity */
3843 
3844 	/*
3845 	**	Select some other
3846 	*/
3847 	if (driver_setup.master_parity)
3848 		np->rv_ctest4	|= MPEE;	/* Master parity checking */
3849 	if (driver_setup.scsi_parity)
3850 		np->rv_scntl0	|= 0x0a;	/*  full arb., ena parity, par->ATN  */
3851 
3852 	/*
3853 	**  Get SCSI addr of host adapter (set by bios?).
3854 	*/
3855 	if (np->myaddr == 255) {
3856 		np->myaddr = INB(nc_scid) & 0x07;
3857 		if (!np->myaddr)
3858 			np->myaddr = SCSI_NCR_MYADDR;
3859 	}
3860 
3861 #endif /* SCSI_NCR_TRUST_BIOS_SETTING */
3862 
3863 	/*
3864 	 *	Prepare initial io register bits for burst length
3865 	 */
3866 	ncr_init_burst(np, burst_max);
3867 
3868 	/*
3869 	**	Set SCSI BUS mode.
3870 	**
3871 	**	- ULTRA2 chips (895/895A/896) report the current
3872 	**	  BUS mode through the STEST4 IO register.
3873 	**	- For previous generation chips (825/825A/875),
3874 	**	  user has to tell us how to check against HVD,
3875 	**	  since a 100% safe algorithm is not possible.
3876 	*/
3877 	np->scsi_mode = SMODE_SE;
3878 	if (np->features & FE_DIFF) {
3879 		switch(driver_setup.diff_support) {
3880 		case 4:	/* Trust previous settings if present, then GPIO3 */
3881 			if (np->sv_scntl3) {
3882 				if (np->sv_stest2 & 0x20)
3883 					np->scsi_mode = SMODE_HVD;
3884 				break;
3885 			}
3886 			fallthrough;
3887 		case 3:	/* SYMBIOS controllers report HVD through GPIO3 */
3888 			if (INB(nc_gpreg) & 0x08)
3889 				break;
3890 			fallthrough;
3891 		case 2:	/* Set HVD unconditionally */
3892 			np->scsi_mode = SMODE_HVD;
3893 			fallthrough;
3894 		case 1:	/* Trust previous settings for HVD */
3895 			if (np->sv_stest2 & 0x20)
3896 				np->scsi_mode = SMODE_HVD;
3897 			break;
3898 		default:/* Don't care about HVD */
3899 			break;
3900 		}
3901 	}
3902 	if (np->scsi_mode == SMODE_HVD)
3903 		np->rv_stest2 |= 0x20;
3904 
3905 	/*
3906 	**	Set LED support from SCRIPTS.
3907 	**	Ignore this feature for boards known to use a
3908 	**	specific GPIO wiring and for the 895A or 896
3909 	**	that drive the LED directly.
3910 	**	Also probe initial setting of GPIO0 as output.
3911 	*/
3912 	if ((driver_setup.led_pin) &&
3913 	    !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
3914 		np->features |= FE_LED0;
3915 
3916 	/*
3917 	**	Set irq mode.
3918 	*/
3919 	switch(driver_setup.irqm & 3) {
3920 	case 2:
3921 		np->rv_dcntl	|= IRQM;
3922 		break;
3923 	case 1:
3924 		np->rv_dcntl	|= (np->sv_dcntl & IRQM);
3925 		break;
3926 	default:
3927 		break;
3928 	}
3929 
3930 	/*
3931 	**	Configure targets according to driver setup.
3932 	**	Allow to override sync, wide and NOSCAN from
3933 	**	boot command line.
3934 	*/
3935 	for (i = 0 ; i < MAX_TARGET ; i++) {
3936 		struct tcb *tp = &np->target[i];
3937 
3938 		tp->usrsync = driver_setup.default_sync;
3939 		tp->usrwide = driver_setup.max_wide;
3940 		tp->usrtags = MAX_TAGS;
3941 		tp->period = 0xffff;
3942 		if (!driver_setup.disconnection)
3943 			np->target[i].usrflag = UF_NODISC;
3944 	}
3945 
3946 	/*
3947 	**	Announce all that stuff to user.
3948 	*/
3949 
3950 	printk(KERN_INFO "%s: ID %d, Fast-%d%s%s\n", ncr_name(np),
3951 		np->myaddr,
3952 		np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10),
3953 		(np->rv_scntl0 & 0xa)	? ", Parity Checking"	: ", NO Parity",
3954 		(np->rv_stest2 & 0x20)	? ", Differential"	: "");
3955 
3956 	if (bootverbose > 1) {
3957 		printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3958 			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3959 			ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
3960 			np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
3961 
3962 		printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
3963 			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
3964 			ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
3965 			np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
3966 	}
3967 
3968 	if (bootverbose && np->paddr2)
3969 		printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
3970 			ncr_name(np), np->paddr2);
3971 }
3972 
3973 /*==========================================================
3974 **
3975 **
3976 **	Done SCSI commands list management.
3977 **
3978 **	We donnot enter the scsi_done() callback immediately
3979 **	after a command has been seen as completed but we
3980 **	insert it into a list which is flushed outside any kind
3981 **	of driver critical section.
3982 **	This allows to do minimal stuff under interrupt and
3983 **	inside critical sections and to also avoid locking up
3984 **	on recursive calls to driver entry points under SMP.
3985 **	In fact, the only kernel point which is entered by the
3986 **	driver with a driver lock set is kmalloc(GFP_ATOMIC)
3987 **	that shall not reenter the driver under any circumstances,
3988 **	AFAIK.
3989 **
3990 **==========================================================
3991 */
3992 static inline void ncr_queue_done_cmd(struct ncb *np, struct scsi_cmnd *cmd)
3993 {
3994 	unmap_scsi_data(np, cmd);
3995 	cmd->host_scribble = (char *) np->done_list;
3996 	np->done_list = cmd;
3997 }
3998 
3999 static inline void ncr_flush_done_cmds(struct scsi_cmnd *lcmd)
4000 {
4001 	struct scsi_cmnd *cmd;
4002 
4003 	while (lcmd) {
4004 		cmd = lcmd;
4005 		lcmd = (struct scsi_cmnd *) cmd->host_scribble;
4006 		scsi_done(cmd);
4007 	}
4008 }
4009 
4010 /*==========================================================
4011 **
4012 **
4013 **	Prepare the next negotiation message if needed.
4014 **
4015 **	Fill in the part of message buffer that contains the
4016 **	negotiation and the nego_status field of the CCB.
4017 **	Returns the size of the message in bytes.
4018 **
4019 **
4020 **==========================================================
4021 */
4022 
4023 
4024 static int ncr_prepare_nego(struct ncb *np, struct ccb *cp, u_char *msgptr)
4025 {
4026 	struct tcb *tp = &np->target[cp->target];
4027 	int msglen = 0;
4028 	int nego = 0;
4029 	struct scsi_target *starget = tp->starget;
4030 
4031 	/* negotiate wide transfers ?  */
4032 	if (!tp->widedone) {
4033 		if (spi_support_wide(starget)) {
4034 			nego = NS_WIDE;
4035 		} else
4036 			tp->widedone=1;
4037 	}
4038 
4039 	/* negotiate synchronous transfers?  */
4040 	if (!nego && !tp->period) {
4041 		if (spi_support_sync(starget)) {
4042 			nego = NS_SYNC;
4043 		} else {
4044 			tp->period  =0xffff;
4045 			dev_info(&starget->dev, "target did not report SYNC.\n");
4046 		}
4047 	}
4048 
4049 	switch (nego) {
4050 	case NS_SYNC:
4051 		msglen += spi_populate_sync_msg(msgptr + msglen,
4052 				tp->maxoffs ? tp->minsync : 0, tp->maxoffs);
4053 		break;
4054 	case NS_WIDE:
4055 		msglen += spi_populate_width_msg(msgptr + msglen, tp->usrwide);
4056 		break;
4057 	}
4058 
4059 	cp->nego_status = nego;
4060 
4061 	if (nego) {
4062 		tp->nego_cp = cp;
4063 		if (DEBUG_FLAGS & DEBUG_NEGO) {
4064 			ncr_print_msg(cp, nego == NS_WIDE ?
4065 					  "wide msgout":"sync_msgout", msgptr);
4066 		}
4067 	}
4068 
4069 	return msglen;
4070 }
4071 
4072 
4073 
4074 /*==========================================================
4075 **
4076 **
4077 **	Start execution of a SCSI command.
4078 **	This is called from the generic SCSI driver.
4079 **
4080 **
4081 **==========================================================
4082 */
4083 static int ncr_queue_command (struct ncb *np, struct scsi_cmnd *cmd)
4084 {
4085 	struct scsi_device *sdev = cmd->device;
4086 	struct tcb *tp = &np->target[sdev->id];
4087 	struct lcb *lp = tp->lp[sdev->lun];
4088 	struct ccb *cp;
4089 
4090 	int	segments;
4091 	u_char	idmsg, *msgptr;
4092 	u32	msglen;
4093 	int	direction;
4094 	u32	lastp, goalp;
4095 
4096 	/*---------------------------------------------
4097 	**
4098 	**      Some shortcuts ...
4099 	**
4100 	**---------------------------------------------
4101 	*/
4102 	if ((sdev->id == np->myaddr	  ) ||
4103 		(sdev->id >= MAX_TARGET) ||
4104 		(sdev->lun    >= MAX_LUN   )) {
4105 		return(DID_BAD_TARGET);
4106 	}
4107 
4108 	/*---------------------------------------------
4109 	**
4110 	**	Complete the 1st TEST UNIT READY command
4111 	**	with error condition if the device is
4112 	**	flagged NOSCAN, in order to speed up
4113 	**	the boot.
4114 	**
4115 	**---------------------------------------------
4116 	*/
4117 	if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) &&
4118 	    (tp->usrflag & UF_NOSCAN)) {
4119 		tp->usrflag &= ~UF_NOSCAN;
4120 		return DID_BAD_TARGET;
4121 	}
4122 
4123 	if (DEBUG_FLAGS & DEBUG_TINY) {
4124 		PRINT_ADDR(cmd, "CMD=%x ", cmd->cmnd[0]);
4125 	}
4126 
4127 	/*---------------------------------------------------
4128 	**
4129 	**	Assign a ccb / bind cmd.
4130 	**	If resetting, shorten settle_time if necessary
4131 	**	in order to avoid spurious timeouts.
4132 	**	If resetting or no free ccb,
4133 	**	insert cmd into the waiting list.
4134 	**
4135 	**----------------------------------------------------
4136 	*/
4137 	if (np->settle_time && scsi_cmd_to_rq(cmd)->timeout >= HZ) {
4138 		u_long tlimit = jiffies + scsi_cmd_to_rq(cmd)->timeout - HZ;
4139 		if (time_after(np->settle_time, tlimit))
4140 			np->settle_time = tlimit;
4141 	}
4142 
4143 	if (np->settle_time || !(cp=ncr_get_ccb (np, cmd))) {
4144 		insert_into_waiting_list(np, cmd);
4145 		return(DID_OK);
4146 	}
4147 	cp->cmd = cmd;
4148 
4149 	/*----------------------------------------------------
4150 	**
4151 	**	Build the identify / tag / sdtr message
4152 	**
4153 	**----------------------------------------------------
4154 	*/
4155 
4156 	idmsg = IDENTIFY(0, sdev->lun);
4157 
4158 	if (cp ->tag != NO_TAG ||
4159 		(cp != np->ccb && np->disc && !(tp->usrflag & UF_NODISC)))
4160 		idmsg |= 0x40;
4161 
4162 	msgptr = cp->scsi_smsg;
4163 	msglen = 0;
4164 	msgptr[msglen++] = idmsg;
4165 
4166 	if (cp->tag != NO_TAG) {
4167 		char order = np->order;
4168 
4169 		/*
4170 		**	Force ordered tag if necessary to avoid timeouts
4171 		**	and to preserve interactivity.
4172 		*/
4173 		if (lp && time_after(jiffies, lp->tags_stime)) {
4174 			if (lp->tags_smap) {
4175 				order = ORDERED_QUEUE_TAG;
4176 				if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>2){
4177 					PRINT_ADDR(cmd,
4178 						"ordered tag forced.\n");
4179 				}
4180 			}
4181 			lp->tags_stime = jiffies + 3*HZ;
4182 			lp->tags_smap = lp->tags_umap;
4183 		}
4184 
4185 		if (order == 0) {
4186 			/*
4187 			**	Ordered write ops, unordered read ops.
4188 			*/
4189 			switch (cmd->cmnd[0]) {
4190 			case 0x08:  /* READ_SMALL (6) */
4191 			case 0x28:  /* READ_BIG  (10) */
4192 			case 0xa8:  /* READ_HUGE (12) */
4193 				order = SIMPLE_QUEUE_TAG;
4194 				break;
4195 			default:
4196 				order = ORDERED_QUEUE_TAG;
4197 			}
4198 		}
4199 		msgptr[msglen++] = order;
4200 		/*
4201 		**	Actual tags are numbered 1,3,5,..2*MAXTAGS+1,
4202 		**	since we may have to deal with devices that have
4203 		**	problems with #TAG 0 or too great #TAG numbers.
4204 		*/
4205 		msgptr[msglen++] = (cp->tag << 1) + 1;
4206 	}
4207 
4208 	/*----------------------------------------------------
4209 	**
4210 	**	Build the data descriptors
4211 	**
4212 	**----------------------------------------------------
4213 	*/
4214 
4215 	direction = cmd->sc_data_direction;
4216 	if (direction != DMA_NONE) {
4217 		segments = ncr_scatter(np, cp, cp->cmd);
4218 		if (segments < 0) {
4219 			ncr_free_ccb(np, cp);
4220 			return(DID_ERROR);
4221 		}
4222 	}
4223 	else {
4224 		cp->data_len = 0;
4225 		segments = 0;
4226 	}
4227 
4228 	/*---------------------------------------------------
4229 	**
4230 	**	negotiation required?
4231 	**
4232 	**	(nego_status is filled by ncr_prepare_nego())
4233 	**
4234 	**---------------------------------------------------
4235 	*/
4236 
4237 	cp->nego_status = 0;
4238 
4239 	if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
4240 		msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
4241 	}
4242 
4243 	/*----------------------------------------------------
4244 	**
4245 	**	Determine xfer direction.
4246 	**
4247 	**----------------------------------------------------
4248 	*/
4249 	if (!cp->data_len)
4250 		direction = DMA_NONE;
4251 
4252 	/*
4253 	**	If data direction is BIDIRECTIONAL, speculate FROM_DEVICE
4254 	**	but prepare alternate pointers for TO_DEVICE in case
4255 	**	of our speculation will be just wrong.
4256 	**	SCRIPTS will swap values if needed.
4257 	*/
4258 	switch(direction) {
4259 	case DMA_BIDIRECTIONAL:
4260 	case DMA_TO_DEVICE:
4261 		goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
4262 		if (segments <= MAX_SCATTERL)
4263 			lastp = goalp - 8 - (segments * 16);
4264 		else {
4265 			lastp = NCB_SCRIPTH_PHYS (np, hdata_out2);
4266 			lastp -= (segments - MAX_SCATTERL) * 16;
4267 		}
4268 		if (direction != DMA_BIDIRECTIONAL)
4269 			break;
4270 		cp->phys.header.wgoalp	= cpu_to_scr(goalp);
4271 		cp->phys.header.wlastp	= cpu_to_scr(lastp);
4272 		fallthrough;
4273 	case DMA_FROM_DEVICE:
4274 		goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
4275 		if (segments <= MAX_SCATTERL)
4276 			lastp = goalp - 8 - (segments * 16);
4277 		else {
4278 			lastp = NCB_SCRIPTH_PHYS (np, hdata_in2);
4279 			lastp -= (segments - MAX_SCATTERL) * 16;
4280 		}
4281 		break;
4282 	default:
4283 	case DMA_NONE:
4284 		lastp = goalp = NCB_SCRIPT_PHYS (np, no_data);
4285 		break;
4286 	}
4287 
4288 	/*
4289 	**	Set all pointers values needed by SCRIPTS.
4290 	**	If direction is unknown, start at data_io.
4291 	*/
4292 	cp->phys.header.lastp = cpu_to_scr(lastp);
4293 	cp->phys.header.goalp = cpu_to_scr(goalp);
4294 
4295 	if (direction == DMA_BIDIRECTIONAL)
4296 		cp->phys.header.savep =
4297 			cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
4298 	else
4299 		cp->phys.header.savep= cpu_to_scr(lastp);
4300 
4301 	/*
4302 	**	Save the initial data pointer in order to be able
4303 	**	to redo the command.
4304 	*/
4305 	cp->startp = cp->phys.header.savep;
4306 
4307 	/*----------------------------------------------------
4308 	**
4309 	**	fill in ccb
4310 	**
4311 	**----------------------------------------------------
4312 	**
4313 	**
4314 	**	physical -> virtual backlink
4315 	**	Generic SCSI command
4316 	*/
4317 
4318 	/*
4319 	**	Startqueue
4320 	*/
4321 	cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4322 	cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_dsa));
4323 	/*
4324 	**	select
4325 	*/
4326 	cp->phys.select.sel_id		= sdev_id(sdev);
4327 	cp->phys.select.sel_scntl3	= tp->wval;
4328 	cp->phys.select.sel_sxfer	= tp->sval;
4329 	/*
4330 	**	message
4331 	*/
4332 	cp->phys.smsg.addr		= cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
4333 	cp->phys.smsg.size		= cpu_to_scr(msglen);
4334 
4335 	/*
4336 	**	command
4337 	*/
4338 	memcpy(cp->cdb_buf, cmd->cmnd, min_t(int, cmd->cmd_len, sizeof(cp->cdb_buf)));
4339 	cp->phys.cmd.addr		= cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
4340 	cp->phys.cmd.size		= cpu_to_scr(cmd->cmd_len);
4341 
4342 	/*
4343 	**	status
4344 	*/
4345 	cp->actualquirks		= 0;
4346 	cp->host_status			= cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
4347 	cp->scsi_status			= SAM_STAT_ILLEGAL;
4348 	cp->parity_status		= 0;
4349 
4350 	cp->xerr_status			= XE_OK;
4351 
4352 	/*----------------------------------------------------
4353 	**
4354 	**	Critical region: start this job.
4355 	**
4356 	**----------------------------------------------------
4357 	*/
4358 
4359 	/* activate this job.  */
4360 	cp->magic		= CCB_MAGIC;
4361 
4362 	/*
4363 	**	insert next CCBs into start queue.
4364 	**	2 max at a time is enough to flush the CCB wait queue.
4365 	*/
4366 	cp->auto_sense = 0;
4367 	if (lp)
4368 		ncr_start_next_ccb(np, lp, 2);
4369 	else
4370 		ncr_put_start_queue(np, cp);
4371 
4372 	/* Command is successfully queued.  */
4373 
4374 	return DID_OK;
4375 }
4376 
4377 
4378 /*==========================================================
4379 **
4380 **
4381 **	Insert a CCB into the start queue and wake up the
4382 **	SCRIPTS processor.
4383 **
4384 **
4385 **==========================================================
4386 */
4387 
4388 static void ncr_start_next_ccb(struct ncb *np, struct lcb *lp, int maxn)
4389 {
4390 	struct list_head *qp;
4391 	struct ccb *cp;
4392 
4393 	if (lp->held_ccb)
4394 		return;
4395 
4396 	while (maxn-- && lp->queuedccbs < lp->queuedepth) {
4397 		qp = ncr_list_pop(&lp->wait_ccbq);
4398 		if (!qp)
4399 			break;
4400 		++lp->queuedccbs;
4401 		cp = list_entry(qp, struct ccb, link_ccbq);
4402 		list_add_tail(qp, &lp->busy_ccbq);
4403 		lp->jump_ccb[cp->tag == NO_TAG ? 0 : cp->tag] =
4404 			cpu_to_scr(CCB_PHYS (cp, restart));
4405 		ncr_put_start_queue(np, cp);
4406 	}
4407 }
4408 
4409 static void ncr_put_start_queue(struct ncb *np, struct ccb *cp)
4410 {
4411 	u16	qidx;
4412 
4413 	/*
4414 	**	insert into start queue.
4415 	*/
4416 	if (!np->squeueput) np->squeueput = 1;
4417 	qidx = np->squeueput + 2;
4418 	if (qidx >= MAX_START + MAX_START) qidx = 1;
4419 
4420 	np->scripth->tryloop [qidx] = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
4421 	MEMORY_BARRIER();
4422 	np->scripth->tryloop [np->squeueput] = cpu_to_scr(CCB_PHYS (cp, start));
4423 
4424 	np->squeueput = qidx;
4425 	++np->queuedccbs;
4426 	cp->queued = 1;
4427 
4428 	if (DEBUG_FLAGS & DEBUG_QUEUE)
4429 		printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
4430 
4431 	/*
4432 	**	Script processor may be waiting for reselect.
4433 	**	Wake it up.
4434 	*/
4435 	MEMORY_BARRIER();
4436 	OUTB (nc_istat, SIGP);
4437 }
4438 
4439 
4440 static int ncr_reset_scsi_bus(struct ncb *np, int enab_int, int settle_delay)
4441 {
4442 	u32 term;
4443 	int retv = 0;
4444 
4445 	np->settle_time	= jiffies + settle_delay * HZ;
4446 
4447 	if (bootverbose > 1)
4448 		printk("%s: resetting, "
4449 			"command processing suspended for %d seconds\n",
4450 			ncr_name(np), settle_delay);
4451 
4452 	ncr_chip_reset(np, 100);
4453 	udelay(2000);	/* The 895 needs time for the bus mode to settle */
4454 	if (enab_int)
4455 		OUTW (nc_sien, RST);
4456 	/*
4457 	**	Enable Tolerant, reset IRQD if present and
4458 	**	properly set IRQ mode, prior to resetting the bus.
4459 	*/
4460 	OUTB (nc_stest3, TE);
4461 	OUTB (nc_scntl1, CRST);
4462 	udelay(200);
4463 
4464 	if (!driver_setup.bus_check)
4465 		goto out;
4466 	/*
4467 	**	Check for no terminators or SCSI bus shorts to ground.
4468 	**	Read SCSI data bus, data parity bits and control signals.
4469 	**	We are expecting RESET to be TRUE and other signals to be
4470 	**	FALSE.
4471 	*/
4472 
4473 	term =	INB(nc_sstat0);
4474 	term =	((term & 2) << 7) + ((term & 1) << 17);	/* rst sdp0 */
4475 	term |= ((INB(nc_sstat2) & 0x01) << 26) |	/* sdp1     */
4476 		((INW(nc_sbdl) & 0xff)   << 9)  |	/* d7-0     */
4477 		((INW(nc_sbdl) & 0xff00) << 10) |	/* d15-8    */
4478 		INB(nc_sbcl);	/* req ack bsy sel atn msg cd io    */
4479 
4480 	if (!(np->features & FE_WIDE))
4481 		term &= 0x3ffff;
4482 
4483 	if (term != (2<<7)) {
4484 		printk("%s: suspicious SCSI data while resetting the BUS.\n",
4485 			ncr_name(np));
4486 		printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
4487 			"0x%lx, expecting 0x%lx\n",
4488 			ncr_name(np),
4489 			(np->features & FE_WIDE) ? "dp1,d15-8," : "",
4490 			(u_long)term, (u_long)(2<<7));
4491 		if (driver_setup.bus_check == 1)
4492 			retv = 1;
4493 	}
4494 out:
4495 	OUTB (nc_scntl1, 0);
4496 	return retv;
4497 }
4498 
4499 /*
4500  * Start reset process.
4501  * If reset in progress do nothing.
4502  * The interrupt handler will reinitialize the chip.
4503  * The timeout handler will wait for settle_time before
4504  * clearing it and so resuming command processing.
4505  */
4506 static void ncr_start_reset(struct ncb *np)
4507 {
4508 	if (!np->settle_time) {
4509 		ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
4510  	}
4511 }
4512 
4513 /*==========================================================
4514 **
4515 **
4516 **	Reset the SCSI BUS.
4517 **	This is called from the generic SCSI driver.
4518 **
4519 **
4520 **==========================================================
4521 */
4522 static int ncr_reset_bus (struct ncb *np)
4523 {
4524 /*
4525  * Return immediately if reset is in progress.
4526  */
4527 	if (np->settle_time) {
4528 		return FAILED;
4529 	}
4530 /*
4531  * Start the reset process.
4532  * The script processor is then assumed to be stopped.
4533  * Commands will now be queued in the waiting list until a settle
4534  * delay of 2 seconds will be completed.
4535  */
4536 	ncr_start_reset(np);
4537 /*
4538  * Wake-up all awaiting commands with DID_RESET.
4539  */
4540 	reset_waiting_list(np);
4541 /*
4542  * Wake-up all pending commands with HS_RESET -> DID_RESET.
4543  */
4544 	ncr_wakeup(np, HS_RESET);
4545 
4546 	return SUCCESS;
4547 }
4548 
4549 static void ncr_detach(struct ncb *np)
4550 {
4551 	struct ccb *cp;
4552 	struct tcb *tp;
4553 	struct lcb *lp;
4554 	int target, lun;
4555 	int i;
4556 	char inst_name[16];
4557 
4558 	/* Local copy so we don't access np after freeing it! */
4559 	strlcpy(inst_name, ncr_name(np), sizeof(inst_name));
4560 
4561 	printk("%s: releasing host resources\n", ncr_name(np));
4562 
4563 /*
4564 **	Stop the ncr_timeout process
4565 **	Set release_stage to 1 and wait that ncr_timeout() set it to 2.
4566 */
4567 
4568 #ifdef DEBUG_NCR53C8XX
4569 	printk("%s: stopping the timer\n", ncr_name(np));
4570 #endif
4571 	np->release_stage = 1;
4572 	for (i = 50 ; i && np->release_stage != 2 ; i--)
4573 		mdelay(100);
4574 	if (np->release_stage != 2)
4575 		printk("%s: the timer seems to be already stopped\n", ncr_name(np));
4576 	else np->release_stage = 2;
4577 
4578 /*
4579 **	Disable chip interrupts
4580 */
4581 
4582 #ifdef DEBUG_NCR53C8XX
4583 	printk("%s: disabling chip interrupts\n", ncr_name(np));
4584 #endif
4585 	OUTW (nc_sien , 0);
4586 	OUTB (nc_dien , 0);
4587 
4588 	/*
4589 	**	Reset NCR chip
4590 	**	Restore bios setting for automatic clock detection.
4591 	*/
4592 
4593 	printk("%s: resetting chip\n", ncr_name(np));
4594 	ncr_chip_reset(np, 100);
4595 
4596 	OUTB(nc_dmode,	np->sv_dmode);
4597 	OUTB(nc_dcntl,	np->sv_dcntl);
4598 	OUTB(nc_ctest0,	np->sv_ctest0);
4599 	OUTB(nc_ctest3,	np->sv_ctest3);
4600 	OUTB(nc_ctest4,	np->sv_ctest4);
4601 	OUTB(nc_ctest5,	np->sv_ctest5);
4602 	OUTB(nc_gpcntl,	np->sv_gpcntl);
4603 	OUTB(nc_stest2,	np->sv_stest2);
4604 
4605 	ncr_selectclock(np, np->sv_scntl3);
4606 
4607 	/*
4608 	**	Free allocated ccb(s)
4609 	*/
4610 
4611 	while ((cp=np->ccb->link_ccb) != NULL) {
4612 		np->ccb->link_ccb = cp->link_ccb;
4613 		if (cp->host_status) {
4614 		printk("%s: shall free an active ccb (host_status=%d)\n",
4615 			ncr_name(np), cp->host_status);
4616 		}
4617 #ifdef DEBUG_NCR53C8XX
4618 	printk("%s: freeing ccb (%lx)\n", ncr_name(np), (u_long) cp);
4619 #endif
4620 		m_free_dma(cp, sizeof(*cp), "CCB");
4621 	}
4622 
4623 	/* Free allocated tp(s) */
4624 
4625 	for (target = 0; target < MAX_TARGET ; target++) {
4626 		tp=&np->target[target];
4627 		for (lun = 0 ; lun < MAX_LUN ; lun++) {
4628 			lp = tp->lp[lun];
4629 			if (lp) {
4630 #ifdef DEBUG_NCR53C8XX
4631 	printk("%s: freeing lp (%lx)\n", ncr_name(np), (u_long) lp);
4632 #endif
4633 				if (lp->jump_ccb != &lp->jump_ccb_0)
4634 					m_free_dma(lp->jump_ccb,256,"JUMP_CCB");
4635 				m_free_dma(lp, sizeof(*lp), "LCB");
4636 			}
4637 		}
4638 	}
4639 
4640 	if (np->scripth0)
4641 		m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
4642 	if (np->script0)
4643 		m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
4644 	if (np->ccb)
4645 		m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
4646 	m_free_dma(np, sizeof(struct ncb), "NCB");
4647 
4648 	printk("%s: host resources successfully released\n", inst_name);
4649 }
4650 
4651 /*==========================================================
4652 **
4653 **
4654 **	Complete execution of a SCSI command.
4655 **	Signal completion to the generic SCSI driver.
4656 **
4657 **
4658 **==========================================================
4659 */
4660 
4661 void ncr_complete (struct ncb *np, struct ccb *cp)
4662 {
4663 	struct scsi_cmnd *cmd;
4664 	struct tcb *tp;
4665 	struct lcb *lp;
4666 
4667 	/*
4668 	**	Sanity check
4669 	*/
4670 
4671 	if (!cp || cp->magic != CCB_MAGIC || !cp->cmd)
4672 		return;
4673 
4674 	/*
4675 	**	Print minimal debug information.
4676 	*/
4677 
4678 	if (DEBUG_FLAGS & DEBUG_TINY)
4679 		printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
4680 			cp->host_status,cp->scsi_status);
4681 
4682 	/*
4683 	**	Get command, target and lun pointers.
4684 	*/
4685 
4686 	cmd = cp->cmd;
4687 	cp->cmd = NULL;
4688 	tp = &np->target[cmd->device->id];
4689 	lp = tp->lp[cmd->device->lun];
4690 
4691 	/*
4692 	**	We donnot queue more than 1 ccb per target
4693 	**	with negotiation at any time. If this ccb was
4694 	**	used for negotiation, clear this info in the tcb.
4695 	*/
4696 
4697 	if (cp == tp->nego_cp)
4698 		tp->nego_cp = NULL;
4699 
4700 	/*
4701 	**	If auto-sense performed, change scsi status.
4702 	*/
4703 	if (cp->auto_sense) {
4704 		cp->scsi_status = cp->auto_sense;
4705 	}
4706 
4707 	/*
4708 	**	If we were recovering from queue full or performing
4709 	**	auto-sense, requeue skipped CCBs to the wait queue.
4710 	*/
4711 
4712 	if (lp && lp->held_ccb) {
4713 		if (cp == lp->held_ccb) {
4714 			list_splice_init(&lp->skip_ccbq, &lp->wait_ccbq);
4715 			lp->held_ccb = NULL;
4716 		}
4717 	}
4718 
4719 	/*
4720 	**	Check for parity errors.
4721 	*/
4722 
4723 	if (cp->parity_status > 1) {
4724 		PRINT_ADDR(cmd, "%d parity error(s).\n",cp->parity_status);
4725 	}
4726 
4727 	/*
4728 	**	Check for extended errors.
4729 	*/
4730 
4731 	if (cp->xerr_status != XE_OK) {
4732 		switch (cp->xerr_status) {
4733 		case XE_EXTRA_DATA:
4734 			PRINT_ADDR(cmd, "extraneous data discarded.\n");
4735 			break;
4736 		case XE_BAD_PHASE:
4737 			PRINT_ADDR(cmd, "invalid scsi phase (4/5).\n");
4738 			break;
4739 		default:
4740 			PRINT_ADDR(cmd, "extended error %d.\n",
4741 					cp->xerr_status);
4742 			break;
4743 		}
4744 		if (cp->host_status==HS_COMPLETE)
4745 			cp->host_status = HS_FAIL;
4746 	}
4747 
4748 	/*
4749 	**	Print out any error for debugging purpose.
4750 	*/
4751 	if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4752 		if (cp->host_status != HS_COMPLETE ||
4753 		    cp->scsi_status != SAM_STAT_GOOD) {
4754 			PRINT_ADDR(cmd, "ERROR: cmd=%x host_status=%x "
4755 					"scsi_status=%x\n", cmd->cmnd[0],
4756 					cp->host_status, cp->scsi_status);
4757 		}
4758 	}
4759 
4760 	/*
4761 	**	Check the status.
4762 	*/
4763 	cmd->result = 0;
4764 	if (   (cp->host_status == HS_COMPLETE)
4765 		&& (cp->scsi_status == SAM_STAT_GOOD ||
4766 		    cp->scsi_status == SAM_STAT_CONDITION_MET)) {
4767 		/*
4768 		 *	All went well (GOOD status).
4769 		 *	CONDITION MET status is returned on
4770 		 *	`Pre-Fetch' or `Search data' success.
4771 		 */
4772 		set_status_byte(cmd, cp->scsi_status);
4773 
4774 		/*
4775 		**	@RESID@
4776 		**	Could dig out the correct value for resid,
4777 		**	but it would be quite complicated.
4778 		*/
4779 		/* if (cp->phys.header.lastp != cp->phys.header.goalp) */
4780 
4781 		/*
4782 		**	Allocate the lcb if not yet.
4783 		*/
4784 		if (!lp)
4785 			ncr_alloc_lcb (np, cmd->device->id, cmd->device->lun);
4786 
4787 		tp->bytes     += cp->data_len;
4788 		tp->transfers ++;
4789 
4790 		/*
4791 		**	If tags was reduced due to queue full,
4792 		**	increase tags if 1000 good status received.
4793 		*/
4794 		if (lp && lp->usetags && lp->numtags < lp->maxtags) {
4795 			++lp->num_good;
4796 			if (lp->num_good >= 1000) {
4797 				lp->num_good = 0;
4798 				++lp->numtags;
4799 				ncr_setup_tags (np, cmd->device);
4800 			}
4801 		}
4802 	} else if ((cp->host_status == HS_COMPLETE)
4803 		&& (cp->scsi_status == SAM_STAT_CHECK_CONDITION)) {
4804 		/*
4805 		**   Check condition code
4806 		*/
4807 		set_status_byte(cmd, SAM_STAT_CHECK_CONDITION);
4808 
4809 		/*
4810 		**	Copy back sense data to caller's buffer.
4811 		*/
4812 		memcpy(cmd->sense_buffer, cp->sense_buf,
4813 		       min_t(size_t, SCSI_SENSE_BUFFERSIZE,
4814 			     sizeof(cp->sense_buf)));
4815 
4816 		if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
4817 			u_char *p = cmd->sense_buffer;
4818 			int i;
4819 			PRINT_ADDR(cmd, "sense data:");
4820 			for (i=0; i<14; i++) printk (" %x", *p++);
4821 			printk (".\n");
4822 		}
4823 	} else if ((cp->host_status == HS_COMPLETE)
4824 		&& (cp->scsi_status == SAM_STAT_RESERVATION_CONFLICT)) {
4825 		/*
4826 		**   Reservation Conflict condition code
4827 		*/
4828 		set_status_byte(cmd, SAM_STAT_RESERVATION_CONFLICT);
4829 
4830 	} else if ((cp->host_status == HS_COMPLETE)
4831 		&& (cp->scsi_status == SAM_STAT_BUSY ||
4832 		    cp->scsi_status == SAM_STAT_TASK_SET_FULL)) {
4833 
4834 		/*
4835 		**   Target is busy.
4836 		*/
4837 		set_status_byte(cmd, cp->scsi_status);
4838 
4839 	} else if ((cp->host_status == HS_SEL_TIMEOUT)
4840 		|| (cp->host_status == HS_TIMEOUT)) {
4841 
4842 		/*
4843 		**   No response
4844 		*/
4845 		set_status_byte(cmd, cp->scsi_status);
4846 		set_host_byte(cmd, DID_TIME_OUT);
4847 
4848 	} else if (cp->host_status == HS_RESET) {
4849 
4850 		/*
4851 		**   SCSI bus reset
4852 		*/
4853 		set_status_byte(cmd, cp->scsi_status);
4854 		set_host_byte(cmd, DID_RESET);
4855 
4856 	} else if (cp->host_status == HS_ABORTED) {
4857 
4858 		/*
4859 		**   Transfer aborted
4860 		*/
4861 		set_status_byte(cmd, cp->scsi_status);
4862 		set_host_byte(cmd, DID_ABORT);
4863 
4864 	} else {
4865 
4866 		/*
4867 		**  Other protocol messes
4868 		*/
4869 		PRINT_ADDR(cmd, "COMMAND FAILED (%x %x) @%p.\n",
4870 			cp->host_status, cp->scsi_status, cp);
4871 
4872 		set_status_byte(cmd, cp->scsi_status);
4873 		set_host_byte(cmd, DID_ERROR);
4874 	}
4875 
4876 	/*
4877 	**	trace output
4878 	*/
4879 
4880 	if (tp->usrflag & UF_TRACE) {
4881 		u_char * p;
4882 		int i;
4883 		PRINT_ADDR(cmd, " CMD:");
4884 		p = (u_char*) &cmd->cmnd[0];
4885 		for (i=0; i<cmd->cmd_len; i++) printk (" %x", *p++);
4886 
4887 		if (cp->host_status==HS_COMPLETE) {
4888 			switch (cp->scsi_status) {
4889 			case SAM_STAT_GOOD:
4890 				printk ("  GOOD");
4891 				break;
4892 			case SAM_STAT_CHECK_CONDITION:
4893 				printk ("  SENSE:");
4894 				p = (u_char*) &cmd->sense_buffer;
4895 				for (i=0; i<14; i++)
4896 					printk (" %x", *p++);
4897 				break;
4898 			default:
4899 				printk ("  STAT: %x\n", cp->scsi_status);
4900 				break;
4901 			}
4902 		} else printk ("  HOSTERROR: %x", cp->host_status);
4903 		printk ("\n");
4904 	}
4905 
4906 	/*
4907 	**	Free this ccb
4908 	*/
4909 	ncr_free_ccb (np, cp);
4910 
4911 	/*
4912 	**	requeue awaiting scsi commands for this lun.
4913 	*/
4914 	if (lp && lp->queuedccbs < lp->queuedepth &&
4915 	    !list_empty(&lp->wait_ccbq))
4916 		ncr_start_next_ccb(np, lp, 2);
4917 
4918 	/*
4919 	**	requeue awaiting scsi commands for this controller.
4920 	*/
4921 	if (np->waiting_list)
4922 		requeue_waiting_list(np);
4923 
4924 	/*
4925 	**	signal completion to generic driver.
4926 	*/
4927 	ncr_queue_done_cmd(np, cmd);
4928 }
4929 
4930 /*==========================================================
4931 **
4932 **
4933 **	Signal all (or one) control block done.
4934 **
4935 **
4936 **==========================================================
4937 */
4938 
4939 /*
4940 **	This CCB has been skipped by the NCR.
4941 **	Queue it in the corresponding unit queue.
4942 */
4943 static void ncr_ccb_skipped(struct ncb *np, struct ccb *cp)
4944 {
4945 	struct tcb *tp = &np->target[cp->target];
4946 	struct lcb *lp = tp->lp[cp->lun];
4947 
4948 	if (lp && cp != np->ccb) {
4949 		cp->host_status &= ~HS_SKIPMASK;
4950 		cp->start.schedule.l_paddr =
4951 			cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
4952 		list_move_tail(&cp->link_ccbq, &lp->skip_ccbq);
4953 		if (cp->queued) {
4954 			--lp->queuedccbs;
4955 		}
4956 	}
4957 	if (cp->queued) {
4958 		--np->queuedccbs;
4959 		cp->queued = 0;
4960 	}
4961 }
4962 
4963 /*
4964 **	The NCR has completed CCBs.
4965 **	Look at the DONE QUEUE if enabled, otherwise scan all CCBs
4966 */
4967 void ncr_wakeup_done (struct ncb *np)
4968 {
4969 	struct ccb *cp;
4970 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
4971 	int i, j;
4972 
4973 	i = np->ccb_done_ic;
4974 	while (1) {
4975 		j = i+1;
4976 		if (j >= MAX_DONE)
4977 			j = 0;
4978 
4979 		cp = np->ccb_done[j];
4980 		if (!CCB_DONE_VALID(cp))
4981 			break;
4982 
4983 		np->ccb_done[j] = (struct ccb *)CCB_DONE_EMPTY;
4984 		np->scripth->done_queue[5*j + 4] =
4985 				cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
4986 		MEMORY_BARRIER();
4987 		np->scripth->done_queue[5*i + 4] =
4988 				cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
4989 
4990 		if (cp->host_status & HS_DONEMASK)
4991 			ncr_complete (np, cp);
4992 		else if (cp->host_status & HS_SKIPMASK)
4993 			ncr_ccb_skipped (np, cp);
4994 
4995 		i = j;
4996 	}
4997 	np->ccb_done_ic = i;
4998 #else
4999 	cp = np->ccb;
5000 	while (cp) {
5001 		if (cp->host_status & HS_DONEMASK)
5002 			ncr_complete (np, cp);
5003 		else if (cp->host_status & HS_SKIPMASK)
5004 			ncr_ccb_skipped (np, cp);
5005 		cp = cp->link_ccb;
5006 	}
5007 #endif
5008 }
5009 
5010 /*
5011 **	Complete all active CCBs.
5012 */
5013 void ncr_wakeup (struct ncb *np, u_long code)
5014 {
5015 	struct ccb *cp = np->ccb;
5016 
5017 	while (cp) {
5018 		if (cp->host_status != HS_IDLE) {
5019 			cp->host_status = code;
5020 			ncr_complete (np, cp);
5021 		}
5022 		cp = cp->link_ccb;
5023 	}
5024 }
5025 
5026 /*
5027 ** Reset ncr chip.
5028 */
5029 
5030 /* Some initialisation must be done immediately following reset, for 53c720,
5031  * at least.  EA (dcntl bit 5) isn't set here as it is set once only in
5032  * the _detect function.
5033  */
5034 static void ncr_chip_reset(struct ncb *np, int delay)
5035 {
5036 	OUTB (nc_istat,  SRST);
5037 	udelay(delay);
5038 	OUTB (nc_istat,  0   );
5039 
5040 	if (np->features & FE_EHP)
5041 		OUTB (nc_ctest0, EHP);
5042 	if (np->features & FE_MUX)
5043 		OUTB (nc_ctest4, MUX);
5044 }
5045 
5046 
5047 /*==========================================================
5048 **
5049 **
5050 **	Start NCR chip.
5051 **
5052 **
5053 **==========================================================
5054 */
5055 
5056 void ncr_init (struct ncb *np, int reset, char * msg, u_long code)
5057 {
5058  	int	i;
5059 
5060  	/*
5061 	**	Reset chip if asked, otherwise just clear fifos.
5062  	*/
5063 
5064 	if (reset) {
5065 		OUTB (nc_istat,  SRST);
5066 		udelay(100);
5067 	}
5068 	else {
5069 		OUTB (nc_stest3, TE|CSF);
5070 		OUTONB (nc_ctest3, CLF);
5071 	}
5072 
5073 	/*
5074 	**	Message.
5075 	*/
5076 
5077 	if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
5078 
5079 	/*
5080 	**	Clear Start Queue
5081 	*/
5082 	np->queuedepth = MAX_START - 1;	/* 1 entry needed as end marker */
5083 	for (i = 1; i < MAX_START + MAX_START; i += 2)
5084 		np->scripth0->tryloop[i] =
5085 				cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5086 
5087 	/*
5088 	**	Start at first entry.
5089 	*/
5090 	np->squeueput = 0;
5091 	np->script0->startpos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np, tryloop));
5092 
5093 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
5094 	/*
5095 	**	Clear Done Queue
5096 	*/
5097 	for (i = 0; i < MAX_DONE; i++) {
5098 		np->ccb_done[i] = (struct ccb *)CCB_DONE_EMPTY;
5099 		np->scripth0->done_queue[5*i + 4] =
5100 			cpu_to_scr(NCB_SCRIPT_PHYS (np, done_end));
5101 	}
5102 #endif
5103 
5104 	/*
5105 	**	Start at first entry.
5106 	*/
5107 	np->script0->done_pos[0] = cpu_to_scr(NCB_SCRIPTH_PHYS (np,done_queue));
5108 	np->ccb_done_ic = MAX_DONE-1;
5109 	np->scripth0->done_queue[5*(MAX_DONE-1) + 4] =
5110 			cpu_to_scr(NCB_SCRIPT_PHYS (np, done_plug));
5111 
5112 	/*
5113 	**	Wakeup all pending jobs.
5114 	*/
5115 	ncr_wakeup (np, code);
5116 
5117 	/*
5118 	**	Init chip.
5119 	*/
5120 
5121 	/*
5122 	** Remove reset; big delay because the 895 needs time for the
5123 	** bus mode to settle
5124 	*/
5125 	ncr_chip_reset(np, 2000);
5126 
5127 	OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
5128 					/*  full arb., ena parity, par->ATN  */
5129 	OUTB (nc_scntl1, 0x00);		/*  odd parity, and remove CRST!! */
5130 
5131 	ncr_selectclock(np, np->rv_scntl3);	/* Select SCSI clock */
5132 
5133 	OUTB (nc_scid  , RRE|np->myaddr);	/* Adapter SCSI address */
5134 	OUTW (nc_respid, 1ul<<np->myaddr);	/* Id to respond to */
5135 	OUTB (nc_istat , SIGP	);		/*  Signal Process */
5136 	OUTB (nc_dmode , np->rv_dmode);		/* Burst length, dma mode */
5137 	OUTB (nc_ctest5, np->rv_ctest5);	/* Large fifo + large burst */
5138 
5139 	OUTB (nc_dcntl , NOCOM|np->rv_dcntl);	/* Protect SFBR */
5140 	OUTB (nc_ctest0, np->rv_ctest0);	/* 720: CDIS and EHP */
5141 	OUTB (nc_ctest3, np->rv_ctest3);	/* Write and invalidate */
5142 	OUTB (nc_ctest4, np->rv_ctest4);	/* Master parity checking */
5143 
5144 	OUTB (nc_stest2, EXT|np->rv_stest2);	/* Extended Sreq/Sack filtering */
5145 	OUTB (nc_stest3, TE);			/* TolerANT enable */
5146 	OUTB (nc_stime0, 0x0c	);		/* HTH disabled  STO 0.25 sec */
5147 
5148 	/*
5149 	**	Disable disconnects.
5150 	*/
5151 
5152 	np->disc = 0;
5153 
5154 	/*
5155 	**    Enable GPIO0 pin for writing if LED support.
5156 	*/
5157 
5158 	if (np->features & FE_LED0) {
5159 		OUTOFFB (nc_gpcntl, 0x01);
5160 	}
5161 
5162 	/*
5163 	**      enable ints
5164 	*/
5165 
5166 	OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
5167 	OUTB (nc_dien , MDPE|BF|ABRT|SSI|SIR|IID);
5168 
5169 	/*
5170 	**	Fill in target structure.
5171 	**	Reinitialize usrsync.
5172 	**	Reinitialize usrwide.
5173 	**	Prepare sync negotiation according to actual SCSI bus mode.
5174 	*/
5175 
5176 	for (i=0;i<MAX_TARGET;i++) {
5177 		struct tcb *tp = &np->target[i];
5178 
5179 		tp->sval    = 0;
5180 		tp->wval    = np->rv_scntl3;
5181 
5182 		if (tp->usrsync != 255) {
5183 			if (tp->usrsync <= np->maxsync) {
5184 				if (tp->usrsync < np->minsync) {
5185 					tp->usrsync = np->minsync;
5186 				}
5187 			}
5188 			else
5189 				tp->usrsync = 255;
5190 		}
5191 
5192 		if (tp->usrwide > np->maxwide)
5193 			tp->usrwide = np->maxwide;
5194 
5195 	}
5196 
5197 	/*
5198 	**    Start script processor.
5199 	*/
5200 	if (np->paddr2) {
5201 		if (bootverbose)
5202 			printk ("%s: Downloading SCSI SCRIPTS.\n",
5203 				ncr_name(np));
5204 		OUTL (nc_scratcha, vtobus(np->script0));
5205 		OUTL_DSP (NCB_SCRIPTH_PHYS (np, start_ram));
5206 	}
5207 	else
5208 		OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
5209 }
5210 
5211 /*==========================================================
5212 **
5213 **	Prepare the negotiation values for wide and
5214 **	synchronous transfers.
5215 **
5216 **==========================================================
5217 */
5218 
5219 static void ncr_negotiate (struct ncb* np, struct tcb* tp)
5220 {
5221 	/*
5222 	**	minsync unit is 4ns !
5223 	*/
5224 
5225 	u_long minsync = tp->usrsync;
5226 
5227 	/*
5228 	**	SCSI bus mode limit
5229 	*/
5230 
5231 	if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
5232 		if (minsync < 12) minsync = 12;
5233 	}
5234 
5235 	/*
5236 	**	our limit ..
5237 	*/
5238 
5239 	if (minsync < np->minsync)
5240 		minsync = np->minsync;
5241 
5242 	/*
5243 	**	divider limit
5244 	*/
5245 
5246 	if (minsync > np->maxsync)
5247 		minsync = 255;
5248 
5249 	if (tp->maxoffs > np->maxoffs)
5250 		tp->maxoffs = np->maxoffs;
5251 
5252 	tp->minsync = minsync;
5253 	tp->maxoffs = (minsync<255 ? tp->maxoffs : 0);
5254 
5255 	/*
5256 	**	period=0: has to negotiate sync transfer
5257 	*/
5258 
5259 	tp->period=0;
5260 
5261 	/*
5262 	**	widedone=0: has to negotiate wide transfer
5263 	*/
5264 	tp->widedone=0;
5265 }
5266 
5267 /*==========================================================
5268 **
5269 **	Get clock factor and sync divisor for a given
5270 **	synchronous factor period.
5271 **	Returns the clock factor (in sxfer) and scntl3
5272 **	synchronous divisor field.
5273 **
5274 **==========================================================
5275 */
5276 
5277 static void ncr_getsync(struct ncb *np, u_char sfac, u_char *fakp, u_char *scntl3p)
5278 {
5279 	u_long	clk = np->clock_khz;	/* SCSI clock frequency in kHz	*/
5280 	int	div = np->clock_divn;	/* Number of divisors supported	*/
5281 	u_long	fak;			/* Sync factor in sxfer		*/
5282 	u_long	per;			/* Period in tenths of ns	*/
5283 	u_long	kpc;			/* (per * clk)			*/
5284 
5285 	/*
5286 	**	Compute the synchronous period in tenths of nano-seconds
5287 	*/
5288 	if	(sfac <= 10)	per = 250;
5289 	else if	(sfac == 11)	per = 303;
5290 	else if	(sfac == 12)	per = 500;
5291 	else			per = 40 * sfac;
5292 
5293 	/*
5294 	**	Look for the greatest clock divisor that allows an
5295 	**	input speed faster than the period.
5296 	*/
5297 	kpc = per * clk;
5298 	while (--div > 0)
5299 		if (kpc >= (div_10M[div] << 2)) break;
5300 
5301 	/*
5302 	**	Calculate the lowest clock factor that allows an output
5303 	**	speed not faster than the period.
5304 	*/
5305 	fak = (kpc - 1) / div_10M[div] + 1;
5306 
5307 	if (fak < 4) fak = 4;	/* Should never happen, too bad ... */
5308 
5309 	/*
5310 	**	Compute and return sync parameters for the ncr
5311 	*/
5312 	*fakp		= fak - 4;
5313 	*scntl3p	= ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
5314 }
5315 
5316 
5317 /*==========================================================
5318 **
5319 **	Set actual values, sync status and patch all ccbs of
5320 **	a target according to new sync/wide agreement.
5321 **
5322 **==========================================================
5323 */
5324 
5325 static void ncr_set_sync_wide_status (struct ncb *np, u_char target)
5326 {
5327 	struct ccb *cp;
5328 	struct tcb *tp = &np->target[target];
5329 
5330 	/*
5331 	**	set actual value and sync_status
5332 	*/
5333 	OUTB (nc_sxfer, tp->sval);
5334 	np->sync_st = tp->sval;
5335 	OUTB (nc_scntl3, tp->wval);
5336 	np->wide_st = tp->wval;
5337 
5338 	/*
5339 	**	patch ALL ccbs of this target.
5340 	*/
5341 	for (cp = np->ccb; cp; cp = cp->link_ccb) {
5342 		if (!cp->cmd) continue;
5343 		if (scmd_id(cp->cmd) != target) continue;
5344 		cp->phys.select.sel_scntl3 = tp->wval;
5345 		cp->phys.select.sel_sxfer  = tp->sval;
5346 	}
5347 }
5348 
5349 /*==========================================================
5350 **
5351 **	Switch sync mode for current job and it's target
5352 **
5353 **==========================================================
5354 */
5355 
5356 static void ncr_setsync (struct ncb *np, struct ccb *cp, u_char scntl3, u_char sxfer)
5357 {
5358 	struct scsi_cmnd *cmd = cp->cmd;
5359 	struct tcb *tp;
5360 	u_char target = INB (nc_sdid) & 0x0f;
5361 	u_char idiv;
5362 
5363 	BUG_ON(target != (scmd_id(cmd) & 0xf));
5364 
5365 	tp = &np->target[target];
5366 
5367 	if (!scntl3 || !(sxfer & 0x1f))
5368 		scntl3 = np->rv_scntl3;
5369 	scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) | (np->rv_scntl3 & 0x07);
5370 
5371 	/*
5372 	**	Deduce the value of controller sync period from scntl3.
5373 	**	period is in tenths of nano-seconds.
5374 	*/
5375 
5376 	idiv = ((scntl3 >> 4) & 0x7);
5377 	if ((sxfer & 0x1f) && idiv)
5378 		tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
5379 	else
5380 		tp->period = 0xffff;
5381 
5382 	/* Stop there if sync parameters are unchanged */
5383 	if (tp->sval == sxfer && tp->wval == scntl3)
5384 		return;
5385 	tp->sval = sxfer;
5386 	tp->wval = scntl3;
5387 
5388 	if (sxfer & 0x01f) {
5389 		/* Disable extended Sreq/Sack filtering */
5390 		if (tp->period <= 2000)
5391 			OUTOFFB(nc_stest2, EXT);
5392 	}
5393 
5394 	spi_display_xfer_agreement(tp->starget);
5395 
5396 	/*
5397 	**	set actual value and sync_status
5398 	**	patch ALL ccbs of this target.
5399 	*/
5400 	ncr_set_sync_wide_status(np, target);
5401 }
5402 
5403 /*==========================================================
5404 **
5405 **	Switch wide mode for current job and it's target
5406 **	SCSI specs say: a SCSI device that accepts a WDTR
5407 **	message shall reset the synchronous agreement to
5408 **	asynchronous mode.
5409 **
5410 **==========================================================
5411 */
5412 
5413 static void ncr_setwide (struct ncb *np, struct ccb *cp, u_char wide, u_char ack)
5414 {
5415 	struct scsi_cmnd *cmd = cp->cmd;
5416 	u16 target = INB (nc_sdid) & 0x0f;
5417 	struct tcb *tp;
5418 	u_char	scntl3;
5419 	u_char	sxfer;
5420 
5421 	BUG_ON(target != (scmd_id(cmd) & 0xf));
5422 
5423 	tp = &np->target[target];
5424 	tp->widedone  =  wide+1;
5425 	scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
5426 
5427 	sxfer = ack ? 0 : tp->sval;
5428 
5429 	/*
5430 	**	 Stop there if sync/wide parameters are unchanged
5431 	*/
5432 	if (tp->sval == sxfer && tp->wval == scntl3) return;
5433 	tp->sval = sxfer;
5434 	tp->wval = scntl3;
5435 
5436 	/*
5437 	**	Bells and whistles   ;-)
5438 	*/
5439 	if (bootverbose >= 2) {
5440 		dev_info(&cmd->device->sdev_target->dev, "WIDE SCSI %sabled.\n",
5441 				(scntl3 & EWS) ? "en" : "dis");
5442 	}
5443 
5444 	/*
5445 	**	set actual value and sync_status
5446 	**	patch ALL ccbs of this target.
5447 	*/
5448 	ncr_set_sync_wide_status(np, target);
5449 }
5450 
5451 /*==========================================================
5452 **
5453 **	Switch tagged mode for a target.
5454 **
5455 **==========================================================
5456 */
5457 
5458 static void ncr_setup_tags (struct ncb *np, struct scsi_device *sdev)
5459 {
5460 	unsigned char tn = sdev->id, ln = sdev->lun;
5461 	struct tcb *tp = &np->target[tn];
5462 	struct lcb *lp = tp->lp[ln];
5463 	u_char   reqtags, maxdepth;
5464 
5465 	/*
5466 	**	Just in case ...
5467 	*/
5468 	if ((!tp) || (!lp) || !sdev)
5469 		return;
5470 
5471 	/*
5472 	**	If SCSI device queue depth is not yet set, leave here.
5473 	*/
5474 	if (!lp->scdev_depth)
5475 		return;
5476 
5477 	/*
5478 	**	Donnot allow more tags than the SCSI driver can queue
5479 	**	for this device.
5480 	**	Donnot allow more tags than we can handle.
5481 	*/
5482 	maxdepth = lp->scdev_depth;
5483 	if (maxdepth > lp->maxnxs)	maxdepth    = lp->maxnxs;
5484 	if (lp->maxtags > maxdepth)	lp->maxtags = maxdepth;
5485 	if (lp->numtags > maxdepth)	lp->numtags = maxdepth;
5486 
5487 	/*
5488 	**	only devices conformant to ANSI Version >= 2
5489 	**	only devices capable of tagged commands
5490 	**	only if enabled by user ..
5491 	*/
5492 	if (sdev->tagged_supported && lp->numtags > 1) {
5493 		reqtags = lp->numtags;
5494 	} else {
5495 		reqtags = 1;
5496 	}
5497 
5498 	/*
5499 	**	Update max number of tags
5500 	*/
5501 	lp->numtags = reqtags;
5502 	if (lp->numtags > lp->maxtags)
5503 		lp->maxtags = lp->numtags;
5504 
5505 	/*
5506 	**	If we want to switch tag mode, we must wait
5507 	**	for no CCB to be active.
5508 	*/
5509 	if	(reqtags > 1 && lp->usetags) {	 /* Stay in tagged mode    */
5510 		if (lp->queuedepth == reqtags)	 /* Already announced	   */
5511 			return;
5512 		lp->queuedepth	= reqtags;
5513 	}
5514 	else if	(reqtags <= 1 && !lp->usetags) { /* Stay in untagged mode  */
5515 		lp->queuedepth	= reqtags;
5516 		return;
5517 	}
5518 	else {					 /* Want to switch tag mode */
5519 		if (lp->busyccbs)		 /* If not yet safe, return */
5520 			return;
5521 		lp->queuedepth	= reqtags;
5522 		lp->usetags	= reqtags > 1 ? 1 : 0;
5523 	}
5524 
5525 	/*
5526 	**	Patch the lun mini-script, according to tag mode.
5527 	*/
5528 	lp->jump_tag.l_paddr = lp->usetags?
5529 			cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_tag)) :
5530 			cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
5531 
5532 	/*
5533 	**	Announce change to user.
5534 	*/
5535 	if (bootverbose) {
5536 		if (lp->usetags) {
5537 			dev_info(&sdev->sdev_gendev,
5538 				"tagged command queue depth set to %d\n",
5539 				reqtags);
5540 		} else {
5541 			dev_info(&sdev->sdev_gendev,
5542 					"tagged command queueing disabled\n");
5543 		}
5544 	}
5545 }
5546 
5547 /*==========================================================
5548 **
5549 **
5550 **	ncr timeout handler.
5551 **
5552 **
5553 **==========================================================
5554 **
5555 **	Misused to keep the driver running when
5556 **	interrupts are not configured correctly.
5557 **
5558 **----------------------------------------------------------
5559 */
5560 
5561 static void ncr_timeout (struct ncb *np)
5562 {
5563 	u_long	thistime = jiffies;
5564 
5565 	/*
5566 	**	If release process in progress, let's go
5567 	**	Set the release stage from 1 to 2 to synchronize
5568 	**	with the release process.
5569 	*/
5570 
5571 	if (np->release_stage) {
5572 		if (np->release_stage == 1) np->release_stage = 2;
5573 		return;
5574 	}
5575 
5576 	np->timer.expires = jiffies + SCSI_NCR_TIMER_INTERVAL;
5577 	add_timer(&np->timer);
5578 
5579 	/*
5580 	**	If we are resetting the ncr, wait for settle_time before
5581 	**	clearing it. Then command processing will be resumed.
5582 	*/
5583 	if (np->settle_time) {
5584 		if (np->settle_time <= thistime) {
5585 			if (bootverbose > 1)
5586 				printk("%s: command processing resumed\n", ncr_name(np));
5587 			np->settle_time	= 0;
5588 			np->disc	= 1;
5589 			requeue_waiting_list(np);
5590 		}
5591 		return;
5592 	}
5593 
5594 	/*
5595 	**	Since the generic scsi driver only allows us 0.5 second
5596 	**	to perform abort of a command, we must look at ccbs about
5597 	**	every 0.25 second.
5598 	*/
5599 	if (np->lasttime + 4*HZ < thistime) {
5600 		/*
5601 		**	block ncr interrupts
5602 		*/
5603 		np->lasttime = thistime;
5604 	}
5605 
5606 #ifdef SCSI_NCR_BROKEN_INTR
5607 	if (INB(nc_istat) & (INTF|SIP|DIP)) {
5608 
5609 		/*
5610 		**	Process pending interrupts.
5611 		*/
5612 		if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
5613 		ncr_exception (np);
5614 		if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
5615 	}
5616 #endif /* SCSI_NCR_BROKEN_INTR */
5617 }
5618 
5619 /*==========================================================
5620 **
5621 **	log message for real hard errors
5622 **
5623 **	"ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
5624 **	"	      reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
5625 **
5626 **	exception register:
5627 **		ds:	dstat
5628 **		si:	sist
5629 **
5630 **	SCSI bus lines:
5631 **		so:	control lines as driver by NCR.
5632 **		si:	control lines as seen by NCR.
5633 **		sd:	scsi data lines as seen by NCR.
5634 **
5635 **	wide/fastmode:
5636 **		sxfer:	(see the manual)
5637 **		scntl3:	(see the manual)
5638 **
5639 **	current script command:
5640 **		dsp:	script address (relative to start of script).
5641 **		dbc:	first word of script command.
5642 **
5643 **	First 16 register of the chip:
5644 **		r0..rf
5645 **
5646 **==========================================================
5647 */
5648 
5649 static void ncr_log_hard_error(struct ncb *np, u16 sist, u_char dstat)
5650 {
5651 	u32	dsp;
5652 	int	script_ofs;
5653 	int	script_size;
5654 	char	*script_name;
5655 	u_char	*script_base;
5656 	int	i;
5657 
5658 	dsp	= INL (nc_dsp);
5659 
5660 	if (dsp > np->p_script && dsp <= np->p_script + sizeof(struct script)) {
5661 		script_ofs	= dsp - np->p_script;
5662 		script_size	= sizeof(struct script);
5663 		script_base	= (u_char *) np->script0;
5664 		script_name	= "script";
5665 	}
5666 	else if (np->p_scripth < dsp &&
5667 		 dsp <= np->p_scripth + sizeof(struct scripth)) {
5668 		script_ofs	= dsp - np->p_scripth;
5669 		script_size	= sizeof(struct scripth);
5670 		script_base	= (u_char *) np->scripth0;
5671 		script_name	= "scripth";
5672 	} else {
5673 		script_ofs	= dsp;
5674 		script_size	= 0;
5675 		script_base	= NULL;
5676 		script_name	= "mem";
5677 	}
5678 
5679 	printk ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
5680 		ncr_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
5681 		(unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
5682 		(unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
5683 		(unsigned)INL (nc_dbc));
5684 
5685 	if (((script_ofs & 3) == 0) &&
5686 	    (unsigned)script_ofs < script_size) {
5687 		printk ("%s: script cmd = %08x\n", ncr_name(np),
5688 			scr_to_cpu((int) *(ncrcmd *)(script_base + script_ofs)));
5689 	}
5690 
5691 	printk ("%s: regdump:", ncr_name(np));
5692 	for (i=0; i<16;i++)
5693             printk (" %02x", (unsigned)INB_OFF(i));
5694 	printk (".\n");
5695 }
5696 
5697 /*============================================================
5698 **
5699 **	ncr chip exception handler.
5700 **
5701 **============================================================
5702 **
5703 **	In normal cases, interrupt conditions occur one at a
5704 **	time. The ncr is able to stack in some extra registers
5705 **	other interrupts that will occur after the first one.
5706 **	But, several interrupts may occur at the same time.
5707 **
5708 **	We probably should only try to deal with the normal
5709 **	case, but it seems that multiple interrupts occur in
5710 **	some cases that are not abnormal at all.
5711 **
5712 **	The most frequent interrupt condition is Phase Mismatch.
5713 **	We should want to service this interrupt quickly.
5714 **	A SCSI parity error may be delivered at the same time.
5715 **	The SIR interrupt is not very frequent in this driver,
5716 **	since the INTFLY is likely used for command completion
5717 **	signaling.
5718 **	The Selection Timeout interrupt may be triggered with
5719 **	IID and/or UDC.
5720 **	The SBMC interrupt (SCSI Bus Mode Change) may probably
5721 **	occur at any time.
5722 **
5723 **	This handler try to deal as cleverly as possible with all
5724 **	the above.
5725 **
5726 **============================================================
5727 */
5728 
5729 void ncr_exception (struct ncb *np)
5730 {
5731 	u_char	istat, dstat;
5732 	u16	sist;
5733 	int	i;
5734 
5735 	/*
5736 	**	interrupt on the fly ?
5737 	**	Since the global header may be copied back to a CCB
5738 	**	using a posted PCI memory write, the last operation on
5739 	**	the istat register is a READ in order to flush posted
5740 	**	PCI write commands.
5741 	*/
5742 	istat = INB (nc_istat);
5743 	if (istat & INTF) {
5744 		OUTB (nc_istat, (istat & SIGP) | INTF);
5745 		istat = INB (nc_istat);
5746 		if (DEBUG_FLAGS & DEBUG_TINY) printk ("F ");
5747 		ncr_wakeup_done (np);
5748 	}
5749 
5750 	if (!(istat & (SIP|DIP)))
5751 		return;
5752 
5753 	if (istat & CABRT)
5754 		OUTB (nc_istat, CABRT);
5755 
5756 	/*
5757 	**	Steinbach's Guideline for Systems Programming:
5758 	**	Never test for an error condition you don't know how to handle.
5759 	*/
5760 
5761 	sist  = (istat & SIP) ? INW (nc_sist)  : 0;
5762 	dstat = (istat & DIP) ? INB (nc_dstat) : 0;
5763 
5764 	if (DEBUG_FLAGS & DEBUG_TINY)
5765 		printk ("<%d|%x:%x|%x:%x>",
5766 			(int)INB(nc_scr0),
5767 			dstat,sist,
5768 			(unsigned)INL(nc_dsp),
5769 			(unsigned)INL(nc_dbc));
5770 
5771 	/*========================================================
5772 	**	First, interrupts we want to service cleanly.
5773 	**
5774 	**	Phase mismatch is the most frequent interrupt, and
5775 	**	so we have to service it as quickly and as cleanly
5776 	**	as possible.
5777 	**	Programmed interrupts are rarely used in this driver,
5778 	**	but we must handle them cleanly anyway.
5779 	**	We try to deal with PAR and SBMC combined with
5780 	**	some other interrupt(s).
5781 	**=========================================================
5782 	*/
5783 
5784 	if (!(sist  & (STO|GEN|HTH|SGE|UDC|RST)) &&
5785 	    !(dstat & (MDPE|BF|ABRT|IID))) {
5786 		if ((sist & SBMC) && ncr_int_sbmc (np))
5787 			return;
5788 		if ((sist & PAR)  && ncr_int_par  (np))
5789 			return;
5790 		if (sist & MA) {
5791 			ncr_int_ma (np);
5792 			return;
5793 		}
5794 		if (dstat & SIR) {
5795 			ncr_int_sir (np);
5796 			return;
5797 		}
5798 		/*
5799 		**  DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 2.
5800 		*/
5801 		if (!(sist & (SBMC|PAR)) && !(dstat & SSI)) {
5802 			printk(	"%s: unknown interrupt(s) ignored, "
5803 				"ISTAT=%x DSTAT=%x SIST=%x\n",
5804 				ncr_name(np), istat, dstat, sist);
5805 			return;
5806 		}
5807 		OUTONB_STD ();
5808 		return;
5809 	}
5810 
5811 	/*========================================================
5812 	**	Now, interrupts that need some fixing up.
5813 	**	Order and multiple interrupts is so less important.
5814 	**
5815 	**	If SRST has been asserted, we just reset the chip.
5816 	**
5817 	**	Selection is intirely handled by the chip. If the
5818 	**	chip says STO, we trust it. Seems some other
5819 	**	interrupts may occur at the same time (UDC, IID), so
5820 	**	we ignore them. In any case we do enough fix-up
5821 	**	in the service routine.
5822 	**	We just exclude some fatal dma errors.
5823 	**=========================================================
5824 	*/
5825 
5826 	if (sist & RST) {
5827 		ncr_init (np, 1, bootverbose ? "scsi reset" : NULL, HS_RESET);
5828 		return;
5829 	}
5830 
5831 	if ((sist & STO) &&
5832 		!(dstat & (MDPE|BF|ABRT))) {
5833 	/*
5834 	**	DEL 397 - 53C875 Rev 3 - Part Number 609-0392410 - ITEM 1.
5835 	*/
5836 		OUTONB (nc_ctest3, CLF);
5837 
5838 		ncr_int_sto (np);
5839 		return;
5840 	}
5841 
5842 	/*=========================================================
5843 	**	Now, interrupts we are not able to recover cleanly.
5844 	**	(At least for the moment).
5845 	**
5846 	**	Do the register dump.
5847 	**	Log message for real hard errors.
5848 	**	Clear all fifos.
5849 	**	For MDPE, BF, ABORT, IID, SGE and HTH we reset the
5850 	**	BUS and the chip.
5851 	**	We are more soft for UDC.
5852 	**=========================================================
5853 	*/
5854 
5855 	if (time_after(jiffies, np->regtime)) {
5856 		np->regtime = jiffies + 10*HZ;
5857 		for (i = 0; i<sizeof(np->regdump); i++)
5858 			((char*)&np->regdump)[i] = INB_OFF(i);
5859 		np->regdump.nc_dstat = dstat;
5860 		np->regdump.nc_sist  = sist;
5861 	}
5862 
5863 	ncr_log_hard_error(np, sist, dstat);
5864 
5865 	printk ("%s: have to clear fifos.\n", ncr_name (np));
5866 	OUTB (nc_stest3, TE|CSF);
5867 	OUTONB (nc_ctest3, CLF);
5868 
5869 	if ((sist & (SGE)) ||
5870 		(dstat & (MDPE|BF|ABRT|IID))) {
5871 		ncr_start_reset(np);
5872 		return;
5873 	}
5874 
5875 	if (sist & HTH) {
5876 		printk ("%s: handshake timeout\n", ncr_name(np));
5877 		ncr_start_reset(np);
5878 		return;
5879 	}
5880 
5881 	if (sist & UDC) {
5882 		printk ("%s: unexpected disconnect\n", ncr_name(np));
5883 		OUTB (HS_PRT, HS_UNEXPECTED);
5884 		OUTL_DSP (NCB_SCRIPT_PHYS (np, cleanup));
5885 		return;
5886 	}
5887 
5888 	/*=========================================================
5889 	**	We just miss the cause of the interrupt. :(
5890 	**	Print a message. The timeout will do the real work.
5891 	**=========================================================
5892 	*/
5893 	printk ("%s: unknown interrupt\n", ncr_name(np));
5894 }
5895 
5896 /*==========================================================
5897 **
5898 **	ncr chip exception handler for selection timeout
5899 **
5900 **==========================================================
5901 **
5902 **	There seems to be a bug in the 53c810.
5903 **	Although a STO-Interrupt is pending,
5904 **	it continues executing script commands.
5905 **	But it will fail and interrupt (IID) on
5906 **	the next instruction where it's looking
5907 **	for a valid phase.
5908 **
5909 **----------------------------------------------------------
5910 */
5911 
5912 void ncr_int_sto (struct ncb *np)
5913 {
5914 	u_long dsa;
5915 	struct ccb *cp;
5916 	if (DEBUG_FLAGS & DEBUG_TINY) printk ("T");
5917 
5918 	/*
5919 	**	look for ccb and set the status.
5920 	*/
5921 
5922 	dsa = INL (nc_dsa);
5923 	cp = np->ccb;
5924 	while (cp && (CCB_PHYS (cp, phys) != dsa))
5925 		cp = cp->link_ccb;
5926 
5927 	if (cp) {
5928 		cp-> host_status = HS_SEL_TIMEOUT;
5929 		ncr_complete (np, cp);
5930 	}
5931 
5932 	/*
5933 	**	repair start queue and jump to start point.
5934 	*/
5935 
5936 	OUTL_DSP (NCB_SCRIPTH_PHYS (np, sto_restart));
5937 	return;
5938 }
5939 
5940 /*==========================================================
5941 **
5942 **	ncr chip exception handler for SCSI bus mode change
5943 **
5944 **==========================================================
5945 **
5946 **	spi2-r12 11.2.3 says a transceiver mode change must
5947 **	generate a reset event and a device that detects a reset
5948 **	event shall initiate a hard reset. It says also that a
5949 **	device that detects a mode change shall set data transfer
5950 **	mode to eight bit asynchronous, etc...
5951 **	So, just resetting should be enough.
5952 **
5953 **
5954 **----------------------------------------------------------
5955 */
5956 
5957 static int ncr_int_sbmc (struct ncb *np)
5958 {
5959 	u_char scsi_mode = INB (nc_stest4) & SMODE;
5960 
5961 	if (scsi_mode != np->scsi_mode) {
5962 		printk("%s: SCSI bus mode change from %x to %x.\n",
5963 			ncr_name(np), np->scsi_mode, scsi_mode);
5964 
5965 		np->scsi_mode = scsi_mode;
5966 
5967 
5968 		/*
5969 		**	Suspend command processing for 1 second and
5970 		**	reinitialize all except the chip.
5971 		*/
5972 		np->settle_time	= jiffies + HZ;
5973 		ncr_init (np, 0, bootverbose ? "scsi mode change" : NULL, HS_RESET);
5974 		return 1;
5975 	}
5976 	return 0;
5977 }
5978 
5979 /*==========================================================
5980 **
5981 **	ncr chip exception handler for SCSI parity error.
5982 **
5983 **==========================================================
5984 **
5985 **
5986 **----------------------------------------------------------
5987 */
5988 
5989 static int ncr_int_par (struct ncb *np)
5990 {
5991 	u_char	hsts	= INB (HS_PRT);
5992 	u32	dbc	= INL (nc_dbc);
5993 	u_char	sstat1	= INB (nc_sstat1);
5994 	int phase	= -1;
5995 	int msg		= -1;
5996 	u32 jmp;
5997 
5998 	printk("%s: SCSI parity error detected: SCR1=%d DBC=%x SSTAT1=%x\n",
5999 		ncr_name(np), hsts, dbc, sstat1);
6000 
6001 	/*
6002 	 *	Ignore the interrupt if the NCR is not connected
6003 	 *	to the SCSI bus, since the right work should have
6004 	 *	been done on unexpected disconnection handling.
6005 	 */
6006 	if (!(INB (nc_scntl1) & ISCON))
6007 		return 0;
6008 
6009 	/*
6010 	 *	If the nexus is not clearly identified, reset the bus.
6011 	 *	We will try to do better later.
6012 	 */
6013 	if (hsts & HS_INVALMASK)
6014 		goto reset_all;
6015 
6016 	/*
6017 	 *	If the SCSI parity error occurs in MSG IN phase, prepare a
6018 	 *	MSG PARITY message. Otherwise, prepare a INITIATOR DETECTED
6019 	 *	ERROR message and let the device decide to retry the command
6020 	 *	or to terminate with check condition. If we were in MSG IN
6021 	 *	phase waiting for the response of a negotiation, we will
6022 	 *	get SIR_NEGO_FAILED at dispatch.
6023 	 */
6024 	if (!(dbc & 0xc0000000))
6025 		phase = (dbc >> 24) & 7;
6026 	if (phase == 7)
6027 		msg = MSG_PARITY_ERROR;
6028 	else
6029 		msg = INITIATOR_ERROR;
6030 
6031 
6032 	/*
6033 	 *	If the NCR stopped on a MOVE ^ DATA_IN, we jump to a
6034 	 *	script that will ignore all data in bytes until phase
6035 	 *	change, since we are not sure the chip will wait the phase
6036 	 *	change prior to delivering the interrupt.
6037 	 */
6038 	if (phase == 1)
6039 		jmp = NCB_SCRIPTH_PHYS (np, par_err_data_in);
6040 	else
6041 		jmp = NCB_SCRIPTH_PHYS (np, par_err_other);
6042 
6043 	OUTONB (nc_ctest3, CLF );	/* clear dma fifo  */
6044 	OUTB (nc_stest3, TE|CSF);	/* clear scsi fifo */
6045 
6046 	np->msgout[0] = msg;
6047 	OUTL_DSP (jmp);
6048 	return 1;
6049 
6050 reset_all:
6051 	ncr_start_reset(np);
6052 	return 1;
6053 }
6054 
6055 /*==========================================================
6056 **
6057 **
6058 **	ncr chip exception handler for phase errors.
6059 **
6060 **
6061 **==========================================================
6062 **
6063 **	We have to construct a new transfer descriptor,
6064 **	to transfer the rest of the current block.
6065 **
6066 **----------------------------------------------------------
6067 */
6068 
6069 static void ncr_int_ma (struct ncb *np)
6070 {
6071 	u32	dbc;
6072 	u32	rest;
6073 	u32	dsp;
6074 	u32	dsa;
6075 	u32	nxtdsp;
6076 	u32	newtmp;
6077 	u32	*vdsp;
6078 	u32	oadr, olen;
6079 	u32	*tblp;
6080 	ncrcmd *newcmd;
6081 	u_char	cmd, sbcl;
6082 	struct ccb *cp;
6083 
6084 	dsp	= INL (nc_dsp);
6085 	dbc	= INL (nc_dbc);
6086 	sbcl	= INB (nc_sbcl);
6087 
6088 	cmd	= dbc >> 24;
6089 	rest	= dbc & 0xffffff;
6090 
6091 	/*
6092 	**	Take into account dma fifo and various buffers and latches,
6093 	**	only if the interrupted phase is an OUTPUT phase.
6094 	*/
6095 
6096 	if ((cmd & 1) == 0) {
6097 		u_char	ctest5, ss0, ss2;
6098 		u16	delta;
6099 
6100 		ctest5 = (np->rv_ctest5 & DFS) ? INB (nc_ctest5) : 0;
6101 		if (ctest5 & DFS)
6102 			delta=(((ctest5 << 8) | (INB (nc_dfifo) & 0xff)) - rest) & 0x3ff;
6103 		else
6104 			delta=(INB (nc_dfifo) - rest) & 0x7f;
6105 
6106 		/*
6107 		**	The data in the dma fifo has not been transferred to
6108 		**	the target -> add the amount to the rest
6109 		**	and clear the data.
6110 		**	Check the sstat2 register in case of wide transfer.
6111 		*/
6112 
6113 		rest += delta;
6114 		ss0  = INB (nc_sstat0);
6115 		if (ss0 & OLF) rest++;
6116 		if (ss0 & ORF) rest++;
6117 		if (INB(nc_scntl3) & EWS) {
6118 			ss2 = INB (nc_sstat2);
6119 			if (ss2 & OLF1) rest++;
6120 			if (ss2 & ORF1) rest++;
6121 		}
6122 
6123 		if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6124 			printk ("P%x%x RL=%d D=%d SS0=%x ", cmd&7, sbcl&7,
6125 				(unsigned) rest, (unsigned) delta, ss0);
6126 
6127 	} else	{
6128 		if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
6129 			printk ("P%x%x RL=%d ", cmd&7, sbcl&7, rest);
6130 	}
6131 
6132 	/*
6133 	**	Clear fifos.
6134 	*/
6135 	OUTONB (nc_ctest3, CLF );	/* clear dma fifo  */
6136 	OUTB (nc_stest3, TE|CSF);	/* clear scsi fifo */
6137 
6138 	/*
6139 	**	locate matching cp.
6140 	**	if the interrupted phase is DATA IN or DATA OUT,
6141 	**	trust the global header.
6142 	*/
6143 	dsa = INL (nc_dsa);
6144 	if (!(cmd & 6)) {
6145 		cp = np->header.cp;
6146 		if (CCB_PHYS(cp, phys) != dsa)
6147 			cp = NULL;
6148 	} else {
6149 		cp  = np->ccb;
6150 		while (cp && (CCB_PHYS (cp, phys) != dsa))
6151 			cp = cp->link_ccb;
6152 	}
6153 
6154 	/*
6155 	**	try to find the interrupted script command,
6156 	**	and the address at which to continue.
6157 	*/
6158 	vdsp	= NULL;
6159 	nxtdsp	= 0;
6160 	if	(dsp >  np->p_script &&
6161 		 dsp <= np->p_script + sizeof(struct script)) {
6162 		vdsp = (u32 *)((char*)np->script0 + (dsp-np->p_script-8));
6163 		nxtdsp = dsp;
6164 	}
6165 	else if	(dsp >  np->p_scripth &&
6166 		 dsp <= np->p_scripth + sizeof(struct scripth)) {
6167 		vdsp = (u32 *)((char*)np->scripth0 + (dsp-np->p_scripth-8));
6168 		nxtdsp = dsp;
6169 	}
6170 	else if (cp) {
6171 		if	(dsp == CCB_PHYS (cp, patch[2])) {
6172 			vdsp = &cp->patch[0];
6173 			nxtdsp = scr_to_cpu(vdsp[3]);
6174 		}
6175 		else if (dsp == CCB_PHYS (cp, patch[6])) {
6176 			vdsp = &cp->patch[4];
6177 			nxtdsp = scr_to_cpu(vdsp[3]);
6178 		}
6179 	}
6180 
6181 	/*
6182 	**	log the information
6183 	*/
6184 
6185 	if (DEBUG_FLAGS & DEBUG_PHASE) {
6186 		printk ("\nCP=%p CP2=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
6187 			cp, np->header.cp,
6188 			(unsigned)dsp,
6189 			(unsigned)nxtdsp, vdsp, cmd);
6190 	}
6191 
6192 	/*
6193 	**	cp=0 means that the DSA does not point to a valid control
6194 	**	block. This should not happen since we donnot use multi-byte
6195 	**	move while we are being reselected ot after command complete.
6196 	**	We are not able to recover from such a phase error.
6197 	*/
6198 	if (!cp) {
6199 		printk ("%s: SCSI phase error fixup: "
6200 			"CCB already dequeued (0x%08lx)\n",
6201 			ncr_name (np), (u_long) np->header.cp);
6202 		goto reset_all;
6203 	}
6204 
6205 	/*
6206 	**	get old startaddress and old length.
6207 	*/
6208 
6209 	oadr = scr_to_cpu(vdsp[1]);
6210 
6211 	if (cmd & 0x10) {	/* Table indirect */
6212 		tblp = (u32 *) ((char*) &cp->phys + oadr);
6213 		olen = scr_to_cpu(tblp[0]);
6214 		oadr = scr_to_cpu(tblp[1]);
6215 	} else {
6216 		tblp = (u32 *) 0;
6217 		olen = scr_to_cpu(vdsp[0]) & 0xffffff;
6218 	}
6219 
6220 	if (DEBUG_FLAGS & DEBUG_PHASE) {
6221 		printk ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
6222 			(unsigned) (scr_to_cpu(vdsp[0]) >> 24),
6223 			tblp,
6224 			(unsigned) olen,
6225 			(unsigned) oadr);
6226 	}
6227 
6228 	/*
6229 	**	check cmd against assumed interrupted script command.
6230 	*/
6231 
6232 	if (cmd != (scr_to_cpu(vdsp[0]) >> 24)) {
6233 		PRINT_ADDR(cp->cmd, "internal error: cmd=%02x != %02x=(vdsp[0] "
6234 				">> 24)\n", cmd, scr_to_cpu(vdsp[0]) >> 24);
6235 
6236 		goto reset_all;
6237 	}
6238 
6239 	/*
6240 	**	cp != np->header.cp means that the header of the CCB
6241 	**	currently being processed has not yet been copied to
6242 	**	the global header area. That may happen if the device did
6243 	**	not accept all our messages after having been selected.
6244 	*/
6245 	if (cp != np->header.cp) {
6246 		printk ("%s: SCSI phase error fixup: "
6247 			"CCB address mismatch (0x%08lx != 0x%08lx)\n",
6248 			ncr_name (np), (u_long) cp, (u_long) np->header.cp);
6249 	}
6250 
6251 	/*
6252 	**	if old phase not dataphase, leave here.
6253 	*/
6254 
6255 	if (cmd & 0x06) {
6256 		PRINT_ADDR(cp->cmd, "phase change %x-%x %d@%08x resid=%d.\n",
6257 			cmd&7, sbcl&7, (unsigned)olen,
6258 			(unsigned)oadr, (unsigned)rest);
6259 		goto unexpected_phase;
6260 	}
6261 
6262 	/*
6263 	**	choose the correct patch area.
6264 	**	if savep points to one, choose the other.
6265 	*/
6266 
6267 	newcmd = cp->patch;
6268 	newtmp = CCB_PHYS (cp, patch);
6269 	if (newtmp == scr_to_cpu(cp->phys.header.savep)) {
6270 		newcmd = &cp->patch[4];
6271 		newtmp = CCB_PHYS (cp, patch[4]);
6272 	}
6273 
6274 	/*
6275 	**	fillin the commands
6276 	*/
6277 
6278 	newcmd[0] = cpu_to_scr(((cmd & 0x0f) << 24) | rest);
6279 	newcmd[1] = cpu_to_scr(oadr + olen - rest);
6280 	newcmd[2] = cpu_to_scr(SCR_JUMP);
6281 	newcmd[3] = cpu_to_scr(nxtdsp);
6282 
6283 	if (DEBUG_FLAGS & DEBUG_PHASE) {
6284 		PRINT_ADDR(cp->cmd, "newcmd[%d] %x %x %x %x.\n",
6285 			(int) (newcmd - cp->patch),
6286 			(unsigned)scr_to_cpu(newcmd[0]),
6287 			(unsigned)scr_to_cpu(newcmd[1]),
6288 			(unsigned)scr_to_cpu(newcmd[2]),
6289 			(unsigned)scr_to_cpu(newcmd[3]));
6290 	}
6291 	/*
6292 	**	fake the return address (to the patch).
6293 	**	and restart script processor at dispatcher.
6294 	*/
6295 	OUTL (nc_temp, newtmp);
6296 	OUTL_DSP (NCB_SCRIPT_PHYS (np, dispatch));
6297 	return;
6298 
6299 	/*
6300 	**	Unexpected phase changes that occurs when the current phase
6301 	**	is not a DATA IN or DATA OUT phase are due to error conditions.
6302 	**	Such event may only happen when the SCRIPTS is using a
6303 	**	multibyte SCSI MOVE.
6304 	**
6305 	**	Phase change		Some possible cause
6306 	**
6307 	**	COMMAND  --> MSG IN	SCSI parity error detected by target.
6308 	**	COMMAND  --> STATUS	Bad command or refused by target.
6309 	**	MSG OUT  --> MSG IN     Message rejected by target.
6310 	**	MSG OUT  --> COMMAND    Bogus target that discards extended
6311 	**				negotiation messages.
6312 	**
6313 	**	The code below does not care of the new phase and so
6314 	**	trusts the target. Why to annoy it ?
6315 	**	If the interrupted phase is COMMAND phase, we restart at
6316 	**	dispatcher.
6317 	**	If a target does not get all the messages after selection,
6318 	**	the code assumes blindly that the target discards extended
6319 	**	messages and clears the negotiation status.
6320 	**	If the target does not want all our response to negotiation,
6321 	**	we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids
6322 	**	bloat for such a should_not_happen situation).
6323 	**	In all other situation, we reset the BUS.
6324 	**	Are these assumptions reasonable ? (Wait and see ...)
6325 	*/
6326 unexpected_phase:
6327 	dsp -= 8;
6328 	nxtdsp = 0;
6329 
6330 	switch (cmd & 7) {
6331 	case 2:	/* COMMAND phase */
6332 		nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6333 		break;
6334 #if 0
6335 	case 3:	/* STATUS  phase */
6336 		nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
6337 		break;
6338 #endif
6339 	case 6:	/* MSG OUT phase */
6340 		np->scripth->nxtdsp_go_on[0] = cpu_to_scr(dsp + 8);
6341 		if	(dsp == NCB_SCRIPT_PHYS (np, send_ident)) {
6342 			cp->host_status = HS_BUSY;
6343 			nxtdsp = NCB_SCRIPTH_PHYS (np, clratn_go_on);
6344 		}
6345 		else if	(dsp == NCB_SCRIPTH_PHYS (np, send_wdtr) ||
6346 			 dsp == NCB_SCRIPTH_PHYS (np, send_sdtr)) {
6347 			nxtdsp = NCB_SCRIPTH_PHYS (np, nego_bad_phase);
6348 		}
6349 		break;
6350 #if 0
6351 	case 7:	/* MSG IN  phase */
6352 		nxtdsp = NCB_SCRIPT_PHYS (np, clrack);
6353 		break;
6354 #endif
6355 	}
6356 
6357 	if (nxtdsp) {
6358 		OUTL_DSP (nxtdsp);
6359 		return;
6360 	}
6361 
6362 reset_all:
6363 	ncr_start_reset(np);
6364 }
6365 
6366 
6367 static void ncr_sir_to_redo(struct ncb *np, int num, struct ccb *cp)
6368 {
6369 	struct scsi_cmnd *cmd	= cp->cmd;
6370 	struct tcb *tp	= &np->target[cmd->device->id];
6371 	struct lcb *lp	= tp->lp[cmd->device->lun];
6372 	struct list_head *qp;
6373 	struct ccb *	cp2;
6374 	int		disc_cnt = 0;
6375 	int		busy_cnt = 0;
6376 	u32		startp;
6377 	u_char		s_status = INB (SS_PRT);
6378 
6379 	/*
6380 	**	Let the SCRIPTS processor skip all not yet started CCBs,
6381 	**	and count disconnected CCBs. Since the busy queue is in
6382 	**	the same order as the chip start queue, disconnected CCBs
6383 	**	are before cp and busy ones after.
6384 	*/
6385 	if (lp) {
6386 		qp = lp->busy_ccbq.prev;
6387 		while (qp != &lp->busy_ccbq) {
6388 			cp2 = list_entry(qp, struct ccb, link_ccbq);
6389 			qp  = qp->prev;
6390 			++busy_cnt;
6391 			if (cp2 == cp)
6392 				break;
6393 			cp2->start.schedule.l_paddr =
6394 			cpu_to_scr(NCB_SCRIPTH_PHYS (np, skip));
6395 		}
6396 		lp->held_ccb = cp;	/* Requeue when this one completes */
6397 		disc_cnt = lp->queuedccbs - busy_cnt;
6398 	}
6399 
6400 	switch(s_status) {
6401 	default:	/* Just for safety, should never happen */
6402 	case SAM_STAT_TASK_SET_FULL:
6403 		/*
6404 		**	Decrease number of tags to the number of
6405 		**	disconnected commands.
6406 		*/
6407 		if (!lp)
6408 			goto out;
6409 		if (bootverbose >= 1) {
6410 			PRINT_ADDR(cmd, "QUEUE FULL! %d busy, %d disconnected "
6411 					"CCBs\n", busy_cnt, disc_cnt);
6412 		}
6413 		if (disc_cnt < lp->numtags) {
6414 			lp->numtags	= disc_cnt > 2 ? disc_cnt : 2;
6415 			lp->num_good	= 0;
6416 			ncr_setup_tags (np, cmd->device);
6417 		}
6418 		/*
6419 		**	Requeue the command to the start queue.
6420 		**	If any disconnected commands,
6421 		**		Clear SIGP.
6422 		**		Jump to reselect.
6423 		*/
6424 		cp->phys.header.savep = cp->startp;
6425 		cp->host_status = HS_BUSY;
6426 		cp->scsi_status = SAM_STAT_ILLEGAL;
6427 
6428 		ncr_put_start_queue(np, cp);
6429 		if (disc_cnt)
6430 			INB (nc_ctest2);		/* Clear SIGP */
6431 		OUTL_DSP (NCB_SCRIPT_PHYS (np, reselect));
6432 		return;
6433 	case SAM_STAT_COMMAND_TERMINATED:
6434 	case SAM_STAT_CHECK_CONDITION:
6435 		/*
6436 		**	If we were requesting sense, give up.
6437 		*/
6438 		if (cp->auto_sense)
6439 			goto out;
6440 
6441 		/*
6442 		**	Device returned CHECK CONDITION status.
6443 		**	Prepare all needed data strutures for getting
6444 		**	sense data.
6445 		**
6446 		**	identify message
6447 		*/
6448 		cp->scsi_smsg2[0]	= IDENTIFY(0, cmd->device->lun);
6449 		cp->phys.smsg.addr	= cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
6450 		cp->phys.smsg.size	= cpu_to_scr(1);
6451 
6452 		/*
6453 		**	sense command
6454 		*/
6455 		cp->phys.cmd.addr	= cpu_to_scr(CCB_PHYS (cp, sensecmd));
6456 		cp->phys.cmd.size	= cpu_to_scr(6);
6457 
6458 		/*
6459 		**	patch requested size into sense command
6460 		*/
6461 		cp->sensecmd[0]		= 0x03;
6462 		cp->sensecmd[1]		= (cmd->device->lun & 0x7) << 5;
6463 		cp->sensecmd[4]		= sizeof(cp->sense_buf);
6464 
6465 		/*
6466 		**	sense data
6467 		*/
6468 		memset(cp->sense_buf, 0, sizeof(cp->sense_buf));
6469 		cp->phys.sense.addr	= cpu_to_scr(CCB_PHYS(cp,sense_buf[0]));
6470 		cp->phys.sense.size	= cpu_to_scr(sizeof(cp->sense_buf));
6471 
6472 		/*
6473 		**	requeue the command.
6474 		*/
6475 		startp = cpu_to_scr(NCB_SCRIPTH_PHYS (np, sdata_in));
6476 
6477 		cp->phys.header.savep	= startp;
6478 		cp->phys.header.goalp	= startp + 24;
6479 		cp->phys.header.lastp	= startp;
6480 		cp->phys.header.wgoalp	= startp + 24;
6481 		cp->phys.header.wlastp	= startp;
6482 
6483 		cp->host_status = HS_BUSY;
6484 		cp->scsi_status = SAM_STAT_ILLEGAL;
6485 		cp->auto_sense	= s_status;
6486 
6487 		cp->start.schedule.l_paddr =
6488 			cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
6489 
6490 		/*
6491 		**	Select without ATN for quirky devices.
6492 		*/
6493 		if (cmd->device->select_no_atn)
6494 			cp->start.schedule.l_paddr =
6495 			cpu_to_scr(NCB_SCRIPTH_PHYS (np, select_no_atn));
6496 
6497 		ncr_put_start_queue(np, cp);
6498 
6499 		OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
6500 		return;
6501 	}
6502 
6503 out:
6504 	OUTONB_STD ();
6505 	return;
6506 }
6507 
6508 
6509 /*==========================================================
6510 **
6511 **
6512 **      ncr chip exception handler for programmed interrupts.
6513 **
6514 **
6515 **==========================================================
6516 */
6517 
6518 void ncr_int_sir (struct ncb *np)
6519 {
6520 	u_char scntl3;
6521 	u_char chg, ofs, per, fak, wide;
6522 	u_char num = INB (nc_dsps);
6523 	struct ccb *cp=NULL;
6524 	u_long	dsa    = INL (nc_dsa);
6525 	u_char	target = INB (nc_sdid) & 0x0f;
6526 	struct tcb *tp     = &np->target[target];
6527 	struct scsi_target *starget = tp->starget;
6528 
6529 	if (DEBUG_FLAGS & DEBUG_TINY) printk ("I#%d", num);
6530 
6531 	switch (num) {
6532 	case SIR_INTFLY:
6533 		/*
6534 		**	This is used for HP Zalon/53c720 where INTFLY
6535 		**	operation is currently broken.
6536 		*/
6537 		ncr_wakeup_done(np);
6538 #ifdef SCSI_NCR_CCB_DONE_SUPPORT
6539 		OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, done_end) + 8);
6540 #else
6541 		OUTL(nc_dsp, NCB_SCRIPT_PHYS (np, start));
6542 #endif
6543 		return;
6544 	case SIR_RESEL_NO_MSG_IN:
6545 	case SIR_RESEL_NO_IDENTIFY:
6546 		/*
6547 		**	If devices reselecting without sending an IDENTIFY
6548 		**	message still exist, this should help.
6549 		**	We just assume lun=0, 1 CCB, no tag.
6550 		*/
6551 		if (tp->lp[0]) {
6552 			OUTL_DSP (scr_to_cpu(tp->lp[0]->jump_ccb[0]));
6553 			return;
6554 		}
6555 		fallthrough;
6556 	case SIR_RESEL_BAD_TARGET:	/* Will send a TARGET RESET message */
6557 	case SIR_RESEL_BAD_LUN:		/* Will send a TARGET RESET message */
6558 	case SIR_RESEL_BAD_I_T_L_Q:	/* Will send an ABORT TAG message   */
6559 	case SIR_RESEL_BAD_I_T_L:	/* Will send an ABORT message	    */
6560 		printk ("%s:%d: SIR %d, "
6561 			"incorrect nexus identification on reselection\n",
6562 			ncr_name (np), target, num);
6563 		goto out;
6564 	case SIR_DONE_OVERFLOW:
6565 		printk ("%s:%d: SIR %d, "
6566 			"CCB done queue overflow\n",
6567 			ncr_name (np), target, num);
6568 		goto out;
6569 	case SIR_BAD_STATUS:
6570 		cp = np->header.cp;
6571 		if (!cp || CCB_PHYS (cp, phys) != dsa)
6572 			goto out;
6573 		ncr_sir_to_redo(np, num, cp);
6574 		return;
6575 	default:
6576 		/*
6577 		**	lookup the ccb
6578 		*/
6579 		cp = np->ccb;
6580 		while (cp && (CCB_PHYS (cp, phys) != dsa))
6581 			cp = cp->link_ccb;
6582 
6583 		BUG_ON(!cp);
6584 		BUG_ON(cp != np->header.cp);
6585 
6586 		if (!cp || cp != np->header.cp)
6587 			goto out;
6588 	}
6589 
6590 	switch (num) {
6591 /*-----------------------------------------------------------------------------
6592 **
6593 **	Was Sie schon immer ueber transfermode negotiation wissen wollten ...
6594 **	("Everything you've always wanted to know about transfer mode
6595 **	  negotiation")
6596 **
6597 **	We try to negotiate sync and wide transfer only after
6598 **	a successful inquire command. We look at byte 7 of the
6599 **	inquire data to determine the capabilities of the target.
6600 **
6601 **	When we try to negotiate, we append the negotiation message
6602 **	to the identify and (maybe) simple tag message.
6603 **	The host status field is set to HS_NEGOTIATE to mark this
6604 **	situation.
6605 **
6606 **	If the target doesn't answer this message immediately
6607 **	(as required by the standard), the SIR_NEGO_FAIL interrupt
6608 **	will be raised eventually.
6609 **	The handler removes the HS_NEGOTIATE status, and sets the
6610 **	negotiated value to the default (async / nowide).
6611 **
6612 **	If we receive a matching answer immediately, we check it
6613 **	for validity, and set the values.
6614 **
6615 **	If we receive a Reject message immediately, we assume the
6616 **	negotiation has failed, and fall back to standard values.
6617 **
6618 **	If we receive a negotiation message while not in HS_NEGOTIATE
6619 **	state, it's a target initiated negotiation. We prepare a
6620 **	(hopefully) valid answer, set our parameters, and send back
6621 **	this answer to the target.
6622 **
6623 **	If the target doesn't fetch the answer (no message out phase),
6624 **	we assume the negotiation has failed, and fall back to default
6625 **	settings.
6626 **
6627 **	When we set the values, we adjust them in all ccbs belonging
6628 **	to this target, in the controller's register, and in the "phys"
6629 **	field of the controller's struct ncb.
6630 **
6631 **	Possible cases:		   hs  sir   msg_in value  send   goto
6632 **	We try to negotiate:
6633 **	-> target doesn't msgin    NEG FAIL  noop   defa.  -      dispatch
6634 **	-> target rejected our msg NEG FAIL  reject defa.  -      dispatch
6635 **	-> target answered  (ok)   NEG SYNC  sdtr   set    -      clrack
6636 **	-> target answered (!ok)   NEG SYNC  sdtr   defa.  REJ--->msg_bad
6637 **	-> target answered  (ok)   NEG WIDE  wdtr   set    -      clrack
6638 **	-> target answered (!ok)   NEG WIDE  wdtr   defa.  REJ--->msg_bad
6639 **	-> any other msgin	   NEG FAIL  noop   defa.  -      dispatch
6640 **
6641 **	Target tries to negotiate:
6642 **	-> incoming message	   --- SYNC  sdtr   set    SDTR   -
6643 **	-> incoming message	   --- WIDE  wdtr   set    WDTR   -
6644 **      We sent our answer:
6645 **	-> target doesn't msgout   --- PROTO ?      defa.  -      dispatch
6646 **
6647 **-----------------------------------------------------------------------------
6648 */
6649 
6650 	case SIR_NEGO_FAILED:
6651 		/*-------------------------------------------------------
6652 		**
6653 		**	Negotiation failed.
6654 		**	Target doesn't send an answer message,
6655 		**	or target rejected our message.
6656 		**
6657 		**      Remove negotiation request.
6658 		**
6659 		**-------------------------------------------------------
6660 		*/
6661 		OUTB (HS_PRT, HS_BUSY);
6662 
6663 		fallthrough;
6664 
6665 	case SIR_NEGO_PROTO:
6666 		/*-------------------------------------------------------
6667 		**
6668 		**	Negotiation failed.
6669 		**	Target doesn't fetch the answer message.
6670 		**
6671 		**-------------------------------------------------------
6672 		*/
6673 
6674 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6675 			PRINT_ADDR(cp->cmd, "negotiation failed sir=%x "
6676 					"status=%x.\n", num, cp->nego_status);
6677 		}
6678 
6679 		/*
6680 		**	any error in negotiation:
6681 		**	fall back to default mode.
6682 		*/
6683 		switch (cp->nego_status) {
6684 
6685 		case NS_SYNC:
6686 			spi_period(starget) = 0;
6687 			spi_offset(starget) = 0;
6688 			ncr_setsync (np, cp, 0, 0xe0);
6689 			break;
6690 
6691 		case NS_WIDE:
6692 			spi_width(starget) = 0;
6693 			ncr_setwide (np, cp, 0, 0);
6694 			break;
6695 
6696 		}
6697 		np->msgin [0] = NOP;
6698 		np->msgout[0] = NOP;
6699 		cp->nego_status = 0;
6700 		break;
6701 
6702 	case SIR_NEGO_SYNC:
6703 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6704 			ncr_print_msg(cp, "sync msgin", np->msgin);
6705 		}
6706 
6707 		chg = 0;
6708 		per = np->msgin[3];
6709 		ofs = np->msgin[4];
6710 		if (ofs==0) per=255;
6711 
6712 		/*
6713 		**      if target sends SDTR message,
6714 		**	      it CAN transfer synch.
6715 		*/
6716 
6717 		if (ofs && starget)
6718 			spi_support_sync(starget) = 1;
6719 
6720 		/*
6721 		**	check values against driver limits.
6722 		*/
6723 
6724 		if (per < np->minsync)
6725 			{chg = 1; per = np->minsync;}
6726 		if (per < tp->minsync)
6727 			{chg = 1; per = tp->minsync;}
6728 		if (ofs > tp->maxoffs)
6729 			{chg = 1; ofs = tp->maxoffs;}
6730 
6731 		/*
6732 		**	Check against controller limits.
6733 		*/
6734 		fak	= 7;
6735 		scntl3	= 0;
6736 		if (ofs != 0) {
6737 			ncr_getsync(np, per, &fak, &scntl3);
6738 			if (fak > 7) {
6739 				chg = 1;
6740 				ofs = 0;
6741 			}
6742 		}
6743 		if (ofs == 0) {
6744 			fak	= 7;
6745 			per	= 0;
6746 			scntl3	= 0;
6747 			tp->minsync = 0;
6748 		}
6749 
6750 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6751 			PRINT_ADDR(cp->cmd, "sync: per=%d scntl3=0x%x ofs=%d "
6752 				"fak=%d chg=%d.\n", per, scntl3, ofs, fak, chg);
6753 		}
6754 
6755 		if (INB (HS_PRT) == HS_NEGOTIATE) {
6756 			OUTB (HS_PRT, HS_BUSY);
6757 			switch (cp->nego_status) {
6758 
6759 			case NS_SYNC:
6760 				/* This was an answer message */
6761 				if (chg) {
6762 					/* Answer wasn't acceptable.  */
6763 					spi_period(starget) = 0;
6764 					spi_offset(starget) = 0;
6765 					ncr_setsync(np, cp, 0, 0xe0);
6766 					OUTL_DSP(NCB_SCRIPT_PHYS (np, msg_bad));
6767 				} else {
6768 					/* Answer is ok.  */
6769 					spi_period(starget) = per;
6770 					spi_offset(starget) = ofs;
6771 					ncr_setsync(np, cp, scntl3, (fak<<5)|ofs);
6772 					OUTL_DSP(NCB_SCRIPT_PHYS (np, clrack));
6773 				}
6774 				return;
6775 
6776 			case NS_WIDE:
6777 				spi_width(starget) = 0;
6778 				ncr_setwide(np, cp, 0, 0);
6779 				break;
6780 			}
6781 		}
6782 
6783 		/*
6784 		**	It was a request. Set value and
6785 		**      prepare an answer message
6786 		*/
6787 
6788 		spi_period(starget) = per;
6789 		spi_offset(starget) = ofs;
6790 		ncr_setsync(np, cp, scntl3, (fak<<5)|ofs);
6791 
6792 		spi_populate_sync_msg(np->msgout, per, ofs);
6793 		cp->nego_status = NS_SYNC;
6794 
6795 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6796 			ncr_print_msg(cp, "sync msgout", np->msgout);
6797 		}
6798 
6799 		if (!ofs) {
6800 			OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
6801 			return;
6802 		}
6803 		np->msgin [0] = NOP;
6804 
6805 		break;
6806 
6807 	case SIR_NEGO_WIDE:
6808 		/*
6809 		**	Wide request message received.
6810 		*/
6811 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6812 			ncr_print_msg(cp, "wide msgin", np->msgin);
6813 		}
6814 
6815 		/*
6816 		**	get requested values.
6817 		*/
6818 
6819 		chg  = 0;
6820 		wide = np->msgin[3];
6821 
6822 		/*
6823 		**      if target sends WDTR message,
6824 		**	      it CAN transfer wide.
6825 		*/
6826 
6827 		if (wide && starget)
6828 			spi_support_wide(starget) = 1;
6829 
6830 		/*
6831 		**	check values against driver limits.
6832 		*/
6833 
6834 		if (wide > tp->usrwide)
6835 			{chg = 1; wide = tp->usrwide;}
6836 
6837 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6838 			PRINT_ADDR(cp->cmd, "wide: wide=%d chg=%d.\n", wide,
6839 					chg);
6840 		}
6841 
6842 		if (INB (HS_PRT) == HS_NEGOTIATE) {
6843 			OUTB (HS_PRT, HS_BUSY);
6844 			switch (cp->nego_status) {
6845 
6846 			case NS_WIDE:
6847 				/*
6848 				**      This was an answer message
6849 				*/
6850 				if (chg) {
6851 					/* Answer wasn't acceptable.  */
6852 					spi_width(starget) = 0;
6853 					ncr_setwide(np, cp, 0, 1);
6854 					OUTL_DSP (NCB_SCRIPT_PHYS (np, msg_bad));
6855 				} else {
6856 					/* Answer is ok.  */
6857 					spi_width(starget) = wide;
6858 					ncr_setwide(np, cp, wide, 1);
6859 					OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
6860 				}
6861 				return;
6862 
6863 			case NS_SYNC:
6864 				spi_period(starget) = 0;
6865 				spi_offset(starget) = 0;
6866 				ncr_setsync(np, cp, 0, 0xe0);
6867 				break;
6868 			}
6869 		}
6870 
6871 		/*
6872 		**	It was a request, set value and
6873 		**      prepare an answer message
6874 		*/
6875 
6876 		spi_width(starget) = wide;
6877 		ncr_setwide(np, cp, wide, 1);
6878 		spi_populate_width_msg(np->msgout, wide);
6879 
6880 		np->msgin [0] = NOP;
6881 
6882 		cp->nego_status = NS_WIDE;
6883 
6884 		if (DEBUG_FLAGS & DEBUG_NEGO) {
6885 			ncr_print_msg(cp, "wide msgout", np->msgin);
6886 		}
6887 		break;
6888 
6889 /*--------------------------------------------------------------------
6890 **
6891 **	Processing of special messages
6892 **
6893 **--------------------------------------------------------------------
6894 */
6895 
6896 	case SIR_REJECT_RECEIVED:
6897 		/*-----------------------------------------------
6898 		**
6899 		**	We received a MESSAGE_REJECT.
6900 		**
6901 		**-----------------------------------------------
6902 		*/
6903 
6904 		PRINT_ADDR(cp->cmd, "MESSAGE_REJECT received (%x:%x).\n",
6905 			(unsigned)scr_to_cpu(np->lastmsg), np->msgout[0]);
6906 		break;
6907 
6908 	case SIR_REJECT_SENT:
6909 		/*-----------------------------------------------
6910 		**
6911 		**	We received an unknown message
6912 		**
6913 		**-----------------------------------------------
6914 		*/
6915 
6916 		ncr_print_msg(cp, "MESSAGE_REJECT sent for", np->msgin);
6917 		break;
6918 
6919 /*--------------------------------------------------------------------
6920 **
6921 **	Processing of special messages
6922 **
6923 **--------------------------------------------------------------------
6924 */
6925 
6926 	case SIR_IGN_RESIDUE:
6927 		/*-----------------------------------------------
6928 		**
6929 		**	We received an IGNORE RESIDUE message,
6930 		**	which couldn't be handled by the script.
6931 		**
6932 		**-----------------------------------------------
6933 		*/
6934 
6935 		PRINT_ADDR(cp->cmd, "IGNORE_WIDE_RESIDUE received, but not yet "
6936 				"implemented.\n");
6937 		break;
6938 #if 0
6939 	case SIR_MISSING_SAVE:
6940 		/*-----------------------------------------------
6941 		**
6942 		**	We received an DISCONNECT message,
6943 		**	but the datapointer wasn't saved before.
6944 		**
6945 		**-----------------------------------------------
6946 		*/
6947 
6948 		PRINT_ADDR(cp->cmd, "DISCONNECT received, but datapointer "
6949 				"not saved: data=%x save=%x goal=%x.\n",
6950 			(unsigned) INL (nc_temp),
6951 			(unsigned) scr_to_cpu(np->header.savep),
6952 			(unsigned) scr_to_cpu(np->header.goalp));
6953 		break;
6954 #endif
6955 	}
6956 
6957 out:
6958 	OUTONB_STD ();
6959 }
6960 
6961 /*==========================================================
6962 **
6963 **
6964 **	Acquire a control block
6965 **
6966 **
6967 **==========================================================
6968 */
6969 
6970 static struct ccb *ncr_get_ccb(struct ncb *np, struct scsi_cmnd *cmd)
6971 {
6972 	u_char tn = cmd->device->id;
6973 	u_char ln = cmd->device->lun;
6974 	struct tcb *tp = &np->target[tn];
6975 	struct lcb *lp = tp->lp[ln];
6976 	u_char tag = NO_TAG;
6977 	struct ccb *cp = NULL;
6978 
6979 	/*
6980 	**	Lun structure available ?
6981 	*/
6982 	if (lp) {
6983 		struct list_head *qp;
6984 		/*
6985 		**	Keep from using more tags than we can handle.
6986 		*/
6987 		if (lp->usetags && lp->busyccbs >= lp->maxnxs)
6988 			return NULL;
6989 
6990 		/*
6991 		**	Allocate a new CCB if needed.
6992 		*/
6993 		if (list_empty(&lp->free_ccbq))
6994 			ncr_alloc_ccb(np, tn, ln);
6995 
6996 		/*
6997 		**	Look for free CCB
6998 		*/
6999 		qp = ncr_list_pop(&lp->free_ccbq);
7000 		if (qp) {
7001 			cp = list_entry(qp, struct ccb, link_ccbq);
7002 			if (cp->magic) {
7003 				PRINT_ADDR(cmd, "ccb free list corrupted "
7004 						"(@%p)\n", cp);
7005 				cp = NULL;
7006 			} else {
7007 				list_add_tail(qp, &lp->wait_ccbq);
7008 				++lp->busyccbs;
7009 			}
7010 		}
7011 
7012 		/*
7013 		**	If a CCB is available,
7014 		**	Get a tag for this nexus if required.
7015 		*/
7016 		if (cp) {
7017 			if (lp->usetags)
7018 				tag = lp->cb_tags[lp->ia_tag];
7019 		}
7020 		else if (lp->actccbs > 0)
7021 			return NULL;
7022 	}
7023 
7024 	/*
7025 	**	if nothing available, take the default.
7026 	*/
7027 	if (!cp)
7028 		cp = np->ccb;
7029 
7030 	/*
7031 	**	Wait until available.
7032 	*/
7033 #if 0
7034 	while (cp->magic) {
7035 		if (flags & SCSI_NOSLEEP) break;
7036 		if (tsleep ((caddr_t)cp, PRIBIO|PCATCH, "ncr", 0))
7037 			break;
7038 	}
7039 #endif
7040 
7041 	if (cp->magic)
7042 		return NULL;
7043 
7044 	cp->magic = 1;
7045 
7046 	/*
7047 	**	Move to next available tag if tag used.
7048 	*/
7049 	if (lp) {
7050 		if (tag != NO_TAG) {
7051 			++lp->ia_tag;
7052 			if (lp->ia_tag == MAX_TAGS)
7053 				lp->ia_tag = 0;
7054 			lp->tags_umap |= (((tagmap_t) 1) << tag);
7055 		}
7056 	}
7057 
7058 	/*
7059 	**	Remember all informations needed to free this CCB.
7060 	*/
7061 	cp->tag	   = tag;
7062 	cp->target = tn;
7063 	cp->lun    = ln;
7064 
7065 	if (DEBUG_FLAGS & DEBUG_TAGS) {
7066 		PRINT_ADDR(cmd, "ccb @%p using tag %d.\n", cp, tag);
7067 	}
7068 
7069 	return cp;
7070 }
7071 
7072 /*==========================================================
7073 **
7074 **
7075 **	Release one control block
7076 **
7077 **
7078 **==========================================================
7079 */
7080 
7081 static void ncr_free_ccb (struct ncb *np, struct ccb *cp)
7082 {
7083 	struct tcb *tp = &np->target[cp->target];
7084 	struct lcb *lp = tp->lp[cp->lun];
7085 
7086 	if (DEBUG_FLAGS & DEBUG_TAGS) {
7087 		PRINT_ADDR(cp->cmd, "ccb @%p freeing tag %d.\n", cp, cp->tag);
7088 	}
7089 
7090 	/*
7091 	**	If lun control block available,
7092 	**	decrement active commands and increment credit,
7093 	**	free the tag if any and remove the JUMP for reselect.
7094 	*/
7095 	if (lp) {
7096 		if (cp->tag != NO_TAG) {
7097 			lp->cb_tags[lp->if_tag++] = cp->tag;
7098 			if (lp->if_tag == MAX_TAGS)
7099 				lp->if_tag = 0;
7100 			lp->tags_umap &= ~(((tagmap_t) 1) << cp->tag);
7101 			lp->tags_smap &= lp->tags_umap;
7102 			lp->jump_ccb[cp->tag] =
7103 				cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l_q));
7104 		} else {
7105 			lp->jump_ccb[0] =
7106 				cpu_to_scr(NCB_SCRIPTH_PHYS(np, bad_i_t_l));
7107 		}
7108 	}
7109 
7110 	/*
7111 	**	Make this CCB available.
7112 	*/
7113 
7114 	if (lp) {
7115 		if (cp != np->ccb)
7116 			list_move(&cp->link_ccbq, &lp->free_ccbq);
7117 		--lp->busyccbs;
7118 		if (cp->queued) {
7119 			--lp->queuedccbs;
7120 		}
7121 	}
7122 	cp -> host_status = HS_IDLE;
7123 	cp -> magic = 0;
7124 	if (cp->queued) {
7125 		--np->queuedccbs;
7126 		cp->queued = 0;
7127 	}
7128 
7129 #if 0
7130 	if (cp == np->ccb)
7131 		wakeup ((caddr_t) cp);
7132 #endif
7133 }
7134 
7135 
7136 #define ncr_reg_bus_addr(r) (np->paddr + offsetof (struct ncr_reg, r))
7137 
7138 /*------------------------------------------------------------------------
7139 **	Initialize the fixed part of a CCB structure.
7140 **------------------------------------------------------------------------
7141 **------------------------------------------------------------------------
7142 */
7143 static void ncr_init_ccb(struct ncb *np, struct ccb *cp)
7144 {
7145 	ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7146 
7147 	/*
7148 	**	Remember virtual and bus address of this ccb.
7149 	*/
7150 	cp->p_ccb 	   = vtobus(cp);
7151 	cp->phys.header.cp = cp;
7152 
7153 	/*
7154 	**	This allows list_del to work for the default ccb.
7155 	*/
7156 	INIT_LIST_HEAD(&cp->link_ccbq);
7157 
7158 	/*
7159 	**	Initialyze the start and restart launch script.
7160 	**
7161 	**	COPY(4) @(...p_phys), @(dsa)
7162 	**	JUMP @(sched_point)
7163 	*/
7164 	cp->start.setup_dsa[0]	 = cpu_to_scr(copy_4);
7165 	cp->start.setup_dsa[1]	 = cpu_to_scr(CCB_PHYS(cp, start.p_phys));
7166 	cp->start.setup_dsa[2]	 = cpu_to_scr(ncr_reg_bus_addr(nc_dsa));
7167 	cp->start.schedule.l_cmd = cpu_to_scr(SCR_JUMP);
7168 	cp->start.p_phys	 = cpu_to_scr(CCB_PHYS(cp, phys));
7169 
7170 	memcpy(&cp->restart, &cp->start, sizeof(cp->restart));
7171 
7172 	cp->start.schedule.l_paddr   = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
7173 	cp->restart.schedule.l_paddr = cpu_to_scr(NCB_SCRIPTH_PHYS (np, abort));
7174 }
7175 
7176 
7177 /*------------------------------------------------------------------------
7178 **	Allocate a CCB and initialize its fixed part.
7179 **------------------------------------------------------------------------
7180 **------------------------------------------------------------------------
7181 */
7182 static void ncr_alloc_ccb(struct ncb *np, u_char tn, u_char ln)
7183 {
7184 	struct tcb *tp = &np->target[tn];
7185 	struct lcb *lp = tp->lp[ln];
7186 	struct ccb *cp = NULL;
7187 
7188 	/*
7189 	**	Allocate memory for this CCB.
7190 	*/
7191 	cp = m_calloc_dma(sizeof(struct ccb), "CCB");
7192 	if (!cp)
7193 		return;
7194 
7195 	/*
7196 	**	Count it and initialyze it.
7197 	*/
7198 	lp->actccbs++;
7199 	np->actccbs++;
7200 	memset(cp, 0, sizeof (*cp));
7201 	ncr_init_ccb(np, cp);
7202 
7203 	/*
7204 	**	Chain into wakeup list and free ccb queue and take it
7205 	**	into account for tagged commands.
7206 	*/
7207 	cp->link_ccb      = np->ccb->link_ccb;
7208 	np->ccb->link_ccb = cp;
7209 
7210 	list_add(&cp->link_ccbq, &lp->free_ccbq);
7211 }
7212 
7213 /*==========================================================
7214 **
7215 **
7216 **      Allocation of resources for Targets/Luns/Tags.
7217 **
7218 **
7219 **==========================================================
7220 */
7221 
7222 
7223 /*------------------------------------------------------------------------
7224 **	Target control block initialisation.
7225 **------------------------------------------------------------------------
7226 **	This data structure is fully initialized after a SCSI command
7227 **	has been successfully completed for this target.
7228 **	It contains a SCRIPT that is called on target reselection.
7229 **------------------------------------------------------------------------
7230 */
7231 static void ncr_init_tcb (struct ncb *np, u_char tn)
7232 {
7233 	struct tcb *tp = &np->target[tn];
7234 	ncrcmd copy_1 = np->features & FE_PFEN ? SCR_COPY(1) : SCR_COPY_F(1);
7235 	int th = tn & 3;
7236 	int i;
7237 
7238 	/*
7239 	**	Jump to next tcb if SFBR does not match this target.
7240 	**	JUMP  IF (SFBR != #target#), @(next tcb)
7241 	*/
7242 	tp->jump_tcb.l_cmd   =
7243 		cpu_to_scr((SCR_JUMP ^ IFFALSE (DATA (0x80 + tn))));
7244 	tp->jump_tcb.l_paddr = np->jump_tcb[th].l_paddr;
7245 
7246 	/*
7247 	**	Load the synchronous transfer register.
7248 	**	COPY @(tp->sval), @(sxfer)
7249 	*/
7250 	tp->getscr[0] =	cpu_to_scr(copy_1);
7251 	tp->getscr[1] = cpu_to_scr(vtobus (&tp->sval));
7252 #ifdef SCSI_NCR_BIG_ENDIAN
7253 	tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer) ^ 3);
7254 #else
7255 	tp->getscr[2] = cpu_to_scr(ncr_reg_bus_addr(nc_sxfer));
7256 #endif
7257 
7258 	/*
7259 	**	Load the timing register.
7260 	**	COPY @(tp->wval), @(scntl3)
7261 	*/
7262 	tp->getscr[3] =	cpu_to_scr(copy_1);
7263 	tp->getscr[4] = cpu_to_scr(vtobus (&tp->wval));
7264 #ifdef SCSI_NCR_BIG_ENDIAN
7265 	tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3) ^ 3);
7266 #else
7267 	tp->getscr[5] = cpu_to_scr(ncr_reg_bus_addr(nc_scntl3));
7268 #endif
7269 
7270 	/*
7271 	**	Get the IDENTIFY message and the lun.
7272 	**	CALL @script(resel_lun)
7273 	*/
7274 	tp->call_lun.l_cmd   = cpu_to_scr(SCR_CALL);
7275 	tp->call_lun.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_lun));
7276 
7277 	/*
7278 	**	Look for the lun control block of this nexus.
7279 	**	For i = 0 to 3
7280 	**		JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
7281 	*/
7282 	for (i = 0 ; i < 4 ; i++) {
7283 		tp->jump_lcb[i].l_cmd   =
7284 				cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
7285 		tp->jump_lcb[i].l_paddr =
7286 				cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_identify));
7287 	}
7288 
7289 	/*
7290 	**	Link this target control block to the JUMP chain.
7291 	*/
7292 	np->jump_tcb[th].l_paddr = cpu_to_scr(vtobus (&tp->jump_tcb));
7293 
7294 	/*
7295 	**	These assert's should be moved at driver initialisations.
7296 	*/
7297 #ifdef SCSI_NCR_BIG_ENDIAN
7298 	BUG_ON(((offsetof(struct ncr_reg, nc_sxfer) ^
7299 		 offsetof(struct tcb    , sval    )) &3) != 3);
7300 	BUG_ON(((offsetof(struct ncr_reg, nc_scntl3) ^
7301 		 offsetof(struct tcb    , wval    )) &3) != 3);
7302 #else
7303 	BUG_ON(((offsetof(struct ncr_reg, nc_sxfer) ^
7304 		 offsetof(struct tcb    , sval    )) &3) != 0);
7305 	BUG_ON(((offsetof(struct ncr_reg, nc_scntl3) ^
7306 		 offsetof(struct tcb    , wval    )) &3) != 0);
7307 #endif
7308 }
7309 
7310 
7311 /*------------------------------------------------------------------------
7312 **	Lun control block allocation and initialization.
7313 **------------------------------------------------------------------------
7314 **	This data structure is allocated and initialized after a SCSI
7315 **	command has been successfully completed for this target/lun.
7316 **------------------------------------------------------------------------
7317 */
7318 static struct lcb *ncr_alloc_lcb (struct ncb *np, u_char tn, u_char ln)
7319 {
7320 	struct tcb *tp = &np->target[tn];
7321 	struct lcb *lp = tp->lp[ln];
7322 	ncrcmd copy_4 = np->features & FE_PFEN ? SCR_COPY(4) : SCR_COPY_F(4);
7323 	int lh = ln & 3;
7324 
7325 	/*
7326 	**	Already done, return.
7327 	*/
7328 	if (lp)
7329 		return lp;
7330 
7331 	/*
7332 	**	Allocate the lcb.
7333 	*/
7334 	lp = m_calloc_dma(sizeof(struct lcb), "LCB");
7335 	if (!lp)
7336 		goto fail;
7337 	memset(lp, 0, sizeof(*lp));
7338 	tp->lp[ln] = lp;
7339 
7340 	/*
7341 	**	Initialize the target control block if not yet.
7342 	*/
7343 	if (!tp->jump_tcb.l_cmd)
7344 		ncr_init_tcb(np, tn);
7345 
7346 	/*
7347 	**	Initialize the CCB queue headers.
7348 	*/
7349 	INIT_LIST_HEAD(&lp->free_ccbq);
7350 	INIT_LIST_HEAD(&lp->busy_ccbq);
7351 	INIT_LIST_HEAD(&lp->wait_ccbq);
7352 	INIT_LIST_HEAD(&lp->skip_ccbq);
7353 
7354 	/*
7355 	**	Set max CCBs to 1 and use the default 1 entry
7356 	**	jump table by default.
7357 	*/
7358 	lp->maxnxs	= 1;
7359 	lp->jump_ccb	= &lp->jump_ccb_0;
7360 	lp->p_jump_ccb	= cpu_to_scr(vtobus(lp->jump_ccb));
7361 
7362 	/*
7363 	**	Initilialyze the reselect script:
7364 	**
7365 	**	Jump to next lcb if SFBR does not match this lun.
7366 	**	Load TEMP with the CCB direct jump table bus address.
7367 	**	Get the SIMPLE TAG message and the tag.
7368 	**
7369 	**	JUMP  IF (SFBR != #lun#), @(next lcb)
7370 	**	COPY @(lp->p_jump_ccb),	  @(temp)
7371 	**	JUMP @script(resel_notag)
7372 	*/
7373 	lp->jump_lcb.l_cmd   =
7374 		cpu_to_scr((SCR_JUMP ^ IFFALSE (MASK (0x80+ln, 0xff))));
7375 	lp->jump_lcb.l_paddr = tp->jump_lcb[lh].l_paddr;
7376 
7377 	lp->load_jump_ccb[0] = cpu_to_scr(copy_4);
7378 	lp->load_jump_ccb[1] = cpu_to_scr(vtobus (&lp->p_jump_ccb));
7379 	lp->load_jump_ccb[2] = cpu_to_scr(ncr_reg_bus_addr(nc_temp));
7380 
7381 	lp->jump_tag.l_cmd   = cpu_to_scr(SCR_JUMP);
7382 	lp->jump_tag.l_paddr = cpu_to_scr(NCB_SCRIPT_PHYS (np, resel_notag));
7383 
7384 	/*
7385 	**	Link this lun control block to the JUMP chain.
7386 	*/
7387 	tp->jump_lcb[lh].l_paddr = cpu_to_scr(vtobus (&lp->jump_lcb));
7388 
7389 	/*
7390 	**	Initialize command queuing control.
7391 	*/
7392 	lp->busyccbs	= 1;
7393 	lp->queuedccbs	= 1;
7394 	lp->queuedepth	= 1;
7395 fail:
7396 	return lp;
7397 }
7398 
7399 
7400 /*------------------------------------------------------------------------
7401 **	Lun control block setup on INQUIRY data received.
7402 **------------------------------------------------------------------------
7403 **	We only support WIDE, SYNC for targets and CMDQ for logical units.
7404 **	This setup is done on each INQUIRY since we are expecting user
7405 **	will play with CHANGE DEFINITION commands. :-)
7406 **------------------------------------------------------------------------
7407 */
7408 static struct lcb *ncr_setup_lcb (struct ncb *np, struct scsi_device *sdev)
7409 {
7410 	unsigned char tn = sdev->id, ln = sdev->lun;
7411 	struct tcb *tp = &np->target[tn];
7412 	struct lcb *lp = tp->lp[ln];
7413 
7414 	/* If no lcb, try to allocate it.  */
7415 	if (!lp && !(lp = ncr_alloc_lcb(np, tn, ln)))
7416 		goto fail;
7417 
7418 	/*
7419 	**	If unit supports tagged commands, allocate the
7420 	**	CCB JUMP table if not yet.
7421 	*/
7422 	if (sdev->tagged_supported && lp->jump_ccb == &lp->jump_ccb_0) {
7423 		int i;
7424 		lp->jump_ccb = m_calloc_dma(256, "JUMP_CCB");
7425 		if (!lp->jump_ccb) {
7426 			lp->jump_ccb = &lp->jump_ccb_0;
7427 			goto fail;
7428 		}
7429 		lp->p_jump_ccb = cpu_to_scr(vtobus(lp->jump_ccb));
7430 		for (i = 0 ; i < 64 ; i++)
7431 			lp->jump_ccb[i] =
7432 				cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l_q));
7433 		for (i = 0 ; i < MAX_TAGS ; i++)
7434 			lp->cb_tags[i] = i;
7435 		lp->maxnxs = MAX_TAGS;
7436 		lp->tags_stime = jiffies + 3*HZ;
7437 		ncr_setup_tags (np, sdev);
7438 	}
7439 
7440 
7441 fail:
7442 	return lp;
7443 }
7444 
7445 /*==========================================================
7446 **
7447 **
7448 **	Build Scatter Gather Block
7449 **
7450 **
7451 **==========================================================
7452 **
7453 **	The transfer area may be scattered among
7454 **	several non adjacent physical pages.
7455 **
7456 **	We may use MAX_SCATTER blocks.
7457 **
7458 **----------------------------------------------------------
7459 */
7460 
7461 /*
7462 **	We try to reduce the number of interrupts caused
7463 **	by unexpected phase changes due to disconnects.
7464 **	A typical harddisk may disconnect before ANY block.
7465 **	If we wanted to avoid unexpected phase changes at all
7466 **	we had to use a break point every 512 bytes.
7467 **	Of course the number of scatter/gather blocks is
7468 **	limited.
7469 **	Under Linux, the scatter/gatter blocks are provided by
7470 **	the generic driver. We just have to copy addresses and
7471 **	sizes to the data segment array.
7472 */
7473 
7474 static int ncr_scatter(struct ncb *np, struct ccb *cp, struct scsi_cmnd *cmd)
7475 {
7476 	int segment	= 0;
7477 	int use_sg	= scsi_sg_count(cmd);
7478 
7479 	cp->data_len	= 0;
7480 
7481 	use_sg = map_scsi_sg_data(np, cmd);
7482 	if (use_sg > 0) {
7483 		struct scatterlist *sg;
7484 		struct scr_tblmove *data;
7485 
7486 		if (use_sg > MAX_SCATTER) {
7487 			unmap_scsi_data(np, cmd);
7488 			return -1;
7489 		}
7490 
7491 		data = &cp->phys.data[MAX_SCATTER - use_sg];
7492 
7493 		scsi_for_each_sg(cmd, sg, use_sg, segment) {
7494 			dma_addr_t baddr = sg_dma_address(sg);
7495 			unsigned int len = sg_dma_len(sg);
7496 
7497 			ncr_build_sge(np, &data[segment], baddr, len);
7498 			cp->data_len += len;
7499 		}
7500 	} else
7501 		segment = -2;
7502 
7503 	return segment;
7504 }
7505 
7506 /*==========================================================
7507 **
7508 **
7509 **	Test the bus snoop logic :-(
7510 **
7511 **	Has to be called with interrupts disabled.
7512 **
7513 **
7514 **==========================================================
7515 */
7516 
7517 static int __init ncr_regtest (struct ncb* np)
7518 {
7519 	register volatile u32 data;
7520 	/*
7521 	**	ncr registers may NOT be cached.
7522 	**	write 0xffffffff to a read only register area,
7523 	**	and try to read it back.
7524 	*/
7525 	data = 0xffffffff;
7526 	OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
7527 	data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
7528 #if 1
7529 	if (data == 0xffffffff) {
7530 #else
7531 	if ((data & 0xe2f0fffd) != 0x02000080) {
7532 #endif
7533 		printk ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
7534 			(unsigned) data);
7535 		return (0x10);
7536 	}
7537 	return (0);
7538 }
7539 
7540 static int __init ncr_snooptest (struct ncb* np)
7541 {
7542 	u32	ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
7543 	int	i, err=0;
7544 	if (np->reg) {
7545 		err |= ncr_regtest (np);
7546 		if (err)
7547 			return (err);
7548 	}
7549 
7550 	/* init */
7551 	pc  = NCB_SCRIPTH_PHYS (np, snooptest);
7552 	host_wr = 1;
7553 	ncr_wr  = 2;
7554 	/*
7555 	**	Set memory and register.
7556 	*/
7557 	np->ncr_cache = cpu_to_scr(host_wr);
7558 	OUTL (nc_temp, ncr_wr);
7559 	/*
7560 	**	Start script (exchange values)
7561 	*/
7562 	OUTL_DSP (pc);
7563 	/*
7564 	**	Wait 'til done (with timeout)
7565 	*/
7566 	for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
7567 		if (INB(nc_istat) & (INTF|SIP|DIP))
7568 			break;
7569 	/*
7570 	**	Save termination position.
7571 	*/
7572 	pc = INL (nc_dsp);
7573 	/*
7574 	**	Read memory and register.
7575 	*/
7576 	host_rd = scr_to_cpu(np->ncr_cache);
7577 	ncr_rd  = INL (nc_scratcha);
7578 	ncr_bk  = INL (nc_temp);
7579 	/*
7580 	**	Reset ncr chip
7581 	*/
7582 	ncr_chip_reset(np, 100);
7583 	/*
7584 	**	check for timeout
7585 	*/
7586 	if (i>=NCR_SNOOP_TIMEOUT) {
7587 		printk ("CACHE TEST FAILED: timeout.\n");
7588 		return (0x20);
7589 	}
7590 	/*
7591 	**	Check termination position.
7592 	*/
7593 	if (pc != NCB_SCRIPTH_PHYS (np, snoopend)+8) {
7594 		printk ("CACHE TEST FAILED: script execution failed.\n");
7595 		printk ("start=%08lx, pc=%08lx, end=%08lx\n",
7596 			(u_long) NCB_SCRIPTH_PHYS (np, snooptest), (u_long) pc,
7597 			(u_long) NCB_SCRIPTH_PHYS (np, snoopend) +8);
7598 		return (0x40);
7599 	}
7600 	/*
7601 	**	Show results.
7602 	*/
7603 	if (host_wr != ncr_rd) {
7604 		printk ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
7605 			(int) host_wr, (int) ncr_rd);
7606 		err |= 1;
7607 	}
7608 	if (host_rd != ncr_wr) {
7609 		printk ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
7610 			(int) ncr_wr, (int) host_rd);
7611 		err |= 2;
7612 	}
7613 	if (ncr_bk != ncr_wr) {
7614 		printk ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
7615 			(int) ncr_wr, (int) ncr_bk);
7616 		err |= 4;
7617 	}
7618 	return (err);
7619 }
7620 
7621 /*==========================================================
7622 **
7623 **	Determine the ncr's clock frequency.
7624 **	This is essential for the negotiation
7625 **	of the synchronous transfer rate.
7626 **
7627 **==========================================================
7628 **
7629 **	Note: we have to return the correct value.
7630 **	THERE IS NO SAFE DEFAULT VALUE.
7631 **
7632 **	Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
7633 **	53C860 and 53C875 rev. 1 support fast20 transfers but
7634 **	do not have a clock doubler and so are provided with a
7635 **	80 MHz clock. All other fast20 boards incorporate a doubler
7636 **	and so should be delivered with a 40 MHz clock.
7637 **	The future fast40 chips (895/895) use a 40 Mhz base clock
7638 **	and provide a clock quadrupler (160 Mhz). The code below
7639 **	tries to deal as cleverly as possible with all this stuff.
7640 **
7641 **----------------------------------------------------------
7642 */
7643 
7644 /*
7645  *	Select NCR SCSI clock frequency
7646  */
7647 static void ncr_selectclock(struct ncb *np, u_char scntl3)
7648 {
7649 	if (np->multiplier < 2) {
7650 		OUTB(nc_scntl3,	scntl3);
7651 		return;
7652 	}
7653 
7654 	if (bootverbose >= 2)
7655 		printk ("%s: enabling clock multiplier\n", ncr_name(np));
7656 
7657 	OUTB(nc_stest1, DBLEN);	   /* Enable clock multiplier		  */
7658 	if (np->multiplier > 2) {  /* Poll bit 5 of stest4 for quadrupler */
7659 		int i = 20;
7660 		while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
7661 			udelay(20);
7662 		if (!i)
7663 			printk("%s: the chip cannot lock the frequency\n", ncr_name(np));
7664 	} else			/* Wait 20 micro-seconds for doubler	*/
7665 		udelay(20);
7666 	OUTB(nc_stest3, HSC);		/* Halt the scsi clock		*/
7667 	OUTB(nc_scntl3,	scntl3);
7668 	OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier	*/
7669 	OUTB(nc_stest3, 0x00);		/* Restart scsi clock 		*/
7670 }
7671 
7672 
7673 /*
7674  *	calculate NCR SCSI clock frequency (in KHz)
7675  */
7676 static unsigned __init ncrgetfreq (struct ncb *np, int gen)
7677 {
7678 	unsigned ms = 0;
7679 	char count = 0;
7680 
7681 	/*
7682 	 * Measure GEN timer delay in order
7683 	 * to calculate SCSI clock frequency
7684 	 *
7685 	 * This code will never execute too
7686 	 * many loop iterations (if DELAY is
7687 	 * reasonably correct). It could get
7688 	 * too low a delay (too high a freq.)
7689 	 * if the CPU is slow executing the
7690 	 * loop for some reason (an NMI, for
7691 	 * example). For this reason we will
7692 	 * if multiple measurements are to be
7693 	 * performed trust the higher delay
7694 	 * (lower frequency returned).
7695 	 */
7696 	OUTB (nc_stest1, 0);	/* make sure clock doubler is OFF */
7697 	OUTW (nc_sien , 0);	/* mask all scsi interrupts */
7698 	(void) INW (nc_sist);	/* clear pending scsi interrupt */
7699 	OUTB (nc_dien , 0);	/* mask all dma interrupts */
7700 	(void) INW (nc_sist);	/* another one, just to be sure :) */
7701 	OUTB (nc_scntl3, 4);	/* set pre-scaler to divide by 3 */
7702 	OUTB (nc_stime1, 0);	/* disable general purpose timer */
7703 	OUTB (nc_stime1, gen);	/* set to nominal delay of 1<<gen * 125us */
7704 	while (!(INW(nc_sist) & GEN) && ms++ < 100000) {
7705 		for (count = 0; count < 10; count ++)
7706 			udelay(100);	/* count ms */
7707 	}
7708 	OUTB (nc_stime1, 0);	/* disable general purpose timer */
7709  	/*
7710  	 * set prescaler to divide by whatever 0 means
7711  	 * 0 ought to choose divide by 2, but appears
7712  	 * to set divide by 3.5 mode in my 53c810 ...
7713  	 */
7714  	OUTB (nc_scntl3, 0);
7715 
7716 	if (bootverbose >= 2)
7717 		printk ("%s: Delay (GEN=%d): %u msec\n", ncr_name(np), gen, ms);
7718   	/*
7719  	 * adjust for prescaler, and convert into KHz
7720   	 */
7721 	return ms ? ((1 << gen) * 4340) / ms : 0;
7722 }
7723 
7724 /*
7725  *	Get/probe NCR SCSI clock frequency
7726  */
7727 static void __init ncr_getclock (struct ncb *np, int mult)
7728 {
7729 	unsigned char scntl3 = INB(nc_scntl3);
7730 	unsigned char stest1 = INB(nc_stest1);
7731 	unsigned f1;
7732 
7733 	np->multiplier = 1;
7734 	f1 = 40000;
7735 
7736 	/*
7737 	**	True with 875 or 895 with clock multiplier selected
7738 	*/
7739 	if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
7740 		if (bootverbose >= 2)
7741 			printk ("%s: clock multiplier found\n", ncr_name(np));
7742 		np->multiplier = mult;
7743 	}
7744 
7745 	/*
7746 	**	If multiplier not found or scntl3 not 7,5,3,
7747 	**	reset chip and get frequency from general purpose timer.
7748 	**	Otherwise trust scntl3 BIOS setting.
7749 	*/
7750 	if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
7751 		unsigned f2;
7752 
7753 		ncr_chip_reset(np, 5);
7754 
7755 		(void) ncrgetfreq (np, 11);	/* throw away first result */
7756 		f1 = ncrgetfreq (np, 11);
7757 		f2 = ncrgetfreq (np, 11);
7758 
7759 		if(bootverbose)
7760 			printk ("%s: NCR clock is %uKHz, %uKHz\n", ncr_name(np), f1, f2);
7761 
7762 		if (f1 > f2) f1 = f2;		/* trust lower result	*/
7763 
7764 		if	(f1 <	45000)		f1 =  40000;
7765 		else if (f1 <	55000)		f1 =  50000;
7766 		else				f1 =  80000;
7767 
7768 		if (f1 < 80000 && mult > 1) {
7769 			if (bootverbose >= 2)
7770 				printk ("%s: clock multiplier assumed\n", ncr_name(np));
7771 			np->multiplier	= mult;
7772 		}
7773 	} else {
7774 		if	((scntl3 & 7) == 3)	f1 =  40000;
7775 		else if	((scntl3 & 7) == 5)	f1 =  80000;
7776 		else 				f1 = 160000;
7777 
7778 		f1 /= np->multiplier;
7779 	}
7780 
7781 	/*
7782 	**	Compute controller synchronous parameters.
7783 	*/
7784 	f1		*= np->multiplier;
7785 	np->clock_khz	= f1;
7786 }
7787 
7788 /*===================== LINUX ENTRY POINTS SECTION ==========================*/
7789 
7790 static int ncr53c8xx_slave_alloc(struct scsi_device *device)
7791 {
7792 	struct Scsi_Host *host = device->host;
7793 	struct ncb *np = ((struct host_data *) host->hostdata)->ncb;
7794 	struct tcb *tp = &np->target[device->id];
7795 	tp->starget = device->sdev_target;
7796 
7797 	return 0;
7798 }
7799 
7800 static int ncr53c8xx_slave_configure(struct scsi_device *device)
7801 {
7802 	struct Scsi_Host *host = device->host;
7803 	struct ncb *np = ((struct host_data *) host->hostdata)->ncb;
7804 	struct tcb *tp = &np->target[device->id];
7805 	struct lcb *lp = tp->lp[device->lun];
7806 	int numtags, depth_to_use;
7807 
7808 	ncr_setup_lcb(np, device);
7809 
7810 	/*
7811 	**	Select queue depth from driver setup.
7812 	**	Donnot use more than configured by user.
7813 	**	Use at least 2.
7814 	**	Donnot use more than our maximum.
7815 	*/
7816 	numtags = device_queue_depth(np->unit, device->id, device->lun);
7817 	if (numtags > tp->usrtags)
7818 		numtags = tp->usrtags;
7819 	if (!device->tagged_supported)
7820 		numtags = 1;
7821 	depth_to_use = numtags;
7822 	if (depth_to_use < 2)
7823 		depth_to_use = 2;
7824 	if (depth_to_use > MAX_TAGS)
7825 		depth_to_use = MAX_TAGS;
7826 
7827 	scsi_change_queue_depth(device, depth_to_use);
7828 
7829 	/*
7830 	**	Since the queue depth is not tunable under Linux,
7831 	**	we need to know this value in order not to
7832 	**	announce stupid things to user.
7833 	**
7834 	**	XXX(hch): As of Linux 2.6 it certainly _is_ tunable..
7835 	**		  In fact we just tuned it, or did I miss
7836 	**		  something important? :)
7837 	*/
7838 	if (lp) {
7839 		lp->numtags = lp->maxtags = numtags;
7840 		lp->scdev_depth = depth_to_use;
7841 	}
7842 	ncr_setup_tags (np, device);
7843 
7844 #ifdef DEBUG_NCR53C8XX
7845 	printk("ncr53c8xx_select_queue_depth: host=%d, id=%d, lun=%d, depth=%d\n",
7846 	       np->unit, device->id, device->lun, depth_to_use);
7847 #endif
7848 
7849 	if (spi_support_sync(device->sdev_target) &&
7850 	    !spi_initial_dv(device->sdev_target))
7851 		spi_dv_device(device);
7852 	return 0;
7853 }
7854 
7855 static int ncr53c8xx_queue_command_lck(struct scsi_cmnd *cmd)
7856 {
7857      void (*done)(struct scsi_cmnd *) = scsi_done;
7858      struct ncb *np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
7859      unsigned long flags;
7860      int sts;
7861 
7862 #ifdef DEBUG_NCR53C8XX
7863 printk("ncr53c8xx_queue_command\n");
7864 #endif
7865 
7866      cmd->host_scribble = NULL;
7867      cmd->__data_mapped = 0;
7868      cmd->__data_mapping = 0;
7869 
7870      spin_lock_irqsave(&np->smp_lock, flags);
7871 
7872      if ((sts = ncr_queue_command(np, cmd)) != DID_OK) {
7873 	     set_host_byte(cmd, sts);
7874 #ifdef DEBUG_NCR53C8XX
7875 printk("ncr53c8xx : command not queued - result=%d\n", sts);
7876 #endif
7877      }
7878 #ifdef DEBUG_NCR53C8XX
7879      else
7880 printk("ncr53c8xx : command successfully queued\n");
7881 #endif
7882 
7883      spin_unlock_irqrestore(&np->smp_lock, flags);
7884 
7885      if (sts != DID_OK) {
7886           unmap_scsi_data(np, cmd);
7887           done(cmd);
7888 	  sts = 0;
7889      }
7890 
7891      return sts;
7892 }
7893 
7894 static DEF_SCSI_QCMD(ncr53c8xx_queue_command)
7895 
7896 irqreturn_t ncr53c8xx_intr(int irq, void *dev_id)
7897 {
7898      unsigned long flags;
7899      struct Scsi_Host *shost = (struct Scsi_Host *)dev_id;
7900      struct host_data *host_data = (struct host_data *)shost->hostdata;
7901      struct ncb *np = host_data->ncb;
7902      struct scsi_cmnd *done_list;
7903 
7904 #ifdef DEBUG_NCR53C8XX
7905      printk("ncr53c8xx : interrupt received\n");
7906 #endif
7907 
7908      if (DEBUG_FLAGS & DEBUG_TINY) printk ("[");
7909 
7910      spin_lock_irqsave(&np->smp_lock, flags);
7911      ncr_exception(np);
7912      done_list     = np->done_list;
7913      np->done_list = NULL;
7914      spin_unlock_irqrestore(&np->smp_lock, flags);
7915 
7916      if (DEBUG_FLAGS & DEBUG_TINY) printk ("]\n");
7917 
7918      if (done_list)
7919 	     ncr_flush_done_cmds(done_list);
7920      return IRQ_HANDLED;
7921 }
7922 
7923 static void ncr53c8xx_timeout(struct timer_list *t)
7924 {
7925 	struct ncb *np = from_timer(np, t, timer);
7926 	unsigned long flags;
7927 	struct scsi_cmnd *done_list;
7928 
7929 	spin_lock_irqsave(&np->smp_lock, flags);
7930 	ncr_timeout(np);
7931 	done_list     = np->done_list;
7932 	np->done_list = NULL;
7933 	spin_unlock_irqrestore(&np->smp_lock, flags);
7934 
7935 	if (done_list)
7936 		ncr_flush_done_cmds(done_list);
7937 }
7938 
7939 static int ncr53c8xx_bus_reset(struct scsi_cmnd *cmd)
7940 {
7941 	struct ncb *np = ((struct host_data *) cmd->device->host->hostdata)->ncb;
7942 	int sts;
7943 	unsigned long flags;
7944 	struct scsi_cmnd *done_list;
7945 
7946 	/*
7947 	 * If the mid-level driver told us reset is synchronous, it seems
7948 	 * that we must call the done() callback for the involved command,
7949 	 * even if this command was not queued to the low-level driver,
7950 	 * before returning SUCCESS.
7951 	 */
7952 
7953 	spin_lock_irqsave(&np->smp_lock, flags);
7954 	sts = ncr_reset_bus(np);
7955 
7956 	done_list     = np->done_list;
7957 	np->done_list = NULL;
7958 	spin_unlock_irqrestore(&np->smp_lock, flags);
7959 
7960 	ncr_flush_done_cmds(done_list);
7961 
7962 	return sts;
7963 }
7964 
7965 
7966 /*
7967 **	Scsi command waiting list management.
7968 **
7969 **	It may happen that we cannot insert a scsi command into the start queue,
7970 **	in the following circumstances.
7971 ** 		Too few preallocated ccb(s),
7972 **		maxtags < cmd_per_lun of the Linux host control block,
7973 **		etc...
7974 **	Such scsi commands are inserted into a waiting list.
7975 **	When a scsi command complete, we try to requeue the commands of the
7976 **	waiting list.
7977 */
7978 
7979 #define next_wcmd host_scribble
7980 
7981 static void insert_into_waiting_list(struct ncb *np, struct scsi_cmnd *cmd)
7982 {
7983 	struct scsi_cmnd *wcmd;
7984 
7985 #ifdef DEBUG_WAITING_LIST
7986 	printk("%s: cmd %lx inserted into waiting list\n", ncr_name(np), (u_long) cmd);
7987 #endif
7988 	cmd->next_wcmd = NULL;
7989 	if (!(wcmd = np->waiting_list)) np->waiting_list = cmd;
7990 	else {
7991 		while (wcmd->next_wcmd)
7992 			wcmd = (struct scsi_cmnd *) wcmd->next_wcmd;
7993 		wcmd->next_wcmd = (char *) cmd;
7994 	}
7995 }
7996 
7997 static void process_waiting_list(struct ncb *np, int sts)
7998 {
7999 	struct scsi_cmnd *waiting_list, *wcmd;
8000 
8001 	waiting_list = np->waiting_list;
8002 	np->waiting_list = NULL;
8003 
8004 #ifdef DEBUG_WAITING_LIST
8005 	if (waiting_list) printk("%s: waiting_list=%lx processing sts=%d\n", ncr_name(np), (u_long) waiting_list, sts);
8006 #endif
8007 	while ((wcmd = waiting_list) != NULL) {
8008 		waiting_list = (struct scsi_cmnd *) wcmd->next_wcmd;
8009 		wcmd->next_wcmd = NULL;
8010 		if (sts == DID_OK) {
8011 #ifdef DEBUG_WAITING_LIST
8012 	printk("%s: cmd %lx trying to requeue\n", ncr_name(np), (u_long) wcmd);
8013 #endif
8014 			sts = ncr_queue_command(np, wcmd);
8015 		}
8016 		if (sts != DID_OK) {
8017 #ifdef DEBUG_WAITING_LIST
8018 	printk("%s: cmd %lx done forced sts=%d\n", ncr_name(np), (u_long) wcmd, sts);
8019 #endif
8020 			set_host_byte(wcmd, sts);
8021 			ncr_queue_done_cmd(np, wcmd);
8022 		}
8023 	}
8024 }
8025 
8026 #undef next_wcmd
8027 
8028 static ssize_t show_ncr53c8xx_revision(struct device *dev,
8029 				       struct device_attribute *attr, char *buf)
8030 {
8031 	struct Scsi_Host *host = class_to_shost(dev);
8032 	struct host_data *host_data = (struct host_data *)host->hostdata;
8033 
8034 	return snprintf(buf, 20, "0x%x\n", host_data->ncb->revision_id);
8035 }
8036 
8037 static struct device_attribute ncr53c8xx_revision_attr = {
8038 	.attr	= { .name = "revision", .mode = S_IRUGO, },
8039 	.show	= show_ncr53c8xx_revision,
8040 };
8041 
8042 static struct attribute *ncr53c8xx_host_attrs[] = {
8043 	&ncr53c8xx_revision_attr.attr,
8044 	NULL
8045 };
8046 
8047 ATTRIBUTE_GROUPS(ncr53c8xx_host);
8048 
8049 /*==========================================================
8050 **
8051 **	Boot command line.
8052 **
8053 **==========================================================
8054 */
8055 #ifdef	MODULE
8056 char *ncr53c8xx;	/* command line passed by insmod */
8057 module_param(ncr53c8xx, charp, 0);
8058 #endif
8059 
8060 #ifndef MODULE
8061 static int __init ncr53c8xx_setup(char *str)
8062 {
8063 	return sym53c8xx__setup(str);
8064 }
8065 
8066 __setup("ncr53c8xx=", ncr53c8xx_setup);
8067 #endif
8068 
8069 
8070 /*
8071  *	Host attach and initialisations.
8072  *
8073  *	Allocate host data and ncb structure.
8074  *	Request IO region and remap MMIO region.
8075  *	Do chip initialization.
8076  *	If all is OK, install interrupt handling and
8077  *	start the timer daemon.
8078  */
8079 struct Scsi_Host * __init ncr_attach(struct scsi_host_template *tpnt,
8080 					int unit, struct ncr_device *device)
8081 {
8082 	struct host_data *host_data;
8083 	struct ncb *np = NULL;
8084 	struct Scsi_Host *instance = NULL;
8085 	u_long flags = 0;
8086 	int i;
8087 
8088 	if (!tpnt->name)
8089 		tpnt->name	= SCSI_NCR_DRIVER_NAME;
8090 	if (!tpnt->shost_groups)
8091 		tpnt->shost_groups = ncr53c8xx_host_groups;
8092 
8093 	tpnt->queuecommand	= ncr53c8xx_queue_command;
8094 	tpnt->slave_configure	= ncr53c8xx_slave_configure;
8095 	tpnt->slave_alloc	= ncr53c8xx_slave_alloc;
8096 	tpnt->eh_bus_reset_handler = ncr53c8xx_bus_reset;
8097 	tpnt->can_queue		= SCSI_NCR_CAN_QUEUE;
8098 	tpnt->this_id		= 7;
8099 	tpnt->sg_tablesize	= SCSI_NCR_SG_TABLESIZE;
8100 	tpnt->cmd_per_lun	= SCSI_NCR_CMD_PER_LUN;
8101 
8102 	if (device->differential)
8103 		driver_setup.diff_support = device->differential;
8104 
8105 	printk(KERN_INFO "ncr53c720-%d: rev 0x%x irq %d\n",
8106 		unit, device->chip.revision_id, device->slot.irq);
8107 
8108 	instance = scsi_host_alloc(tpnt, sizeof(*host_data));
8109 	if (!instance)
8110 	        goto attach_error;
8111 	host_data = (struct host_data *) instance->hostdata;
8112 
8113 	np = __m_calloc_dma(device->dev, sizeof(struct ncb), "NCB");
8114 	if (!np)
8115 		goto attach_error;
8116 	spin_lock_init(&np->smp_lock);
8117 	np->dev = device->dev;
8118 	np->p_ncb = vtobus(np);
8119 	host_data->ncb = np;
8120 
8121 	np->ccb = m_calloc_dma(sizeof(struct ccb), "CCB");
8122 	if (!np->ccb)
8123 		goto attach_error;
8124 
8125 	/* Store input information in the host data structure.  */
8126 	np->unit	= unit;
8127 	np->verbose	= driver_setup.verbose;
8128 	sprintf(np->inst_name, "ncr53c720-%d", np->unit);
8129 	np->revision_id	= device->chip.revision_id;
8130 	np->features	= device->chip.features;
8131 	np->clock_divn	= device->chip.nr_divisor;
8132 	np->maxoffs	= device->chip.offset_max;
8133 	np->maxburst	= device->chip.burst_max;
8134 	np->myaddr	= device->host_id;
8135 
8136 	/* Allocate SCRIPTS areas.  */
8137 	np->script0 = m_calloc_dma(sizeof(struct script), "SCRIPT");
8138 	if (!np->script0)
8139 		goto attach_error;
8140 	np->scripth0 = m_calloc_dma(sizeof(struct scripth), "SCRIPTH");
8141 	if (!np->scripth0)
8142 		goto attach_error;
8143 
8144 	timer_setup(&np->timer, ncr53c8xx_timeout, 0);
8145 
8146 	/* Try to map the controller chip to virtual and physical memory. */
8147 
8148 	np->paddr	= device->slot.base;
8149 	np->paddr2	= (np->features & FE_RAM) ? device->slot.base_2 : 0;
8150 
8151 	if (device->slot.base_v)
8152 		np->vaddr = device->slot.base_v;
8153 	else
8154 		np->vaddr = ioremap(device->slot.base_c, 128);
8155 
8156 	if (!np->vaddr) {
8157 		printk(KERN_ERR
8158 			"%s: can't map memory mapped IO region\n",ncr_name(np));
8159 		goto attach_error;
8160 	} else {
8161 		if (bootverbose > 1)
8162 			printk(KERN_INFO
8163 				"%s: using memory mapped IO at virtual address 0x%lx\n", ncr_name(np), (u_long) np->vaddr);
8164 	}
8165 
8166 	/* Make the controller's registers available.  Now the INB INW INL
8167 	 * OUTB OUTW OUTL macros can be used safely.
8168 	 */
8169 
8170 	np->reg = (struct ncr_reg __iomem *)np->vaddr;
8171 
8172 	/* Do chip dependent initialization.  */
8173 	ncr_prepare_setting(np);
8174 
8175 	if (np->paddr2 && sizeof(struct script) > 4096) {
8176 		np->paddr2 = 0;
8177 		printk(KERN_WARNING "%s: script too large, NOT using on chip RAM.\n",
8178 			ncr_name(np));
8179 	}
8180 
8181 	instance->max_channel	= 0;
8182 	instance->this_id       = np->myaddr;
8183 	instance->max_id	= np->maxwide ? 16 : 8;
8184 	instance->max_lun	= SCSI_NCR_MAX_LUN;
8185 	instance->base		= (unsigned long) np->reg;
8186 	instance->irq		= device->slot.irq;
8187 	instance->unique_id	= device->slot.base;
8188 	instance->dma_channel	= 0;
8189 	instance->cmd_per_lun	= MAX_TAGS;
8190 	instance->can_queue	= (MAX_START-4);
8191 	/* This can happen if you forget to call ncr53c8xx_init from
8192 	 * your module_init */
8193 	BUG_ON(!ncr53c8xx_transport_template);
8194 	instance->transportt	= ncr53c8xx_transport_template;
8195 
8196 	/* Patch script to physical addresses */
8197 	ncr_script_fill(&script0, &scripth0);
8198 
8199 	np->scripth	= np->scripth0;
8200 	np->p_scripth	= vtobus(np->scripth);
8201 	np->p_script	= (np->paddr2) ?  np->paddr2 : vtobus(np->script0);
8202 
8203 	ncr_script_copy_and_bind(np, (ncrcmd *) &script0,
8204 			(ncrcmd *) np->script0, sizeof(struct script));
8205 	ncr_script_copy_and_bind(np, (ncrcmd *) &scripth0,
8206 			(ncrcmd *) np->scripth0, sizeof(struct scripth));
8207 	np->ccb->p_ccb	= vtobus (np->ccb);
8208 
8209 	/* Patch the script for LED support.  */
8210 
8211 	if (np->features & FE_LED0) {
8212 		np->script0->idle[0]  =
8213 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
8214 		np->script0->reselected[0] =
8215 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
8216 		np->script0->start[0] =
8217 				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
8218 	}
8219 
8220 	/*
8221 	 * Look for the target control block of this nexus.
8222 	 * For i = 0 to 3
8223 	 *   JUMP ^ IFTRUE (MASK (i, 3)), @(next_lcb)
8224 	 */
8225 	for (i = 0 ; i < 4 ; i++) {
8226 		np->jump_tcb[i].l_cmd   =
8227 				cpu_to_scr((SCR_JUMP ^ IFTRUE (MASK (i, 3))));
8228 		np->jump_tcb[i].l_paddr =
8229 				cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_target));
8230 	}
8231 
8232 	ncr_chip_reset(np, 100);
8233 
8234 	/* Now check the cache handling of the chipset.  */
8235 
8236 	if (ncr_snooptest(np)) {
8237 		printk(KERN_ERR "CACHE INCORRECTLY CONFIGURED.\n");
8238 		goto attach_error;
8239 	}
8240 
8241 	/* Install the interrupt handler.  */
8242 	np->irq = device->slot.irq;
8243 
8244 	/* Initialize the fixed part of the default ccb.  */
8245 	ncr_init_ccb(np, np->ccb);
8246 
8247 	/*
8248 	 * After SCSI devices have been opened, we cannot reset the bus
8249 	 * safely, so we do it here.  Interrupt handler does the real work.
8250 	 * Process the reset exception if interrupts are not enabled yet.
8251 	 * Then enable disconnects.
8252 	 */
8253 	spin_lock_irqsave(&np->smp_lock, flags);
8254 	if (ncr_reset_scsi_bus(np, 0, driver_setup.settle_delay) != 0) {
8255 		printk(KERN_ERR "%s: FATAL ERROR: CHECK SCSI BUS - CABLES, TERMINATION, DEVICE POWER etc.!\n", ncr_name(np));
8256 
8257 		spin_unlock_irqrestore(&np->smp_lock, flags);
8258 		goto attach_error;
8259 	}
8260 	ncr_exception(np);
8261 
8262 	np->disc = 1;
8263 
8264 	/*
8265 	 * The middle-level SCSI driver does not wait for devices to settle.
8266 	 * Wait synchronously if more than 2 seconds.
8267 	 */
8268 	if (driver_setup.settle_delay > 2) {
8269 		printk(KERN_INFO "%s: waiting %d seconds for scsi devices to settle...\n",
8270 			ncr_name(np), driver_setup.settle_delay);
8271 		mdelay(1000 * driver_setup.settle_delay);
8272 	}
8273 
8274 	/* start the timeout daemon */
8275 	np->lasttime=0;
8276 	ncr_timeout (np);
8277 
8278 	/* use SIMPLE TAG messages by default */
8279 #ifdef SCSI_NCR_ALWAYS_SIMPLE_TAG
8280 	np->order = SIMPLE_QUEUE_TAG;
8281 #endif
8282 
8283 	spin_unlock_irqrestore(&np->smp_lock, flags);
8284 
8285 	return instance;
8286 
8287  attach_error:
8288 	if (!instance)
8289 		return NULL;
8290 	printk(KERN_INFO "%s: detaching...\n", ncr_name(np));
8291 	if (!np)
8292 		goto unregister;
8293 	if (np->scripth0)
8294 		m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
8295 	if (np->script0)
8296 		m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
8297 	if (np->ccb)
8298 		m_free_dma(np->ccb, sizeof(struct ccb), "CCB");
8299 	m_free_dma(np, sizeof(struct ncb), "NCB");
8300 	host_data->ncb = NULL;
8301 
8302  unregister:
8303 	scsi_host_put(instance);
8304 
8305 	return NULL;
8306 }
8307 
8308 
8309 void ncr53c8xx_release(struct Scsi_Host *host)
8310 {
8311 	struct host_data *host_data = shost_priv(host);
8312 #ifdef DEBUG_NCR53C8XX
8313 	printk("ncr53c8xx: release\n");
8314 #endif
8315 	if (host_data->ncb)
8316 		ncr_detach(host_data->ncb);
8317 	scsi_host_put(host);
8318 }
8319 
8320 static void ncr53c8xx_set_period(struct scsi_target *starget, int period)
8321 {
8322 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8323 	struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8324 	struct tcb *tp = &np->target[starget->id];
8325 
8326 	if (period > np->maxsync)
8327 		period = np->maxsync;
8328 	else if (period < np->minsync)
8329 		period = np->minsync;
8330 
8331 	tp->usrsync = period;
8332 
8333 	ncr_negotiate(np, tp);
8334 }
8335 
8336 static void ncr53c8xx_set_offset(struct scsi_target *starget, int offset)
8337 {
8338 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8339 	struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8340 	struct tcb *tp = &np->target[starget->id];
8341 
8342 	if (offset > np->maxoffs)
8343 		offset = np->maxoffs;
8344 	else if (offset < 0)
8345 		offset = 0;
8346 
8347 	tp->maxoffs = offset;
8348 
8349 	ncr_negotiate(np, tp);
8350 }
8351 
8352 static void ncr53c8xx_set_width(struct scsi_target *starget, int width)
8353 {
8354 	struct Scsi_Host *shost = dev_to_shost(starget->dev.parent);
8355 	struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8356 	struct tcb *tp = &np->target[starget->id];
8357 
8358 	if (width > np->maxwide)
8359 		width = np->maxwide;
8360 	else if (width < 0)
8361 		width = 0;
8362 
8363 	tp->usrwide = width;
8364 
8365 	ncr_negotiate(np, tp);
8366 }
8367 
8368 static void ncr53c8xx_get_signalling(struct Scsi_Host *shost)
8369 {
8370 	struct ncb *np = ((struct host_data *)shost->hostdata)->ncb;
8371 	enum spi_signal_type type;
8372 
8373 	switch (np->scsi_mode) {
8374 	case SMODE_SE:
8375 		type = SPI_SIGNAL_SE;
8376 		break;
8377 	case SMODE_HVD:
8378 		type = SPI_SIGNAL_HVD;
8379 		break;
8380 	default:
8381 		type = SPI_SIGNAL_UNKNOWN;
8382 		break;
8383 	}
8384 	spi_signalling(shost) = type;
8385 }
8386 
8387 static struct spi_function_template ncr53c8xx_transport_functions =  {
8388 	.set_period	= ncr53c8xx_set_period,
8389 	.show_period	= 1,
8390 	.set_offset	= ncr53c8xx_set_offset,
8391 	.show_offset	= 1,
8392 	.set_width	= ncr53c8xx_set_width,
8393 	.show_width	= 1,
8394 	.get_signalling	= ncr53c8xx_get_signalling,
8395 };
8396 
8397 int __init ncr53c8xx_init(void)
8398 {
8399 	ncr53c8xx_transport_template = spi_attach_transport(&ncr53c8xx_transport_functions);
8400 	if (!ncr53c8xx_transport_template)
8401 		return -ENODEV;
8402 	return 0;
8403 }
8404 
8405 void ncr53c8xx_exit(void)
8406 {
8407 	spi_release_transport(ncr53c8xx_transport_template);
8408 }
8409