1/******************************************************************************
2**  High Performance device driver for the Symbios 53C896 controller.
3**
4**  Copyright (C) 1998-2001  Gerard Roudier <groudier@free.fr>
5**
6**  This driver also supports all the Symbios 53C8XX controller family,
7**  except 53C810 revisions < 16, 53C825 revisions < 16 and all
8**  revisions of 53C815 controllers.
9**
10**  This driver is based on the Linux port of the FreeBSD ncr driver.
11**
12**  Copyright (C) 1994  Wolfgang Stanglmeier
13**
14**-----------------------------------------------------------------------------
15**
16**  This program is free software; you can redistribute it and/or modify
17**  it under the terms of the GNU General Public License as published by
18**  the Free Software Foundation; either version 2 of the License, or
19**  (at your option) any later version.
20**
21**  This program is distributed in the hope that it will be useful,
22**  but WITHOUT ANY WARRANTY; without even the implied warranty of
23**  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24**  GNU General Public License for more details.
25**
26**  You should have received a copy of the GNU General Public License
27**  along with this program; if not, write to the Free Software
28**  Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29**
30**-----------------------------------------------------------------------------
31**
32**  The Linux port of the FreeBSD ncr driver has been achieved in
33**  november 1995 by:
34**
35**          Gerard Roudier              <groudier@free.fr>
36**
37**  Being given that this driver originates from the FreeBSD version, and
38**  in order to keep synergy on both, any suggested enhancements and corrections
39**  received on Linux are automatically a potential candidate for the FreeBSD
40**  version.
41**
42**  The original driver has been written for 386bsd and FreeBSD by
43**          Wolfgang Stanglmeier        <wolf@cologne.de>
44**          Stefan Esser                <se@mi.Uni-Koeln.de>
45**
46**-----------------------------------------------------------------------------
47**
48**  Major contributions:
49**  --------------------
50**
51**  NVRAM detection and reading.
52**    Copyright (C) 1997 Richard Waltham <dormouse@farsrobt.demon.co.uk>
53**
54*******************************************************************************
55*/
56
57/*
58**	Supported SCSI features:
59**	    Synchronous data transfers
60**	    Wide16 SCSI BUS
61**	    Disconnection/Reselection
62**	    Tagged command queuing
63**	    SCSI Parity checking
64**
65**	Supported NCR/SYMBIOS chips:
66**		53C810A	  (8 bits, Fast 10,	 no rom BIOS)
67**		53C825A	  (Wide,   Fast 10,	 on-board rom BIOS)
68**		53C860	  (8 bits, Fast 20,	 no rom BIOS)
69**		53C875	  (Wide,   Fast 20,	 on-board rom BIOS)
70**		53C876	  (Wide,   Fast 20 Dual, on-board rom BIOS)
71**		53C895	  (Wide,   Fast 40,	 on-board rom BIOS)
72**		53C895A	  (Wide,   Fast 40,	 on-board rom BIOS)
73**		53C896	  (Wide,   Fast 40 Dual, on-board rom BIOS)
74**		53C897	  (Wide,   Fast 40 Dual, on-board rom BIOS)
75**		53C1510D  (Wide,   Fast 40 Dual, on-board rom BIOS)
76**		53C1010	  (Wide,   Fast 80 Dual, on-board rom BIOS)
77**		53C1010_66(Wide,   Fast 80 Dual, on-board rom BIOS, 33/66MHz PCI)
78**
79**	Other features:
80**		Memory mapped IO
81**		Module
82**		Shared IRQ
83*/
84
85/*
86**	Name and version of the driver
87*/
88#define SCSI_NCR_DRIVER_NAME	"sym53c8xx-1.7.3c-20010512"
89
90#define SCSI_NCR_DEBUG_FLAGS	(0)
91
92#define NAME53C		"sym53c"
93#define NAME53C8XX	"sym53c8xx"
94
95/*==========================================================
96**
97**      Include files
98**
99**==========================================================
100*/
101
102#define LinuxVersionCode(v, p, s) (((v)<<16)+((p)<<8)+(s))
103
104#include <linux/module.h>
105
106#include <asm/dma.h>
107#include <asm/io.h>
108#include <asm/system.h>
109#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,17)
110#include <linux/spinlock.h>
111#elif LINUX_VERSION_CODE >= LinuxVersionCode(2,1,93)
112#include <asm/spinlock.h>
113#endif
114#include <linux/delay.h>
115#include <linux/signal.h>
116#include <linux/sched.h>
117#include <linux/errno.h>
118#include <linux/pci.h>
119#include <linux/string.h>
120#include <linux/mm.h>
121#include <linux/ioport.h>
122#include <linux/time.h>
123#include <linux/timer.h>
124#include <linux/stat.h>
125
126#include <linux/version.h>
127#include <linux/blk.h>
128
129#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,35)
130#include <linux/init.h>
131#endif
132
133#ifndef	__init
134#define	__init
135#endif
136#ifndef	__initdata
137#define	__initdata
138#endif
139
140#if LINUX_VERSION_CODE <= LinuxVersionCode(2,1,92)
141#include <linux/bios32.h>
142#endif
143
144#include "scsi.h"
145#include "hosts.h"
146#include "constants.h"
147#include "sd.h"
148
149#include <linux/types.h>
150
151/*
152**	Define BITS_PER_LONG for earlier linux versions.
153*/
154#ifndef	BITS_PER_LONG
155#if (~0UL) == 0xffffffffUL
156#define	BITS_PER_LONG	32
157#else
158#define	BITS_PER_LONG	64
159#endif
160#endif
161
162/*
163**	Define the BSD style u_int32 and u_int64 type.
164**	Are in fact u_int32_t and u_int64_t :-)
165*/
166typedef u32 u_int32;
167typedef u64 u_int64;
168
169#include "sym53c8xx.h"
170
171/*
172**	Donnot compile integrity checking code for Linux-2.3.0
173**	and above since SCSI data structures are not ready yet.
174*/
175/* #if LINUX_VERSION_CODE < LinuxVersionCode(2,3,0) */
176
177#define MIN(a,b)        (((a) < (b)) ? (a) : (b))
178#define MAX(a,b)        (((a) > (b)) ? (a) : (b))
179
180/*
181**	Hmmm... What complex some PCI-HOST bridges actually are,
182**	despite the fact that the PCI specifications are looking
183**	so smart and simple! ;-)
184*/
185#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,47)
186#define SCSI_NCR_DYNAMIC_DMA_MAPPING
187#endif
188
189/*==========================================================
190**
191**	A la VMS/CAM-3 queue management.
192**	Implemented from linux list management.
193**
194**==========================================================
195*/
196
197typedef struct xpt_quehead {
198	struct xpt_quehead *flink;	/* Forward  pointer */
199	struct xpt_quehead *blink;	/* Backward pointer */
200} XPT_QUEHEAD;
201
202#define xpt_que_init(ptr) do { \
203	(ptr)->flink = (ptr); (ptr)->blink = (ptr); \
204} while (0)
205
206static inline void __xpt_que_add(struct xpt_quehead * new,
207	struct xpt_quehead * blink,
208	struct xpt_quehead * flink)
209{
210	flink->blink	= new;
211	new->flink	= flink;
212	new->blink	= blink;
213	blink->flink	= new;
214}
215
216static inline void __xpt_que_del(struct xpt_quehead * blink,
217	struct xpt_quehead * flink)
218{
219	flink->blink = blink;
220	blink->flink = flink;
221}
222
223static inline int xpt_que_empty(struct xpt_quehead *head)
224{
225	return head->flink == head;
226}
227
228static inline void xpt_que_splice(struct xpt_quehead *list,
229	struct xpt_quehead *head)
230{
231	struct xpt_quehead *first = list->flink;
232
233	if (first != list) {
234		struct xpt_quehead *last = list->blink;
235		struct xpt_quehead *at   = head->flink;
236
237		first->blink = head;
238		head->flink  = first;
239
240		last->flink = at;
241		at->blink   = last;
242	}
243}
244
245#define xpt_que_entry(ptr, type, member) \
246	((type *)((char *)(ptr)-(unsigned long)(&((type *)0)->member)))
247
248
249#define xpt_insque(new, pos)		__xpt_que_add(new, pos, (pos)->flink)
250
251#define xpt_remque(el)			__xpt_que_del((el)->blink, (el)->flink)
252
253#define xpt_insque_head(new, head)	__xpt_que_add(new, head, (head)->flink)
254
255static inline struct xpt_quehead *xpt_remque_head(struct xpt_quehead *head)
256{
257	struct xpt_quehead *elem = head->flink;
258
259	if (elem != head)
260		__xpt_que_del(head, elem->flink);
261	else
262		elem = 0;
263	return elem;
264}
265
266#define xpt_insque_tail(new, head)	__xpt_que_add(new, (head)->blink, head)
267
268static inline struct xpt_quehead *xpt_remque_tail(struct xpt_quehead *head)
269{
270	struct xpt_quehead *elem = head->blink;
271
272	if (elem != head)
273		__xpt_que_del(elem->blink, head);
274	else
275		elem = 0;
276	return elem;
277}
278
279/*==========================================================
280**
281**	Configuration and Debugging
282**
283**==========================================================
284*/
285
286/*
287**    SCSI address of this device.
288**    The boot routines should have set it.
289**    If not, use this.
290*/
291
292#ifndef SCSI_NCR_MYADDR
293#define SCSI_NCR_MYADDR      (7)
294#endif
295
296/*
297**    The maximum number of tags per logic unit.
298**    Used only for devices that support tags.
299*/
300
301#ifndef SCSI_NCR_MAX_TAGS
302#define SCSI_NCR_MAX_TAGS    (8)
303#endif
304
305/*
306**    TAGS are actually unlimited (256 tags/lun).
307**    But Linux only supports 255. :)
308*/
309#if	SCSI_NCR_MAX_TAGS > 255
310#define	MAX_TAGS	255
311#else
312#define	MAX_TAGS SCSI_NCR_MAX_TAGS
313#endif
314
315/*
316**    Since the ncr chips only have a 8 bit ALU, we try to be clever
317**    about offset calculation in the TASK TABLE per LUN that is an
318**    array of DWORDS = 4 bytes.
319*/
320#if	MAX_TAGS > (512/4)
321#define MAX_TASKS  (1024/4)
322#elif	MAX_TAGS > (256/4)
323#define MAX_TASKS  (512/4)
324#else
325#define MAX_TASKS  (256/4)
326#endif
327
328/*
329**    This one means 'NO TAG for this job'
330*/
331#define NO_TAG	(256)
332
333/*
334**    Number of targets supported by the driver.
335**    n permits target numbers 0..n-1.
336**    Default is 16, meaning targets #0..#15.
337**    #7 .. is myself.
338*/
339
340#ifdef SCSI_NCR_MAX_TARGET
341#define MAX_TARGET  (SCSI_NCR_MAX_TARGET)
342#else
343#define MAX_TARGET  (16)
344#endif
345
346/*
347**    Number of logic units supported by the driver.
348**    n enables logic unit numbers 0..n-1.
349**    The common SCSI devices require only
350**    one lun, so take 1 as the default.
351*/
352
353#ifdef SCSI_NCR_MAX_LUN
354#define MAX_LUN    64
355#else
356#define MAX_LUN    (1)
357#endif
358
359/*
360**    Asynchronous pre-scaler (ns). Shall be 40 for
361**    the SCSI timings to be compliant.
362*/
363
364#ifndef SCSI_NCR_MIN_ASYNC
365#define SCSI_NCR_MIN_ASYNC (40)
366#endif
367
368/*
369**    The maximum number of jobs scheduled for starting.
370**    We allocate 4 entries more than the value we announce
371**    to the SCSI upper layer. Guess why ! :-)
372*/
373
374#ifdef SCSI_NCR_CAN_QUEUE
375#define MAX_START   (SCSI_NCR_CAN_QUEUE + 4)
376#else
377#define MAX_START   (MAX_TARGET + 7 * MAX_TAGS)
378#endif
379
380/*
381**    We donnot want to allocate more than 1 PAGE for the
382**    the start queue and the done queue. We hard-code entry
383**    size to 8 in order to let cpp do the checking.
384**    Allows 512-4=508 pending IOs for i386 but Linux seems for
385**    now not able to provide the driver with this amount of IOs.
386*/
387#if	MAX_START > PAGE_SIZE/8
388#undef	MAX_START
389#define MAX_START (PAGE_SIZE/8)
390#endif
391
392/*
393**    The maximum number of segments a transfer is split into.
394**    We support up to 127 segments for both read and write.
395*/
396
397#define MAX_SCATTER (SCSI_NCR_MAX_SCATTER)
398#define	SCR_SG_SIZE	(2)
399
400/*
401**	other
402*/
403
404#define NCR_SNOOP_TIMEOUT (1000000)
405
406/*==========================================================
407**
408**	Miscallaneous BSDish defines.
409**
410**==========================================================
411*/
412
413#define u_char		unsigned char
414#define u_short		unsigned short
415#define u_int		unsigned int
416#define u_long		unsigned long
417
418#ifndef bcopy
419#define bcopy(s, d, n)	memcpy((d), (s), (n))
420#endif
421
422#ifndef bzero
423#define bzero(d, n)	memset((d), 0, (n))
424#endif
425
426#ifndef offsetof
427#define offsetof(t, m)	((size_t) (&((t *)0)->m))
428#endif
429
430/*
431**	Simple Wrapper to kernel PCI bus interface.
432**
433**	This wrapper allows to get rid of old kernel PCI interface
434**	and still allows to preserve linux-2.0 compatibilty.
435**	In fact, it is mostly an incomplete emulation of the new
436**	PCI code for pre-2.2 kernels. When kernel-2.0 support
437**	will be dropped, we will just have to remove most of this
438**	code.
439*/
440
441#if LINUX_VERSION_CODE >= LinuxVersionCode(2,2,0)
442
443typedef struct pci_dev *pcidev_t;
444#define PCIDEV_NULL		(0)
445#define PciBusNumber(d)		(d)->bus->number
446#define PciDeviceFn(d)		(d)->devfn
447#define PciVendorId(d)		(d)->vendor
448#define PciDeviceId(d)		(d)->device
449#define PciIrqLine(d)		(d)->irq
450
451static u_long __init
452pci_get_base_cookie(struct pci_dev *pdev, int index)
453{
454	u_long base;
455
456#if LINUX_VERSION_CODE > LinuxVersionCode(2,3,12)
457	base = pdev->resource[index].start;
458#else
459	base = pdev->base_address[index];
460#if BITS_PER_LONG > 32
461	if ((base & 0x7) == 0x4)
462		*base |= (((u_long)pdev->base_address[++index]) << 32);
463#endif
464#endif
465	return (base & ~0x7ul);
466}
467
468static int __init
469pci_get_base_address(struct pci_dev *pdev, int index, u_long *base)
470{
471	u32 tmp;
472#define PCI_BAR_OFFSET(index) (PCI_BASE_ADDRESS_0 + (index<<2))
473
474	pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
475	*base = tmp;
476	++index;
477	if ((tmp & 0x7) == 0x4) {
478#if BITS_PER_LONG > 32
479		pci_read_config_dword(pdev, PCI_BAR_OFFSET(index), &tmp);
480		*base |= (((u_long)tmp) << 32);
481#endif
482		++index;
483	}
484	return index;
485#undef PCI_BAR_OFFSET
486}
487
488#else	/* Incomplete emulation of current PCI code for pre-2.2 kernels */
489
490typedef unsigned int pcidev_t;
491#define PCIDEV_NULL		(~0u)
492#define PciBusNumber(d)		((d)>>8)
493#define PciDeviceFn(d)		((d)&0xff)
494#define __PciDev(busn, devfn)	(((busn)<<8)+(devfn))
495
496#define pci_present pcibios_present
497
498#define pci_read_config_byte(d, w, v) \
499	pcibios_read_config_byte(PciBusNumber(d), PciDeviceFn(d), w, v)
500#define pci_read_config_word(d, w, v) \
501	pcibios_read_config_word(PciBusNumber(d), PciDeviceFn(d), w, v)
502#define pci_read_config_dword(d, w, v) \
503	pcibios_read_config_dword(PciBusNumber(d), PciDeviceFn(d), w, v)
504
505#define pci_write_config_byte(d, w, v) \
506	pcibios_write_config_byte(PciBusNumber(d), PciDeviceFn(d), w, v)
507#define pci_write_config_word(d, w, v) \
508	pcibios_write_config_word(PciBusNumber(d), PciDeviceFn(d), w, v)
509#define pci_write_config_dword(d, w, v) \
510	pcibios_write_config_dword(PciBusNumber(d), PciDeviceFn(d), w, v)
511
512static pcidev_t __init
513pci_find_device(unsigned int vendor, unsigned int device, pcidev_t prev)
514{
515	static unsigned short pci_index;
516	int retv;
517	unsigned char bus_number, device_fn;
518
519	if (prev == PCIDEV_NULL)
520		pci_index = 0;
521	else
522		++pci_index;
523	retv = pcibios_find_device (vendor, device, pci_index,
524				    &bus_number, &device_fn);
525	return retv ? PCIDEV_NULL : __PciDev(bus_number, device_fn);
526}
527
528static u_short __init PciVendorId(pcidev_t dev)
529{
530	u_short vendor_id;
531	pci_read_config_word(dev, PCI_VENDOR_ID, &vendor_id);
532	return vendor_id;
533}
534
535static u_short __init PciDeviceId(pcidev_t dev)
536{
537	u_short device_id;
538	pci_read_config_word(dev, PCI_DEVICE_ID, &device_id);
539	return device_id;
540}
541
542static u_int __init PciIrqLine(pcidev_t dev)
543{
544	u_char irq;
545	pci_read_config_byte(dev, PCI_INTERRUPT_LINE, &irq);
546	return irq;
547}
548
549static int __init
550pci_get_base_address(pcidev_t dev, int offset, u_long *base)
551{
552	u_int32 tmp;
553
554	pci_read_config_dword(dev, PCI_BASE_ADDRESS_0 + offset, &tmp);
555	*base = tmp;
556	offset += sizeof(u_int32);
557	if ((tmp & 0x7) == 0x4) {
558#if BITS_PER_LONG > 32
559		pci_read_config_dword(dev, PCI_BASE_ADDRESS_0 + offset, &tmp);
560		*base |= (((u_long)tmp) << 32);
561#endif
562		offset += sizeof(u_int32);
563	}
564	return offset;
565}
566static u_long __init
567pci_get_base_cookie(struct pci_dev *pdev, int offset)
568{
569	u_long base;
570
571	(void) pci_get_base_address(dev, offset, &base);
572
573	return base;
574}
575
576#endif	/* LINUX_VERSION_CODE >= LinuxVersionCode(2,2,0) */
577
578/* Does not make sense in earlier kernels */
579#if LINUX_VERSION_CODE < LinuxVersionCode(2,4,0)
580#define pci_enable_device(pdev)		(0)
581#endif
582#if LINUX_VERSION_CODE < LinuxVersionCode(2,4,4)
583#define	scsi_set_pci_device(inst, pdev)	(0)
584#endif
585
586/*==========================================================
587**
588**	Debugging tags
589**
590**==========================================================
591*/
592
593#define DEBUG_ALLOC    (0x0001)
594#define DEBUG_PHASE    (0x0002)
595#define DEBUG_QUEUE    (0x0008)
596#define DEBUG_RESULT   (0x0010)
597#define DEBUG_POINTER  (0x0020)
598#define DEBUG_SCRIPT   (0x0040)
599#define DEBUG_TINY     (0x0080)
600#define DEBUG_TIMING   (0x0100)
601#define DEBUG_NEGO     (0x0200)
602#define DEBUG_TAGS     (0x0400)
603#define DEBUG_IC       (0x0800)
604
605/*
606**    Enable/Disable debug messages.
607**    Can be changed at runtime too.
608*/
609
610#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
611static int ncr_debug = SCSI_NCR_DEBUG_FLAGS;
612	#define DEBUG_FLAGS ncr_debug
613#else
614	#define DEBUG_FLAGS	SCSI_NCR_DEBUG_FLAGS
615#endif
616
617/*
618**	SMP threading.
619**
620**	Assuming that SMP systems are generally high end systems and may
621**	use several SCSI adapters, we are using one lock per controller
622**	instead of some global one. For the moment (linux-2.1.95), driver's
623**	entry points are called with the 'io_request_lock' lock held, so:
624**	- We are uselessly loosing a couple of micro-seconds to lock the
625**	  controller data structure.
626**	- But the driver is not broken by design for SMP and so can be
627**	  more resistant to bugs or bad changes in the IO sub-system code.
628**	- A small advantage could be that the interrupt code is grained as
629**	  wished (e.g.: threaded by controller).
630*/
631
632#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,93)
633
634spinlock_t sym53c8xx_lock = SPIN_LOCK_UNLOCKED;
635#define	NCR_LOCK_DRIVER(flags)     spin_lock_irqsave(&sym53c8xx_lock, flags)
636#define	NCR_UNLOCK_DRIVER(flags)   spin_unlock_irqrestore(&sym53c8xx_lock,flags)
637
638#define NCR_INIT_LOCK_NCB(np)      spin_lock_init(&np->smp_lock);
639#define	NCR_LOCK_NCB(np, flags)    spin_lock_irqsave(&np->smp_lock, flags)
640#define	NCR_UNLOCK_NCB(np, flags)  spin_unlock_irqrestore(&np->smp_lock, flags)
641
642#define	NCR_LOCK_SCSI_DONE(np, flags) \
643		spin_lock_irqsave(&io_request_lock, flags)
644#define	NCR_UNLOCK_SCSI_DONE(np, flags) \
645		spin_unlock_irqrestore(&io_request_lock, flags)
646
647#else
648
649#define	NCR_LOCK_DRIVER(flags)     do { save_flags(flags); cli(); } while (0)
650#define	NCR_UNLOCK_DRIVER(flags)   do { restore_flags(flags); } while (0)
651
652#define	NCR_INIT_LOCK_NCB(np)      do { } while (0)
653#define	NCR_LOCK_NCB(np, flags)    do { save_flags(flags); cli(); } while (0)
654#define	NCR_UNLOCK_NCB(np, flags)  do { restore_flags(flags); } while (0)
655
656#define	NCR_LOCK_SCSI_DONE(np, flags)    do {;} while (0)
657#define	NCR_UNLOCK_SCSI_DONE(np, flags)  do {;} while (0)
658
659#endif
660
661/*
662**	Memory mapped IO
663**
664**	Since linux-2.1, we must use ioremap() to map the io memory space.
665**	iounmap() to unmap it. That allows portability.
666**	Linux 1.3.X and 2.0.X allow to remap physical pages addresses greater
667**	than the highest physical memory address to kernel virtual pages with
668**	vremap() / vfree(). That was not portable but worked with i386
669**	architecture.
670*/
671
672#if LINUX_VERSION_CODE < LinuxVersionCode(2,1,0)
673#define ioremap vremap
674#define iounmap vfree
675#endif
676
677#ifdef __sparc__
678#  include <asm/irq.h>
679#  define memcpy_to_pci(a, b, c)	memcpy_toio((a), (b), (c))
680#elif defined(__alpha__)
681#  define memcpy_to_pci(a, b, c)	memcpy_toio((a), (b), (c))
682#else	/* others */
683#  define memcpy_to_pci(a, b, c)	memcpy_toio((a), (b), (c))
684#endif
685
686#ifndef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
687static u_long __init remap_pci_mem(u_long base, u_long size)
688{
689	u_long page_base	= ((u_long) base) & PAGE_MASK;
690	u_long page_offs	= ((u_long) base) - page_base;
691	u_long page_remapped	= (u_long) ioremap(page_base, page_offs+size);
692
693	return page_remapped? (page_remapped + page_offs) : 0UL;
694}
695
696static void __init unmap_pci_mem(u_long vaddr, u_long size)
697{
698	if (vaddr)
699		iounmap((void *) (vaddr & PAGE_MASK));
700}
701
702#endif /* not def SCSI_NCR_PCI_MEM_NOT_SUPPORTED */
703
704/*
705**	Insert a delay in micro-seconds and milli-seconds.
706**	-------------------------------------------------
707**	Under Linux, udelay() is restricted to delay < 1 milli-second.
708**	In fact, it generally works for up to 1 second delay.
709**	Since 2.1.105, the mdelay() function is provided for delays
710**	in milli-seconds.
711**	Under 2.0 kernels, udelay() is an inline function that is very
712**	inaccurate on Pentium processors.
713*/
714
715#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,105)
716#define UDELAY udelay
717#define MDELAY mdelay
718#else
719static void UDELAY(long us) { udelay(us); }
720static void MDELAY(long ms) { while (ms--) UDELAY(1000); }
721#endif
722
723/*
724**	Simple power of two buddy-like allocator
725**	----------------------------------------
726**	This simple code is not intended to be fast, but to provide
727**	power of 2 aligned memory allocations.
728**	Since the SCRIPTS processor only supplies 8 bit arithmetic,
729**	this allocator allows simple and fast address calculations
730**	from the SCRIPTS code. In addition, cache line alignment
731**	is guaranteed for power of 2 cache line size.
732**	Enhanced in linux-2.3.44 to provide a memory pool per pcidev
733**	to support dynamic dma mapping. (I would have preferred a
734**	real bus astraction, btw).
735*/
736
737#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,0)
738#define __GetFreePages(flags, order) __get_free_pages(flags, order)
739#else
740#define __GetFreePages(flags, order) __get_free_pages(flags, order, 0)
741#endif
742
743#define MEMO_SHIFT	4	/* 16 bytes minimum memory chunk */
744#if PAGE_SIZE >= 8192
745#define MEMO_PAGE_ORDER	0	/* 1 PAGE  maximum */
746#else
747#define MEMO_PAGE_ORDER	1	/* 2 PAGES maximum */
748#endif
749#define MEMO_FREE_UNUSED	/* Free unused pages immediately */
750#define MEMO_WARN	1
751#define MEMO_GFP_FLAGS	GFP_ATOMIC
752#define MEMO_CLUSTER_SHIFT	(PAGE_SHIFT+MEMO_PAGE_ORDER)
753#define MEMO_CLUSTER_SIZE	(1UL << MEMO_CLUSTER_SHIFT)
754#define MEMO_CLUSTER_MASK	(MEMO_CLUSTER_SIZE-1)
755
756typedef u_long m_addr_t;	/* Enough bits to bit-hack addresses */
757typedef pcidev_t m_bush_t;	/* Something that addresses DMAable */
758
759typedef struct m_link {		/* Link between free memory chunks */
760	struct m_link *next;
761} m_link_s;
762
763#ifdef	SCSI_NCR_DYNAMIC_DMA_MAPPING
764typedef struct m_vtob {		/* Virtual to Bus address translation */
765	struct m_vtob *next;
766	m_addr_t vaddr;
767	m_addr_t baddr;
768} m_vtob_s;
769#define VTOB_HASH_SHIFT		5
770#define VTOB_HASH_SIZE		(1UL << VTOB_HASH_SHIFT)
771#define VTOB_HASH_MASK		(VTOB_HASH_SIZE-1)
772#define VTOB_HASH_CODE(m)	\
773	((((m_addr_t) (m)) >> MEMO_CLUSTER_SHIFT) & VTOB_HASH_MASK)
774#endif
775
776typedef struct m_pool {		/* Memory pool of a given kind */
777#ifdef	SCSI_NCR_DYNAMIC_DMA_MAPPING
778	m_bush_t bush;
779	m_addr_t (*getp)(struct m_pool *);
780	void (*freep)(struct m_pool *, m_addr_t);
781#define M_GETP()		mp->getp(mp)
782#define M_FREEP(p)		mp->freep(mp, p)
783#define GetPages()		__GetFreePages(MEMO_GFP_FLAGS, MEMO_PAGE_ORDER)
784#define FreePages(p)		free_pages(p, MEMO_PAGE_ORDER)
785	int nump;
786	m_vtob_s *(vtob[VTOB_HASH_SIZE]);
787	struct m_pool *next;
788#else
789#define M_GETP()		__GetFreePages(MEMO_GFP_FLAGS, MEMO_PAGE_ORDER)
790#define M_FREEP(p)		free_pages(p, MEMO_PAGE_ORDER)
791#endif	/* SCSI_NCR_DYNAMIC_DMA_MAPPING */
792	struct m_link h[PAGE_SHIFT-MEMO_SHIFT+MEMO_PAGE_ORDER+1];
793} m_pool_s;
794
795static void *___m_alloc(m_pool_s *mp, int size)
796{
797	int i = 0;
798	int s = (1 << MEMO_SHIFT);
799	int j;
800	m_addr_t a;
801	m_link_s *h = mp->h;
802
803	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
804		return 0;
805
806	while (size > s) {
807		s <<= 1;
808		++i;
809	}
810
811	j = i;
812	while (!h[j].next) {
813		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
814			h[j].next = (m_link_s *) M_GETP();
815			if (h[j].next)
816				h[j].next->next = 0;
817			break;
818		}
819		++j;
820		s <<= 1;
821	}
822	a = (m_addr_t) h[j].next;
823	if (a) {
824		h[j].next = h[j].next->next;
825		while (j > i) {
826			j -= 1;
827			s >>= 1;
828			h[j].next = (m_link_s *) (a+s);
829			h[j].next->next = 0;
830		}
831	}
832#ifdef DEBUG
833	printk("___m_alloc(%d) = %p\n", size, (void *) a);
834#endif
835	return (void *) a;
836}
837
838static void ___m_free(m_pool_s *mp, void *ptr, int size)
839{
840	int i = 0;
841	int s = (1 << MEMO_SHIFT);
842	m_link_s *q;
843	m_addr_t a, b;
844	m_link_s *h = mp->h;
845
846#ifdef DEBUG
847	printk("___m_free(%p, %d)\n", ptr, size);
848#endif
849
850	if (size > (PAGE_SIZE << MEMO_PAGE_ORDER))
851		return;
852
853	while (size > s) {
854		s <<= 1;
855		++i;
856	}
857
858	a = (m_addr_t) ptr;
859
860	while (1) {
861#ifdef MEMO_FREE_UNUSED
862		if (s == (PAGE_SIZE << MEMO_PAGE_ORDER)) {
863			M_FREEP(a);
864			break;
865		}
866#endif
867		b = a ^ s;
868		q = &h[i];
869		while (q->next && q->next != (m_link_s *) b) {
870			q = q->next;
871		}
872		if (!q->next) {
873			((m_link_s *) a)->next = h[i].next;
874			h[i].next = (m_link_s *) a;
875			break;
876		}
877		q->next = q->next->next;
878		a = a & b;
879		s <<= 1;
880		++i;
881	}
882}
883
884static void *__m_calloc2(m_pool_s *mp, int size, char *name, int uflags)
885{
886	void *p;
887
888	p = ___m_alloc(mp, size);
889
890	if (DEBUG_FLAGS & DEBUG_ALLOC)
891		printk ("new %-10s[%4d] @%p.\n", name, size, p);
892
893	if (p)
894		bzero(p, size);
895	else if (uflags & MEMO_WARN)
896		printk (NAME53C8XX ": failed to allocate %s[%d]\n", name, size);
897
898	return p;
899}
900
901#define __m_calloc(mp, s, n)	__m_calloc2(mp, s, n, MEMO_WARN)
902
903static void __m_free(m_pool_s *mp, void *ptr, int size, char *name)
904{
905	if (DEBUG_FLAGS & DEBUG_ALLOC)
906		printk ("freeing %-10s[%4d] @%p.\n", name, size, ptr);
907
908	___m_free(mp, ptr, size);
909
910}
911
912/*
913 * With pci bus iommu support, we use a default pool of unmapped memory
914 * for memory we donnot need to DMA from/to and one pool per pcidev for
915 * memory accessed by the PCI chip. `mp0' is the default not DMAable pool.
916 */
917
918#ifndef	SCSI_NCR_DYNAMIC_DMA_MAPPING
919
920static m_pool_s mp0;
921
922#else
923
924static m_addr_t ___mp0_getp(m_pool_s *mp)
925{
926	m_addr_t m = GetPages();
927	if (m)
928		++mp->nump;
929	return m;
930}
931
932static void ___mp0_freep(m_pool_s *mp, m_addr_t m)
933{
934	FreePages(m);
935	--mp->nump;
936}
937
938static m_pool_s mp0 = {0, ___mp0_getp, ___mp0_freep};
939
940#endif	/* SCSI_NCR_DYNAMIC_DMA_MAPPING */
941
942static void *m_calloc(int size, char *name)
943{
944	u_long flags;
945	void *m;
946	NCR_LOCK_DRIVER(flags);
947	m = __m_calloc(&mp0, size, name);
948	NCR_UNLOCK_DRIVER(flags);
949	return m;
950}
951
952static void m_free(void *ptr, int size, char *name)
953{
954	u_long flags;
955	NCR_LOCK_DRIVER(flags);
956	__m_free(&mp0, ptr, size, name);
957	NCR_UNLOCK_DRIVER(flags);
958}
959
960/*
961 * DMAable pools.
962 */
963
964#ifndef	SCSI_NCR_DYNAMIC_DMA_MAPPING
965
966/* Without pci bus iommu support, all the memory is assumed DMAable */
967
968#define __m_calloc_dma(b, s, n)		m_calloc(s, n)
969#define __m_free_dma(b, p, s, n)	m_free(p, s, n)
970#define __vtobus(b, p)			virt_to_bus(p)
971
972#else
973
974/*
975 * With pci bus iommu support, we maintain one pool per pcidev and a
976 * hashed reverse table for virtual to bus physical address translations.
977 */
978static m_addr_t ___dma_getp(m_pool_s *mp)
979{
980	m_addr_t vp;
981	m_vtob_s *vbp;
982
983	vbp = __m_calloc(&mp0, sizeof(*vbp), "VTOB");
984	if (vbp) {
985		dma_addr_t daddr;
986		vp = (m_addr_t) pci_alloc_consistent(mp->bush,
987						     PAGE_SIZE<<MEMO_PAGE_ORDER,
988						     &daddr);
989		if (vp) {
990			int hc = VTOB_HASH_CODE(vp);
991			vbp->vaddr = vp;
992			vbp->baddr = daddr;
993			vbp->next = mp->vtob[hc];
994			mp->vtob[hc] = vbp;
995			++mp->nump;
996			return vp;
997		}
998		else
999			__m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
1000	}
1001	return 0;
1002}
1003
1004static void ___dma_freep(m_pool_s *mp, m_addr_t m)
1005{
1006	m_vtob_s **vbpp, *vbp;
1007	int hc = VTOB_HASH_CODE(m);
1008
1009	vbpp = &mp->vtob[hc];
1010	while (*vbpp && (*vbpp)->vaddr != m)
1011		vbpp = &(*vbpp)->next;
1012	if (*vbpp) {
1013		vbp = *vbpp;
1014		*vbpp = (*vbpp)->next;
1015		pci_free_consistent(mp->bush, PAGE_SIZE<<MEMO_PAGE_ORDER,
1016				    (void *)vbp->vaddr, (dma_addr_t)vbp->baddr);
1017		__m_free(&mp0, vbp, sizeof(*vbp), "VTOB");
1018		--mp->nump;
1019	}
1020}
1021
1022static inline m_pool_s *___get_dma_pool(m_bush_t bush)
1023{
1024	m_pool_s *mp;
1025	for (mp = mp0.next; mp && mp->bush != bush; mp = mp->next);
1026	return mp;
1027}
1028
1029static m_pool_s *___cre_dma_pool(m_bush_t bush)
1030{
1031	m_pool_s *mp;
1032	mp = __m_calloc(&mp0, sizeof(*mp), "MPOOL");
1033	if (mp) {
1034		bzero(mp, sizeof(*mp));
1035		mp->bush = bush;
1036		mp->getp = ___dma_getp;
1037		mp->freep = ___dma_freep;
1038		mp->next = mp0.next;
1039		mp0.next = mp;
1040	}
1041	return mp;
1042}
1043
1044static void ___del_dma_pool(m_pool_s *p)
1045{
1046	struct m_pool **pp = &mp0.next;
1047
1048	while (*pp && *pp != p)
1049		pp = &(*pp)->next;
1050	if (*pp) {
1051		*pp = (*pp)->next;
1052		__m_free(&mp0, p, sizeof(*p), "MPOOL");
1053	}
1054}
1055
1056static void *__m_calloc_dma(m_bush_t bush, int size, char *name)
1057{
1058	u_long flags;
1059	struct m_pool *mp;
1060	void *m = 0;
1061
1062	NCR_LOCK_DRIVER(flags);
1063	mp = ___get_dma_pool(bush);
1064	if (!mp)
1065		mp = ___cre_dma_pool(bush);
1066	if (mp)
1067		m = __m_calloc(mp, size, name);
1068	if (mp && !mp->nump)
1069		___del_dma_pool(mp);
1070	NCR_UNLOCK_DRIVER(flags);
1071
1072	return m;
1073}
1074
1075static void __m_free_dma(m_bush_t bush, void *m, int size, char *name)
1076{
1077	u_long flags;
1078	struct m_pool *mp;
1079
1080	NCR_LOCK_DRIVER(flags);
1081	mp = ___get_dma_pool(bush);
1082	if (mp)
1083		__m_free(mp, m, size, name);
1084	if (mp && !mp->nump)
1085		___del_dma_pool(mp);
1086	NCR_UNLOCK_DRIVER(flags);
1087}
1088
1089static m_addr_t __vtobus(m_bush_t bush, void *m)
1090{
1091	u_long flags;
1092	m_pool_s *mp;
1093	int hc = VTOB_HASH_CODE(m);
1094	m_vtob_s *vp = 0;
1095	m_addr_t a = ((m_addr_t) m) & ~MEMO_CLUSTER_MASK;
1096
1097	NCR_LOCK_DRIVER(flags);
1098	mp = ___get_dma_pool(bush);
1099	if (mp) {
1100		vp = mp->vtob[hc];
1101		while (vp && (m_addr_t) vp->vaddr != a)
1102			vp = vp->next;
1103	}
1104	NCR_UNLOCK_DRIVER(flags);
1105	return vp ? vp->baddr + (((m_addr_t) m) - a) : 0;
1106}
1107
1108#endif	/* SCSI_NCR_DYNAMIC_DMA_MAPPING */
1109
1110#define _m_calloc_dma(np, s, n)		__m_calloc_dma(np->pdev, s, n)
1111#define _m_free_dma(np, p, s, n)	__m_free_dma(np->pdev, p, s, n)
1112#define m_calloc_dma(s, n)		_m_calloc_dma(np, s, n)
1113#define m_free_dma(p, s, n)		_m_free_dma(np, p, s, n)
1114#define _vtobus(np, p)			__vtobus(np->pdev, p)
1115#define vtobus(p)			_vtobus(np, p)
1116
1117/*
1118 *  Deal with DMA mapping/unmapping.
1119 */
1120
1121#ifndef SCSI_NCR_DYNAMIC_DMA_MAPPING
1122
1123/* Linux versions prior to pci bus iommu kernel interface */
1124
1125#define __unmap_scsi_data(pdev, cmd)	do {; } while (0)
1126#define __map_scsi_single_data(pdev, cmd) (__vtobus(pdev,(cmd)->request_buffer))
1127#define __map_scsi_sg_data(pdev, cmd)	((cmd)->use_sg)
1128#define __sync_scsi_data(pdev, cmd)	do {; } while (0)
1129
1130#define scsi_sg_dma_address(sc)		vtobus((sc)->address)
1131#define scsi_sg_dma_len(sc)		((sc)->length)
1132
1133#else
1134
1135/* Linux version with pci bus iommu kernel interface */
1136
1137/* To keep track of the dma mapping (sg/single) that has been set */
1138#define __data_mapped(cmd)	(cmd)->SCp.phase
1139#define __data_mapping(cmd)	(cmd)->SCp.dma_handle
1140
1141static void __unmap_scsi_data(pcidev_t pdev, Scsi_Cmnd *cmd)
1142{
1143	int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
1144
1145	switch(__data_mapped(cmd)) {
1146	case 2:
1147		pci_unmap_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
1148		break;
1149	case 1:
1150		pci_unmap_page(pdev, __data_mapping(cmd),
1151			       cmd->request_bufflen, dma_dir);
1152		break;
1153	}
1154	__data_mapped(cmd) = 0;
1155}
1156
1157static dma_addr_t __map_scsi_single_data(pcidev_t pdev, Scsi_Cmnd *cmd)
1158{
1159	dma_addr_t mapping;
1160	int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
1161
1162	if (cmd->request_bufflen == 0)
1163		return 0;
1164
1165	mapping = pci_map_page(pdev,
1166			       virt_to_page(cmd->request_buffer),
1167			       ((unsigned long)cmd->request_buffer &
1168				~PAGE_MASK),
1169			       cmd->request_bufflen, dma_dir);
1170	__data_mapped(cmd) = 1;
1171	__data_mapping(cmd) = mapping;
1172
1173	return mapping;
1174}
1175
1176static int __map_scsi_sg_data(pcidev_t pdev, Scsi_Cmnd *cmd)
1177{
1178	int use_sg;
1179	int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
1180
1181	if (cmd->use_sg == 0)
1182		return 0;
1183
1184	use_sg = pci_map_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
1185	__data_mapped(cmd) = 2;
1186	__data_mapping(cmd) = use_sg;
1187
1188	return use_sg;
1189}
1190
1191static void __sync_scsi_data(pcidev_t pdev, Scsi_Cmnd *cmd)
1192{
1193	int dma_dir = scsi_to_pci_dma_dir(cmd->sc_data_direction);
1194
1195	switch(__data_mapped(cmd)) {
1196	case 2:
1197		pci_dma_sync_sg(pdev, cmd->buffer, cmd->use_sg, dma_dir);
1198		break;
1199	case 1:
1200		pci_dma_sync_single(pdev, __data_mapping(cmd),
1201				    cmd->request_bufflen, dma_dir);
1202		break;
1203	}
1204}
1205
1206#define scsi_sg_dma_address(sc)		sg_dma_address(sc)
1207#define scsi_sg_dma_len(sc)		sg_dma_len(sc)
1208
1209#endif	/* SCSI_NCR_DYNAMIC_DMA_MAPPING */
1210
1211#define unmap_scsi_data(np, cmd)	__unmap_scsi_data(np->pdev, cmd)
1212#define map_scsi_single_data(np, cmd)	__map_scsi_single_data(np->pdev, cmd)
1213#define map_scsi_sg_data(np, cmd)	__map_scsi_sg_data(np->pdev, cmd)
1214#define sync_scsi_data(np, cmd)		__sync_scsi_data(np->pdev, cmd)
1215
1216
1217/*
1218 * Print out some buffer.
1219 */
1220static void ncr_print_hex(u_char *p, int n)
1221{
1222	while (n-- > 0)
1223		printk (" %x", *p++);
1224}
1225
1226static void ncr_printl_hex(char *label, u_char *p, int n)
1227{
1228	printk("%s", label);
1229	ncr_print_hex(p, n);
1230	printk (".\n");
1231}
1232
1233/*
1234**	Transfer direction
1235**
1236**	Until some linux kernel version near 2.3.40, low-level scsi
1237**	drivers were not told about data transfer direction.
1238**	We check the existence of this feature that has been expected
1239**	for a _long_ time by all SCSI driver developers by just
1240**	testing against the definition of SCSI_DATA_UNKNOWN. Indeed
1241**	this is a hack, but testing against a kernel version would
1242**	have been a shame. ;-)
1243*/
1244#ifdef	SCSI_DATA_UNKNOWN
1245
1246#define scsi_data_direction(cmd)	(cmd->sc_data_direction)
1247
1248#else
1249
1250#define	SCSI_DATA_UNKNOWN	0
1251#define	SCSI_DATA_WRITE		1
1252#define	SCSI_DATA_READ		2
1253#define	SCSI_DATA_NONE		3
1254
1255static __inline__ int scsi_data_direction(Scsi_Cmnd *cmd)
1256{
1257	int direction;
1258
1259	switch((int) cmd->cmnd[0]) {
1260	case 0x08:  /*	READ(6)				08 */
1261	case 0x28:  /*	READ(10)			28 */
1262	case 0xA8:  /*	READ(12)			A8 */
1263		direction = SCSI_DATA_READ;
1264		break;
1265	case 0x0A:  /*	WRITE(6)			0A */
1266	case 0x2A:  /*	WRITE(10)			2A */
1267	case 0xAA:  /*	WRITE(12)			AA */
1268		direction = SCSI_DATA_WRITE;
1269		break;
1270	default:
1271		direction = SCSI_DATA_UNKNOWN;
1272		break;
1273	}
1274
1275	return direction;
1276}
1277
1278#endif	/* SCSI_DATA_UNKNOWN */
1279
1280/*
1281**	Head of list of NCR boards
1282**
1283**	For kernel version < 1.3.70, host is retrieved by its irq level.
1284**	For later kernels, the internal host control block address
1285**	(struct ncb) is used as device id parameter of the irq stuff.
1286*/
1287
1288static struct Scsi_Host	*first_host = NULL;
1289
1290
1291/*
1292**	/proc directory entry and proc_info function
1293*/
1294#if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
1295static struct proc_dir_entry proc_scsi_sym53c8xx = {
1296    PROC_SCSI_SYM53C8XX, 9, NAME53C8XX,
1297    S_IFDIR | S_IRUGO | S_IXUGO, 2
1298};
1299#endif
1300#ifdef SCSI_NCR_PROC_INFO_SUPPORT
1301static int sym53c8xx_proc_info(char *buffer, char **start, off_t offset,
1302			int length, int hostno, int func);
1303#endif
1304
1305/*
1306**	Driver setup.
1307**
1308**	This structure is initialized from linux config options.
1309**	It can be overridden at boot-up by the boot command line.
1310*/
1311static struct ncr_driver_setup
1312	driver_setup			= SCSI_NCR_DRIVER_SETUP;
1313
1314#ifdef	SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
1315static struct ncr_driver_setup
1316	driver_safe_setup __initdata	= SCSI_NCR_DRIVER_SAFE_SETUP;
1317# ifdef	MODULE
1318char *sym53c8xx = 0;	/* command line passed by insmod */
1319#  if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,30)
1320MODULE_PARM(sym53c8xx, "s");
1321#  endif
1322# endif
1323#endif
1324
1325/*
1326**	Other Linux definitions
1327*/
1328#define SetScsiResult(cmd, h_sts, s_sts) \
1329	cmd->result = (((h_sts) << 16) + ((s_sts) & 0x7f))
1330
1331/* We may have to remind our amnesiac SCSI layer of the reason of the abort */
1332#define SetScsiAbortResult(cmd) SetScsiResult(cmd, DID_ABORT, 0xff)
1333
1334static void sym53c8xx_select_queue_depths(
1335	struct Scsi_Host *host, struct scsi_device *devlist);
1336static void sym53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs);
1337static void sym53c8xx_timeout(unsigned long np);
1338
1339#define initverbose (driver_setup.verbose)
1340#define bootverbose (np->verbose)
1341
1342#ifdef SCSI_NCR_NVRAM_SUPPORT
1343static u_char Tekram_sync[16] __initdata =
1344	{25,31,37,43, 50,62,75,125, 12,15,18,21, 6,7,9,10};
1345#endif /* SCSI_NCR_NVRAM_SUPPORT */
1346
1347/*
1348**	Structures used by sym53c8xx_detect/sym53c8xx_pci_init to
1349**	transmit device configuration to the ncr_attach() function.
1350*/
1351typedef struct {
1352	int	bus;
1353	u_char	device_fn;
1354	u_long	base;
1355	u_long	base_2;
1356	u_long	io_port;
1357	u_long	base_c;
1358	u_long	base_2_c;
1359	int	irq;
1360/* port and reg fields to use INB, OUTB macros */
1361	u_long	base_io;
1362	volatile struct ncr_reg	*reg;
1363} ncr_slot;
1364
1365typedef struct {
1366	int type;
1367#define	SCSI_NCR_SYMBIOS_NVRAM	(1)
1368#define	SCSI_NCR_TEKRAM_NVRAM	(2)
1369#ifdef	SCSI_NCR_NVRAM_SUPPORT
1370	union {
1371		Symbios_nvram Symbios;
1372		Tekram_nvram Tekram;
1373	} data;
1374#endif
1375} ncr_nvram;
1376
1377/*
1378**	Structure used by sym53c8xx_detect/sym53c8xx_pci_init
1379**	to save data on each detected board for ncr_attach().
1380*/
1381typedef struct {
1382	pcidev_t  pdev;
1383	ncr_slot  slot;
1384	ncr_chip  chip;
1385	ncr_nvram *nvram;
1386	u_char host_id;
1387#ifdef	SCSI_NCR_PQS_PDS_SUPPORT
1388	u_char pqs_pds;
1389#endif
1390	int attach_done;
1391} ncr_device;
1392
1393/*==========================================================
1394**
1395**	assert ()
1396**
1397**==========================================================
1398**
1399**	modified copy from 386bsd:/usr/include/sys/assert.h
1400**
1401**----------------------------------------------------------
1402*/
1403
1404#define	assert(expression) { \
1405	if (!(expression)) { \
1406		(void)panic( \
1407			"assertion \"%s\" failed: file \"%s\", line %d\n", \
1408			#expression, \
1409			__FILE__, __LINE__); \
1410	} \
1411}
1412
1413/*==========================================================
1414**
1415**	Command control block states.
1416**
1417**==========================================================
1418*/
1419
1420#define HS_IDLE		(0)
1421#define HS_BUSY		(1)
1422#define HS_NEGOTIATE	(2)	/* sync/wide data transfer*/
1423#define HS_DISCONNECT	(3)	/* Disconnected by target */
1424
1425#define HS_DONEMASK	(0x80)
1426#define HS_COMPLETE	(4|HS_DONEMASK)
1427#define HS_SEL_TIMEOUT	(5|HS_DONEMASK)	/* Selection timeout      */
1428#define HS_RESET	(6|HS_DONEMASK)	/* SCSI reset	          */
1429#define HS_ABORTED	(7|HS_DONEMASK)	/* Transfer aborted       */
1430#define HS_TIMEOUT	(8|HS_DONEMASK)	/* Software timeout       */
1431#define HS_FAIL		(9|HS_DONEMASK)	/* SCSI or PCI bus errors */
1432#define HS_UNEXPECTED	(10|HS_DONEMASK)/* Unexpected disconnect  */
1433
1434#define DSA_INVALID 0xffffffff
1435
1436/*==========================================================
1437**
1438**	Software Interrupt Codes
1439**
1440**==========================================================
1441*/
1442
1443#define	SIR_BAD_STATUS		(1)
1444#define	SIR_SEL_ATN_NO_MSG_OUT	(2)
1445#define	SIR_MSG_RECEIVED	(3)
1446#define	SIR_MSG_WEIRD		(4)
1447#define	SIR_NEGO_FAILED		(5)
1448#define	SIR_NEGO_PROTO		(6)
1449#define	SIR_SCRIPT_STOPPED	(7)
1450#define	SIR_REJECT_TO_SEND	(8)
1451#define	SIR_SWIDE_OVERRUN	(9)
1452#define	SIR_SODL_UNDERRUN	(10)
1453#define	SIR_RESEL_NO_MSG_IN	(11)
1454#define	SIR_RESEL_NO_IDENTIFY	(12)
1455#define	SIR_RESEL_BAD_LUN	(13)
1456#define	SIR_TARGET_SELECTED	(14)
1457#define	SIR_RESEL_BAD_I_T_L	(15)
1458#define	SIR_RESEL_BAD_I_T_L_Q	(16)
1459#define	SIR_ABORT_SENT		(17)
1460#define	SIR_RESEL_ABORTED	(18)
1461#define	SIR_MSG_OUT_DONE	(19)
1462#define	SIR_AUTO_SENSE_DONE	(20)
1463#define	SIR_DUMMY_INTERRUPT	(21)
1464#define	SIR_DATA_OVERRUN	(22)
1465#define	SIR_BAD_PHASE		(23)
1466#define	SIR_MAX			(23)
1467
1468/*==========================================================
1469**
1470**	Extended error bits.
1471**	xerr_status field of struct ccb.
1472**
1473**==========================================================
1474*/
1475
1476#define	XE_EXTRA_DATA	(1)	/* unexpected data phase	 */
1477#define	XE_BAD_PHASE	(2)	/* illegal phase (4/5)		 */
1478#define	XE_PARITY_ERR	(4)	/* unrecovered SCSI parity error */
1479#define XE_SODL_UNRUN   (1<<3)
1480#define XE_SWIDE_OVRUN  (1<<4)
1481
1482/*==========================================================
1483**
1484**	Negotiation status.
1485**	nego_status field	of struct ccb.
1486**
1487**==========================================================
1488*/
1489
1490#define NS_NOCHANGE	(0)
1491#define NS_SYNC		(1)
1492#define NS_WIDE		(2)
1493#define NS_PPR		(4)
1494
1495/*==========================================================
1496**
1497**	"Special features" of targets.
1498**	quirks field		of struct tcb.
1499**	actualquirks field	of struct ccb.
1500**
1501**==========================================================
1502*/
1503
1504#define	QUIRK_AUTOSAVE	(0x01)
1505
1506/*==========================================================
1507**
1508**	Capability bits in Inquire response byte 7.
1509**
1510**==========================================================
1511*/
1512
1513#define	INQ7_QUEUE	(0x02)
1514#define	INQ7_SYNC	(0x10)
1515#define	INQ7_WIDE16	(0x20)
1516
1517/*==========================================================
1518**
1519**	A CCB hashed table is used to retrieve CCB address
1520**	from DSA value.
1521**
1522**==========================================================
1523*/
1524
1525#define CCB_HASH_SHIFT		8
1526#define CCB_HASH_SIZE		(1UL << CCB_HASH_SHIFT)
1527#define CCB_HASH_MASK		(CCB_HASH_SIZE-1)
1528#define CCB_HASH_CODE(dsa)	(((dsa) >> 11) & CCB_HASH_MASK)
1529
1530/*==========================================================
1531**
1532**	Declaration of structs.
1533**
1534**==========================================================
1535*/
1536
1537struct tcb;
1538struct lcb;
1539struct ccb;
1540struct ncb;
1541struct script;
1542
1543typedef struct ncb * ncb_p;
1544typedef struct tcb * tcb_p;
1545typedef struct lcb * lcb_p;
1546typedef struct ccb * ccb_p;
1547
1548struct link {
1549	ncrcmd	l_cmd;
1550	ncrcmd	l_paddr;
1551};
1552
1553struct	usrcmd {
1554	u_long	target;
1555	u_long	lun;
1556	u_long	data;
1557	u_long	cmd;
1558};
1559
1560#define UC_SETSYNC      10
1561#define UC_SETTAGS	11
1562#define UC_SETDEBUG	12
1563#define UC_SETORDER	13
1564#define UC_SETWIDE	14
1565#define UC_SETFLAG	15
1566#define UC_SETVERBOSE	17
1567#define UC_RESETDEV	18
1568#define UC_CLEARDEV	19
1569
1570#define	UF_TRACE	(0x01)
1571#define	UF_NODISC	(0x02)
1572#define	UF_NOSCAN	(0x04)
1573
1574/*========================================================================
1575**
1576**	Declaration of structs:		target control block
1577**
1578**========================================================================
1579*/
1580struct tcb {
1581	/*----------------------------------------------------------------
1582	**	LUN tables.
1583	**	An array of bus addresses is used on reselection by
1584	**	the SCRIPT.
1585	**----------------------------------------------------------------
1586	*/
1587	u_int32		*luntbl;	/* lcbs bus address table	*/
1588	u_int32		b_luntbl;	/* bus address of this table	*/
1589	u_int32		b_lun0;		/* bus address of lun0		*/
1590	lcb_p		l0p;		/* lcb of LUN #0 (normal case)	*/
1591#if MAX_LUN > 1
1592	lcb_p		*lmp;		/* Other lcb's [1..MAX_LUN]	*/
1593#endif
1594	/*----------------------------------------------------------------
1595	**	Target capabilities.
1596	**----------------------------------------------------------------
1597	*/
1598	u_char		inq_done;	/* Target capabilities received	*/
1599	u_char		inq_byte7;	/* Contains these capabilities	*/
1600
1601	/*----------------------------------------------------------------
1602	**	Some flags.
1603	**----------------------------------------------------------------
1604	*/
1605	u_char		to_reset;	/* This target is to be reset	*/
1606
1607	/*----------------------------------------------------------------
1608	**	Pointer to the ccb used for negotiation.
1609	**	Prevent from starting a negotiation for all queued commands
1610	**	when tagged command queuing is enabled.
1611	**----------------------------------------------------------------
1612	*/
1613	ccb_p   nego_cp;
1614
1615	/*----------------------------------------------------------------
1616	**	negotiation of wide and synch transfer and device quirks.
1617	**	sval, wval and uval are read from SCRIPTS and so have alignment
1618	**	constraints.
1619	**----------------------------------------------------------------
1620	*/
1621/*0*/	u_char	uval;
1622/*1*/	u_char	sval;
1623/*2*/	u_char	filler2;
1624/*3*/	u_char	wval;
1625	u_short	period;
1626	u_char	minsync;
1627	u_char	maxoffs;
1628	u_char	quirks;
1629	u_char	widedone;
1630
1631#ifdef	SCSI_NCR_INTEGRITY_CHECKING
1632	u_char ic_min_sync;
1633	u_char ic_max_width;
1634	u_char ic_done;
1635#endif
1636	u_char ic_maximums_set;
1637	u_char ppr_negotiation;
1638
1639	/*----------------------------------------------------------------
1640	**	User settable limits and options.
1641	**	These limits are read from the NVRAM if present.
1642	**----------------------------------------------------------------
1643	*/
1644	u_char	usrsync;
1645	u_char	usrwide;
1646	u_short	usrtags;
1647	u_char	usrflag;
1648};
1649
1650/*========================================================================
1651**
1652**	Declaration of structs:		lun control block
1653**
1654**========================================================================
1655*/
1656struct lcb {
1657	/*----------------------------------------------------------------
1658	**	On reselection, SCRIPTS use this value as a JUMP address
1659	**	after the IDENTIFY has been successfully received.
1660	**	This field is set to 'resel_tag' if TCQ is enabled and
1661	**	to 'resel_notag' if TCQ is disabled.
1662	**	(Must be at zero due to bad lun handling on reselection)
1663	**----------------------------------------------------------------
1664	*/
1665/*0*/	u_int32		resel_task;
1666
1667	/*----------------------------------------------------------------
1668	**	Task table used by the script processor to retrieve the
1669	**	task corresponding to a reselected nexus. The TAG is used
1670	**	as offset to determine the corresponding entry.
1671	**	Each entry contains the associated CCB bus address.
1672	**----------------------------------------------------------------
1673	*/
1674	u_int32		tasktbl_0;	/* Used if TCQ not enabled	*/
1675	u_int32		*tasktbl;
1676	u_int32		b_tasktbl;
1677
1678	/*----------------------------------------------------------------
1679	**	CCB queue management.
1680	**----------------------------------------------------------------
1681	*/
1682	XPT_QUEHEAD	busy_ccbq;	/* Queue of busy CCBs		*/
1683	XPT_QUEHEAD	wait_ccbq;	/* Queue of waiting for IO CCBs	*/
1684	u_short		busyccbs;	/* CCBs busy for this lun	*/
1685	u_short		queuedccbs;	/* CCBs queued to the controller*/
1686	u_short		queuedepth;	/* Queue depth for this lun	*/
1687	u_short		scdev_depth;	/* SCSI device queue depth	*/
1688	u_short		maxnxs;		/* Max possible nexuses		*/
1689
1690	/*----------------------------------------------------------------
1691	**	Control of tagged command queuing.
1692	**	Tags allocation is performed using a circular buffer.
1693	**	This avoids using a loop for tag allocation.
1694	**----------------------------------------------------------------
1695	*/
1696	u_short		ia_tag;		/* Tag allocation index		*/
1697	u_short		if_tag;		/* Tag release index		*/
1698	u_char		*cb_tags;	/* Circular tags buffer		*/
1699	u_char		inq_byte7;	/* Store unit CmdQ capability	*/
1700	u_char		usetags;	/* Command queuing is active	*/
1701	u_char		to_clear;	/* User wants to clear all tasks*/
1702	u_short		maxtags;	/* Max NR of tags asked by user	*/
1703	u_short		numtags;	/* Current number of tags	*/
1704
1705	/*----------------------------------------------------------------
1706	**	QUEUE FULL and ORDERED tag control.
1707	**----------------------------------------------------------------
1708	*/
1709	u_short		num_good;	/* Nr of GOOD since QUEUE FULL	*/
1710	u_short		tags_sum[2];	/* Tags sum counters		*/
1711	u_char		tags_si;	/* Current index to tags sum	*/
1712	u_long		tags_stime;	/* Last time we switch tags_sum	*/
1713};
1714
1715/*========================================================================
1716**
1717**      Declaration of structs: actions for a task.
1718**
1719**========================================================================
1720**
1721**	It is part of the CCB and is called by the scripts processor to
1722**	start or restart the data structure (nexus).
1723**
1724**------------------------------------------------------------------------
1725*/
1726struct action {
1727	u_int32		start;
1728	u_int32		restart;
1729};
1730
1731/*========================================================================
1732**
1733**      Declaration of structs: Phase mismatch context.
1734**
1735**========================================================================
1736**
1737**	It is part of the CCB and is used as parameters for the DATA
1738**	pointer. We need two contexts to handle correctly the SAVED
1739**	DATA POINTER.
1740**
1741**------------------------------------------------------------------------
1742*/
1743struct pm_ctx {
1744	struct scr_tblmove sg;	/* Updated interrupted SG block	*/
1745	u_int32	ret;		/* SCRIPT return address	*/
1746};
1747
1748/*========================================================================
1749**
1750**      Declaration of structs:     global HEADER.
1751**
1752**========================================================================
1753**
1754**	In earlier driver versions, this substructure was copied from the
1755**	ccb to a global address after selection (or reselection) and copied
1756**	back before disconnect. Since we are now using LOAD/STORE DSA
1757**	RELATIVE instructions, the script is able to access directly these
1758**	fields, and so, this header is no more copied.
1759**
1760**------------------------------------------------------------------------
1761*/
1762
1763struct head {
1764	/*----------------------------------------------------------------
1765	**	Start and restart SCRIPTS addresses (must be at 0).
1766	**----------------------------------------------------------------
1767	*/
1768	struct action	go;
1769
1770	/*----------------------------------------------------------------
1771	**	Saved data pointer.
1772	**	Points to the position in the script responsible for the
1773	**	actual transfer of data.
1774	**	It's written after reception of a SAVE_DATA_POINTER message.
1775	**	The goalpointer points after the last transfer command.
1776	**----------------------------------------------------------------
1777	*/
1778	u_int32		savep;
1779	u_int32		lastp;
1780	u_int32		goalp;
1781
1782	/*----------------------------------------------------------------
1783	**	Alternate data pointer.
1784	**	They are copied back to savep/lastp/goalp by the SCRIPTS
1785	**	when the direction is unknown and the device claims data out.
1786	**----------------------------------------------------------------
1787	*/
1788	u_int32		wlastp;
1789	u_int32		wgoalp;
1790
1791	/*----------------------------------------------------------------
1792	**	Status fields.
1793	**----------------------------------------------------------------
1794	*/
1795	u_char		status[4];	/* host status			*/
1796};
1797
1798/*
1799**	LUN control block lookup.
1800**	We use a direct pointer for LUN #0, and a table of pointers
1801**	which is only allocated for devices that support LUN(s) > 0.
1802*/
1803#if MAX_LUN <= 1
1804#define ncr_lp(np, tp, lun) (!lun) ? (tp)->l0p : 0
1805#else
1806#define ncr_lp(np, tp, lun) \
1807	(!lun) ? (tp)->l0p : (tp)->lmp ? (tp)->lmp[(lun)] : 0
1808#endif
1809
1810/*
1811**	The status bytes are used by the host and the script processor.
1812**
1813**	The four bytes (status[4]) are copied to the scratchb register
1814**	(declared as scr0..scr3 in ncr_reg.h) just after the select/reselect,
1815**	and copied back just after disconnecting.
1816**	Inside the script the XX_REG are used.
1817*/
1818
1819/*
1820**	Last four bytes (script)
1821*/
1822#define  QU_REG	scr0
1823#define  HS_REG	scr1
1824#define  HS_PRT	nc_scr1
1825#define  SS_REG	scr2
1826#define  SS_PRT	nc_scr2
1827#define  HF_REG	scr3
1828#define  HF_PRT	nc_scr3
1829
1830/*
1831**	Last four bytes (host)
1832*/
1833#define  actualquirks  phys.header.status[0]
1834#define  host_status   phys.header.status[1]
1835#define  scsi_status   phys.header.status[2]
1836#define  host_flags    phys.header.status[3]
1837
1838/*
1839**	Host flags
1840*/
1841#define HF_IN_PM0	1u
1842#define HF_IN_PM1	(1u<<1)
1843#define HF_ACT_PM	(1u<<2)
1844#define HF_DP_SAVED	(1u<<3)
1845#define HF_AUTO_SENSE	(1u<<4)
1846#define HF_DATA_IN	(1u<<5)
1847#define HF_PM_TO_C	(1u<<6)
1848#define HF_EXT_ERR	(1u<<7)
1849
1850#ifdef SCSI_NCR_IARB_SUPPORT
1851#define HF_HINT_IARB	(1u<<7)
1852#endif
1853
1854/*
1855**	This one is stolen from QU_REG.:)
1856*/
1857#define HF_DATA_ST	(1u<<7)
1858
1859/*==========================================================
1860**
1861**      Declaration of structs:     Data structure block
1862**
1863**==========================================================
1864**
1865**	During execution of a ccb by the script processor,
1866**	the DSA (data structure address) register points
1867**	to this substructure of the ccb.
1868**	This substructure contains the header with
1869**	the script-processor-changable data and
1870**	data blocks for the indirect move commands.
1871**
1872**----------------------------------------------------------
1873*/
1874
1875struct dsb {
1876
1877	/*
1878	**	Header.
1879	*/
1880
1881	struct head	header;
1882
1883	/*
1884	**	Table data for Script
1885	*/
1886
1887	struct scr_tblsel  select;
1888	struct scr_tblmove smsg  ;
1889	struct scr_tblmove smsg_ext ;
1890	struct scr_tblmove cmd   ;
1891	struct scr_tblmove sense ;
1892	struct scr_tblmove wresid;
1893	struct scr_tblmove data [MAX_SCATTER];
1894
1895	/*
1896	**	Phase mismatch contexts.
1897	**	We need two to handle correctly the
1898	**	SAVED DATA POINTER.
1899	*/
1900
1901	struct pm_ctx pm0;
1902	struct pm_ctx pm1;
1903};
1904
1905
1906/*========================================================================
1907**
1908**      Declaration of structs:     Command control block.
1909**
1910**========================================================================
1911*/
1912struct ccb {
1913	/*----------------------------------------------------------------
1914	**	This is the data structure which is pointed by the DSA
1915	**	register when it is executed by the script processor.
1916	**	It must be the first entry.
1917	**----------------------------------------------------------------
1918	*/
1919	struct dsb	phys;
1920
1921	/*----------------------------------------------------------------
1922	**	The general SCSI driver provides a
1923	**	pointer to a control block.
1924	**----------------------------------------------------------------
1925	*/
1926	Scsi_Cmnd	*cmd;		/* SCSI command 		*/
1927	u_char		cdb_buf[16];	/* Copy of CDB			*/
1928	u_char		sense_buf[64];
1929	int		data_len;	/* Total data length		*/
1930	int		segments;	/* Number of SG segments	*/
1931
1932	/*----------------------------------------------------------------
1933	**	Message areas.
1934	**	We prepare a message to be sent after selection.
1935	**	We may use a second one if the command is rescheduled
1936	**	due to CHECK_CONDITION or QUEUE FULL status.
1937	**      Contents are IDENTIFY and SIMPLE_TAG.
1938	**	While negotiating sync or wide transfer,
1939	**	a SDTR or WDTR message is appended.
1940	**----------------------------------------------------------------
1941	*/
1942	u_char		scsi_smsg [12];
1943	u_char		scsi_smsg2[12];
1944
1945	/*----------------------------------------------------------------
1946	**	Miscellaneous status'.
1947	**----------------------------------------------------------------
1948	*/
1949	u_char		nego_status;	/* Negotiation status		*/
1950	u_char		xerr_status;	/* Extended error flags		*/
1951	u_int32		extra_bytes;	/* Extraneous bytes transferred	*/
1952
1953	/*----------------------------------------------------------------
1954	**	Saved info for auto-sense
1955	**----------------------------------------------------------------
1956	*/
1957	u_char		sv_scsi_status;
1958	u_char		sv_xerr_status;
1959
1960	/*----------------------------------------------------------------
1961	**	Other fields.
1962	**----------------------------------------------------------------
1963	*/
1964	u_long		p_ccb;		/* BUS address of this CCB	*/
1965	u_char		sensecmd[6];	/* Sense command		*/
1966	u_char		to_abort;	/* This CCB is to be aborted	*/
1967	u_short		tag;		/* Tag for this transfer	*/
1968					/*  NO_TAG means no tag		*/
1969	u_char		tags_si;	/* Lun tags sum index (0,1)	*/
1970
1971	u_char		target;
1972	u_char		lun;
1973	u_short		queued;
1974	ccb_p		link_ccb;	/* Host adapter CCB chain	*/
1975	ccb_p		link_ccbh;	/* Host adapter CCB hash chain	*/
1976	XPT_QUEHEAD	link_ccbq;	/* Link to unit CCB queue	*/
1977	u_int32		startp;		/* Initial data pointer		*/
1978	u_int32		lastp0;		/* Initial 'lastp'		*/
1979	int		ext_sg;		/* Extreme data pointer, used	*/
1980	int		ext_ofs;	/*  to calculate the residual.	*/
1981	int		resid;
1982};
1983
1984#define CCB_PHYS(cp,lbl)	(cp->p_ccb + offsetof(struct ccb, lbl))
1985
1986
1987/*========================================================================
1988**
1989**      Declaration of structs:     NCR device descriptor
1990**
1991**========================================================================
1992*/
1993struct ncb {
1994	/*----------------------------------------------------------------
1995	**	Idle task and invalid task actions and their bus
1996	**	addresses.
1997	**----------------------------------------------------------------
1998	*/
1999	struct action	idletask;
2000	struct action	notask;
2001	struct action	bad_i_t_l;
2002	struct action	bad_i_t_l_q;
2003	u_long		p_idletask;
2004	u_long		p_notask;
2005	u_long		p_bad_i_t_l;
2006	u_long		p_bad_i_t_l_q;
2007
2008	/*----------------------------------------------------------------
2009	**	Dummy lun table to protect us against target returning bad
2010	**	lun number on reselection.
2011	**----------------------------------------------------------------
2012	*/
2013	u_int32		*badluntbl;	/* Table physical address	*/
2014	u_int32		resel_badlun;	/* SCRIPT handler BUS address	*/
2015
2016	/*----------------------------------------------------------------
2017	**	Bit 32-63 of the on-chip RAM bus address in LE format.
2018	**	The START_RAM64 script loads the MMRS and MMWS from this
2019	**	field.
2020	**----------------------------------------------------------------
2021	*/
2022	u_int32		scr_ram_seg;
2023
2024	/*----------------------------------------------------------------
2025	**	CCBs management queues.
2026	**----------------------------------------------------------------
2027	*/
2028	Scsi_Cmnd	*waiting_list;	/* Commands waiting for a CCB	*/
2029					/*  when lcb is not allocated.	*/
2030	Scsi_Cmnd	*done_list;	/* Commands waiting for done()  */
2031					/* callback to be invoked.      */
2032#if LINUX_VERSION_CODE >= LinuxVersionCode(2,1,93)
2033	spinlock_t	smp_lock;	/* Lock for SMP threading       */
2034#endif
2035
2036	/*----------------------------------------------------------------
2037	**	Chip and controller indentification.
2038	**----------------------------------------------------------------
2039	*/
2040	int		unit;		/* Unit number			*/
2041	char		chip_name[8];	/* Chip name			*/
2042	char		inst_name[16];	/* ncb instance name		*/
2043
2044	/*----------------------------------------------------------------
2045	**	Initial value of some IO register bits.
2046	**	These values are assumed to have been set by BIOS, and may
2047	**	be used for probing adapter implementation differences.
2048	**----------------------------------------------------------------
2049	*/
2050	u_char	sv_scntl0, sv_scntl3, sv_dmode, sv_dcntl, sv_ctest3, sv_ctest4,
2051		sv_ctest5, sv_gpcntl, sv_stest2, sv_stest4, sv_stest1, sv_scntl4;
2052
2053	/*----------------------------------------------------------------
2054	**	Actual initial value of IO register bits used by the
2055	**	driver. They are loaded at initialisation according to
2056	**	features that are to be enabled.
2057	**----------------------------------------------------------------
2058	*/
2059	u_char	rv_scntl0, rv_scntl3, rv_dmode, rv_dcntl, rv_ctest3, rv_ctest4,
2060		rv_ctest5, rv_stest2, rv_ccntl0, rv_ccntl1, rv_scntl4;
2061
2062	/*----------------------------------------------------------------
2063	**	Target data.
2064	**	Target control block bus address array used by the SCRIPT
2065	**	on reselection.
2066	**----------------------------------------------------------------
2067	*/
2068	struct tcb	target[MAX_TARGET];
2069	u_int32		*targtbl;
2070
2071	/*----------------------------------------------------------------
2072	**	Virtual and physical bus addresses of the chip.
2073	**----------------------------------------------------------------
2074	*/
2075#ifndef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
2076	u_long		base_va;	/* MMIO base virtual address	*/
2077	u_long		base2_va;	/* On-chip RAM virtual address	*/
2078#endif
2079	u_long		base_ba;	/* MMIO base bus address	*/
2080	u_long		base_io;	/* IO space base address	*/
2081	u_long		base_ws;	/* (MM)IO window size		*/
2082	u_long		base2_ba;	/* On-chip RAM bus address	*/
2083	u_long		base2_ws;	/* On-chip RAM window size	*/
2084	u_int		irq;		/* IRQ number			*/
2085	volatile			/* Pointer to volatile for 	*/
2086	struct ncr_reg	*reg;		/*  memory mapped IO.		*/
2087
2088	/*----------------------------------------------------------------
2089	**	SCRIPTS virtual and physical bus addresses.
2090	**	'script'  is loaded in the on-chip RAM if present.
2091	**	'scripth' stays in main memory for all chips except the
2092	**	53C895A and 53C896 that provide 8K on-chip RAM.
2093	**----------------------------------------------------------------
2094	*/
2095	struct script	*script0;	/* Copies of script and scripth	*/
2096	struct scripth	*scripth0;	/*  relocated for this ncb.	*/
2097	u_long		p_script;	/* Actual script and scripth	*/
2098	u_long		p_scripth;	/*  bus addresses.		*/
2099	u_long		p_scripth0;
2100
2101	/*----------------------------------------------------------------
2102	**	General controller parameters and configuration.
2103	**----------------------------------------------------------------
2104	*/
2105	pcidev_t	pdev;
2106	u_short		device_id;	/* PCI device id		*/
2107	u_char		revision_id;	/* PCI device revision id	*/
2108	u_char		bus;		/* PCI BUS number		*/
2109	u_char		device_fn;	/* PCI BUS device and function	*/
2110	u_char		myaddr;		/* SCSI id of the adapter	*/
2111	u_char		maxburst;	/* log base 2 of dwords burst	*/
2112	u_char		maxwide;	/* Maximum transfer width	*/
2113	u_char		minsync;	/* Minimum sync period factor	*/
2114	u_char		maxsync;	/* Maximum sync period factor	*/
2115	u_char		maxoffs;	/* Max scsi offset		*/
2116	u_char		maxoffs_st;	/* Max scsi offset in ST mode	*/
2117	u_char		multiplier;	/* Clock multiplier (1,2,4)	*/
2118	u_char		clock_divn;	/* Number of clock divisors	*/
2119	u_long		clock_khz;	/* SCSI clock frequency in KHz	*/
2120	u_int		features;	/* Chip features map		*/
2121
2122	/*----------------------------------------------------------------
2123	**	Range for the PCI clock frequency measurement result
2124	**	that ensures the algorithm used by the driver can be
2125	**	trusted for the SCSI clock frequency measurement.
2126	**	(Assuming a PCI clock frequency of 33 MHz).
2127	**----------------------------------------------------------------
2128	*/
2129	u_int		pciclock_min;
2130	u_int		pciclock_max;
2131
2132	/*----------------------------------------------------------------
2133	**	Start queue management.
2134	**	It is filled up by the host processor and accessed by the
2135	**	SCRIPTS processor in order to start SCSI commands.
2136	**----------------------------------------------------------------
2137	*/
2138	u_long		p_squeue;	/* Start queue BUS address	*/
2139	u_int32		*squeue;	/* Start queue virtual address	*/
2140	u_short		squeueput;	/* Next free slot of the queue	*/
2141	u_short		actccbs;	/* Number of allocated CCBs	*/
2142	u_short		queuedepth;	/* Start queue depth		*/
2143
2144	/*----------------------------------------------------------------
2145	**	Command completion queue.
2146	**	It is the same size as the start queue to avoid overflow.
2147	**----------------------------------------------------------------
2148	*/
2149	u_short		dqueueget;	/* Next position to scan	*/
2150	u_int32		*dqueue;	/* Completion (done) queue	*/
2151
2152	/*----------------------------------------------------------------
2153	**	Timeout handler.
2154	**----------------------------------------------------------------
2155	*/
2156	struct timer_list timer;	/* Timer handler link header	*/
2157	u_long		lasttime;
2158	u_long		settle_time;	/* Resetting the SCSI BUS	*/
2159
2160	/*----------------------------------------------------------------
2161	**	Debugging and profiling.
2162	**----------------------------------------------------------------
2163	*/
2164	struct ncr_reg	regdump;	/* Register dump		*/
2165	u_long		regtime;	/* Time it has been done	*/
2166
2167	/*----------------------------------------------------------------
2168	**	Miscellaneous buffers accessed by the scripts-processor.
2169	**	They shall be DWORD aligned, because they may be read or
2170	**	written with a script command.
2171	**----------------------------------------------------------------
2172	*/
2173	u_char		msgout[12];	/* Buffer for MESSAGE OUT 	*/
2174	u_char		msgin [12];	/* Buffer for MESSAGE IN	*/
2175	u_int32		lastmsg;	/* Last SCSI message sent	*/
2176	u_char		scratch;	/* Scratch for SCSI receive	*/
2177
2178	/*----------------------------------------------------------------
2179	**	Miscellaneous configuration and status parameters.
2180	**----------------------------------------------------------------
2181	*/
2182	u_char		scsi_mode;	/* Current SCSI BUS mode	*/
2183	u_char		order;		/* Tag order to use		*/
2184	u_char		verbose;	/* Verbosity for this controller*/
2185	u_int32		ncr_cache;	/* Used for cache test at init.	*/
2186	u_long		p_ncb;		/* BUS address of this NCB	*/
2187
2188	/*----------------------------------------------------------------
2189	**	CCB lists and queue.
2190	**----------------------------------------------------------------
2191	*/
2192	ccb_p ccbh[CCB_HASH_SIZE];	/* CCB hashed by DSA value	*/
2193	struct ccb	*ccbc;		/* CCB chain			*/
2194	XPT_QUEHEAD	free_ccbq;	/* Queue of available CCBs	*/
2195
2196	/*----------------------------------------------------------------
2197	**	IMMEDIATE ARBITRATION (IARB) control.
2198	**	We keep track in 'last_cp' of the last CCB that has been
2199	**	queued to the SCRIPTS processor and clear 'last_cp' when
2200	**	this CCB completes. If last_cp is not zero at the moment
2201	**	we queue a new CCB, we set a flag in 'last_cp' that is
2202	**	used by the SCRIPTS as a hint for setting IARB.
2203	**	We donnot set more than 'iarb_max' consecutive hints for
2204	**	IARB in order to leave devices a chance to reselect.
2205	**	By the way, any non zero value of 'iarb_max' is unfair. :)
2206	**----------------------------------------------------------------
2207	*/
2208#ifdef SCSI_NCR_IARB_SUPPORT
2209	struct ccb	*last_cp;	/* Last queud CCB used for IARB	*/
2210	u_short		iarb_max;	/* Max. # consecutive IARB hints*/
2211	u_short		iarb_count;	/* Actual # of these hints	*/
2212#endif
2213
2214	/*----------------------------------------------------------------
2215	**	We need the LCB in order to handle disconnections and
2216	**	to count active CCBs for task management. So, we use
2217	**	a unique CCB for LUNs we donnot have the LCB yet.
2218	**	This queue normally should have at most 1 element.
2219	**----------------------------------------------------------------
2220	*/
2221	XPT_QUEHEAD	b0_ccbq;
2222
2223	/*----------------------------------------------------------------
2224	**	We use a different scatter function for 896 rev 1.
2225	**----------------------------------------------------------------
2226	*/
2227	int (*scatter) (ncb_p, ccb_p, Scsi_Cmnd *);
2228
2229	/*----------------------------------------------------------------
2230	**	Command abort handling.
2231	**	We need to synchronize tightly with the SCRIPTS
2232	**	processor in order to handle things correctly.
2233	**----------------------------------------------------------------
2234	*/
2235	u_char		abrt_msg[4];	/* Message to send buffer	*/
2236	struct scr_tblmove abrt_tbl;	/* Table for the MOV of it 	*/
2237	struct scr_tblsel  abrt_sel;	/* Sync params for selection	*/
2238	u_char		istat_sem;	/* Tells the chip to stop (SEM)	*/
2239
2240	/*----------------------------------------------------------------
2241	**	Fields that should be removed or changed.
2242	**----------------------------------------------------------------
2243	*/
2244	struct usrcmd	user;		/* Command from user		*/
2245	volatile u_char	release_stage;	/* Synchronisation stage on release  */
2246
2247	/*----------------------------------------------------------------
2248	**	Fields that are used (primarily) for integrity check
2249	**----------------------------------------------------------------
2250	*/
2251	unsigned char  check_integrity; /* Enable midlayer integ. check on
2252					 * bus scan. */
2253#ifdef	SCSI_NCR_INTEGRITY_CHECKING
2254	unsigned char check_integ_par;	/* Set if par or Init. Det. error
2255					 * used only during integ check */
2256#endif
2257};
2258
2259#define NCB_PHYS(np, lbl)	 (np->p_ncb + offsetof(struct ncb, lbl))
2260#define NCB_SCRIPT_PHYS(np,lbl)	 (np->p_script  + offsetof (struct script, lbl))
2261#define NCB_SCRIPTH_PHYS(np,lbl) (np->p_scripth + offsetof (struct scripth,lbl))
2262#define NCB_SCRIPTH0_PHYS(np,lbl) (np->p_scripth0+offsetof (struct scripth,lbl))
2263
2264/*==========================================================
2265**
2266**
2267**      Script for NCR-Processor.
2268**
2269**	Use ncr_script_fill() to create the variable parts.
2270**	Use ncr_script_copy_and_bind() to make a copy and
2271**	bind to physical addresses.
2272**
2273**
2274**==========================================================
2275**
2276**	We have to know the offsets of all labels before
2277**	we reach them (for forward jumps).
2278**	Therefore we declare a struct here.
2279**	If you make changes inside the script,
2280**	DONT FORGET TO CHANGE THE LENGTHS HERE!
2281**
2282**----------------------------------------------------------
2283*/
2284
2285/*
2286**	Script fragments which are loaded into the on-chip RAM
2287**	of 825A, 875, 876, 895, 895A and 896 chips.
2288*/
2289struct script {
2290	ncrcmd	start		[ 14];
2291	ncrcmd	getjob_begin	[  4];
2292	ncrcmd	getjob_end	[  4];
2293	ncrcmd	select		[  8];
2294	ncrcmd	wf_sel_done	[  2];
2295	ncrcmd	send_ident	[  2];
2296#ifdef SCSI_NCR_IARB_SUPPORT
2297	ncrcmd	select2		[  8];
2298#else
2299	ncrcmd	select2		[  2];
2300#endif
2301	ncrcmd  command		[  2];
2302	ncrcmd  dispatch	[ 28];
2303	ncrcmd  sel_no_cmd	[ 10];
2304	ncrcmd  init		[  6];
2305	ncrcmd  clrack		[  4];
2306	ncrcmd  disp_status	[  4];
2307	ncrcmd  datai_done	[ 26];
2308	ncrcmd  datao_done	[ 12];
2309	ncrcmd  ign_i_w_r_msg	[  4];
2310	ncrcmd  datai_phase	[  2];
2311	ncrcmd  datao_phase	[  4];
2312	ncrcmd  msg_in		[  2];
2313	ncrcmd  msg_in2		[ 10];
2314#ifdef SCSI_NCR_IARB_SUPPORT
2315	ncrcmd  status		[ 14];
2316#else
2317	ncrcmd  status		[ 10];
2318#endif
2319	ncrcmd  complete	[  8];
2320#ifdef SCSI_NCR_PCIQ_MAY_REORDER_WRITES
2321	ncrcmd  complete2	[ 12];
2322#else
2323	ncrcmd  complete2	[ 10];
2324#endif
2325#ifdef SCSI_NCR_PCIQ_SYNC_ON_INTR
2326	ncrcmd	done		[ 18];
2327#else
2328	ncrcmd	done		[ 14];
2329#endif
2330	ncrcmd	done_end	[  2];
2331	ncrcmd  save_dp		[  8];
2332	ncrcmd  restore_dp	[  4];
2333	ncrcmd  disconnect	[ 20];
2334#ifdef SCSI_NCR_IARB_SUPPORT
2335	ncrcmd  idle		[  4];
2336#else
2337	ncrcmd  idle		[  2];
2338#endif
2339#ifdef SCSI_NCR_IARB_SUPPORT
2340	ncrcmd  ungetjob	[  6];
2341#else
2342	ncrcmd  ungetjob	[  4];
2343#endif
2344	ncrcmd	reselect	[  4];
2345	ncrcmd	reselected	[ 20];
2346	ncrcmd	resel_scntl4	[ 30];
2347#if   MAX_TASKS*4 > 512
2348	ncrcmd	resel_tag	[ 18];
2349#elif MAX_TASKS*4 > 256
2350	ncrcmd	resel_tag	[ 12];
2351#else
2352	ncrcmd	resel_tag	[  8];
2353#endif
2354	ncrcmd	resel_go	[  6];
2355	ncrcmd	resel_notag	[  2];
2356	ncrcmd	resel_dsa	[  8];
2357	ncrcmd  data_in		[MAX_SCATTER * SCR_SG_SIZE];
2358	ncrcmd  data_in2	[  4];
2359	ncrcmd  data_out	[MAX_SCATTER * SCR_SG_SIZE];
2360	ncrcmd  data_out2	[  4];
2361	ncrcmd  pm0_data	[ 12];
2362	ncrcmd  pm0_data_out	[  6];
2363	ncrcmd  pm0_data_end	[  6];
2364	ncrcmd  pm1_data	[ 12];
2365	ncrcmd  pm1_data_out	[  6];
2366	ncrcmd  pm1_data_end	[  6];
2367};
2368
2369/*
2370**	Script fragments which stay in main memory for all chips
2371**	except for the 895A and 896 that support 8K on-chip RAM.
2372*/
2373struct scripth {
2374	ncrcmd	start64		[  2];
2375	ncrcmd	no_data		[  2];
2376	ncrcmd	sel_for_abort	[ 18];
2377	ncrcmd	sel_for_abort_1	[  2];
2378	ncrcmd	select_no_atn	[  8];
2379	ncrcmd	wf_sel_done_no_atn [ 4];
2380
2381	ncrcmd	msg_in_etc	[ 14];
2382	ncrcmd	msg_received	[  4];
2383	ncrcmd	msg_weird_seen	[  4];
2384	ncrcmd	msg_extended	[ 20];
2385	ncrcmd  msg_bad		[  6];
2386	ncrcmd	msg_weird	[  4];
2387	ncrcmd	msg_weird1	[  8];
2388
2389	ncrcmd	wdtr_resp	[  6];
2390	ncrcmd	send_wdtr	[  4];
2391	ncrcmd	sdtr_resp	[  6];
2392	ncrcmd	send_sdtr	[  4];
2393	ncrcmd	ppr_resp	[  6];
2394	ncrcmd	send_ppr	[  4];
2395	ncrcmd	nego_bad_phase	[  4];
2396	ncrcmd	msg_out		[  4];
2397	ncrcmd	msg_out_done	[  4];
2398	ncrcmd	data_ovrun	[  2];
2399	ncrcmd	data_ovrun1	[ 22];
2400	ncrcmd	data_ovrun2	[  8];
2401	ncrcmd	abort_resel	[ 16];
2402	ncrcmd	resend_ident	[  4];
2403	ncrcmd	ident_break	[  4];
2404	ncrcmd	ident_break_atn	[  4];
2405	ncrcmd	sdata_in	[  6];
2406	ncrcmd  data_io		[  2];
2407	ncrcmd  data_io_com	[  8];
2408	ncrcmd  data_io_out	[ 12];
2409	ncrcmd	resel_bad_lun	[  4];
2410	ncrcmd	bad_i_t_l	[  4];
2411	ncrcmd	bad_i_t_l_q	[  4];
2412	ncrcmd	bad_status	[  6];
2413	ncrcmd	tweak_pmj	[ 12];
2414	ncrcmd	pm_handle	[ 20];
2415	ncrcmd	pm_handle1	[  4];
2416	ncrcmd	pm_save		[  4];
2417	ncrcmd	pm0_save	[ 14];
2418	ncrcmd	pm1_save	[ 14];
2419
2420	/* WSR handling */
2421#ifdef SYM_DEBUG_PM_WITH_WSR
2422	ncrcmd  pm_wsr_handle	[ 44];
2423#else
2424	ncrcmd  pm_wsr_handle	[ 42];
2425#endif
2426	ncrcmd  wsr_ma_helper	[  4];
2427
2428	/* Data area */
2429	ncrcmd	zero		[  1];
2430	ncrcmd	scratch		[  1];
2431	ncrcmd	scratch1	[  1];
2432	ncrcmd	pm0_data_addr	[  1];
2433	ncrcmd	pm1_data_addr	[  1];
2434	ncrcmd	saved_dsa	[  1];
2435	ncrcmd	saved_drs	[  1];
2436	ncrcmd	done_pos	[  1];
2437	ncrcmd	startpos	[  1];
2438	ncrcmd	targtbl		[  1];
2439	/* End of data area */
2440
2441#ifdef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
2442	ncrcmd	start_ram	[  1];
2443	ncrcmd	script0_ba	[  4];
2444	ncrcmd	start_ram64	[  3];
2445	ncrcmd	script0_ba64	[  3];
2446	ncrcmd	scripth0_ba64	[  6];
2447	ncrcmd	ram_seg64	[  1];
2448#endif
2449	ncrcmd	snooptest	[  6];
2450	ncrcmd	snoopend	[  2];
2451};
2452
2453/*==========================================================
2454**
2455**
2456**      Function headers.
2457**
2458**
2459**==========================================================
2460*/
2461
2462static	ccb_p	ncr_alloc_ccb	(ncb_p np);
2463static	void	ncr_complete	(ncb_p np, ccb_p cp);
2464static	void	ncr_exception	(ncb_p np);
2465static	void	ncr_free_ccb	(ncb_p np, ccb_p cp);
2466static	ccb_p	ncr_ccb_from_dsa(ncb_p np, u_long dsa);
2467static	void	ncr_init_tcb	(ncb_p np, u_char tn);
2468static	lcb_p	ncr_alloc_lcb	(ncb_p np, u_char tn, u_char ln);
2469static	lcb_p	ncr_setup_lcb	(ncb_p np, u_char tn, u_char ln,
2470				 u_char *inq_data);
2471static	void	ncr_getclock	(ncb_p np, int mult);
2472static	u_int	ncr_getpciclock (ncb_p np);
2473static	void	ncr_selectclock	(ncb_p np, u_char scntl3);
2474static	ccb_p	ncr_get_ccb	(ncb_p np, u_char tn, u_char ln);
2475static	void	ncr_init	(ncb_p np, int reset, char * msg, u_long code);
2476static	void	ncr_int_sbmc	(ncb_p np);
2477static	void	ncr_int_par	(ncb_p np, u_short sist);
2478static	void	ncr_int_ma	(ncb_p np);
2479static	void	ncr_int_sir	(ncb_p np);
2480static  void    ncr_int_sto     (ncb_p np);
2481static  void    ncr_int_udc     (ncb_p np);
2482static	void	ncr_negotiate	(ncb_p np, tcb_p tp);
2483static	int	ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr);
2484#ifdef	SCSI_NCR_INTEGRITY_CHECKING
2485static	int	ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr);
2486#endif
2487static	void	ncr_script_copy_and_bind
2488				(ncb_p np, ncrcmd *src, ncrcmd *dst, int len);
2489static  void    ncr_script_fill (struct script * scr, struct scripth * scripth);
2490static	int	ncr_scatter_896R1 (ncb_p np, ccb_p cp, Scsi_Cmnd *cmd);
2491static	int	ncr_scatter	(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd);
2492static	void	ncr_getsync	(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p);
2493static  void    ncr_get_xfer_info(ncb_p np, tcb_p tp, u_char *factor, u_char *offset, u_char *width);
2494static	void	ncr_setsync	(ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer, u_char scntl4);
2495static void 	ncr_set_sync_wide_status (ncb_p np, u_char target);
2496static	void	ncr_setup_tags	(ncb_p np, u_char tn, u_char ln);
2497static	void	ncr_setwide	(ncb_p np, ccb_p cp, u_char wide, u_char ack);
2498static	void	ncr_setsyncwide	(ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer, u_char scntl4, u_char wide);
2499static	int	ncr_show_msg	(u_char * msg);
2500static	void	ncr_print_msg	(ccb_p cp, char *label, u_char * msg);
2501static	int	ncr_snooptest	(ncb_p np);
2502static	void	ncr_timeout	(ncb_p np);
2503static  void    ncr_wakeup      (ncb_p np, u_long code);
2504static  int     ncr_wakeup_done (ncb_p np);
2505static	void	ncr_start_next_ccb (ncb_p np, lcb_p lp, int maxn);
2506static	void	ncr_put_start_queue(ncb_p np, ccb_p cp);
2507static	void	ncr_chip_reset	(ncb_p np);
2508static	void	ncr_soft_reset	(ncb_p np);
2509static	void	ncr_start_reset	(ncb_p np);
2510static	int	ncr_reset_scsi_bus (ncb_p np, int enab_int, int settle_delay);
2511static	int	ncr_compute_residual (ncb_p np, ccb_p cp);
2512
2513#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
2514static	void	ncr_usercmd	(ncb_p np);
2515#endif
2516
2517static int ncr_attach (Scsi_Host_Template *tpnt, int unit, ncr_device *device);
2518static void ncr_free_resources(ncb_p np);
2519
2520static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd);
2521static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd);
2522static void process_waiting_list(ncb_p np, int sts);
2523
2524#define remove_from_waiting_list(np, cmd) \
2525		retrieve_from_waiting_list(1, (np), (cmd))
2526#define requeue_waiting_list(np) process_waiting_list((np), DID_OK)
2527#define reset_waiting_list(np) process_waiting_list((np), DID_RESET)
2528
2529#ifdef SCSI_NCR_NVRAM_SUPPORT
2530static  void	ncr_get_nvram	       (ncr_device *devp, ncr_nvram *nvp);
2531static  int	sym_read_Tekram_nvram  (ncr_slot *np, u_short device_id,
2532				        Tekram_nvram *nvram);
2533static  int	sym_read_Symbios_nvram (ncr_slot *np, Symbios_nvram *nvram);
2534#endif
2535
2536/*==========================================================
2537**
2538**
2539**      Global static data.
2540**
2541**
2542**==========================================================
2543*/
2544
2545static inline char *ncr_name (ncb_p np)
2546{
2547	return np->inst_name;
2548}
2549
2550
2551/*==========================================================
2552**
2553**
2554**      Scripts for NCR-Processor.
2555**
2556**      Use ncr_script_bind for binding to physical addresses.
2557**
2558**
2559**==========================================================
2560**
2561**	NADDR generates a reference to a field of the controller data.
2562**	PADDR generates a reference to another part of the script.
2563**	RADDR generates a reference to a script processor register.
2564**	FADDR generates a reference to a script processor register
2565**		with offset.
2566**
2567**----------------------------------------------------------
2568*/
2569
2570#define	RELOC_SOFTC	0x40000000
2571#define	RELOC_LABEL	0x50000000
2572#define	RELOC_REGISTER	0x60000000
2573#define	RELOC_LABELH	0x80000000
2574#define	RELOC_MASK	0xf0000000
2575
2576#define	NADDR(label)	(RELOC_SOFTC | offsetof(struct ncb, label))
2577#define PADDR(label)    (RELOC_LABEL | offsetof(struct script, label))
2578#define PADDRH(label)   (RELOC_LABELH | offsetof(struct scripth, label))
2579#define	RADDR(label)	(RELOC_REGISTER | REG(label))
2580#define	FADDR(label,ofs)(RELOC_REGISTER | ((REG(label))+(ofs)))
2581#define	KVAR(which)	(RELOC_KVAR | (which))
2582
2583#define SCR_DATA_ZERO	0xf00ff00f
2584
2585#ifdef	RELOC_KVAR
2586#define	SCRIPT_KVAR_JIFFIES	(0)
2587#define	SCRIPT_KVAR_FIRST	SCRIPT_KVAR_JIFFIES
2588#define	SCRIPT_KVAR_LAST	SCRIPT_KVAR_JIFFIES
2589/*
2590 * Kernel variables referenced in the scripts.
2591 * THESE MUST ALL BE ALIGNED TO A 4-BYTE BOUNDARY.
2592 */
2593static void *script_kvars[] __initdata =
2594	{ (void *)&jiffies };
2595#endif
2596
2597static	struct script script0 __initdata = {
2598/*--------------------------< START >-----------------------*/ {
2599	/*
2600	**	This NOP will be patched with LED ON
2601	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
2602	*/
2603	SCR_NO_OP,
2604		0,
2605	/*
2606	**      Clear SIGP.
2607	*/
2608	SCR_FROM_REG (ctest2),
2609		0,
2610
2611	/*
2612	**	Stop here if the C code wants to perform
2613	**	some error recovery procedure manually.
2614	**	(Indicate this by setting SEM in ISTAT)
2615	*/
2616	SCR_FROM_REG (istat),
2617		0,
2618	/*
2619	**	Report to the C code the next position in
2620	**	the start queue the SCRIPTS will schedule.
2621	**	The C code must not change SCRATCHA.
2622	*/
2623	SCR_LOAD_ABS (scratcha, 4),
2624		PADDRH (startpos),
2625	SCR_INT ^ IFTRUE (MASK (SEM, SEM)),
2626		SIR_SCRIPT_STOPPED,
2627
2628	/*
2629	**	Start the next job.
2630	**
2631	**	@DSA	 = start point for this job.
2632	**	SCRATCHA = address of this job in the start queue.
2633	**
2634	**	We will restore startpos with SCRATCHA if we fails the
2635	**	arbitration or if it is the idle job.
2636	**
2637	**	The below GETJOB_BEGIN to GETJOB_END section of SCRIPTS
2638	**	is a critical path. If it is partially executed, it then
2639	**	may happen that the job address is not yet in the DSA
2640	**	and the next queue position points to the next JOB.
2641	*/
2642	SCR_LOAD_ABS (dsa, 4),
2643		PADDRH (startpos),
2644	SCR_LOAD_REL (temp, 4),
2645		4,
2646}/*-------------------------< GETJOB_BEGIN >------------------*/,{
2647	SCR_STORE_ABS (temp, 4),
2648		PADDRH (startpos),
2649	SCR_LOAD_REL (dsa, 4),
2650		0,
2651}/*-------------------------< GETJOB_END >--------------------*/,{
2652	SCR_LOAD_REL (temp, 4),
2653		0,
2654	SCR_RETURN,
2655		0,
2656
2657}/*-------------------------< SELECT >----------------------*/,{
2658	/*
2659	**	DSA	contains the address of a scheduled
2660	**		data structure.
2661	**
2662	**	SCRATCHA contains the address of the start queue
2663	**		entry which points to the next job.
2664	**
2665	**	Set Initiator mode.
2666	**
2667	**	(Target mode is left as an exercise for the reader)
2668	*/
2669
2670	SCR_CLR (SCR_TRG),
2671		0,
2672	/*
2673	**      And try to select this target.
2674	*/
2675	SCR_SEL_TBL_ATN ^ offsetof (struct dsb, select),
2676		PADDR (ungetjob),
2677	/*
2678	**	Now there are 4 possibilities:
2679	**
2680	**	(1) The ncr looses arbitration.
2681	**	This is ok, because it will try again,
2682	**	when the bus becomes idle.
2683	**	(But beware of the timeout function!)
2684	**
2685	**	(2) The ncr is reselected.
2686	**	Then the script processor takes the jump
2687	**	to the RESELECT label.
2688	**
2689	**	(3) The ncr wins arbitration.
2690	**	Then it will execute SCRIPTS instruction until
2691	**	the next instruction that checks SCSI phase.
2692	**	Then will stop and wait for selection to be
2693	**	complete or selection time-out to occur.
2694	**
2695	**	After having won arbitration, the ncr SCRIPTS
2696	**	processor is able to execute instructions while
2697	**	the SCSI core is performing SCSI selection. But
2698	**	some script instruction that is not waiting for
2699	**	a valid phase (or selection timeout) to occur
2700	**	breaks the selection procedure, by probably
2701	**	affecting timing requirements.
2702	**	So we have to wait immediately for the next phase
2703	**	or the selection to complete or time-out.
2704	*/
2705
2706	/*
2707	**      load the savep (saved pointer) into
2708	**      the actual data pointer.
2709	*/
2710	SCR_LOAD_REL (temp, 4),
2711		offsetof (struct ccb, phys.header.savep),
2712	/*
2713	**      Initialize the status registers
2714	*/
2715	SCR_LOAD_REL (scr0, 4),
2716		offsetof (struct ccb, phys.header.status),
2717
2718}/*-------------------------< WF_SEL_DONE >----------------------*/,{
2719	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_OUT)),
2720		SIR_SEL_ATN_NO_MSG_OUT,
2721}/*-------------------------< SEND_IDENT >----------------------*/,{
2722	/*
2723	**	Selection complete.
2724	**	Send the IDENTIFY and SIMPLE_TAG messages
2725	**	(and the M_X_SYNC_REQ / M_X_WIDE_REQ message)
2726	*/
2727	SCR_MOVE_TBL ^ SCR_MSG_OUT,
2728		offsetof (struct dsb, smsg),
2729}/*-------------------------< SELECT2 >----------------------*/,{
2730#ifdef SCSI_NCR_IARB_SUPPORT
2731	/*
2732	**	Set IMMEDIATE ARBITRATION if we have been given
2733	**	a hint to do so. (Some job to do after this one).
2734	*/
2735	SCR_FROM_REG (HF_REG),
2736		0,
2737	SCR_JUMPR ^ IFFALSE (MASK (HF_HINT_IARB, HF_HINT_IARB)),
2738		8,
2739	SCR_REG_REG (scntl1, SCR_OR, IARB),
2740		0,
2741#endif
2742	/*
2743	**	Anticipate the COMMAND phase.
2744	**	This is the PHASE we expect at this point.
2745	*/
2746	SCR_JUMP ^ IFFALSE (WHEN (SCR_COMMAND)),
2747		PADDR (sel_no_cmd),
2748
2749}/*-------------------------< COMMAND >--------------------*/,{
2750	/*
2751	**	... and send the command
2752	*/
2753	SCR_MOVE_TBL ^ SCR_COMMAND,
2754		offsetof (struct dsb, cmd),
2755
2756}/*-----------------------< DISPATCH >----------------------*/,{
2757	/*
2758	**	MSG_IN is the only phase that shall be
2759	**	entered at least once for each (re)selection.
2760	**	So we test it first.
2761	*/
2762	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2763		PADDR (msg_in),
2764	SCR_JUMP ^ IFTRUE (IF (SCR_DATA_OUT)),
2765		PADDR (datao_phase),
2766	SCR_JUMP ^ IFTRUE (IF (SCR_DATA_IN)),
2767		PADDR (datai_phase),
2768	SCR_JUMP ^ IFTRUE (IF (SCR_STATUS)),
2769		PADDR (status),
2770	SCR_JUMP ^ IFTRUE (IF (SCR_COMMAND)),
2771		PADDR (command),
2772	SCR_JUMP ^ IFTRUE (IF (SCR_MSG_OUT)),
2773		PADDRH (msg_out),
2774	/*
2775	 *  Discard as many illegal phases as
2776	 *  required and tell the C code about.
2777	 */
2778	SCR_JUMPR ^ IFFALSE (WHEN (SCR_ILG_OUT)),
2779		16,
2780	SCR_MOVE_ABS (1) ^ SCR_ILG_OUT,
2781		NADDR (scratch),
2782	SCR_JUMPR ^ IFTRUE (WHEN (SCR_ILG_OUT)),
2783		-16,
2784	SCR_JUMPR ^ IFFALSE (WHEN (SCR_ILG_IN)),
2785		16,
2786	SCR_MOVE_ABS (1) ^ SCR_ILG_IN,
2787		NADDR (scratch),
2788	SCR_JUMPR ^ IFTRUE (WHEN (SCR_ILG_IN)),
2789		-16,
2790	SCR_INT,
2791		SIR_BAD_PHASE,
2792	SCR_JUMP,
2793		PADDR (dispatch),
2794}/*---------------------< SEL_NO_CMD >----------------------*/,{
2795	/*
2796	**	The target does not switch to command
2797	**	phase after IDENTIFY has been sent.
2798	**
2799	**	If it stays in MSG OUT phase send it
2800	**	the IDENTIFY again.
2801	*/
2802	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
2803		PADDRH (resend_ident),
2804	/*
2805	**	If target does not switch to MSG IN phase
2806	**	and we sent a negotiation, assert the
2807	**	failure immediately.
2808	*/
2809	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
2810		PADDR (dispatch),
2811	SCR_FROM_REG (HS_REG),
2812		0,
2813	SCR_INT ^ IFTRUE (DATA (HS_NEGOTIATE)),
2814		SIR_NEGO_FAILED,
2815	/*
2816	**	Jump to dispatcher.
2817	*/
2818	SCR_JUMP,
2819		PADDR (dispatch),
2820
2821}/*-------------------------< INIT >------------------------*/,{
2822	/*
2823	**	Wait for the SCSI RESET signal to be
2824	**	inactive before restarting operations,
2825	**	since the chip may hang on SEL_ATN
2826	**	if SCSI RESET is active.
2827	*/
2828	SCR_FROM_REG (sstat0),
2829		0,
2830	SCR_JUMPR ^ IFTRUE (MASK (IRST, IRST)),
2831		-16,
2832	SCR_JUMP,
2833		PADDR (start),
2834}/*-------------------------< CLRACK >----------------------*/,{
2835	/*
2836	**	Terminate possible pending message phase.
2837	*/
2838	SCR_CLR (SCR_ACK),
2839		0,
2840	SCR_JUMP,
2841		PADDR (dispatch),
2842
2843}/*-------------------------< DISP_STATUS >----------------------*/,{
2844	/*
2845	**	Anticipate STATUS phase.
2846	**
2847	**	Does spare 3 SCRIPTS instructions when we have
2848	**	completed the INPUT of the data.
2849	*/
2850	SCR_JUMP ^ IFTRUE (WHEN (SCR_STATUS)),
2851		PADDR (status),
2852	SCR_JUMP,
2853		PADDR (dispatch),
2854
2855}/*-------------------------< DATAI_DONE >-------------------*/,{
2856	/*
2857	 *  If the device wants us to send more data,
2858	 *  we must count the extra bytes.
2859	 */
2860	SCR_JUMP ^ IFTRUE (WHEN (SCR_DATA_IN)),
2861		PADDRH (data_ovrun),
2862	/*
2863	**	If the SWIDE is not full, jump to dispatcher.
2864	**	We anticipate a STATUS phase.
2865	**	If we get later an IGNORE WIDE RESIDUE, we
2866	**	will alias it as a MODIFY DP (-1).
2867	*/
2868	SCR_FROM_REG (scntl2),
2869		0,
2870	SCR_JUMP ^ IFFALSE (MASK (WSR, WSR)),
2871		PADDR (disp_status),
2872	/*
2873	**	The SWIDE is full.
2874	**	Clear this condition.
2875	*/
2876	SCR_REG_REG (scntl2, SCR_OR, WSR),
2877		0,
2878	/*
2879         *	We are expecting an IGNORE RESIDUE message
2880         *	from the device, otherwise we are in data
2881         *	overrun condition. Check against MSG_IN phase.
2882	*/
2883	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
2884		SIR_SWIDE_OVERRUN,
2885	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
2886		PADDR (disp_status),
2887	/*
2888	 *	We are in MSG_IN phase,
2889	 *	Read the first byte of the message.
2890	 *	If it is not an IGNORE RESIDUE message,
2891	 *	signal overrun and jump to message
2892	 *	processing.
2893	 */
2894	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2895		NADDR (msgin[0]),
2896	SCR_INT ^ IFFALSE (DATA (M_IGN_RESIDUE)),
2897		SIR_SWIDE_OVERRUN,
2898	SCR_JUMP ^ IFFALSE (DATA (M_IGN_RESIDUE)),
2899		PADDR (msg_in2),
2900
2901	/*
2902	 *	We got the message we expected.
2903	 *	Read the 2nd byte, and jump to dispatcher.
2904	 */
2905	SCR_CLR (SCR_ACK),
2906		0,
2907	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2908		NADDR (msgin[1]),
2909	SCR_CLR (SCR_ACK),
2910		0,
2911	SCR_JUMP,
2912		PADDR (disp_status),
2913
2914}/*-------------------------< DATAO_DONE >-------------------*/,{
2915	/*
2916	 *  If the device wants us to send more data,
2917	 *  we must count the extra bytes.
2918	 */
2919	SCR_JUMP ^ IFTRUE (WHEN (SCR_DATA_OUT)),
2920		PADDRH (data_ovrun),
2921	/*
2922	**	If the SODL is not full jump to dispatcher.
2923	**	We anticipate a MSG IN phase or a STATUS phase.
2924	*/
2925	SCR_FROM_REG (scntl2),
2926		0,
2927	SCR_JUMP ^ IFFALSE (MASK (WSS, WSS)),
2928		PADDR (disp_status),
2929	/*
2930	**	The SODL is full, clear this condition.
2931	*/
2932	SCR_REG_REG (scntl2, SCR_OR, WSS),
2933		0,
2934	/*
2935	**	And signal a DATA UNDERRUN condition
2936	**	to the C code.
2937	*/
2938	SCR_INT,
2939		SIR_SODL_UNDERRUN,
2940	SCR_JUMP,
2941		PADDR (dispatch),
2942
2943}/*-------------------------< IGN_I_W_R_MSG >--------------*/,{
2944	/*
2945	**	We jump here from the phase mismatch interrupt,
2946	**	When we have a SWIDE and the device has presented
2947	**	a IGNORE WIDE RESIDUE message on the BUS.
2948	**	We just have to throw away this message and then
2949	**	to jump to dispatcher.
2950	*/
2951	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
2952		NADDR (scratch),
2953	/*
2954	**	Clear ACK and jump to dispatcher.
2955	*/
2956	SCR_JUMP,
2957		PADDR (clrack),
2958
2959}/*-------------------------< DATAI_PHASE >------------------*/,{
2960	SCR_RETURN,
2961		0,
2962}/*-------------------------< DATAO_PHASE >------------------*/,{
2963	/*
2964	**	Patch for 53c1010_66 only - to allow A0 part
2965	**	to operate properly in a 33MHz PCI bus.
2966	**
2967	** 	SCR_REG_REG(scntl4, SCR_OR, 0x0c),
2968	**		0,
2969	*/
2970	SCR_NO_OP,
2971		0,
2972	SCR_RETURN,
2973		0,
2974}/*-------------------------< MSG_IN >--------------------*/,{
2975	/*
2976	**	Get the first byte of the message.
2977	**
2978	**	The script processor doesn't negate the
2979	**	ACK signal after this transfer.
2980	*/
2981	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
2982		NADDR (msgin[0]),
2983}/*-------------------------< MSG_IN2 >--------------------*/,{
2984	/*
2985	**	Check first against 1 byte messages
2986	**	that we handle from SCRIPTS.
2987	*/
2988	SCR_JUMP ^ IFTRUE (DATA (M_COMPLETE)),
2989		PADDR (complete),
2990	SCR_JUMP ^ IFTRUE (DATA (M_DISCONNECT)),
2991		PADDR (disconnect),
2992	SCR_JUMP ^ IFTRUE (DATA (M_SAVE_DP)),
2993		PADDR (save_dp),
2994	SCR_JUMP ^ IFTRUE (DATA (M_RESTORE_DP)),
2995		PADDR (restore_dp),
2996	/*
2997	**	We handle all other messages from the
2998	**	C code, so no need to waste on-chip RAM
2999	**	for those ones.
3000	*/
3001	SCR_JUMP,
3002		PADDRH (msg_in_etc),
3003
3004}/*-------------------------< STATUS >--------------------*/,{
3005	/*
3006	**	get the status
3007	*/
3008	SCR_MOVE_ABS (1) ^ SCR_STATUS,
3009		NADDR (scratch),
3010#ifdef SCSI_NCR_IARB_SUPPORT
3011	/*
3012	**	If STATUS is not GOOD, clear IMMEDIATE ARBITRATION,
3013	**	since we may have to tamper the start queue from
3014	**	the C code.
3015	*/
3016	SCR_JUMPR ^ IFTRUE (DATA (S_GOOD)),
3017		8,
3018	SCR_REG_REG (scntl1, SCR_AND, ~IARB),
3019		0,
3020#endif
3021	/*
3022	**	save status to scsi_status.
3023	**	mark as complete.
3024	*/
3025	SCR_TO_REG (SS_REG),
3026		0,
3027	SCR_LOAD_REG (HS_REG, HS_COMPLETE),
3028		0,
3029	/*
3030	**	Anticipate the MESSAGE PHASE for
3031	**	the TASK COMPLETE message.
3032	*/
3033	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_IN)),
3034		PADDR (msg_in),
3035	SCR_JUMP,
3036		PADDR (dispatch),
3037
3038}/*-------------------------< COMPLETE >-----------------*/,{
3039	/*
3040	**	Complete message.
3041	**
3042	**	Copy the data pointer to LASTP in header.
3043	*/
3044	SCR_STORE_REL (temp, 4),
3045		offsetof (struct ccb, phys.header.lastp),
3046	/*
3047	**	When we terminate the cycle by clearing ACK,
3048	**	the target may disconnect immediately.
3049	**
3050	**	We don't want to be told of an
3051	**	"unexpected disconnect",
3052	**	so we disable this feature.
3053	*/
3054	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3055		0,
3056	/*
3057	**	Terminate cycle ...
3058	*/
3059	SCR_CLR (SCR_ACK|SCR_ATN),
3060		0,
3061	/*
3062	**	... and wait for the disconnect.
3063	*/
3064	SCR_WAIT_DISC,
3065		0,
3066}/*-------------------------< COMPLETE2 >-----------------*/,{
3067	/*
3068	**	Save host status to header.
3069	*/
3070	SCR_STORE_REL (scr0, 4),
3071		offsetof (struct ccb, phys.header.status),
3072
3073#ifdef SCSI_NCR_PCIQ_MAY_REORDER_WRITES
3074	/*
3075	**	Some bridges may reorder DMA writes to memory.
3076	**	We donnot want the CPU to deal with completions
3077	**	without all the posted write having been flushed
3078	**	to memory. This DUMMY READ should flush posted
3079	**	buffers prior to the CPU having to deal with
3080	**	completions.
3081	*/
3082	SCR_LOAD_REL (scr0, 4),	/* DUMMY READ */
3083		offsetof (struct ccb, phys.header.status),
3084#endif
3085	/*
3086	**	If command resulted in not GOOD status,
3087	**	call the C code if needed.
3088	*/
3089	SCR_FROM_REG (SS_REG),
3090		0,
3091	SCR_CALL ^ IFFALSE (DATA (S_GOOD)),
3092		PADDRH (bad_status),
3093
3094	/*
3095	**	If we performed an auto-sense, call
3096	**	the C code to synchronyze task aborts
3097	**	with UNIT ATTENTION conditions.
3098	*/
3099	SCR_FROM_REG (HF_REG),
3100		0,
3101	SCR_INT ^ IFTRUE (MASK (HF_AUTO_SENSE, HF_AUTO_SENSE)),
3102		SIR_AUTO_SENSE_DONE,
3103
3104}/*------------------------< DONE >-----------------*/,{
3105#ifdef SCSI_NCR_PCIQ_SYNC_ON_INTR
3106	/*
3107	**	It seems that some bridges flush everything
3108	**	when the INTR line is raised. For these ones,
3109	**	we can just ensure that the INTR line will be
3110	**	raised before each completion. So, if it happens
3111	**	that we have been faster that the CPU, we just
3112	**	have to synchronize with it. A dummy programmed
3113	**	interrupt will do the trick.
3114	**	Note that we overlap at most 1 IO with the CPU
3115	**	in this situation and that the IRQ line must not
3116	**	be shared.
3117	*/
3118	SCR_FROM_REG (istat),
3119		0,
3120	SCR_INT ^ IFTRUE (MASK (INTF, INTF)),
3121		SIR_DUMMY_INTERRUPT,
3122#endif
3123	/*
3124	**	Copy the DSA to the DONE QUEUE and
3125	**	signal completion to the host.
3126	**	If we are interrupted between DONE
3127	**	and DONE_END, we must reset, otherwise
3128	**	the completed CCB will be lost.
3129	*/
3130	SCR_STORE_ABS (dsa, 4),
3131		PADDRH (saved_dsa),
3132	SCR_LOAD_ABS (dsa, 4),
3133		PADDRH (done_pos),
3134	SCR_LOAD_ABS (scratcha, 4),
3135		PADDRH (saved_dsa),
3136	SCR_STORE_REL (scratcha, 4),
3137		0,
3138	/*
3139	**	The instruction below reads the DONE QUEUE next
3140	**	free position from memory.
3141	**	In addition it ensures that all PCI posted writes
3142	**	are flushed and so the DSA value of the done
3143	**	CCB is visible by the CPU before INTFLY is raised.
3144	*/
3145	SCR_LOAD_REL (temp, 4),
3146		4,
3147	SCR_INT_FLY,
3148		0,
3149	SCR_STORE_ABS (temp, 4),
3150		PADDRH (done_pos),
3151}/*------------------------< DONE_END >-----------------*/,{
3152	SCR_JUMP,
3153		PADDR (start),
3154
3155}/*-------------------------< SAVE_DP >------------------*/,{
3156	/*
3157	**	Clear ACK immediately.
3158	**	No need to delay it.
3159	*/
3160	SCR_CLR (SCR_ACK),
3161		0,
3162	/*
3163	**	Keep track we received a SAVE DP, so
3164	**	we will switch to the other PM context
3165	**	on the next PM since the DP may point
3166	**	to the current PM context.
3167	*/
3168	SCR_REG_REG (HF_REG, SCR_OR, HF_DP_SAVED),
3169		0,
3170	/*
3171	**	SAVE_DP message:
3172	**	Copy the data pointer to SAVEP in header.
3173	*/
3174	SCR_STORE_REL (temp, 4),
3175		offsetof (struct ccb, phys.header.savep),
3176	SCR_JUMP,
3177		PADDR (dispatch),
3178}/*-------------------------< RESTORE_DP >---------------*/,{
3179	/*
3180	**	RESTORE_DP message:
3181	**	Copy SAVEP in header to actual data pointer.
3182	*/
3183	SCR_LOAD_REL  (temp, 4),
3184		offsetof (struct ccb, phys.header.savep),
3185	SCR_JUMP,
3186		PADDR (clrack),
3187
3188}/*-------------------------< DISCONNECT >---------------*/,{
3189	/*
3190	**	DISCONNECTing  ...
3191	**
3192	**	disable the "unexpected disconnect" feature,
3193	**	and remove the ACK signal.
3194	*/
3195	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3196		0,
3197	SCR_CLR (SCR_ACK|SCR_ATN),
3198		0,
3199	/*
3200	**	Wait for the disconnect.
3201	*/
3202	SCR_WAIT_DISC,
3203		0,
3204	/*
3205	**	Status is: DISCONNECTED.
3206	*/
3207	SCR_LOAD_REG (HS_REG, HS_DISCONNECT),
3208		0,
3209	/*
3210	**	Save host status to header.
3211	*/
3212	SCR_STORE_REL (scr0, 4),
3213		offsetof (struct ccb, phys.header.status),
3214	/*
3215	**	If QUIRK_AUTOSAVE is set,
3216	**	do an "save pointer" operation.
3217	*/
3218	SCR_FROM_REG (QU_REG),
3219		0,
3220	SCR_JUMP ^ IFFALSE (MASK (QUIRK_AUTOSAVE, QUIRK_AUTOSAVE)),
3221		PADDR (start),
3222	/*
3223	**	like SAVE_DP message:
3224	**	Remember we saved the data pointer.
3225	**	Copy data pointer to SAVEP in header.
3226	*/
3227	SCR_REG_REG (HF_REG, SCR_OR, HF_DP_SAVED),
3228		0,
3229	SCR_STORE_REL (temp, 4),
3230		offsetof (struct ccb, phys.header.savep),
3231	SCR_JUMP,
3232		PADDR (start),
3233
3234}/*-------------------------< IDLE >------------------------*/,{
3235	/*
3236	**	Nothing to do?
3237	**	Wait for reselect.
3238	**	This NOP will be patched with LED OFF
3239	**	SCR_REG_REG (gpreg, SCR_OR, 0x01)
3240	*/
3241	SCR_NO_OP,
3242		0,
3243#ifdef SCSI_NCR_IARB_SUPPORT
3244	SCR_JUMPR,
3245		8,
3246#endif
3247}/*-------------------------< UNGETJOB >-----------------*/,{
3248#ifdef SCSI_NCR_IARB_SUPPORT
3249	/*
3250	**	Set IMMEDIATE ARBITRATION, for the next time.
3251	**	This will give us better chance to win arbitration
3252	**	for the job we just wanted to do.
3253	*/
3254	SCR_REG_REG (scntl1, SCR_OR, IARB),
3255		0,
3256#endif
3257	/*
3258	**	We are not able to restart the SCRIPTS if we are
3259	**	interrupted and these instruction haven't been
3260	**	all executed. BTW, this is very unlikely to
3261	**	happen, but we check that from the C code.
3262	*/
3263	SCR_LOAD_REG (dsa, 0xff),
3264		0,
3265	SCR_STORE_ABS (scratcha, 4),
3266		PADDRH (startpos),
3267}/*-------------------------< RESELECT >--------------------*/,{
3268	/*
3269	**	make the host status invalid.
3270	*/
3271	SCR_CLR (SCR_TRG),
3272		0,
3273	/*
3274	**	Sleep waiting for a reselection.
3275	**	If SIGP is set, special treatment.
3276	**
3277	**	Zu allem bereit ..
3278	*/
3279	SCR_WAIT_RESEL,
3280		PADDR(start),
3281}/*-------------------------< RESELECTED >------------------*/,{
3282	/*
3283	**	This NOP will be patched with LED ON
3284	**	SCR_REG_REG (gpreg, SCR_AND, 0xfe)
3285	*/
3286	SCR_NO_OP,
3287		0,
3288	/*
3289	**      load the target id into the sdid
3290	*/
3291	SCR_REG_SFBR (ssid, SCR_AND, 0x8F),
3292		0,
3293	SCR_TO_REG (sdid),
3294		0,
3295	/*
3296	**	load the target control block address
3297	*/
3298	SCR_LOAD_ABS (dsa, 4),
3299		PADDRH (targtbl),
3300	SCR_SFBR_REG (dsa, SCR_SHL, 0),
3301		0,
3302	SCR_REG_REG (dsa, SCR_SHL, 0),
3303		0,
3304	SCR_REG_REG (dsa, SCR_AND, 0x3c),
3305		0,
3306	SCR_LOAD_REL (dsa, 4),
3307		0,
3308	/*
3309	**	Load the synchronous transfer registers.
3310	*/
3311	SCR_LOAD_REL (scntl3, 1),
3312		offsetof(struct tcb, wval),
3313	SCR_LOAD_REL (sxfer, 1),
3314		offsetof(struct tcb, sval),
3315}/*-------------------------< RESEL_SCNTL4 >------------------*/,{
3316	/*
3317	**	Write with uval value. Patch if device
3318	**	does not support Ultra3.
3319	**
3320	**	SCR_LOAD_REL (scntl4, 1),
3321	**		offsetof(struct tcb, uval),
3322	*/
3323
3324	SCR_NO_OP,
3325		0,
3326        /*
3327         *  We expect MESSAGE IN phase.
3328         *  If not, get help from the C code.
3329         */
3330	SCR_INT ^ IFFALSE (WHEN (SCR_MSG_IN)),
3331		SIR_RESEL_NO_MSG_IN,
3332	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3333		NADDR (msgin),
3334
3335	/*
3336	 *  If IDENTIFY LUN #0, use a faster path
3337	 *  to find the LCB structure.
3338	 */
3339	SCR_JUMPR ^ IFTRUE (MASK (0x80, 0xbf)),
3340		56,
3341	/*
3342	 *  If message isn't an IDENTIFY,
3343	 *  tell the C code about.
3344	 */
3345	SCR_INT ^ IFFALSE (MASK (0x80, 0x80)),
3346		SIR_RESEL_NO_IDENTIFY,
3347	/*
3348	 *  It is an IDENTIFY message,
3349	 *  Load the LUN control block address.
3350	 */
3351	SCR_LOAD_REL (dsa, 4),
3352		offsetof(struct tcb, b_luntbl),
3353	SCR_SFBR_REG (dsa, SCR_SHL, 0),
3354		0,
3355	SCR_REG_REG (dsa, SCR_SHL, 0),
3356		0,
3357	SCR_REG_REG (dsa, SCR_AND, 0xfc),
3358		0,
3359	SCR_LOAD_REL (dsa, 4),
3360		0,
3361	SCR_JUMPR,
3362		8,
3363	/*
3364	**	LUN 0 special case (but usual one :))
3365	*/
3366	SCR_LOAD_REL (dsa, 4),
3367		offsetof(struct tcb, b_lun0),
3368
3369	/*
3370	**	Load the reselect task action for this LUN.
3371	**	Load the tasks DSA array for this LUN.
3372	**	Call the action.
3373	*/
3374	SCR_LOAD_REL (temp, 4),
3375		offsetof(struct lcb, resel_task),
3376	SCR_LOAD_REL (dsa, 4),
3377		offsetof(struct lcb, b_tasktbl),
3378	SCR_RETURN,
3379		0,
3380}/*-------------------------< RESEL_TAG >-------------------*/,{
3381	/*
3382	**	ACK the IDENTIFY or TAG previously received
3383	*/
3384
3385	SCR_CLR (SCR_ACK),
3386		0,
3387	/*
3388	**	Read IDENTIFY + SIMPLE + TAG using a single MOVE.
3389	**	Agressive optimization, is'nt it?
3390	**	No need to test the SIMPLE TAG message, since the
3391	**	driver only supports conformant devices for tags. ;-)
3392	*/
3393	SCR_MOVE_ABS (2) ^ SCR_MSG_IN,
3394		NADDR (msgin),
3395	/*
3396	**	Read the TAG from the SIDL.
3397	**	Still an aggressive optimization. ;-)
3398	**	Compute the CCB indirect jump address which
3399	**	is (#TAG*2 & 0xfc) due to tag numbering using
3400	**	1,3,5..MAXTAGS*2+1 actual values.
3401	*/
3402	SCR_REG_SFBR (sidl, SCR_SHL, 0),
3403		0,
3404#if MAX_TASKS*4 > 512
3405	SCR_JUMPR ^ IFFALSE (CARRYSET),
3406		8,
3407	SCR_REG_REG (dsa1, SCR_OR, 2),
3408		0,
3409	SCR_REG_REG (sfbr, SCR_SHL, 0),
3410		0,
3411	SCR_JUMPR ^ IFFALSE (CARRYSET),
3412		8,
3413	SCR_REG_REG (dsa1, SCR_OR, 1),
3414		0,
3415#elif MAX_TASKS*4 > 256
3416	SCR_JUMPR ^ IFFALSE (CARRYSET),
3417		8,
3418	SCR_REG_REG (dsa1, SCR_OR, 1),
3419		0,
3420#endif
3421	/*
3422	**	Retrieve the DSA of this task.
3423	**	JUMP indirectly to the restart point of the CCB.
3424	*/
3425	SCR_SFBR_REG (dsa, SCR_AND, 0xfc),
3426		0,
3427}/*-------------------------< RESEL_GO >-------------------*/,{
3428	SCR_LOAD_REL (dsa, 4),
3429		0,
3430	SCR_LOAD_REL (temp, 4),
3431		offsetof(struct ccb, phys.header.go.restart),
3432	SCR_RETURN,
3433		0,
3434	/* In normal situations we branch to RESEL_DSA */
3435}/*-------------------------< RESEL_NOTAG >-------------------*/,{
3436	/*
3437	**	JUMP indirectly to the restart point of the CCB.
3438	*/
3439	SCR_JUMP,
3440		PADDR (resel_go),
3441
3442}/*-------------------------< RESEL_DSA >-------------------*/,{
3443	/*
3444	**	Ack the IDENTIFY or TAG previously received.
3445	*/
3446	SCR_CLR (SCR_ACK),
3447		0,
3448	/*
3449	**      load the savep (saved pointer) into
3450	**      the actual data pointer.
3451	*/
3452	SCR_LOAD_REL (temp, 4),
3453		offsetof (struct ccb, phys.header.savep),
3454	/*
3455	**      Initialize the status registers
3456	*/
3457	SCR_LOAD_REL (scr0, 4),
3458		offsetof (struct ccb, phys.header.status),
3459	/*
3460	**	Jump to dispatcher.
3461	*/
3462	SCR_JUMP,
3463		PADDR (dispatch),
3464
3465}/*-------------------------< DATA_IN >--------------------*/,{
3466/*
3467**	Because the size depends on the
3468**	#define MAX_SCATTER parameter,
3469**	it is filled in at runtime.
3470**
3471**  ##===========< i=0; i<MAX_SCATTER >=========
3472**  ||	SCR_CHMOV_TBL ^ SCR_DATA_IN,
3473**  ||		offsetof (struct dsb, data[ i]),
3474**  ##==========================================
3475**
3476**---------------------------------------------------------
3477*/
34780
3479}/*-------------------------< DATA_IN2 >-------------------*/,{
3480	SCR_CALL,
3481		PADDR (datai_done),
3482	SCR_JUMP,
3483		PADDRH (data_ovrun),
3484}/*-------------------------< DATA_OUT >--------------------*/,{
3485/*
3486**	Because the size depends on the
3487**	#define MAX_SCATTER parameter,
3488**	it is filled in at runtime.
3489**
3490**  ##===========< i=0; i<MAX_SCATTER >=========
3491**  ||	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
3492**  ||		offsetof (struct dsb, data[ i]),
3493**  ##==========================================
3494**
3495**---------------------------------------------------------
3496*/
34970
3498}/*-------------------------< DATA_OUT2 >-------------------*/,{
3499	SCR_CALL,
3500		PADDR (datao_done),
3501	SCR_JUMP,
3502		PADDRH (data_ovrun),
3503
3504}/*-------------------------< PM0_DATA >--------------------*/,{
3505	/*
3506	**	Read our host flags to SFBR, so we will be able
3507	**	to check against the data direction we expect.
3508	*/
3509	SCR_FROM_REG (HF_REG),
3510		0,
3511	/*
3512	**	Check against actual DATA PHASE.
3513	*/
3514	SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
3515		PADDR (pm0_data_out),
3516	/*
3517	**	Actual phase is DATA IN.
3518	**	Check against expected direction.
3519	*/
3520	SCR_JUMP ^ IFFALSE (MASK (HF_DATA_IN, HF_DATA_IN)),
3521		PADDRH (data_ovrun),
3522	/*
3523	**	Keep track we are moving data from the
3524	**	PM0 DATA mini-script.
3525	*/
3526	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM0),
3527		0,
3528	/*
3529	**	Move the data to memory.
3530	*/
3531	SCR_CHMOV_TBL ^ SCR_DATA_IN,
3532		offsetof (struct ccb, phys.pm0.sg),
3533	SCR_JUMP,
3534		PADDR (pm0_data_end),
3535}/*-------------------------< PM0_DATA_OUT >----------------*/,{
3536	/*
3537	**	Actual phase is DATA OUT.
3538	**	Check against expected direction.
3539	*/
3540	SCR_JUMP ^ IFTRUE (MASK (HF_DATA_IN, HF_DATA_IN)),
3541		PADDRH (data_ovrun),
3542	/*
3543	**	Keep track we are moving data from the
3544	**	PM0 DATA mini-script.
3545	*/
3546	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM0),
3547		0,
3548	/*
3549	**	Move the data from memory.
3550	*/
3551	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
3552		offsetof (struct ccb, phys.pm0.sg),
3553}/*-------------------------< PM0_DATA_END >----------------*/,{
3554	/*
3555	**	Clear the flag that told we were moving
3556	**	data from the PM0 DATA mini-script.
3557	*/
3558	SCR_REG_REG (HF_REG, SCR_AND, (~HF_IN_PM0)),
3559		0,
3560	/*
3561	**	Return to the previous DATA script which
3562	**	is guaranteed by design (if no bug) to be
3563	**	the main DATA script for this transfer.
3564	*/
3565	SCR_LOAD_REL (temp, 4),
3566		offsetof (struct ccb, phys.pm0.ret),
3567	SCR_RETURN,
3568		0,
3569}/*-------------------------< PM1_DATA >--------------------*/,{
3570	/*
3571	**	Read our host flags to SFBR, so we will be able
3572	**	to check against the data direction we expect.
3573	*/
3574	SCR_FROM_REG (HF_REG),
3575		0,
3576	/*
3577	**	Check against actual DATA PHASE.
3578	*/
3579	SCR_JUMP ^ IFFALSE (WHEN (SCR_DATA_IN)),
3580		PADDR (pm1_data_out),
3581	/*
3582	**	Actual phase is DATA IN.
3583	**	Check against expected direction.
3584	*/
3585	SCR_JUMP ^ IFFALSE (MASK (HF_DATA_IN, HF_DATA_IN)),
3586		PADDRH (data_ovrun),
3587	/*
3588	**	Keep track we are moving data from the
3589	**	PM1 DATA mini-script.
3590	*/
3591	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM1),
3592		0,
3593	/*
3594	**	Move the data to memory.
3595	*/
3596	SCR_CHMOV_TBL ^ SCR_DATA_IN,
3597		offsetof (struct ccb, phys.pm1.sg),
3598	SCR_JUMP,
3599		PADDR (pm1_data_end),
3600}/*-------------------------< PM1_DATA_OUT >----------------*/,{
3601	/*
3602	**	Actual phase is DATA OUT.
3603	**	Check against expected direction.
3604	*/
3605	SCR_JUMP ^ IFTRUE (MASK (HF_DATA_IN, HF_DATA_IN)),
3606		PADDRH (data_ovrun),
3607	/*
3608	**	Keep track we are moving data from the
3609	**	PM1 DATA mini-script.
3610	*/
3611	SCR_REG_REG (HF_REG, SCR_OR, HF_IN_PM1),
3612		0,
3613	/*
3614	**	Move the data from memory.
3615	*/
3616	SCR_CHMOV_TBL ^ SCR_DATA_OUT,
3617		offsetof (struct ccb, phys.pm1.sg),
3618}/*-------------------------< PM1_DATA_END >----------------*/,{
3619	/*
3620	**	Clear the flag that told we were moving
3621	**	data from the PM1 DATA mini-script.
3622	*/
3623	SCR_REG_REG (HF_REG, SCR_AND, (~HF_IN_PM1)),
3624		0,
3625	/*
3626	**	Return to the previous DATA script which
3627	**	is guaranteed by design (if no bug) to be
3628	**	the main DATA script for this transfer.
3629	*/
3630	SCR_LOAD_REL (temp, 4),
3631		offsetof (struct ccb, phys.pm1.ret),
3632	SCR_RETURN,
3633		0,
3634}/*---------------------------------------------------------*/
3635};
3636
3637
3638static	struct scripth scripth0 __initdata = {
3639/*------------------------< START64 >-----------------------*/{
3640	/*
3641	**	SCRIPT entry point for the 895A and the 896.
3642	**	For now, there is no specific stuff for that
3643	**	chip at this point, but this may come.
3644	*/
3645	SCR_JUMP,
3646		PADDR (init),
3647}/*-------------------------< NO_DATA >-------------------*/,{
3648	SCR_JUMP,
3649		PADDRH (data_ovrun),
3650}/*-----------------------< SEL_FOR_ABORT >------------------*/,{
3651	/*
3652	**	We are jumped here by the C code, if we have
3653	**	some target to reset or some disconnected
3654	**	job to abort. Since error recovery is a serious
3655	**	busyness, we will really reset the SCSI BUS, if
3656	**	case of a SCSI interrupt occuring in this path.
3657	*/
3658
3659	/*
3660	**	Set initiator mode.
3661	*/
3662	SCR_CLR (SCR_TRG),
3663		0,
3664	/*
3665	**      And try to select this target.
3666	*/
3667	SCR_SEL_TBL_ATN ^ offsetof (struct ncb, abrt_sel),
3668		PADDR (reselect),
3669
3670	/*
3671	**	Wait for the selection to complete or
3672	**	the selection to time out.
3673	*/
3674	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3675		-8,
3676	/*
3677	**	Call the C code.
3678	*/
3679	SCR_INT,
3680		SIR_TARGET_SELECTED,
3681	/*
3682	**	The C code should let us continue here.
3683	**	Send the 'kiss of death' message.
3684	**	We expect an immediate disconnect once
3685	**	the target has eaten the message.
3686	*/
3687	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
3688		0,
3689	SCR_MOVE_TBL ^ SCR_MSG_OUT,
3690		offsetof (struct ncb, abrt_tbl),
3691	SCR_CLR (SCR_ACK|SCR_ATN),
3692		0,
3693	SCR_WAIT_DISC,
3694		0,
3695	/*
3696	**	Tell the C code that we are done.
3697	*/
3698	SCR_INT,
3699		SIR_ABORT_SENT,
3700}/*-----------------------< SEL_FOR_ABORT_1 >--------------*/,{
3701	/*
3702	**	Jump at scheduler.
3703	*/
3704	SCR_JUMP,
3705		PADDR (start),
3706
3707}/*------------------------< SELECT_NO_ATN >-----------------*/,{
3708	/*
3709	**	Set Initiator mode.
3710	**      And try to select this target without ATN.
3711	*/
3712
3713	SCR_CLR (SCR_TRG),
3714		0,
3715	SCR_SEL_TBL ^ offsetof (struct dsb, select),
3716		PADDR (ungetjob),
3717	/*
3718	**      load the savep (saved pointer) into
3719	**      the actual data pointer.
3720	*/
3721	SCR_LOAD_REL (temp, 4),
3722		offsetof (struct ccb, phys.header.savep),
3723	/*
3724	**      Initialize the status registers
3725	*/
3726	SCR_LOAD_REL (scr0, 4),
3727		offsetof (struct ccb, phys.header.status),
3728
3729}/*------------------------< WF_SEL_DONE_NO_ATN >-----------------*/,{
3730	/*
3731	**	Wait immediately for the next phase or
3732	**	the selection to complete or time-out.
3733	*/
3734	SCR_JUMPR ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3735		0,
3736	SCR_JUMP,
3737		PADDR (select2),
3738
3739}/*-------------------------< MSG_IN_ETC >--------------------*/,{
3740	/*
3741	**	If it is an EXTENDED (variable size message)
3742	**	Handle it.
3743	*/
3744	SCR_JUMP ^ IFTRUE (DATA (M_EXTENDED)),
3745		PADDRH (msg_extended),
3746	/*
3747	**	Let the C code handle any other
3748	**	1 byte message.
3749	*/
3750	SCR_JUMP ^ IFTRUE (MASK (0x00, 0xf0)),
3751		PADDRH (msg_received),
3752	SCR_JUMP ^ IFTRUE (MASK (0x10, 0xf0)),
3753		PADDRH (msg_received),
3754	/*
3755	**	We donnot handle 2 bytes messages from SCRIPTS.
3756	**	So, let the C code deal with these ones too.
3757	*/
3758	SCR_JUMP ^ IFFALSE (MASK (0x20, 0xf0)),
3759		PADDRH (msg_weird_seen),
3760	SCR_CLR (SCR_ACK),
3761		0,
3762	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3763		NADDR (msgin[1]),
3764	SCR_JUMP,
3765		PADDRH (msg_received),
3766
3767}/*-------------------------< MSG_RECEIVED >--------------------*/,{
3768	SCR_LOAD_REL (scratcha, 4),	/* DUMMY READ */
3769		0,
3770	SCR_INT,
3771		SIR_MSG_RECEIVED,
3772
3773}/*-------------------------< MSG_WEIRD_SEEN >------------------*/,{
3774	SCR_LOAD_REL (scratcha, 4),	/* DUMMY READ */
3775		0,
3776	SCR_INT,
3777		SIR_MSG_WEIRD,
3778
3779}/*-------------------------< MSG_EXTENDED >--------------------*/,{
3780	/*
3781	**	Clear ACK and get the next byte
3782	**	assumed to be the message length.
3783	*/
3784	SCR_CLR (SCR_ACK),
3785		0,
3786	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3787		NADDR (msgin[1]),
3788	/*
3789	**	Try to catch some unlikely situations as 0 length
3790	**	or too large the length.
3791	*/
3792	SCR_JUMP ^ IFTRUE (DATA (0)),
3793		PADDRH (msg_weird_seen),
3794	SCR_TO_REG (scratcha),
3795		0,
3796	SCR_REG_REG (sfbr, SCR_ADD, (256-8)),
3797		0,
3798	SCR_JUMP ^ IFTRUE (CARRYSET),
3799		PADDRH (msg_weird_seen),
3800	/*
3801	**	We donnot handle extended messages from SCRIPTS.
3802	**	Read the amount of data correponding to the
3803	**	message length and call the C code.
3804	*/
3805	SCR_STORE_REL (scratcha, 1),
3806		offsetof (struct dsb, smsg_ext.size),
3807	SCR_CLR (SCR_ACK),
3808		0,
3809	SCR_MOVE_TBL ^ SCR_MSG_IN,
3810		offsetof (struct dsb, smsg_ext),
3811	SCR_JUMP,
3812		PADDRH (msg_received),
3813
3814}/*-------------------------< MSG_BAD >------------------*/,{
3815	/*
3816	**	unimplemented message - reject it.
3817	*/
3818	SCR_INT,
3819		SIR_REJECT_TO_SEND,
3820	SCR_SET (SCR_ATN),
3821		0,
3822	SCR_JUMP,
3823		PADDR (clrack),
3824
3825}/*-------------------------< MSG_WEIRD >--------------------*/,{
3826	/*
3827	**	weird message received
3828	**	ignore all MSG IN phases and reject it.
3829	*/
3830	SCR_INT,
3831		SIR_REJECT_TO_SEND,
3832	SCR_SET (SCR_ATN),
3833		0,
3834}/*-------------------------< MSG_WEIRD1 >--------------------*/,{
3835	SCR_CLR (SCR_ACK),
3836		0,
3837	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_IN)),
3838		PADDR (dispatch),
3839	SCR_MOVE_ABS (1) ^ SCR_MSG_IN,
3840		NADDR (scratch),
3841	SCR_JUMP,
3842		PADDRH (msg_weird1),
3843}/*-------------------------< WDTR_RESP >----------------*/,{
3844	/*
3845	**	let the target fetch our answer.
3846	*/
3847	SCR_SET (SCR_ATN),
3848		0,
3849	SCR_CLR (SCR_ACK),
3850		0,
3851	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3852		PADDRH (nego_bad_phase),
3853
3854}/*-------------------------< SEND_WDTR >----------------*/,{
3855	/*
3856	**	Send the M_X_WIDE_REQ
3857	*/
3858	SCR_MOVE_ABS (4) ^ SCR_MSG_OUT,
3859		NADDR (msgout),
3860	SCR_JUMP,
3861		PADDRH (msg_out_done),
3862
3863}/*-------------------------< SDTR_RESP >-------------*/,{
3864	/*
3865	**	let the target fetch our answer.
3866	*/
3867	SCR_SET (SCR_ATN),
3868		0,
3869	SCR_CLR (SCR_ACK),
3870		0,
3871	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3872		PADDRH (nego_bad_phase),
3873
3874}/*-------------------------< SEND_SDTR >-------------*/,{
3875	/*
3876	**	Send the M_X_SYNC_REQ
3877	*/
3878	SCR_MOVE_ABS (5) ^ SCR_MSG_OUT,
3879		NADDR (msgout),
3880	SCR_JUMP,
3881		PADDRH (msg_out_done),
3882
3883}/*-------------------------< PPR_RESP >-------------*/,{
3884	/*
3885	**	let the target fetch our answer.
3886	*/
3887	SCR_SET (SCR_ATN),
3888		0,
3889	SCR_CLR (SCR_ACK),
3890		0,
3891	SCR_JUMP ^ IFFALSE (WHEN (SCR_MSG_OUT)),
3892		PADDRH (nego_bad_phase),
3893
3894}/*-------------------------< SEND_PPR >-------------*/,{
3895	/*
3896	**	Send the M_X_PPR_REQ
3897	*/
3898	SCR_MOVE_ABS (8) ^ SCR_MSG_OUT,
3899		NADDR (msgout),
3900	SCR_JUMP,
3901		PADDRH (msg_out_done),
3902
3903}/*-------------------------< NEGO_BAD_PHASE >------------*/,{
3904	SCR_INT,
3905		SIR_NEGO_PROTO,
3906	SCR_JUMP,
3907		PADDR (dispatch),
3908
3909}/*-------------------------< MSG_OUT >-------------------*/,{
3910	/*
3911	**	The target requests a message.
3912	*/
3913	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
3914		NADDR (msgout),
3915	/*
3916	**	... wait for the next phase
3917	**	if it's a message out, send it again, ...
3918	*/
3919	SCR_JUMP ^ IFTRUE (WHEN (SCR_MSG_OUT)),
3920		PADDRH (msg_out),
3921}/*-------------------------< MSG_OUT_DONE >--------------*/,{
3922	/*
3923	**	... else clear the message ...
3924	*/
3925	SCR_INT,
3926		SIR_MSG_OUT_DONE,
3927	/*
3928	**	... and process the next phase
3929	*/
3930	SCR_JUMP,
3931		PADDR (dispatch),
3932
3933}/*-------------------------< DATA_OVRUN >-----------------------*/,{
3934	/*
3935	 *  Use scratcha to count the extra bytes.
3936	 */
3937	SCR_LOAD_ABS (scratcha, 4),
3938		PADDRH (zero),
3939}/*-------------------------< DATA_OVRUN1 >----------------------*/,{
3940	/*
3941	 *  The target may want to transfer too much data.
3942	 *
3943	 *  If phase is DATA OUT write 1 byte and count it.
3944	 */
3945	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_OUT)),
3946		16,
3947	SCR_CHMOV_ABS (1) ^ SCR_DATA_OUT,
3948		NADDR (scratch),
3949	SCR_JUMP,
3950		PADDRH (data_ovrun2),
3951	/*
3952	 *  If WSR is set, clear this condition, and
3953	 *  count this byte.
3954	 */
3955	SCR_FROM_REG (scntl2),
3956		0,
3957	SCR_JUMPR ^ IFFALSE (MASK (WSR, WSR)),
3958		16,
3959	SCR_REG_REG (scntl2, SCR_OR, WSR),
3960		0,
3961	SCR_JUMP,
3962		PADDRH (data_ovrun2),
3963	/*
3964	 *  Finally check against DATA IN phase.
3965	 *  Signal data overrun to the C code
3966	 *  and jump to dispatcher if not so.
3967	 *  Read 1 byte otherwise and count it.
3968	 */
3969	SCR_JUMPR ^ IFTRUE (WHEN (SCR_DATA_IN)),
3970		16,
3971	SCR_INT,
3972		SIR_DATA_OVERRUN,
3973	SCR_JUMP,
3974		PADDR (dispatch),
3975	SCR_CHMOV_ABS (1) ^ SCR_DATA_IN,
3976		NADDR (scratch),
3977}/*-------------------------< DATA_OVRUN2 >----------------------*/,{
3978	/*
3979	 *  Count this byte.
3980	 *  This will allow to return a negative
3981	 *  residual to user.
3982	 */
3983	SCR_REG_REG (scratcha,  SCR_ADD,  0x01),
3984		0,
3985	SCR_REG_REG (scratcha1, SCR_ADDC, 0),
3986		0,
3987	SCR_REG_REG (scratcha2, SCR_ADDC, 0),
3988		0,
3989	/*
3990	 *  .. and repeat as required.
3991	 */
3992	SCR_JUMP,
3993		PADDRH (data_ovrun1),
3994
3995}/*-------------------------< ABORT_RESEL >----------------*/,{
3996	SCR_SET (SCR_ATN),
3997		0,
3998	SCR_CLR (SCR_ACK),
3999		0,
4000	/*
4001	**	send the abort/abortag/reset message
4002	**	we expect an immediate disconnect
4003	*/
4004	SCR_REG_REG (scntl2, SCR_AND, 0x7f),
4005		0,
4006	SCR_MOVE_ABS (1) ^ SCR_MSG_OUT,
4007		NADDR (msgout),
4008	SCR_CLR (SCR_ACK|SCR_ATN),
4009		0,
4010	SCR_WAIT_DISC,
4011		0,
4012	SCR_INT,
4013		SIR_RESEL_ABORTED,
4014	SCR_JUMP,
4015		PADDR (start),
4016}/*-------------------------< RESEND_IDENT >-------------------*/,{
4017	/*
4018	**	The target stays in MSG OUT phase after having acked
4019	**	Identify [+ Tag [+ Extended message ]]. Targets shall
4020	**	behave this way on parity error.
4021	**	We must send it again all the messages.
4022	*/
4023	SCR_SET (SCR_ATN), /* Shall be asserted 2 deskew delays before the  */
4024		0,         /* 1rst ACK = 90 ns. Hope the NCR is'nt too fast */
4025	SCR_JUMP,
4026		PADDR (send_ident),
4027}/*-------------------------< IDENT_BREAK >-------------------*/,{
4028	SCR_CLR (SCR_ATN),
4029		0,
4030	SCR_JUMP,
4031		PADDR (select2),
4032}/*-------------------------< IDENT_BREAK_ATN >----------------*/,{
4033	SCR_SET (SCR_ATN),
4034		0,
4035	SCR_JUMP,
4036		PADDR (select2),
4037}/*-------------------------< SDATA_IN >-------------------*/,{
4038	SCR_CHMOV_TBL ^ SCR_DATA_IN,
4039		offsetof (struct dsb, sense),
4040	SCR_CALL,
4041		PADDR (datai_done),
4042	SCR_JUMP,
4043		PADDRH (data_ovrun),
4044}/*-------------------------< DATA_IO >--------------------*/,{
4045	/*
4046	**	We jump here if the data direction was unknown at the
4047	**	time we had to queue the command to the scripts processor.
4048	**	Pointers had been set as follow in this situation:
4049	**	  savep   -->   DATA_IO
4050	**	  lastp   -->   start pointer when DATA_IN
4051	**	  goalp   -->   goal  pointer when DATA_IN
4052	**	  wlastp  -->   start pointer when DATA_OUT
4053	**	  wgoalp  -->   goal  pointer when DATA_OUT
4054	**	This script sets savep/lastp/goalp according to the
4055	**	direction chosen by the target.
4056	*/
4057	SCR_JUMP ^ IFTRUE (WHEN (SCR_DATA_OUT)),
4058		PADDRH(data_io_out),
4059}/*-------------------------< DATA_IO_COM >-----------------*/,{
4060	/*
4061	**	Direction is DATA IN.
4062	**	Warning: we jump here, even when phase is DATA OUT.
4063	*/
4064	SCR_LOAD_REL  (scratcha, 4),
4065		offsetof (struct ccb, phys.header.lastp),
4066	SCR_STORE_REL (scratcha, 4),
4067		offsetof (struct ccb, phys.header.savep),
4068
4069	/*
4070	**	Jump to the SCRIPTS according to actual direction.
4071	*/
4072	SCR_LOAD_REL  (temp, 4),
4073		offsetof (struct ccb, phys.header.savep),
4074	SCR_RETURN,
4075		0,
4076}/*-------------------------< DATA_IO_OUT >-----------------*/,{
4077	/*
4078	**	Direction is DATA OUT.
4079	*/
4080	SCR_REG_REG (HF_REG, SCR_AND, (~HF_DATA_IN)),
4081		0,
4082	SCR_LOAD_REL  (scratcha, 4),
4083		offsetof (struct ccb, phys.header.wlastp),
4084	SCR_STORE_REL (scratcha, 4),
4085		offsetof (struct ccb, phys.header.lastp),
4086	SCR_LOAD_REL  (scratcha, 4),
4087		offsetof (struct ccb, phys.header.wgoalp),
4088	SCR_STORE_REL (scratcha, 4),
4089		offsetof (struct ccb, phys.header.goalp),
4090	SCR_JUMP,
4091		PADDRH(data_io_com),
4092
4093}/*-------------------------< RESEL_BAD_LUN >---------------*/,{
4094	/*
4095	**	Message is an IDENTIFY, but lun is unknown.
4096	**	Signal problem to C code for logging the event.
4097	**	Send a M_ABORT to clear all pending tasks.
4098	*/
4099	SCR_INT,
4100		SIR_RESEL_BAD_LUN,
4101	SCR_JUMP,
4102		PADDRH (abort_resel),
4103}/*-------------------------< BAD_I_T_L >------------------*/,{
4104	/*
4105	**	We donnot have a task for that I_T_L.
4106	**	Signal problem to C code for logging the event.
4107	**	Send a M_ABORT message.
4108	*/
4109	SCR_INT,
4110		SIR_RESEL_BAD_I_T_L,
4111	SCR_JUMP,
4112		PADDRH (abort_resel),
4113}/*-------------------------< BAD_I_T_L_Q >----------------*/,{
4114	/*
4115	**	We donnot have a task that matches the tag.
4116	**	Signal problem to C code for logging the event.
4117	**	Send a M_ABORTTAG message.
4118	*/
4119	SCR_INT,
4120		SIR_RESEL_BAD_I_T_L_Q,
4121	SCR_JUMP,
4122		PADDRH (abort_resel),
4123}/*-------------------------< BAD_STATUS >-----------------*/,{
4124	/*
4125	**	Anything different from INTERMEDIATE
4126	**	CONDITION MET should be a bad SCSI status,
4127	**	given that GOOD status has already been tested.
4128	**	Call the C code.
4129	*/
4130	SCR_LOAD_ABS (scratcha, 4),
4131		PADDRH (startpos),
4132	SCR_INT ^ IFFALSE (DATA (S_COND_MET)),
4133		SIR_BAD_STATUS,
4134	SCR_RETURN,
4135		0,
4136
4137}/*-------------------------< TWEAK_PMJ >------------------*/,{
4138	/*
4139	**	Disable PM handling from SCRIPTS for the data phase
4140	**	and so force PM to be handled from C code if HF_PM_TO_C
4141	**	flag is set.
4142	*/
4143	SCR_FROM_REG(HF_REG),
4144		0,
4145	SCR_JUMPR ^ IFTRUE (MASK (HF_PM_TO_C, HF_PM_TO_C)),
4146		16,
4147	SCR_REG_REG (ccntl0, SCR_OR, ENPMJ),
4148		0,
4149	SCR_RETURN,
4150 		0,
4151	SCR_REG_REG (ccntl0, SCR_AND, (~ENPMJ)),
4152		0,
4153	SCR_RETURN,
4154 		0,
4155
4156}/*-------------------------< PM_HANDLE >------------------*/,{
4157	/*
4158	**	Phase mismatch handling.
4159	**
4160	**	Since we have to deal with 2 SCSI data pointers
4161	**	(current and saved), we need at least 2 contexts.
4162	**	Each context (pm0 and pm1) has a saved area, a
4163	**	SAVE mini-script and a DATA phase mini-script.
4164	*/
4165	/*
4166	**	Get the PM handling flags.
4167	*/
4168	SCR_FROM_REG (HF_REG),
4169		0,
4170	/*
4171	**	If no flags (1rst PM for example), avoid
4172	**	all the below heavy flags testing.
4173	**	This makes the normal case a bit faster.
4174	*/
4175	SCR_JUMP ^ IFTRUE (MASK (0, (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED))),
4176		PADDRH (pm_handle1),
4177	/*
4178	**	If we received a SAVE DP, switch to the
4179	**	other PM context since the savep may point
4180	**	to the current PM context.
4181	*/
4182	SCR_JUMPR ^ IFFALSE (MASK (HF_DP_SAVED, HF_DP_SAVED)),
4183		8,
4184	SCR_REG_REG (sfbr, SCR_XOR, HF_ACT_PM),
4185		0,
4186	/*
4187	**	If we have been interrupt in a PM DATA mini-script,
4188	**	we take the return address from the corresponding
4189	**	saved area.
4190	**	This ensure the return address always points to the
4191	**	main DATA script for this transfer.
4192	*/
4193	SCR_JUMP ^ IFTRUE (MASK (0, (HF_IN_PM0 | HF_IN_PM1))),
4194		PADDRH (pm_handle1),
4195	SCR_JUMPR ^ IFFALSE (MASK (HF_IN_PM0, HF_IN_PM0)),
4196		16,
4197	SCR_LOAD_REL (ia, 4),
4198		offsetof(struct ccb, phys.pm0.ret),
4199	SCR_JUMP,
4200		PADDRH (pm_save),
4201	SCR_LOAD_REL (ia, 4),
4202		offsetof(struct ccb, phys.pm1.ret),
4203	SCR_JUMP,
4204		PADDRH (pm_save),
4205}/*-------------------------< PM_HANDLE1 >-----------------*/,{
4206	/*
4207	**	Normal case.
4208	**	Update the return address so that it
4209	**	will point after the interrupted MOVE.
4210	*/
4211	SCR_REG_REG (ia, SCR_ADD, 8),
4212		0,
4213	SCR_REG_REG (ia1, SCR_ADDC, 0),
4214		0,
4215}/*-------------------------< PM_SAVE >--------------------*/,{
4216	/*
4217	**	Clear all the flags that told us if we were
4218	**	interrupted in a PM DATA mini-script and/or
4219	**	we received a SAVE DP.
4220	*/
4221	SCR_SFBR_REG (HF_REG, SCR_AND, (~(HF_IN_PM0|HF_IN_PM1|HF_DP_SAVED))),
4222		0,
4223	/*
4224	**	Choose the current PM context.
4225	*/
4226	SCR_JUMP ^ IFTRUE (MASK (HF_ACT_PM, HF_ACT_PM)),
4227		PADDRH (pm1_save),
4228}/*-------------------------< PM0_SAVE >-------------------*/,{
4229	SCR_STORE_REL (ia, 4),
4230		offsetof(struct ccb, phys.pm0.ret),
4231	/*
4232	**	If WSR bit is set, either UA and RBC may
4233	**	have to be changed whatever the device wants
4234	**	to ignore this residue ot not.
4235	*/
4236	SCR_FROM_REG (scntl2),
4237		0,
4238	SCR_CALL ^ IFTRUE (MASK (WSR, WSR)),
4239		PADDRH (pm_wsr_handle),
4240	/*
4241	**	Save the remaining byte count, the updated
4242	**	address and the return address.
4243	*/
4244	SCR_STORE_REL (rbc, 4),
4245		offsetof(struct ccb, phys.pm0.sg.size),
4246	SCR_STORE_REL (ua, 4),
4247		offsetof(struct ccb, phys.pm0.sg.addr),
4248	/*
4249	**	Set the current pointer at the PM0 DATA mini-script.
4250	*/
4251	SCR_LOAD_ABS (temp, 4),
4252		PADDRH (pm0_data_addr),
4253	SCR_JUMP,
4254		PADDR (dispatch),
4255}/*-------------------------< PM1_SAVE >-------------------*/,{
4256	SCR_STORE_REL (ia, 4),
4257		offsetof(struct ccb, phys.pm1.ret),
4258	/*
4259	**	If WSR bit is set, either UA and RBC may
4260	**	have been changed whatever the device wants
4261	**	to ignore this residue or not.
4262	*/
4263	SCR_FROM_REG (scntl2),
4264		0,
4265	SCR_CALL ^ IFTRUE (MASK (WSR, WSR)),
4266		PADDRH (pm_wsr_handle),
4267	/*
4268	**	Save the remaining byte count, the updated
4269	**	address and the return address.
4270	*/
4271	SCR_STORE_REL (rbc, 4),
4272		offsetof(struct ccb, phys.pm1.sg.size),
4273	SCR_STORE_REL (ua, 4),
4274		offsetof(struct ccb, phys.pm1.sg.addr),
4275	/*
4276	**	Set the current pointer at the PM1 DATA mini-script.
4277	*/
4278	SCR_LOAD_ABS (temp, 4),
4279		PADDRH (pm1_data_addr),
4280	SCR_JUMP,
4281		PADDR (dispatch),
4282}/*--------------------------< PM_WSR_HANDLE >-----------------------*/,{
4283	/*
4284	 *  Phase mismatch handling from SCRIPT with WSR set.
4285	 *  Such a condition can occur if the chip wants to
4286	 *  execute a CHMOV(size > 1) when the WSR bit is
4287	 *  set and the target changes PHASE.
4288	 */
4289#ifdef	SYM_DEBUG_PM_WITH_WSR
4290	/*
4291	 *  Some debugging may still be needed.:)
4292	 */
4293	SCR_INT,
4294		SIR_PM_WITH_WSR,
4295#endif
4296	/*
4297	 *  We must move the residual byte to memory.
4298	 *
4299	 *  UA contains bit 0..31 of the address to
4300	 *  move the residual byte.
4301	 *  Move it to the table indirect.
4302	 */
4303	SCR_STORE_REL (ua, 4),
4304		offsetof (struct ccb, phys.wresid.addr),
4305	/*
4306	 *  Increment UA (move address to next position).
4307	 */
4308	SCR_REG_REG (ua, SCR_ADD, 1),
4309		0,
4310	SCR_REG_REG (ua1, SCR_ADDC, 0),
4311		0,
4312	SCR_REG_REG (ua2, SCR_ADDC, 0),
4313		0,
4314	SCR_REG_REG (ua3, SCR_ADDC, 0),
4315		0,
4316	/*
4317	 *  Compute SCRATCHA as:
4318	 *  - size to transfer = 1 byte.
4319	 *  - bit 24..31 = high address bit [32...39].
4320	 */
4321	SCR_LOAD_ABS (scratcha, 4),
4322		PADDRH (zero),
4323	SCR_REG_REG (scratcha, SCR_OR, 1),
4324		0,
4325	SCR_FROM_REG (rbc3),
4326		0,
4327	SCR_TO_REG (scratcha3),
4328		0,
4329	/*
4330	 *  Move this value to the table indirect.
4331	 */
4332	SCR_STORE_REL (scratcha, 4),
4333		offsetof (struct ccb, phys.wresid.size),
4334	/*
4335	 *  Wait for a valid phase.
4336	 *  While testing with bogus QUANTUM drives, the C1010
4337	 *  sometimes raised a spurious phase mismatch with
4338	 *  WSR and the CHMOV(1) triggered another PM.
4339	 *  Waiting explicitely for the PHASE seemed to avoid
4340	 *  the nested phase mismatch. Btw, this didn't happen
4341	 *  using my IBM drives.
4342	 */
4343	SCR_JUMPR ^ IFFALSE (WHEN (SCR_DATA_IN)),
4344		0,
4345	/*
4346	 *  Perform the move of the residual byte.
4347	 */
4348	SCR_CHMOV_TBL ^ SCR_DATA_IN,
4349		offsetof (struct ccb, phys.wresid),
4350	/*
4351	 *  We can now handle the phase mismatch with UA fixed.
4352	 *  RBC[0..23]=0 is a special case that does not require
4353	 *  a PM context. The C code also checks against this.
4354	 */
4355	SCR_FROM_REG (rbc),
4356		0,
4357	SCR_RETURN ^ IFFALSE (DATA (0)),
4358		0,
4359	SCR_FROM_REG (rbc1),
4360		0,
4361	SCR_RETURN ^ IFFALSE (DATA (0)),
4362		0,
4363	SCR_FROM_REG (rbc2),
4364		0,
4365	SCR_RETURN ^ IFFALSE (DATA (0)),
4366		0,
4367	/*
4368	 *  RBC[0..23]=0.
4369	 *  Not only we donnot need a PM context, but this would
4370	 *  lead to a bogus CHMOV(0). This condition means that
4371	 *  the residual was the last byte to move from this CHMOV.
4372	 *  So, we just have to move the current data script pointer
4373	 *  (i.e. TEMP) to the SCRIPTS address following the
4374	 *  interrupted CHMOV and jump to dispatcher.
4375	 */
4376	SCR_STORE_ABS (ia, 4),
4377		PADDRH (scratch),
4378	SCR_LOAD_ABS (temp, 4),
4379		PADDRH (scratch),
4380	SCR_JUMP,
4381		PADDR (dispatch),
4382}/*--------------------------< WSR_MA_HELPER >-----------------------*/,{
4383	/*
4384	 *  Helper for the C code when WSR bit is set.
4385	 *  Perform the move of the residual byte.
4386	 */
4387	SCR_CHMOV_TBL ^ SCR_DATA_IN,
4388		offsetof (struct ccb, phys.wresid),
4389	SCR_JUMP,
4390		PADDR (dispatch),
4391}/*-------------------------< ZERO >------------------------*/,{
4392	SCR_DATA_ZERO,
4393}/*-------------------------< SCRATCH >---------------------*/,{
4394	SCR_DATA_ZERO,
4395}/*-------------------------< SCRATCH1 >--------------------*/,{
4396	SCR_DATA_ZERO,
4397}/*-------------------------< PM0_DATA_ADDR >---------------*/,{
4398	SCR_DATA_ZERO,
4399}/*-------------------------< PM1_DATA_ADDR >---------------*/,{
4400	SCR_DATA_ZERO,
4401}/*-------------------------< SAVED_DSA >-------------------*/,{
4402	SCR_DATA_ZERO,
4403}/*-------------------------< SAVED_DRS >-------------------*/,{
4404	SCR_DATA_ZERO,
4405}/*-------------------------< DONE_POS >--------------------*/,{
4406	SCR_DATA_ZERO,
4407}/*-------------------------< STARTPOS >--------------------*/,{
4408	SCR_DATA_ZERO,
4409}/*-------------------------< TARGTBL >---------------------*/,{
4410	SCR_DATA_ZERO,
4411
4412
4413/*
4414** We may use MEMORY MOVE instructions to load the on chip-RAM,
4415** if it happens that mapping PCI memory is not possible.
4416** But writing the RAM from the CPU is the preferred method,
4417** since PCI 2.2 seems to disallow PCI self-mastering.
4418*/
4419
4420#ifdef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
4421
4422}/*-------------------------< START_RAM >-------------------*/,{
4423	/*
4424	**	Load the script into on-chip RAM,
4425	**	and jump to start point.
4426	*/
4427	SCR_COPY (sizeof (struct script)),
4428}/*-------------------------< SCRIPT0_BA >--------------------*/,{
4429		0,
4430		PADDR (start),
4431	SCR_JUMP,
4432		PADDR (init),
4433
4434}/*-------------------------< START_RAM64 >--------------------*/,{
4435	/*
4436	**	Load the RAM and start for 64 bit PCI (895A,896).
4437	**	Both scripts (script and scripth) are loaded into
4438	**	the RAM which is 8K (4K for 825A/875/895).
4439	**	We also need to load some 32-63 bit segments
4440	**	address of the SCRIPTS processor.
4441	**	LOAD/STORE ABSOLUTE always refers to on-chip RAM
4442	**	in our implementation. The main memory is
4443	**	accessed using LOAD/STORE DSA RELATIVE.
4444	*/
4445	SCR_LOAD_REL (mmws, 4),
4446		offsetof (struct ncb, scr_ram_seg),
4447	SCR_COPY (sizeof(struct script)),
4448}/*-------------------------< SCRIPT0_BA64 >--------------------*/,{
4449		0,
4450		PADDR (start),
4451	SCR_COPY (sizeof(struct scripth)),
4452}/*-------------------------< SCRIPTH0_BA64 >--------------------*/,{
4453		0,
4454		PADDRH  (start64),
4455	SCR_LOAD_REL  (mmrs, 4),
4456		offsetof (struct ncb, scr_ram_seg),
4457	SCR_JUMP64,
4458		PADDRH (start64),
4459}/*-------------------------< RAM_SEG64 >--------------------*/,{
4460		0,
4461
4462#endif /* SCSI_NCR_PCI_MEM_NOT_SUPPORTED */
4463
4464}/*-------------------------< SNOOPTEST >-------------------*/,{
4465	/*
4466	**	Read the variable.
4467	*/
4468	SCR_LOAD_REL (scratcha, 4),
4469		offsetof(struct ncb, ncr_cache),
4470	SCR_STORE_REL (temp, 4),
4471		offsetof(struct ncb, ncr_cache),
4472	SCR_LOAD_REL (temp, 4),
4473		offsetof(struct ncb, ncr_cache),
4474}/*-------------------------< SNOOPEND >-------------------*/,{
4475	/*
4476	**	And stop.
4477	*/
4478	SCR_INT,
4479		99,
4480}/*--------------------------------------------------------*/
4481};
4482
4483/*==========================================================
4484**
4485**
4486**	Fill in #define dependent parts of the script
4487**
4488**
4489**==========================================================
4490*/
4491
4492void __init ncr_script_fill (struct script * scr, struct scripth * scrh)
4493{
4494	int	i;
4495	ncrcmd	*p;
4496
4497	p = scr->data_in;
4498	for (i=0; i<MAX_SCATTER; i++) {
4499		*p++ =SCR_CHMOV_TBL ^ SCR_DATA_IN;
4500		*p++ =offsetof (struct dsb, data[i]);
4501	};
4502
4503	assert ((u_long)p == (u_long)&scr->data_in + sizeof (scr->data_in));
4504
4505	p = scr->data_out;
4506
4507	for (i=0; i<MAX_SCATTER; i++) {
4508		*p++ =SCR_CHMOV_TBL ^ SCR_DATA_OUT;
4509		*p++ =offsetof (struct dsb, data[i]);
4510	};
4511
4512	assert ((u_long)p == (u_long)&scr->data_out + sizeof (scr->data_out));
4513}
4514
4515/*==========================================================
4516**
4517**
4518**	Copy and rebind a script.
4519**
4520**
4521**==========================================================
4522*/
4523
4524static void __init
4525ncr_script_copy_and_bind (ncb_p np,ncrcmd *src,ncrcmd *dst,int len)
4526{
4527	ncrcmd  opcode, new, old, tmp1, tmp2;
4528	ncrcmd	*start, *end;
4529	int relocs;
4530	int opchanged = 0;
4531
4532	start = src;
4533	end = src + len/4;
4534
4535	while (src < end) {
4536
4537		opcode = *src++;
4538		*dst++ = cpu_to_scr(opcode);
4539
4540		/*
4541		**	If we forget to change the length
4542		**	in struct script, a field will be
4543		**	padded with 0. This is an illegal
4544		**	command.
4545		*/
4546
4547		if (opcode == 0) {
4548			printk (KERN_INFO "%s: ERROR0 IN SCRIPT at %d.\n",
4549				ncr_name(np), (int) (src-start-1));
4550			MDELAY (10000);
4551			continue;
4552		};
4553
4554		/*
4555		**	We use the bogus value 0xf00ff00f ;-)
4556		**	to reserve data area in SCRIPTS.
4557		*/
4558		if (opcode == SCR_DATA_ZERO) {
4559			dst[-1] = 0;
4560			continue;
4561		}
4562
4563		if (DEBUG_FLAGS & DEBUG_SCRIPT)
4564			printk (KERN_INFO "%p:  <%x>\n",
4565				(src-1), (unsigned)opcode);
4566
4567		/*
4568		**	We don't have to decode ALL commands
4569		*/
4570		switch (opcode >> 28) {
4571
4572		case 0xf:
4573			/*
4574			**	LOAD / STORE DSA relative, don't relocate.
4575			*/
4576			relocs = 0;
4577			break;
4578		case 0xe:
4579			/*
4580			**	LOAD / STORE absolute.
4581			*/
4582			relocs = 1;
4583			break;
4584		case 0xc:
4585			/*
4586			**	COPY has TWO arguments.
4587			*/
4588			relocs = 2;
4589			tmp1 = src[0];
4590			tmp2 = src[1];
4591#ifdef	RELOC_KVAR
4592			if ((tmp1 & RELOC_MASK) == RELOC_KVAR)
4593				tmp1 = 0;
4594			if ((tmp2 & RELOC_MASK) == RELOC_KVAR)
4595				tmp2 = 0;
4596#endif
4597			if ((tmp1 ^ tmp2) & 3) {
4598				printk (KERN_ERR"%s: ERROR1 IN SCRIPT at %d.\n",
4599					ncr_name(np), (int) (src-start-1));
4600				MDELAY (1000);
4601			}
4602			/*
4603			**	If PREFETCH feature not enabled, remove
4604			**	the NO FLUSH bit if present.
4605			*/
4606			if ((opcode & SCR_NO_FLUSH) &&
4607			    !(np->features & FE_PFEN)) {
4608				dst[-1] = cpu_to_scr(opcode & ~SCR_NO_FLUSH);
4609				++opchanged;
4610			}
4611			break;
4612
4613		case 0x0:
4614			/*
4615			**	MOVE/CHMOV (absolute address)
4616			*/
4617			if (!(np->features & FE_WIDE))
4618				dst[-1] = cpu_to_scr(opcode | OPC_MOVE);
4619			relocs = 1;
4620			break;
4621
4622		case 0x1:
4623			/*
4624			**	MOVE/CHMOV (table indirect)
4625			*/
4626			if (!(np->features & FE_WIDE))
4627				dst[-1] = cpu_to_scr(opcode | OPC_MOVE);
4628			relocs = 0;
4629			break;
4630
4631		case 0x8:
4632			/*
4633			**	JUMP / CALL
4634			**	dont't relocate if relative :-)
4635			*/
4636			if (opcode & 0x00800000)
4637				relocs = 0;
4638			else if ((opcode & 0xf8400000) == 0x80400000)/*JUMP64*/
4639				relocs = 2;
4640			else
4641				relocs = 1;
4642			break;
4643
4644		case 0x4:
4645		case 0x5:
4646		case 0x6:
4647		case 0x7:
4648			relocs = 1;
4649			break;
4650
4651		default:
4652			relocs = 0;
4653			break;
4654		};
4655
4656		if (!relocs) {
4657			*dst++ = cpu_to_scr(*src++);
4658			continue;
4659		}
4660		while (relocs--) {
4661			old = *src++;
4662
4663			switch (old & RELOC_MASK) {
4664			case RELOC_REGISTER:
4665				new = (old & ~RELOC_MASK) + np->base_ba;
4666				break;
4667			case RELOC_LABEL:
4668				new = (old & ~RELOC_MASK) + np->p_script;
4669				break;
4670			case RELOC_LABELH:
4671				new = (old & ~RELOC_MASK) + np->p_scripth;
4672				break;
4673			case RELOC_SOFTC:
4674				new = (old & ~RELOC_MASK) + np->p_ncb;
4675				break;
4676#ifdef	RELOC_KVAR
4677			case RELOC_KVAR:
4678				new=0;
4679				if (((old & ~RELOC_MASK) < SCRIPT_KVAR_FIRST) ||
4680				    ((old & ~RELOC_MASK) > SCRIPT_KVAR_LAST))
4681					panic("ncr KVAR out of range");
4682				new = vtobus(script_kvars[old & ~RELOC_MASK]);
4683#endif
4684				break;
4685			case 0:
4686				/* Don't relocate a 0 address. */
4687				if (old == 0) {
4688					new = old;
4689					break;
4690				}
4691				/* fall through */
4692			default:
4693				new = 0;	/* For 'cc' not to complain */
4694				panic("ncr_script_copy_and_bind: "
4695				      "weird relocation %x\n", old);
4696				break;
4697			}
4698
4699			*dst++ = cpu_to_scr(new);
4700		}
4701	};
4702}
4703
4704/*==========================================================
4705**
4706**
4707**      Auto configuration:  attach and init a host adapter.
4708**
4709**
4710**==========================================================
4711*/
4712
4713/*
4714**	Linux host data structure.
4715*/
4716
4717struct host_data {
4718     struct ncb *ncb;
4719};
4720
4721/*
4722**	Print something which allows to retrieve the controler type, unit,
4723**	target, lun concerned by a kernel message.
4724*/
4725
4726static void PRINT_TARGET(ncb_p np, int target)
4727{
4728	printk(KERN_INFO "%s-<%d,*>: ", ncr_name(np), target);
4729}
4730
4731static void PRINT_LUN(ncb_p np, int target, int lun)
4732{
4733	printk(KERN_INFO "%s-<%d,%d>: ", ncr_name(np), target, lun);
4734}
4735
4736static void PRINT_ADDR(Scsi_Cmnd *cmd)
4737{
4738	struct host_data *host_data = (struct host_data *) cmd->host->hostdata;
4739	PRINT_LUN(host_data->ncb, cmd->target, cmd->lun);
4740}
4741
4742/*==========================================================
4743**
4744**	NCR chip clock divisor table.
4745**	Divisors are multiplied by 10,000,000 in order to make
4746**	calculations more simple.
4747**
4748**==========================================================
4749*/
4750
4751#define _5M 5000000
4752static u_long div_10M[] =
4753	{2*_5M, 3*_5M, 4*_5M, 6*_5M, 8*_5M, 12*_5M, 16*_5M};
4754
4755
4756/*===============================================================
4757**
4758**	Prepare io register values used by ncr_init() according
4759**	to selected and supported features.
4760**
4761**	NCR/SYMBIOS chips allow burst lengths of 2, 4, 8, 16, 32, 64,
4762**	128 transfers. All chips support at least 16 transfers bursts.
4763**	The 825A, 875 and 895 chips support bursts of up to 128
4764**	transfers and the 895A and 896 support bursts of up to 64
4765**	transfers. All other chips support up to 16 transfers bursts.
4766**
4767**	For PCI 32 bit data transfers each transfer is a DWORD (4 bytes).
4768**	It is a QUADWORD (8 bytes) for PCI 64 bit data transfers.
4769**	Only the 896 is able to perform 64 bit data transfers.
4770**
4771**	We use log base 2 (burst length) as internal code, with
4772**	value 0 meaning "burst disabled".
4773**
4774**===============================================================
4775*/
4776
4777/*
4778 *	Burst length from burst code.
4779 */
4780#define burst_length(bc) (!(bc))? 0 : 1 << (bc)
4781
4782/*
4783 *	Burst code from io register bits.
4784 */
4785#define burst_code(dmode, ctest4, ctest5) \
4786	(ctest4) & 0x80? 0 : (((dmode) & 0xc0) >> 6) + ((ctest5) & 0x04) + 1
4787
4788/*
4789 *	Set initial io register bits from burst code.
4790 */
4791static inline void ncr_init_burst(ncb_p np, u_char bc)
4792{
4793	np->rv_ctest4	&= ~0x80;
4794	np->rv_dmode	&= ~(0x3 << 6);
4795	np->rv_ctest5	&= ~0x4;
4796
4797	if (!bc) {
4798		np->rv_ctest4	|= 0x80;
4799	}
4800	else {
4801		--bc;
4802		np->rv_dmode	|= ((bc & 0x3) << 6);
4803		np->rv_ctest5	|= (bc & 0x4);
4804	}
4805}
4806
4807#ifdef SCSI_NCR_NVRAM_SUPPORT
4808
4809/*
4810**	Get target set-up from Symbios format NVRAM.
4811*/
4812
4813static void __init
4814ncr_Symbios_setup_target(ncb_p np, int target, Symbios_nvram *nvram)
4815{
4816	tcb_p tp = &np->target[target];
4817	Symbios_target *tn = &nvram->target[target];
4818
4819	tp->usrsync = tn->sync_period ? (tn->sync_period + 3) / 4 : 255;
4820	tp->usrwide = tn->bus_width == 0x10 ? 1 : 0;
4821	tp->usrtags =
4822		(tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? MAX_TAGS : 0;
4823
4824	if (!(tn->flags & SYMBIOS_DISCONNECT_ENABLE))
4825		tp->usrflag |= UF_NODISC;
4826	if (!(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME))
4827		tp->usrflag |= UF_NOSCAN;
4828}
4829
4830/*
4831**	Get target set-up from Tekram format NVRAM.
4832*/
4833
4834static void __init
4835ncr_Tekram_setup_target(ncb_p np, int target, Tekram_nvram *nvram)
4836{
4837	tcb_p tp = &np->target[target];
4838	struct Tekram_target *tn = &nvram->target[target];
4839	int i;
4840
4841	if (tn->flags & TEKRAM_SYNC_NEGO) {
4842		i = tn->sync_index & 0xf;
4843		tp->usrsync = Tekram_sync[i];
4844	}
4845
4846	tp->usrwide = (tn->flags & TEKRAM_WIDE_NEGO) ? 1 : 0;
4847
4848	if (tn->flags & TEKRAM_TAGGED_COMMANDS) {
4849		tp->usrtags = 2 << nvram->max_tags_index;
4850	}
4851
4852	if (!(tn->flags & TEKRAM_DISCONNECT_ENABLE))
4853		tp->usrflag = UF_NODISC;
4854
4855	/* If any device does not support parity, we will not use this option */
4856	if (!(tn->flags & TEKRAM_PARITY_CHECK))
4857		np->rv_scntl0  &= ~0x0a; /* SCSI parity checking disabled */
4858}
4859#endif /* SCSI_NCR_NVRAM_SUPPORT */
4860
4861/*
4862**	Save initial settings of some IO registers.
4863**	Assumed to have been set by BIOS.
4864*/
4865static void __init ncr_save_initial_setting(ncb_p np)
4866{
4867	np->sv_scntl0	= INB(nc_scntl0) & 0x0a;
4868	np->sv_dmode	= INB(nc_dmode)  & 0xce;
4869	np->sv_dcntl	= INB(nc_dcntl)  & 0xa8;
4870	np->sv_ctest3	= INB(nc_ctest3) & 0x01;
4871	np->sv_ctest4	= INB(nc_ctest4) & 0x80;
4872	np->sv_gpcntl	= INB(nc_gpcntl);
4873	np->sv_stest2	= INB(nc_stest2) & 0x20;
4874	np->sv_stest4	= INB(nc_stest4);
4875	np->sv_stest1	= INB(nc_stest1);
4876
4877 	np->sv_scntl3   = INB(nc_scntl3) & 0x07;
4878
4879 	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
4880 	 	(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66) ){
4881 		/*
4882 		** C1010 always uses large fifo, bit 5 rsvd
4883 		** scntl4 used ONLY with C1010
4884 		*/
4885 		np->sv_ctest5 = INB(nc_ctest5) & 0x04 ;
4886 		np->sv_scntl4 = INB(nc_scntl4);
4887         }
4888         else {
4889 		np->sv_ctest5 = INB(nc_ctest5) & 0x24 ;
4890 		np->sv_scntl4 = 0;
4891         }
4892}
4893
4894/*
4895**	Prepare io register values used by ncr_init()
4896**	according to selected and supported features.
4897*/
4898static int __init ncr_prepare_setting(ncb_p np, ncr_nvram *nvram)
4899{
4900	u_char	burst_max;
4901	u_long	period;
4902	int i;
4903
4904	/*
4905	**	Wide ?
4906	*/
4907
4908	np->maxwide	= (np->features & FE_WIDE)? 1 : 0;
4909
4910 	/*
4911	 *  Guess the frequency of the chip's clock.
4912	 */
4913	if	(np->features & (FE_ULTRA3 | FE_ULTRA2))
4914		np->clock_khz = 160000;
4915	else if	(np->features & FE_ULTRA)
4916		np->clock_khz = 80000;
4917	else
4918		np->clock_khz = 40000;
4919
4920	/*
4921	 *  Get the clock multiplier factor.
4922 	 */
4923	if	(np->features & FE_QUAD)
4924		np->multiplier	= 4;
4925	else if	(np->features & FE_DBLR)
4926		np->multiplier	= 2;
4927	else
4928		np->multiplier	= 1;
4929
4930	/*
4931	 *  Measure SCSI clock frequency for chips
4932	 *  it may vary from assumed one.
4933	 */
4934	if (np->features & FE_VARCLK)
4935		ncr_getclock(np, np->multiplier);
4936
4937	/*
4938	 * Divisor to be used for async (timer pre-scaler).
4939	 *
4940	 * Note: For C1010 the async divisor is 2(8) if he
4941	 * quadrupler is disabled (enabled).
4942	 */
4943
4944	if ( (np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
4945		(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
4946
4947		np->rv_scntl3 = 0;
4948	}
4949	else
4950	{
4951		i = np->clock_divn - 1;
4952		while (--i >= 0) {
4953			if (10ul * SCSI_NCR_MIN_ASYNC * np->clock_khz
4954							> div_10M[i]) {
4955				++i;
4956				break;
4957			}
4958		}
4959		np->rv_scntl3 = i+1;
4960	}
4961
4962
4963	/*
4964	 * Save the ultra3 register for the C1010/C1010_66
4965	 */
4966
4967	np->rv_scntl4 = np->sv_scntl4;
4968
4969	/*
4970	 * Minimum synchronous period factor supported by the chip.
4971	 * Btw, 'period' is in tenths of nanoseconds.
4972	 */
4973
4974	period = (4 * div_10M[0] + np->clock_khz - 1) / np->clock_khz;
4975	if	(period <= 250)		np->minsync = 10;
4976	else if	(period <= 303)		np->minsync = 11;
4977	else if	(period <= 500)		np->minsync = 12;
4978	else				np->minsync = (period + 40 - 1) / 40;
4979
4980	/*
4981	 * Fix up. If sync. factor is 10 (160000Khz clock) and chip
4982	 * supports ultra3, then min. sync. period 12.5ns and the factor is 9
4983	 * Also keep track of the maximum offset in ST mode which may differ
4984	 * from the maximum offset in DT mode. For now hardcoded to 31.
4985	 */
4986
4987	if (np->features & FE_ULTRA3) {
4988		if (np->minsync == 10)
4989			np->minsync = 9;
4990		np->maxoffs_st = 31;
4991	}
4992	else
4993		np->maxoffs_st = np->maxoffs;
4994
4995	/*
4996	 * Check against chip SCSI standard support (SCSI-2,ULTRA,ULTRA2).
4997	 *
4998	 * Transfer period minimums: SCSI-1 200 (50); Fast 100 (25)
4999	 *			Ultra 50 (12); Ultra2 (6); Ultra3 (3)
5000	 */
5001
5002	if	(np->minsync < 25 && !(np->features & (FE_ULTRA|FE_ULTRA2|FE_ULTRA3)))
5003		np->minsync = 25;
5004	else if	(np->minsync < 12 && (np->features & FE_ULTRA))
5005		np->minsync = 12;
5006	else if	(np->minsync < 10 && (np->features & FE_ULTRA2))
5007		np->minsync = 10;
5008	else if	(np->minsync < 9 && (np->features & FE_ULTRA3))
5009		np->minsync = 9;
5010
5011	/*
5012	 * Maximum synchronous period factor supported by the chip.
5013	 */
5014
5015	period = (11 * div_10M[np->clock_divn - 1]) / (4 * np->clock_khz);
5016	np->maxsync = period > 2540 ? 254 : period / 10;
5017
5018	/*
5019	**	64 bit (53C895A or 53C896) ?
5020	*/
5021	if (np->features & FE_DAC) {
5022		if (np->features & FE_DAC_IN_USE)
5023			np->rv_ccntl1	|= (XTIMOD | EXTIBMV);
5024		else
5025			np->rv_ccntl1	|= (DDAC);
5026	}
5027
5028	/*
5029	**	Phase mismatch handled by SCRIPTS (53C895A, 53C896 or C1010) ?
5030  	*/
5031	if (np->features & FE_NOPM)
5032		np->rv_ccntl0	|= (ENPMJ);
5033
5034	/*
5035	**	Prepare initial value of other IO registers
5036	*/
5037#if defined SCSI_NCR_TRUST_BIOS_SETTING
5038	np->rv_scntl0	= np->sv_scntl0;
5039	np->rv_dmode	= np->sv_dmode;
5040	np->rv_dcntl	= np->sv_dcntl;
5041	np->rv_ctest3	= np->sv_ctest3;
5042	np->rv_ctest4	= np->sv_ctest4;
5043	np->rv_ctest5	= np->sv_ctest5;
5044	burst_max	= burst_code(np->sv_dmode, np->sv_ctest4, np->sv_ctest5);
5045#else
5046
5047	/*
5048	**	Select burst length (dwords)
5049	*/
5050	burst_max	= driver_setup.burst_max;
5051	if (burst_max == 255)
5052		burst_max = burst_code(np->sv_dmode, np->sv_ctest4, np->sv_ctest5);
5053	if (burst_max > 7)
5054		burst_max = 7;
5055	if (burst_max > np->maxburst)
5056		burst_max = np->maxburst;
5057
5058	/*
5059	**	DEL 352 - 53C810 Rev x11 - Part Number 609-0392140 - ITEM 2.
5060	**	This chip and the 860 Rev 1 may wrongly use PCI cache line
5061	**	based transactions on LOAD/STORE instructions. So we have
5062	**	to prevent these chips from using such PCI transactions in
5063	**	this driver. The generic sym53c8xx driver that does not use
5064	**	LOAD/STORE instructions does not need this work-around.
5065	*/
5066	if ((np->device_id == PCI_DEVICE_ID_NCR_53C810 &&
5067	     np->revision_id >= 0x10 && np->revision_id <= 0x11) ||
5068	    (np->device_id == PCI_DEVICE_ID_NCR_53C860 &&
5069	     np->revision_id <= 0x1))
5070		np->features &= ~(FE_WRIE|FE_ERL|FE_ERMP);
5071
5072	/*
5073	**	DEL ? - 53C1010 Rev 1 - Part Number 609-0393638
5074	**	64-bit Slave Cycles must be disabled.
5075	*/
5076	if ( ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) && (np->revision_id < 0x02) )
5077		|| (np->device_id == PCI_DEVICE_ID_LSI_53C1010_66 ) )
5078		np->rv_ccntl1  |=  0x10;
5079
5080	/*
5081	**	Select all supported special features.
5082	**	If we are using on-board RAM for scripts, prefetch (PFEN)
5083	**	does not help, but burst op fetch (BOF) does.
5084	**	Disabling PFEN makes sure BOF will be used.
5085	*/
5086	if (np->features & FE_ERL)
5087		np->rv_dmode	|= ERL;		/* Enable Read Line */
5088	if (np->features & FE_BOF)
5089		np->rv_dmode	|= BOF;		/* Burst Opcode Fetch */
5090	if (np->features & FE_ERMP)
5091		np->rv_dmode	|= ERMP;	/* Enable Read Multiple */
5092	if ((np->features & FE_PFEN) && !np->base2_ba)
5093		np->rv_dcntl	|= PFEN;	/* Prefetch Enable */
5094	if (np->features & FE_CLSE)
5095		np->rv_dcntl	|= CLSE;	/* Cache Line Size Enable */
5096	if (np->features & FE_WRIE)
5097		np->rv_ctest3	|= WRIE;	/* Write and Invalidate */
5098
5099
5100	if ( (np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
5101			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66) &&
5102			(np->features & FE_DFS))
5103		np->rv_ctest5	|= DFS;		/* Dma Fifo Size */
5104						/* C1010/C1010_66 always large fifo */
5105
5106	/*
5107	**	Select some other
5108	*/
5109	if (driver_setup.master_parity)
5110		np->rv_ctest4	|= MPEE;	/* Master parity checking */
5111	if (driver_setup.scsi_parity)
5112		np->rv_scntl0	|= 0x0a;	/*  full arb., ena parity, par->ATN  */
5113
5114#ifdef SCSI_NCR_NVRAM_SUPPORT
5115	/*
5116	**	Get parity checking, host ID and verbose mode from NVRAM
5117	**/
5118	if (nvram) {
5119		switch(nvram->type) {
5120		case SCSI_NCR_TEKRAM_NVRAM:
5121			np->myaddr = nvram->data.Tekram.host_id & 0x0f;
5122			break;
5123		case SCSI_NCR_SYMBIOS_NVRAM:
5124			if (!(nvram->data.Symbios.flags & SYMBIOS_PARITY_ENABLE))
5125				np->rv_scntl0  &= ~0x0a;
5126			np->myaddr = nvram->data.Symbios.host_id & 0x0f;
5127			if (nvram->data.Symbios.flags & SYMBIOS_VERBOSE_MSGS)
5128				np->verbose += 1;
5129			break;
5130		}
5131	}
5132#endif
5133	/*
5134	**  Get SCSI addr of host adapter (set by bios?).
5135	*/
5136	if (np->myaddr == 255) {
5137		np->myaddr = INB(nc_scid) & 0x07;
5138		if (!np->myaddr)
5139			np->myaddr = SCSI_NCR_MYADDR;
5140	}
5141
5142#endif /* SCSI_NCR_TRUST_BIOS_SETTING */
5143
5144	/*
5145	 *	Prepare initial io register bits for burst length
5146	 */
5147	ncr_init_burst(np, burst_max);
5148
5149	/*
5150	**	Set SCSI BUS mode.
5151	**
5152	**	- ULTRA2 chips (895/895A/896)
5153	**	  and ULTRA 3 chips (1010) report the current
5154	**	  BUS mode through the STEST4 IO register.
5155	**	- For previous generation chips (825/825A/875),
5156	**	  user has to tell us how to check against HVD,
5157	**	  since a 100% safe algorithm is not possible.
5158	*/
5159	np->scsi_mode = SMODE_SE;
5160	if	(np->features & (FE_ULTRA2 | FE_ULTRA3))
5161		np->scsi_mode = (np->sv_stest4 & SMODE);
5162	else if	(np->features & FE_DIFF) {
5163		switch(driver_setup.diff_support) {
5164		case 4:	/* Trust previous settings if present, then GPIO3 */
5165			if (np->sv_scntl3) {
5166				if (np->sv_stest2 & 0x20)
5167					np->scsi_mode = SMODE_HVD;
5168				break;
5169			}
5170		case 3:	/* SYMBIOS controllers report HVD through GPIO3 */
5171			if (nvram && nvram->type != SCSI_NCR_SYMBIOS_NVRAM)
5172				break;
5173			if (INB(nc_gpreg) & 0x08)
5174				break;
5175		case 2:	/* Set HVD unconditionally */
5176			np->scsi_mode = SMODE_HVD;
5177		case 1:	/* Trust previous settings for HVD */
5178			if (np->sv_stest2 & 0x20)
5179				np->scsi_mode = SMODE_HVD;
5180			break;
5181		default:/* Don't care about HVD */
5182			break;
5183		}
5184	}
5185	if (np->scsi_mode == SMODE_HVD)
5186		np->rv_stest2 |= 0x20;
5187
5188	/*
5189	**	Set LED support from SCRIPTS.
5190	**	Ignore this feature for boards known to use a
5191	**	specific GPIO wiring and for the 895A or 896
5192	**	that drive the LED directly.
5193	**	Also probe initial setting of GPIO0 as output.
5194	*/
5195	if ((driver_setup.led_pin ||
5196	     (nvram && nvram->type == SCSI_NCR_SYMBIOS_NVRAM)) &&
5197	    !(np->features & FE_LEDC) && !(np->sv_gpcntl & 0x01))
5198		np->features |= FE_LED0;
5199
5200	/*
5201	**	Set irq mode.
5202	*/
5203	switch(driver_setup.irqm & 3) {
5204	case 2:
5205		np->rv_dcntl	|= IRQM;
5206		break;
5207	case 1:
5208		np->rv_dcntl	|= (np->sv_dcntl & IRQM);
5209		break;
5210	default:
5211		break;
5212	}
5213
5214	/*
5215	**	Configure targets according to driver setup.
5216	**	If NVRAM present get targets setup from NVRAM.
5217	**	Allow to override sync, wide and NOSCAN from
5218	**	boot command line.
5219	*/
5220	for (i = 0 ; i < MAX_TARGET ; i++) {
5221		tcb_p tp = &np->target[i];
5222
5223		tp->usrsync = 255;
5224#ifdef SCSI_NCR_NVRAM_SUPPORT
5225		if (nvram) {
5226			switch(nvram->type) {
5227			case SCSI_NCR_TEKRAM_NVRAM:
5228				ncr_Tekram_setup_target(np, i, &nvram->data.Tekram);
5229				break;
5230			case SCSI_NCR_SYMBIOS_NVRAM:
5231				ncr_Symbios_setup_target(np, i, &nvram->data.Symbios);
5232				break;
5233			}
5234			if (driver_setup.use_nvram & 0x2)
5235				tp->usrsync = driver_setup.default_sync;
5236			if (driver_setup.use_nvram & 0x4)
5237				tp->usrwide = driver_setup.max_wide;
5238			if (driver_setup.use_nvram & 0x8)
5239				tp->usrflag &= ~UF_NOSCAN;
5240		}
5241		else {
5242#else
5243		if (1) {
5244#endif
5245			tp->usrsync = driver_setup.default_sync;
5246			tp->usrwide = driver_setup.max_wide;
5247			tp->usrtags = MAX_TAGS;
5248			if (!driver_setup.disconnection)
5249				np->target[i].usrflag = UF_NODISC;
5250		}
5251	}
5252
5253	/*
5254	**	Announce all that stuff to user.
5255	*/
5256
5257	i = nvram ? nvram->type : 0;
5258	printk(KERN_INFO "%s: %sID %d, Fast-%d%s%s\n", ncr_name(np),
5259		i  == SCSI_NCR_SYMBIOS_NVRAM ? "Symbios format NVRAM, " :
5260		(i == SCSI_NCR_TEKRAM_NVRAM  ? "Tekram format NVRAM, " : ""),
5261		np->myaddr,
5262		np->minsync < 10 ? 80 :
5263			(np->minsync < 12 ? 40 : (np->minsync < 25 ? 20 : 10) ),
5264		(np->rv_scntl0 & 0xa)	? ", Parity Checking"	: ", NO Parity",
5265		(np->rv_stest2 & 0x20)	? ", Differential"	: "");
5266
5267	if (bootverbose > 1) {
5268		printk (KERN_INFO "%s: initial SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
5269			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
5270			ncr_name(np), np->sv_scntl3, np->sv_dmode, np->sv_dcntl,
5271			np->sv_ctest3, np->sv_ctest4, np->sv_ctest5);
5272
5273		printk (KERN_INFO "%s: final   SCNTL3/DMODE/DCNTL/CTEST3/4/5 = "
5274			"(hex) %02x/%02x/%02x/%02x/%02x/%02x\n",
5275			ncr_name(np), np->rv_scntl3, np->rv_dmode, np->rv_dcntl,
5276			np->rv_ctest3, np->rv_ctest4, np->rv_ctest5);
5277	}
5278
5279	if (bootverbose && np->base2_ba)
5280		printk (KERN_INFO "%s: on-chip RAM at 0x%lx\n",
5281			ncr_name(np), np->base2_ba);
5282
5283	return 0;
5284}
5285
5286
5287#ifdef SCSI_NCR_DEBUG_NVRAM
5288
5289void __init ncr_display_Symbios_nvram(ncb_p np, Symbios_nvram *nvram)
5290{
5291	int i;
5292
5293	/* display Symbios nvram host data */
5294	printk(KERN_DEBUG "%s: HOST ID=%d%s%s%s%s%s\n",
5295		ncr_name(np), nvram->host_id & 0x0f,
5296		(nvram->flags  & SYMBIOS_SCAM_ENABLE)	? " SCAM"	:"",
5297		(nvram->flags  & SYMBIOS_PARITY_ENABLE)	? " PARITY"	:"",
5298		(nvram->flags  & SYMBIOS_VERBOSE_MSGS)	? " VERBOSE"	:"",
5299		(nvram->flags  & SYMBIOS_CHS_MAPPING)	? " CHS_ALT"	:"",
5300		(nvram->flags1 & SYMBIOS_SCAN_HI_LO)	? " HI_LO"	:"");
5301
5302	/* display Symbios nvram drive data */
5303	for (i = 0 ; i < 15 ; i++) {
5304		struct Symbios_target *tn = &nvram->target[i];
5305		printk(KERN_DEBUG "%s-%d:%s%s%s%s WIDTH=%d SYNC=%d TMO=%d\n",
5306		ncr_name(np), i,
5307		(tn->flags & SYMBIOS_DISCONNECT_ENABLE)	? " DISC"	: "",
5308		(tn->flags & SYMBIOS_SCAN_AT_BOOT_TIME)	? " SCAN_BOOT"	: "",
5309		(tn->flags & SYMBIOS_SCAN_LUNS)		? " SCAN_LUNS"	: "",
5310		(tn->flags & SYMBIOS_QUEUE_TAGS_ENABLED)? " TCQ"	: "",
5311		tn->bus_width,
5312		tn->sync_period / 4,
5313		tn->timeout);
5314	}
5315}
5316
5317static u_char Tekram_boot_delay[7] __initdata = {3, 5, 10, 20, 30, 60, 120};
5318
5319void __init ncr_display_Tekram_nvram(ncb_p np, Tekram_nvram *nvram)
5320{
5321	int i, tags, boot_delay;
5322	char *rem;
5323
5324	/* display Tekram nvram host data */
5325	tags = 2 << nvram->max_tags_index;
5326	boot_delay = 0;
5327	if (nvram->boot_delay_index < 6)
5328		boot_delay = Tekram_boot_delay[nvram->boot_delay_index];
5329	switch((nvram->flags & TEKRAM_REMOVABLE_FLAGS) >> 6) {
5330	default:
5331	case 0:	rem = "";			break;
5332	case 1: rem = " REMOVABLE=boot device";	break;
5333	case 2: rem = " REMOVABLE=all";		break;
5334	}
5335
5336	printk(KERN_DEBUG
5337		"%s: HOST ID=%d%s%s%s%s%s%s%s%s%s BOOT DELAY=%d tags=%d\n",
5338		ncr_name(np), nvram->host_id & 0x0f,
5339		(nvram->flags1 & SYMBIOS_SCAM_ENABLE)	? " SCAM"	:"",
5340		(nvram->flags & TEKRAM_MORE_THAN_2_DRIVES) ? " >2DRIVES"	:"",
5341		(nvram->flags & TEKRAM_DRIVES_SUP_1GB)	? " >1GB"	:"",
5342		(nvram->flags & TEKRAM_RESET_ON_POWER_ON) ? " RESET"	:"",
5343		(nvram->flags & TEKRAM_ACTIVE_NEGATION)	? " ACT_NEG"	:"",
5344		(nvram->flags & TEKRAM_IMMEDIATE_SEEK)	? " IMM_SEEK"	:"",
5345		(nvram->flags & TEKRAM_SCAN_LUNS)	? " SCAN_LUNS"	:"",
5346		(nvram->flags1 & TEKRAM_F2_F6_ENABLED)	? " F2_F6"	:"",
5347		rem, boot_delay, tags);
5348
5349	/* display Tekram nvram drive data */
5350	for (i = 0; i <= 15; i++) {
5351		int sync, j;
5352		struct Tekram_target *tn = &nvram->target[i];
5353		j = tn->sync_index & 0xf;
5354		sync = Tekram_sync[j];
5355		printk(KERN_DEBUG "%s-%d:%s%s%s%s%s%s PERIOD=%d\n",
5356		ncr_name(np), i,
5357		(tn->flags & TEKRAM_PARITY_CHECK)	? " PARITY"	: "",
5358		(tn->flags & TEKRAM_SYNC_NEGO)		? " SYNC"	: "",
5359		(tn->flags & TEKRAM_DISCONNECT_ENABLE)	? " DISC"	: "",
5360		(tn->flags & TEKRAM_START_CMD)		? " START"	: "",
5361		(tn->flags & TEKRAM_TAGGED_COMMANDS)	? " TCQ"	: "",
5362		(tn->flags & TEKRAM_WIDE_NEGO)		? " WIDE"	: "",
5363		sync);
5364	}
5365}
5366#endif /* SCSI_NCR_DEBUG_NVRAM */
5367
5368/*
5369**	Host attach and initialisations.
5370**
5371**	Allocate host data and ncb structure.
5372**	Request IO region and remap MMIO region.
5373**	Do chip initialization.
5374**	If all is OK, install interrupt handling and
5375**	start the timer daemon.
5376*/
5377
5378static int __init
5379ncr_attach (Scsi_Host_Template *tpnt, int unit, ncr_device *device)
5380{
5381        struct host_data *host_data;
5382	ncb_p np = 0;
5383        struct Scsi_Host *instance = 0;
5384	u_long flags = 0;
5385	ncr_nvram *nvram = device->nvram;
5386	int i;
5387
5388	printk(KERN_INFO NAME53C "%s-%d: rev 0x%x on pci bus %d device %d function %d "
5389#ifdef __sparc__
5390		"irq %s\n",
5391#else
5392		"irq %d\n",
5393#endif
5394		device->chip.name, unit, device->chip.revision_id,
5395		device->slot.bus, (device->slot.device_fn & 0xf8) >> 3,
5396		device->slot.device_fn & 7,
5397#ifdef __sparc__
5398		__irq_itoa(device->slot.irq));
5399#else
5400		device->slot.irq);
5401#endif
5402
5403	/*
5404	**	Allocate host_data structure
5405	*/
5406        if (!(instance = scsi_register(tpnt, sizeof(*host_data))))
5407	        goto attach_error;
5408	host_data = (struct host_data *) instance->hostdata;
5409
5410	/*
5411	**	Allocate the host control block.
5412	*/
5413	np = __m_calloc_dma(device->pdev, sizeof(struct ncb), "NCB");
5414	if (!np)
5415		goto attach_error;
5416	NCR_INIT_LOCK_NCB(np);
5417	np->pdev  = device->pdev;
5418	np->p_ncb = vtobus(np);
5419	host_data->ncb = np;
5420
5421	/*
5422	**	Store input informations in the host data structure.
5423	*/
5424	strncpy(np->chip_name, device->chip.name, sizeof(np->chip_name) - 1);
5425	np->unit	= unit;
5426	np->verbose	= driver_setup.verbose;
5427	sprintf(np->inst_name, NAME53C "%s-%d", np->chip_name, np->unit);
5428	np->device_id	= device->chip.device_id;
5429	np->revision_id	= device->chip.revision_id;
5430	np->bus		= device->slot.bus;
5431	np->device_fn	= device->slot.device_fn;
5432	np->features	= device->chip.features;
5433	np->clock_divn	= device->chip.nr_divisor;
5434	np->maxoffs	= device->chip.offset_max;
5435	np->maxburst	= device->chip.burst_max;
5436	np->myaddr	= device->host_id;
5437
5438	/*
5439	**	Allocate the start queue.
5440	*/
5441	np->squeue = (ncrcmd *)
5442		m_calloc_dma(sizeof(ncrcmd)*(MAX_START*2), "SQUEUE");
5443	if (!np->squeue)
5444		goto attach_error;
5445	np->p_squeue = vtobus(np->squeue);
5446
5447	/*
5448	**	Allocate the done queue.
5449	*/
5450	np->dqueue = (ncrcmd *)
5451		m_calloc_dma(sizeof(ncrcmd)*(MAX_START*2), "DQUEUE");
5452	if (!np->dqueue)
5453		goto attach_error;
5454
5455	/*
5456	**	Allocate the target bus address array.
5457	*/
5458	np->targtbl = (u_int32 *) m_calloc_dma(256, "TARGTBL");
5459	if (!np->targtbl)
5460		goto attach_error;
5461
5462	/*
5463	**	Allocate SCRIPTS areas
5464	*/
5465	np->script0	= (struct script *)
5466		m_calloc_dma(sizeof(struct script),  "SCRIPT");
5467	if (!np->script0)
5468		goto attach_error;
5469	np->scripth0	= (struct scripth *)
5470		m_calloc_dma(sizeof(struct scripth), "SCRIPTH");
5471	if (!np->scripth0)
5472		goto attach_error;
5473
5474	/*
5475	**	Initialyze the CCB free queue and,
5476	**	allocate some CCB. We need at least ONE.
5477	*/
5478	xpt_que_init(&np->free_ccbq);
5479	xpt_que_init(&np->b0_ccbq);
5480	if (!ncr_alloc_ccb(np))
5481		goto attach_error;
5482
5483	/*
5484	**    Initialize timer structure
5485        **
5486        */
5487	init_timer(&np->timer);
5488	np->timer.data     = (unsigned long) np;
5489	np->timer.function = sym53c8xx_timeout;
5490
5491	/*
5492	**	Try to map the controller chip to
5493	**	virtual and physical memory.
5494	*/
5495
5496	np->base_ba	= device->slot.base;
5497	np->base_ws	= (np->features & FE_IO256)? 256 : 128;
5498	np->base2_ba	= (np->features & FE_RAM)? device->slot.base_2 : 0;
5499
5500#ifndef SCSI_NCR_IOMAPPED
5501	np->base_va = remap_pci_mem(device->slot.base_c, np->base_ws);
5502	if (!np->base_va) {
5503		printk(KERN_ERR "%s: can't map PCI MMIO region\n",ncr_name(np));
5504		goto attach_error;
5505	}
5506	else if (bootverbose > 1)
5507		printk(KERN_INFO "%s: using memory mapped IO\n", ncr_name(np));
5508
5509	/*
5510	**	Make the controller's registers available.
5511	**	Now the INB INW INL OUTB OUTW OUTL macros
5512	**	can be used safely.
5513	*/
5514
5515	np->reg = (struct ncr_reg *) np->base_va;
5516
5517#endif /* !defined SCSI_NCR_IOMAPPED */
5518
5519	/*
5520	**	If on-chip RAM is used, make sure SCRIPTS isn't too large.
5521	*/
5522	if (np->base2_ba && sizeof(struct script) > 4096) {
5523		printk(KERN_ERR "%s: script too large.\n", ncr_name(np));
5524		goto attach_error;
5525	}
5526
5527	/*
5528	**	Try to map the controller chip into iospace.
5529	*/
5530
5531	if (device->slot.io_port) {
5532		request_region(device->slot.io_port, np->base_ws, NAME53C8XX);
5533		np->base_io = device->slot.io_port;
5534	}
5535
5536#ifdef SCSI_NCR_NVRAM_SUPPORT
5537	if (nvram) {
5538		switch(nvram->type) {
5539		case SCSI_NCR_SYMBIOS_NVRAM:
5540#ifdef SCSI_NCR_DEBUG_NVRAM
5541			ncr_display_Symbios_nvram(np, &nvram->data.Symbios);
5542#endif
5543			break;
5544		case SCSI_NCR_TEKRAM_NVRAM:
5545#ifdef SCSI_NCR_DEBUG_NVRAM
5546			ncr_display_Tekram_nvram(np, &nvram->data.Tekram);
5547#endif
5548			break;
5549		default:
5550			nvram = 0;
5551#ifdef SCSI_NCR_DEBUG_NVRAM
5552			printk(KERN_DEBUG "%s: NVRAM: None or invalid data.\n", ncr_name(np));
5553#endif
5554		}
5555	}
5556#endif
5557
5558 	/*
5559	**	Save setting of some IO registers, so we will
5560	**	be able to probe specific implementations.
5561	*/
5562	ncr_save_initial_setting (np);
5563
5564	/*
5565	**	Reset the chip now, since it has been reported
5566	**	that SCSI clock calibration may not work properly
5567	**	if the chip is currently active.
5568	*/
5569	ncr_chip_reset (np);
5570
5571	/*
5572	**	Do chip dependent initialization.
5573	*/
5574	(void) ncr_prepare_setting(np, nvram);
5575
5576	/*
5577	**	Check the PCI clock frequency if needed.
5578	**
5579	**	Must be done after ncr_prepare_setting since it destroys
5580	**	STEST1 that is used to probe for the clock multiplier.
5581	**
5582	**	The range is currently [22688 - 45375 Khz], given
5583	**	the values used by ncr_getclock().
5584	**	This calibration of the frequecy measurement
5585	**	algorithm against the PCI clock frequency is only
5586	**	performed if the driver has had to measure the SCSI
5587	**	clock due to other heuristics not having been enough
5588	**	to deduce the SCSI clock frequency.
5589	**
5590	**	When the chip has been initialized correctly by the
5591	**	SCSI BIOS, the driver deduces the presence of the
5592	**	clock multiplier and the value of the SCSI clock from
5593	**	initial values of IO registers, and therefore no
5594	**	clock measurement is performed.
5595	**	Normally the driver should never have to measure any
5596	**	clock, unless the controller may use a 80 MHz clock
5597	**	or has a clock multiplier and any of the following
5598	**	condition is met:
5599	**
5600	**	- No SCSI BIOS is present.
5601	**	- SCSI BIOS did'nt enable the multiplier for some reason.
5602	**	- User has disabled the controller from the SCSI BIOS.
5603	**	- User booted the O/S from another O/S that did'nt enable
5604	**	  the multiplier for some reason.
5605	**
5606	**	As a result, the driver may only have to measure some
5607	**	frequency in very unusual situations.
5608	**
5609	**	For this reality test against the PCI clock to really
5610	**	protect against flaws in the udelay() calibration or
5611	**	driver problem that affect the clock measurement
5612	**	algorithm, the actual PCI clock frequency must be 33 MHz.
5613	*/
5614	i = np->pciclock_max ? ncr_getpciclock(np) : 0;
5615	if (i && (i < np->pciclock_min  || i > np->pciclock_max)) {
5616		printk(KERN_ERR "%s: PCI clock (%u KHz) is out of range "
5617			"[%u KHz - %u KHz].\n",
5618		       ncr_name(np), i, np->pciclock_min, np->pciclock_max);
5619		goto attach_error;
5620	}
5621
5622	/*
5623	**	Patch script to physical addresses
5624	*/
5625	ncr_script_fill (&script0, &scripth0);
5626
5627	np->p_script	= vtobus(np->script0);
5628	np->p_scripth	= vtobus(np->scripth0);
5629	np->p_scripth0	= np->p_scripth;
5630
5631	if (np->base2_ba) {
5632		np->p_script	= np->base2_ba;
5633		if (np->features & FE_RAM8K) {
5634			np->base2_ws = 8192;
5635			np->p_scripth = np->p_script + 4096;
5636#if BITS_PER_LONG > 32
5637			np->scr_ram_seg = cpu_to_scr(np->base2_ba >> 32);
5638#endif
5639		}
5640		else
5641			np->base2_ws = 4096;
5642#ifndef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
5643		np->base2_va =
5644			remap_pci_mem(device->slot.base_2_c, np->base2_ws);
5645		if (!np->base2_va) {
5646			printk(KERN_ERR "%s: can't map PCI MEMORY region\n",
5647			       ncr_name(np));
5648			goto attach_error;
5649		}
5650#endif
5651	}
5652
5653	ncr_script_copy_and_bind (np, (ncrcmd *) &script0, (ncrcmd *) np->script0, sizeof(struct script));
5654	ncr_script_copy_and_bind (np, (ncrcmd *) &scripth0, (ncrcmd *) np->scripth0, sizeof(struct scripth));
5655
5656	/*
5657	**	Patch some variables in SCRIPTS
5658	*/
5659	np->scripth0->pm0_data_addr[0] =
5660			cpu_to_scr(NCB_SCRIPT_PHYS(np, pm0_data));
5661	np->scripth0->pm1_data_addr[0] =
5662			cpu_to_scr(NCB_SCRIPT_PHYS(np, pm1_data));
5663
5664	/*
5665	**	Patch if not Ultra 3 - Do not write to scntl4
5666	*/
5667	if (np->features & FE_ULTRA3) {
5668		np->script0->resel_scntl4[0] = cpu_to_scr(SCR_LOAD_REL (scntl4, 1));
5669		np->script0->resel_scntl4[1] = cpu_to_scr(offsetof(struct tcb, uval));
5670	}
5671
5672
5673#ifdef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
5674	np->scripth0->script0_ba[0]	= cpu_to_scr(vtobus(np->script0));
5675	np->scripth0->script0_ba64[0]	= cpu_to_scr(vtobus(np->script0));
5676	np->scripth0->scripth0_ba64[0]	= cpu_to_scr(vtobus(np->scripth0));
5677	np->scripth0->ram_seg64[0]	= np->scr_ram_seg;
5678#endif
5679	/*
5680	**	Prepare the idle and invalid task actions.
5681	*/
5682	np->idletask.start	= cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5683	np->idletask.restart	= cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l));
5684	np->p_idletask		= NCB_PHYS(np, idletask);
5685
5686	np->notask.start	= cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5687	np->notask.restart	= cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l));
5688	np->p_notask		= NCB_PHYS(np, notask);
5689
5690	np->bad_i_t_l.start	= cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5691	np->bad_i_t_l.restart	= cpu_to_scr(NCB_SCRIPTH_PHYS (np, bad_i_t_l));
5692	np->p_bad_i_t_l		= NCB_PHYS(np, bad_i_t_l);
5693
5694	np->bad_i_t_l_q.start	= cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
5695	np->bad_i_t_l_q.restart	= cpu_to_scr(NCB_SCRIPTH_PHYS (np,bad_i_t_l_q));
5696	np->p_bad_i_t_l_q	= NCB_PHYS(np, bad_i_t_l_q);
5697
5698	/*
5699	**	Allocate and prepare the bad lun table.
5700	*/
5701	np->badluntbl = m_calloc_dma(256, "BADLUNTBL");
5702	if (!np->badluntbl)
5703		goto attach_error;
5704
5705	assert (offsetof(struct lcb, resel_task) == 0);
5706	np->resel_badlun = cpu_to_scr(NCB_SCRIPTH_PHYS(np, resel_bad_lun));
5707
5708	for (i = 0 ; i < 64 ; i++)
5709		np->badluntbl[i] = cpu_to_scr(NCB_PHYS(np, resel_badlun));
5710
5711	/*
5712	**	Prepare the target bus address array.
5713	*/
5714	np->scripth0->targtbl[0] = cpu_to_scr(vtobus(np->targtbl));
5715	for (i = 0 ; i < MAX_TARGET ; i++) {
5716		np->targtbl[i] = cpu_to_scr(NCB_PHYS(np, target[i]));
5717		np->target[i].b_luntbl = cpu_to_scr(vtobus(np->badluntbl));
5718		np->target[i].b_lun0   = cpu_to_scr(NCB_PHYS(np, resel_badlun));
5719	}
5720
5721	/*
5722	**    Patch the script for LED support.
5723	*/
5724
5725	if (np->features & FE_LED0) {
5726		np->script0->idle[0]  =
5727				cpu_to_scr(SCR_REG_REG(gpreg, SCR_OR,  0x01));
5728		np->script0->reselected[0] =
5729				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
5730		np->script0->start[0] =
5731				cpu_to_scr(SCR_REG_REG(gpreg, SCR_AND, 0xfe));
5732	}
5733
5734	/*
5735	**	Patch the script to provide an extra clock cycle on
5736	**	data out phase - 53C1010_66MHz part only.
5737	**	(Fixed in rev. 1 of the chip)
5738	*/
5739	if (np->device_id == PCI_DEVICE_ID_LSI_53C1010_66 &&
5740	    np->revision_id < 1){
5741		np->script0->datao_phase[0] =
5742				cpu_to_scr(SCR_REG_REG(scntl4, SCR_OR, 0x0c));
5743	}
5744
5745#ifdef SCSI_NCR_IARB_SUPPORT
5746	/*
5747	**    If user does not want to use IMMEDIATE ARBITRATION
5748	**    when we are reselected while attempting to arbitrate,
5749	**    patch the SCRIPTS accordingly with a SCRIPT NO_OP.
5750	*/
5751	if (!(driver_setup.iarb & 1))
5752		np->script0->ungetjob[0] = cpu_to_scr(SCR_NO_OP);
5753	/*
5754	**    If user wants IARB to be set when we win arbitration
5755	**    and have other jobs, compute the max number of consecutive
5756	**    settings of IARB hint before we leave devices a chance to
5757	**    arbitrate for reselection.
5758	*/
5759	np->iarb_max = (driver_setup.iarb >> 4);
5760#endif
5761
5762	/*
5763	**	DEL 472 - 53C896 Rev 1 - Part Number 609-0393055 - ITEM 5.
5764	*/
5765	if (np->device_id == PCI_DEVICE_ID_NCR_53C896 &&
5766	    np->revision_id <= 0x1 && (np->features & FE_NOPM)) {
5767		np->scatter = ncr_scatter_896R1;
5768		np->script0->datai_phase[0] = cpu_to_scr(SCR_JUMP);
5769		np->script0->datai_phase[1] =
5770				cpu_to_scr(NCB_SCRIPTH_PHYS (np, tweak_pmj));
5771		np->script0->datao_phase[0] = cpu_to_scr(SCR_JUMP);
5772		np->script0->datao_phase[1] =
5773				cpu_to_scr(NCB_SCRIPTH_PHYS (np, tweak_pmj));
5774	}
5775	else
5776#ifdef DEBUG_896R1
5777		np->scatter = ncr_scatter_896R1;
5778#else
5779		np->scatter = ncr_scatter;
5780#endif
5781
5782	/*
5783	**	Reset chip.
5784	**	We should use ncr_soft_reset(), but we donnot want to do
5785	**	so, since we may not be safe if ABRT interrupt occurs due
5786	**	to the BIOS or previous O/S having enable this interrupt.
5787	**
5788	**	For C1010 need to set ABRT bit prior to SRST if SCRIPTs
5789	**	are running. Not true in this case.
5790	*/
5791	ncr_chip_reset(np);
5792
5793	/*
5794	**	Now check the cache handling of the pci chipset.
5795	*/
5796
5797	if (ncr_snooptest (np)) {
5798		printk (KERN_ERR "CACHE INCORRECTLY CONFIGURED.\n");
5799		goto attach_error;
5800	};
5801
5802	/*
5803	**	Install the interrupt handler.
5804	**	If we synchonize the C code with SCRIPTS on interrupt,
5805	**	we donnot want to share the INTR line at all.
5806	*/
5807	if (request_irq(device->slot.irq, sym53c8xx_intr,
5808#ifdef SCSI_NCR_PCIQ_SYNC_ON_INTR
5809			((driver_setup.irqm & 0x20) ? 0 : SA_INTERRUPT),
5810#else
5811			((driver_setup.irqm & 0x10) ? 0 : SA_SHIRQ) |
5812#if LINUX_VERSION_CODE < LinuxVersionCode(2,2,0)
5813			((driver_setup.irqm & 0x20) ? 0 : SA_INTERRUPT),
5814#else
5815			0,
5816#endif
5817#endif
5818			NAME53C8XX, np)) {
5819		printk(KERN_ERR "%s: request irq %d failure\n",
5820			ncr_name(np), device->slot.irq);
5821		goto attach_error;
5822	}
5823	np->irq = device->slot.irq;
5824
5825	/*
5826	**	After SCSI devices have been opened, we cannot
5827	**	reset the bus safely, so we do it here.
5828	**	Interrupt handler does the real work.
5829	**	Process the reset exception,
5830	**	if interrupts are not enabled yet.
5831	**	Then enable disconnects.
5832	*/
5833	NCR_LOCK_NCB(np, flags);
5834	if (ncr_reset_scsi_bus(np, 0, driver_setup.settle_delay) != 0) {
5835		printk(KERN_ERR "%s: FATAL ERROR: CHECK SCSI BUS - CABLES, TERMINATION, DEVICE POWER etc.!\n", ncr_name(np));
5836
5837		NCR_UNLOCK_NCB(np, flags);
5838		goto attach_error;
5839	}
5840	ncr_exception (np);
5841
5842	/*
5843	**	The middle-level SCSI driver does not
5844	**	wait for devices to settle.
5845	**	Wait synchronously if more than 2 seconds.
5846	*/
5847	if (driver_setup.settle_delay > 2) {
5848		printk(KERN_INFO "%s: waiting %d seconds for scsi devices to settle...\n",
5849			ncr_name(np), driver_setup.settle_delay);
5850		MDELAY (1000 * driver_setup.settle_delay);
5851	}
5852
5853	/*
5854	**	start the timeout daemon
5855	*/
5856	np->lasttime=0;
5857	ncr_timeout (np);
5858
5859	/*
5860	**  use SIMPLE TAG messages by default
5861	*/
5862#ifdef SCSI_NCR_ALWAYS_SIMPLE_TAG
5863	np->order = M_SIMPLE_TAG;
5864#endif
5865
5866	/*
5867	**  Done.
5868	*/
5869        if (!first_host)
5870        	first_host = instance;
5871
5872	/*
5873	**	Fill Linux host instance structure
5874	**	and return success.
5875	*/
5876	instance->max_channel	= 0;
5877	instance->this_id	= np->myaddr;
5878	instance->max_id	= np->maxwide ? 16 : 8;
5879	instance->max_lun	= MAX_LUN;
5880#ifndef SCSI_NCR_IOMAPPED
5881#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,29)
5882	instance->base		= (unsigned long) np->reg;
5883#else
5884	instance->base		= (char *) np->reg;
5885#endif
5886#endif
5887	instance->irq		= np->irq;
5888	instance->unique_id	= np->base_io;
5889	instance->io_port	= np->base_io;
5890	instance->n_io_port	= np->base_ws;
5891	instance->dma_channel	= 0;
5892	instance->cmd_per_lun	= MAX_TAGS;
5893	instance->can_queue	= (MAX_START-4);
5894	scsi_set_pci_device(instance, device->pdev);
5895
5896	np->check_integrity       = 0;
5897
5898#ifdef	SCSI_NCR_INTEGRITY_CHECKING
5899	instance->check_integrity = 0;
5900
5901#ifdef SCSI_NCR_ENABLE_INTEGRITY_CHECK
5902	if ( !(driver_setup.bus_check & 0x04) ) {
5903		np->check_integrity       = 1;
5904		instance->check_integrity = 1;
5905	}
5906#endif
5907#endif
5908
5909	instance->select_queue_depths = sym53c8xx_select_queue_depths;
5910
5911	NCR_UNLOCK_NCB(np, flags);
5912
5913	/*
5914	**	Now let the generic SCSI driver
5915	**	look for the SCSI devices on the bus ..
5916	*/
5917	return 0;
5918
5919attach_error:
5920	if (!instance) return -1;
5921	printk(KERN_INFO "%s: giving up ...\n", ncr_name(np));
5922	if (np)
5923		ncr_free_resources(np);
5924	scsi_unregister(instance);
5925
5926        return -1;
5927 }
5928
5929
5930/*
5931**	Free controller resources.
5932*/
5933static void ncr_free_resources(ncb_p np)
5934{
5935	ccb_p cp;
5936	tcb_p tp;
5937	lcb_p lp;
5938	int target, lun;
5939
5940	if (np->irq)
5941		free_irq(np->irq, np);
5942	if (np->base_io)
5943		release_region(np->base_io, np->base_ws);
5944#ifndef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
5945	if (np->base_va)
5946		unmap_pci_mem(np->base_va, np->base_ws);
5947	if (np->base2_va)
5948		unmap_pci_mem(np->base2_va, np->base2_ws);
5949#endif
5950	if (np->scripth0)
5951		m_free_dma(np->scripth0, sizeof(struct scripth), "SCRIPTH");
5952	if (np->script0)
5953		m_free_dma(np->script0, sizeof(struct script), "SCRIPT");
5954	if (np->squeue)
5955		m_free_dma(np->squeue, sizeof(ncrcmd)*(MAX_START*2), "SQUEUE");
5956	if (np->dqueue)
5957		m_free_dma(np->dqueue, sizeof(ncrcmd)*(MAX_START*2),"DQUEUE");
5958
5959	while ((cp = np->ccbc) != NULL) {
5960		np->ccbc = cp->link_ccb;
5961		m_free_dma(cp, sizeof(*cp), "CCB");
5962	}
5963
5964	if (np->badluntbl)
5965		m_free_dma(np->badluntbl, 256,"BADLUNTBL");
5966
5967	for (target = 0; target < MAX_TARGET ; target++) {
5968		tp = &np->target[target];
5969		for (lun = 0 ; lun < MAX_LUN ; lun++) {
5970			lp = ncr_lp(np, tp, lun);
5971			if (!lp)
5972				continue;
5973			if (lp->tasktbl != &lp->tasktbl_0)
5974				m_free_dma(lp->tasktbl, MAX_TASKS*4, "TASKTBL");
5975			if (lp->cb_tags)
5976				m_free(lp->cb_tags, MAX_TAGS, "CB_TAGS");
5977			m_free_dma(lp, sizeof(*lp), "LCB");
5978		}
5979#if MAX_LUN > 1
5980		if (tp->lmp)
5981			m_free(tp->lmp, MAX_LUN * sizeof(lcb_p), "LMP");
5982		if (tp->luntbl)
5983			m_free_dma(tp->luntbl, 256, "LUNTBL");
5984#endif
5985	}
5986
5987	if (np->targtbl)
5988		m_free_dma(np->targtbl, 256, "TARGTBL");
5989
5990	m_free_dma(np, sizeof(*np), "NCB");
5991}
5992
5993
5994/*==========================================================
5995**
5996**
5997**	Done SCSI commands list management.
5998**
5999**	We donnot enter the scsi_done() callback immediately
6000**	after a command has been seen as completed but we
6001**	insert it into a list which is flushed outside any kind
6002**	of driver critical section.
6003**	This allows to do minimal stuff under interrupt and
6004**	inside critical sections and to also avoid locking up
6005**	on recursive calls to driver entry points under SMP.
6006**	In fact, the only kernel point which is entered by the
6007**	driver with a driver lock set is get_free_pages(GFP_ATOMIC...)
6008**	that shall not reenter the driver under any circumstance.
6009**
6010**==========================================================
6011*/
6012static inline void ncr_queue_done_cmd(ncb_p np, Scsi_Cmnd *cmd)
6013{
6014	unmap_scsi_data(np, cmd);
6015	cmd->host_scribble = (char *) np->done_list;
6016	np->done_list = cmd;
6017}
6018
6019static inline void ncr_flush_done_cmds(Scsi_Cmnd *lcmd)
6020{
6021	Scsi_Cmnd *cmd;
6022
6023	while (lcmd) {
6024		cmd = lcmd;
6025		lcmd = (Scsi_Cmnd *) cmd->host_scribble;
6026		cmd->scsi_done(cmd);
6027	}
6028}
6029
6030/*==========================================================
6031**
6032**
6033**	Prepare the next negotiation message for integrity check,
6034**	if needed.
6035**
6036**	Fill in the part of message buffer that contains the
6037**	negotiation and the nego_status field of the CCB.
6038**	Returns the size of the message in bytes.
6039**
6040**	If tp->ppr_negotiation is 1 and a M_REJECT occurs, then
6041**	we disable ppr_negotiation.  If the first ppr_negotiation is
6042**	successful, set this flag to 2.
6043**
6044**==========================================================
6045*/
6046#ifdef	SCSI_NCR_INTEGRITY_CHECKING
6047static int ncr_ic_nego(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd, u_char *msgptr)
6048{
6049	tcb_p tp = &np->target[cp->target];
6050	int msglen = 0;
6051	int nego = 0;
6052	u_char new_width, new_offset, new_period;
6053	u_char no_increase;
6054
6055	if (tp->ppr_negotiation == 1)	/* PPR message successful */
6056		tp->ppr_negotiation = 2;
6057
6058	if (tp->inq_done) {
6059
6060		if (!tp->ic_maximums_set) {
6061			tp->ic_maximums_set = 1;
6062
6063			/*
6064			 * Check against target, host and user limits
6065			 */
6066			if ( (tp->inq_byte7 & INQ7_WIDE16) &&
6067					np->maxwide  && tp->usrwide)
6068				tp->ic_max_width = 1;
6069			else
6070				tp->ic_max_width = 0;
6071
6072
6073			if ((tp->inq_byte7 & INQ7_SYNC) && tp->maxoffs)
6074				tp->ic_min_sync = (tp->minsync < np->minsync) ?
6075							np->minsync : tp->minsync;
6076			else
6077				tp->ic_min_sync = 255;
6078
6079			tp->period   = 1;
6080			tp->widedone = 1;
6081
6082			/*
6083			 * Enable PPR negotiation - only if Ultra3 support
6084			 * is accessible.
6085			 */
6086
6087			tp->ppr_negotiation = 0;
6088			if (np->features & FE_ULTRA3) {
6089			    if (tp->ic_max_width && (tp->ic_min_sync == 0x09))
6090				tp->ppr_negotiation = 1;
6091			}
6092
6093			if (!tp->ppr_negotiation)
6094				cmd->ic_nego &= ~NS_PPR;
6095		}
6096
6097		if (DEBUG_FLAGS & DEBUG_IC) {
6098			printk("%s: cmd->ic_nego %d, 1st byte 0x%2X\n",
6099				ncr_name(np), cmd->ic_nego, cmd->cmnd[0]);
6100		}
6101
6102		/* Previous command recorded a parity or an initiator
6103		 * detected error condition. Force bus to narrow for this
6104		 * target. Clear flag. Negotation on request sense.
6105		 * Note: kernel forces 2 bus resets :o( but clears itself out.
6106		 * Minor bug? in scsi_obsolete.c (ugly)
6107		 */
6108		if (np->check_integ_par) {
6109			printk("%s: Parity Error. Target set to narrow.\n",
6110				ncr_name(np));
6111			tp->ic_max_width = 0;
6112			tp->widedone = tp->period = 0;
6113		}
6114
6115		/* Initializing:
6116		 * If ic_nego == NS_PPR, we are in the initial test for
6117		 * PPR messaging support. If driver flag is clear, then
6118		 * either we don't support PPR nego (narrow or async device)
6119		 * or this is the second TUR and we have had a M. REJECT
6120		 * or unexpected disconnect on the first PPR negotiation.
6121		 * Do not negotiate, reset nego flags (in case a reset has
6122		 * occurred), clear ic_nego and return.
6123		 * General case: Kernel will clear flag on a fallback.
6124		 * Do only SDTR or WDTR in the future.
6125		 */
6126                if (!tp->ppr_negotiation &&  (cmd->ic_nego == NS_PPR )) {
6127			tp->ppr_negotiation = 0;
6128			cmd->ic_nego &= ~NS_PPR;
6129			tp->widedone = tp->period = 1;
6130			return msglen;
6131		}
6132		else if (( tp->ppr_negotiation && !(cmd->ic_nego & NS_PPR )) ||
6133                        (!tp->ppr_negotiation &&  (cmd->ic_nego & NS_PPR )) ) {
6134			tp->ppr_negotiation = 0;
6135			cmd->ic_nego &= ~NS_PPR;
6136		}
6137
6138		/*
6139		 * Always check the PPR nego. flag bit if ppr_negotiation
6140		 * is set.  If the ic_nego PPR bit is clear,
6141		 * there must have been a fallback. Do only
6142		 * WDTR / SDTR in the future.
6143		 */
6144		if ((tp->ppr_negotiation) && (!(cmd->ic_nego & NS_PPR)))
6145			tp->ppr_negotiation = 0;
6146
6147		/* In case of a bus reset, ncr_negotiate will reset
6148                 * the flags tp->widedone and tp->period to 0, forcing
6149		 * a new negotiation.  Do WDTR then SDTR. If PPR, do both.
6150		 * Do NOT increase the period.  It is possible for the Scsi_Cmnd
6151		 * flags to be set to increase the period when a bus reset
6152		 * occurs - we don't want to change anything.
6153		 */
6154
6155		no_increase = 0;
6156
6157		if (tp->ppr_negotiation && (!tp->widedone) && (!tp->period) ) {
6158			cmd->ic_nego = NS_PPR;
6159			tp->widedone = tp->period = 1;
6160			no_increase = 1;
6161		}
6162		else if (!tp->widedone) {
6163			cmd->ic_nego = NS_WIDE;
6164			tp->widedone = 1;
6165			no_increase = 1;
6166		}
6167		else if (!tp->period) {
6168			cmd->ic_nego = NS_SYNC;
6169			tp->period = 1;
6170			no_increase = 1;
6171		}
6172
6173		new_width = cmd->ic_nego_width & tp->ic_max_width;
6174
6175		switch (cmd->ic_nego_sync) {
6176		case 2: /* increase the period */
6177			if (!no_increase) {
6178			    if (tp->ic_min_sync <= 0x09)
6179				tp->ic_min_sync = 0x0A;
6180			    else if (tp->ic_min_sync <= 0x0A)
6181				tp->ic_min_sync = 0x0C;
6182			    else if (tp->ic_min_sync <= 0x0C)
6183				tp->ic_min_sync = 0x19;
6184			    else if (tp->ic_min_sync <= 0x19)
6185				tp->ic_min_sync *= 2;
6186			    else  {
6187				tp->ic_min_sync = 255;
6188				cmd->ic_nego_sync = 0;
6189				tp->maxoffs = 0;
6190			    }
6191			}
6192			new_period  = tp->maxoffs?tp->ic_min_sync:0;
6193			new_offset  = tp->maxoffs;
6194			break;
6195
6196		case 1: /* nego. to maximum */
6197			new_period  = tp->maxoffs?tp->ic_min_sync:0;
6198			new_offset  = tp->maxoffs;
6199			break;
6200
6201		case 0:	/* nego to async */
6202		default:
6203			new_period = 0;
6204			new_offset = 0;
6205			break;
6206		};
6207
6208
6209		nego = NS_NOCHANGE;
6210		if (tp->ppr_negotiation) {
6211			u_char options_byte = 0;
6212
6213			/*
6214			** Must make sure data is consistent.
6215			** If period is 9 and sync, must be wide and DT bit set.
6216			** else period must be larger. If the width is 0,
6217			** reset bus to wide but increase the period to 0x0A.
6218			** Note: The strange else clause is due to the integrity check.
6219			** If fails at 0x09, wide, the I.C. code will redo at the same
6220			** speed but a narrow bus. The driver must take care of slowing
6221			** the bus speed down.
6222			**
6223			** The maximum offset in ST mode is 31, in DT mode 62 (1010/1010_66 only)
6224			*/
6225			if ( (new_period==0x09) && new_offset) {
6226				if (new_width)
6227					options_byte = 0x02;
6228				else {
6229					tp->ic_min_sync = 0x0A;
6230					new_period = 0x0A;
6231					cmd->ic_nego_width = 1;
6232					new_width = 1;
6233				}
6234			}
6235			if (!options_byte && new_offset > np->maxoffs_st)
6236				new_offset = np->maxoffs_st;
6237
6238			nego = NS_PPR;
6239
6240			msgptr[msglen++] = M_EXTENDED;
6241			msgptr[msglen++] = 6;
6242			msgptr[msglen++] = M_X_PPR_REQ;
6243			msgptr[msglen++] = new_period;
6244			msgptr[msglen++] = 0;
6245			msgptr[msglen++] = new_offset;
6246			msgptr[msglen++] = new_width;
6247			msgptr[msglen++] = options_byte;
6248
6249		}
6250		else {
6251			switch (cmd->ic_nego & ~NS_PPR) {
6252			case NS_WIDE:
6253			    /*
6254			    **	WDTR negotiation on if device supports
6255			    **  wide or if wide device forced narrow
6256			    **	due to a parity error.
6257			    */
6258
6259			    cmd->ic_nego_width &= tp->ic_max_width;
6260
6261			    if (tp->ic_max_width | np->check_integ_par) {
6262				nego = NS_WIDE;
6263				msgptr[msglen++] = M_EXTENDED;
6264				msgptr[msglen++] = 2;
6265				msgptr[msglen++] = M_X_WIDE_REQ;
6266				msgptr[msglen++] = new_width;
6267			    }
6268		 	    break;
6269
6270			case NS_SYNC:
6271			    /*
6272			    **	negotiate synchronous transfers
6273			    **	Target must support sync transfers.
6274			    **  Min. period = 0x0A, maximum offset of 31=0x1f.
6275		    	    */
6276
6277			    if (tp->inq_byte7 & INQ7_SYNC) {
6278
6279				if (new_offset && (new_period < 0x0A)) {
6280					tp->ic_min_sync = 0x0A;
6281					new_period = 0x0A;
6282				}
6283				if (new_offset > np->maxoffs_st)
6284					new_offset = np->maxoffs_st;
6285				nego = NS_SYNC;
6286				msgptr[msglen++] = M_EXTENDED;
6287				msgptr[msglen++] = 3;
6288				msgptr[msglen++] = M_X_SYNC_REQ;
6289				msgptr[msglen++] = new_period;
6290				msgptr[msglen++] = new_offset;
6291			    }
6292			    else
6293				cmd->ic_nego_sync = 0;
6294			    break;
6295
6296			case NS_NOCHANGE:
6297			    break;
6298			}
6299		}
6300
6301	};
6302
6303	cp->nego_status = nego;
6304	np->check_integ_par = 0;
6305
6306	if (nego) {
6307		tp->nego_cp = cp;
6308		if (DEBUG_FLAGS & DEBUG_NEGO) {
6309			ncr_print_msg(cp, nego == NS_WIDE ?
6310				  "wide/narrow msgout":
6311				(nego == NS_SYNC ? "sync/async msgout" : "ppr msgout"),
6312				msgptr);
6313		};
6314	};
6315
6316	return msglen;
6317}
6318#endif	/* SCSI_NCR_INTEGRITY_CHECKING */
6319
6320/*==========================================================
6321**
6322**
6323**	Prepare the next negotiation message if needed.
6324**
6325**	Fill in the part of message buffer that contains the
6326**	negotiation and the nego_status field of the CCB.
6327**	Returns the size of the message in bytes.
6328**
6329**
6330**==========================================================
6331*/
6332
6333
6334static int ncr_prepare_nego(ncb_p np, ccb_p cp, u_char *msgptr)
6335{
6336	tcb_p tp = &np->target[cp->target];
6337	int msglen = 0;
6338	int nego = 0;
6339	u_char width, offset, factor, last_byte;
6340
6341	if (!np->check_integrity) {
6342		/* If integrity checking disabled, enable PPR messaging
6343		 * if device supports wide, sync and ultra 3
6344		 */
6345		if (tp->ppr_negotiation == 1) /* PPR message successful */
6346			tp->ppr_negotiation = 2;
6347
6348		if ((tp->inq_done) && (!tp->ic_maximums_set)) {
6349			tp->ic_maximums_set = 1;
6350
6351			/*
6352			 * Issue PPR only if board is capable
6353			 * and set-up for Ultra3 transfers.
6354			 */
6355			tp->ppr_negotiation = 0;
6356			if ( (np->features & FE_ULTRA3) &&
6357				(tp->usrwide) && (tp->maxoffs) &&
6358				(tp->minsync == 0x09) )
6359					tp->ppr_negotiation = 1;
6360		}
6361	}
6362
6363	if (tp->inq_done) {
6364		/*
6365		 * Get the current width, offset and period
6366		 */
6367		ncr_get_xfer_info( np, tp, &factor,
6368						&offset, &width);
6369
6370		/*
6371		**	negotiate wide transfers ?
6372		*/
6373
6374		if (!tp->widedone) {
6375			if (tp->inq_byte7 & INQ7_WIDE16) {
6376				if (tp->ppr_negotiation)
6377					nego = NS_PPR;
6378				else
6379					nego = NS_WIDE;
6380
6381				width = tp->usrwide;
6382#ifdef	SCSI_NCR_INTEGRITY_CHECKING
6383				if (tp->ic_done)
6384		       			 width &= tp->ic_max_width;
6385#endif
6386			} else
6387				tp->widedone=1;
6388
6389		};
6390
6391		/*
6392		**	negotiate synchronous transfers?
6393		*/
6394
6395		if ((nego != NS_WIDE) && !tp->period) {
6396			if (tp->inq_byte7 & INQ7_SYNC) {
6397				if (tp->ppr_negotiation)
6398					nego = NS_PPR;
6399				else
6400					nego = NS_SYNC;
6401
6402				/* Check for async flag */
6403				if (tp->maxoffs == 0) {
6404				    offset = 0;
6405				    factor = 0;
6406				}
6407				else {
6408				    offset = tp->maxoffs;
6409				    factor = tp->minsync;
6410#ifdef	SCSI_NCR_INTEGRITY_CHECKING
6411			 	    if ((tp->ic_done) &&
6412						(factor < tp->ic_min_sync))
6413		       			 factor = tp->ic_min_sync;
6414#endif
6415				}
6416
6417			} else {
6418				offset = 0;
6419				factor = 0;
6420				tp->period  =0xffff;
6421				PRINT_TARGET(np, cp->target);
6422				printk ("target did not report SYNC.\n");
6423			};
6424		};
6425	};
6426
6427	switch (nego) {
6428	case NS_PPR:
6429		/*
6430		** Must make sure data is consistent.
6431		** If period is 9 and sync, must be wide and DT bit set
6432		** else period must be larger.
6433		** Maximum offset is 31=0x1f is ST mode, 62 if DT mode
6434		*/
6435		last_byte = 0;
6436		if ( (factor==9) && offset) {
6437			if (!width) {
6438				factor = 0x0A;
6439			}
6440			else
6441				last_byte = 0x02;
6442		}
6443		if (!last_byte && offset > np->maxoffs_st)
6444			offset = np->maxoffs_st;
6445
6446		msgptr[msglen++] = M_EXTENDED;
6447		msgptr[msglen++] = 6;
6448		msgptr[msglen++] = M_X_PPR_REQ;
6449		msgptr[msglen++] = factor;
6450		msgptr[msglen++] = 0;
6451		msgptr[msglen++] = offset;
6452		msgptr[msglen++] = width;
6453		msgptr[msglen++] = last_byte;
6454		break;
6455	case NS_SYNC:
6456		/*
6457		** Never negotiate faster than Ultra 2 (25ns periods)
6458		*/
6459		if (offset && (factor < 0x0A)) {
6460			factor = 0x0A;
6461			tp->minsync = 0x0A;
6462		}
6463		if (offset > np->maxoffs_st)
6464			offset = np->maxoffs_st;
6465
6466		msgptr[msglen++] = M_EXTENDED;
6467		msgptr[msglen++] = 3;
6468		msgptr[msglen++] = M_X_SYNC_REQ;
6469		msgptr[msglen++] = factor;
6470		msgptr[msglen++] = offset;
6471		break;
6472	case NS_WIDE:
6473		msgptr[msglen++] = M_EXTENDED;
6474		msgptr[msglen++] = 2;
6475		msgptr[msglen++] = M_X_WIDE_REQ;
6476		msgptr[msglen++] = width;
6477		break;
6478	};
6479
6480	cp->nego_status = nego;
6481
6482	if (nego) {
6483		tp->nego_cp = cp;
6484		if (DEBUG_FLAGS & DEBUG_NEGO) {
6485			ncr_print_msg(cp, nego == NS_WIDE ?
6486				  "wide msgout":
6487				(nego == NS_SYNC ? "sync msgout" : "ppr msgout"),
6488				msgptr);
6489		};
6490	};
6491
6492	return msglen;
6493}
6494
6495/*==========================================================
6496**
6497**
6498**	Start execution of a SCSI command.
6499**	This is called from the generic SCSI driver.
6500**
6501**
6502**==========================================================
6503*/
6504static int ncr_queue_command (ncb_p np, Scsi_Cmnd *cmd)
6505{
6506/*	Scsi_Device        *device    = cmd->device; */
6507	tcb_p tp                      = &np->target[cmd->target];
6508	lcb_p lp		      = ncr_lp(np, tp, cmd->lun);
6509	ccb_p cp;
6510
6511	u_char	idmsg, *msgptr;
6512	u_int   msglen;
6513	int	direction;
6514	u_int32	lastp, goalp;
6515
6516	/*---------------------------------------------
6517	**
6518	**      Some shortcuts ...
6519	**
6520	**---------------------------------------------
6521	*/
6522	if ((cmd->target == np->myaddr	  ) ||
6523		(cmd->target >= MAX_TARGET) ||
6524		(cmd->lun    >= MAX_LUN   )) {
6525		return(DID_BAD_TARGET);
6526        }
6527
6528	/*---------------------------------------------
6529	**
6530	**	Complete the 1st TEST UNIT READY command
6531	**	with error condition if the device is
6532	**	flagged NOSCAN, in order to speed up
6533	**	the boot.
6534	**
6535	**---------------------------------------------
6536	*/
6537	if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12) &&
6538	    (tp->usrflag & UF_NOSCAN)) {
6539		tp->usrflag &= ~UF_NOSCAN;
6540		return DID_BAD_TARGET;
6541	}
6542
6543	if (DEBUG_FLAGS & DEBUG_TINY) {
6544		PRINT_ADDR(cmd);
6545		printk ("CMD=%x ", cmd->cmnd[0]);
6546	}
6547
6548	/*---------------------------------------------------
6549	**
6550	**	Assign a ccb / bind cmd.
6551	**	If resetting, shorten settle_time if necessary
6552	**	in order to avoid spurious timeouts.
6553	**	If resetting or no free ccb,
6554	**	insert cmd into the waiting list.
6555	**
6556	**----------------------------------------------------
6557	*/
6558	if (np->settle_time && cmd->timeout_per_command >= HZ) {
6559		u_long tlimit = ktime_get(cmd->timeout_per_command - HZ);
6560		if (ktime_dif(np->settle_time, tlimit) > 0)
6561			np->settle_time = tlimit;
6562	}
6563
6564        if (np->settle_time || !(cp=ncr_get_ccb (np, cmd->target, cmd->lun))) {
6565		insert_into_waiting_list(np, cmd);
6566		return(DID_OK);
6567	}
6568	cp->cmd = cmd;
6569
6570	/*---------------------------------------------------
6571	**
6572	**	Enable tagged queue if asked by scsi ioctl
6573	**
6574	**----------------------------------------------------
6575	*/
6576
6577	/*----------------------------------------------------
6578	**
6579	**	Build the identify / tag / sdtr message
6580	**
6581	**----------------------------------------------------
6582	*/
6583
6584	idmsg = M_IDENTIFY | cp->lun;
6585
6586	if (cp ->tag != NO_TAG || (lp && !(tp->usrflag & UF_NODISC)))
6587		idmsg |= 0x40;
6588
6589	msgptr = cp->scsi_smsg;
6590	msglen = 0;
6591	msgptr[msglen++] = idmsg;
6592
6593	if (cp->tag != NO_TAG) {
6594		char order = np->order;
6595
6596		/*
6597		**	Force ordered tag if necessary to avoid timeouts
6598		**	and to preserve interactivity.
6599		*/
6600		if (lp && ktime_exp(lp->tags_stime)) {
6601			lp->tags_si = !(lp->tags_si);
6602			if (lp->tags_sum[lp->tags_si]) {
6603				order = M_ORDERED_TAG;
6604				if ((DEBUG_FLAGS & DEBUG_TAGS)||bootverbose>0){
6605					PRINT_ADDR(cmd);
6606					printk("ordered tag forced.\n");
6607				}
6608			}
6609			lp->tags_stime = ktime_get(3*HZ);
6610		}
6611
6612		if (order == 0) {
6613			/*
6614			**	Ordered write ops, unordered read ops.
6615			*/
6616			switch (cmd->cmnd[0]) {
6617			case 0x08:  /* READ_SMALL (6) */
6618			case 0x28:  /* READ_BIG  (10) */
6619			case 0xa8:  /* READ_HUGE (12) */
6620				order = M_SIMPLE_TAG;
6621				break;
6622			default:
6623				order = M_ORDERED_TAG;
6624			}
6625		}
6626		msgptr[msglen++] = order;
6627		/*
6628		**	For less than 128 tags, actual tags are numbered
6629		**	1,3,5,..2*MAXTAGS+1,since we may have to deal
6630		**	with devices that have problems with #TAG 0 or too
6631		**	great #TAG numbers. For more tags (up to 256),
6632		**	we use directly our tag number.
6633		*/
6634#if MAX_TASKS > (512/4)
6635		msgptr[msglen++] = cp->tag;
6636#else
6637		msgptr[msglen++] = (cp->tag << 1) + 1;
6638#endif
6639	}
6640
6641	cp->host_flags	= 0;
6642
6643	/*----------------------------------------------------
6644	**
6645	**	Build the data descriptors
6646	**
6647	**----------------------------------------------------
6648	*/
6649
6650	direction = scsi_data_direction(cmd);
6651	if (direction != SCSI_DATA_NONE) {
6652		cp->segments = np->scatter (np, cp, cp->cmd);
6653		if (cp->segments < 0) {
6654			ncr_free_ccb(np, cp);
6655			return(DID_ERROR);
6656		}
6657	}
6658	else {
6659		cp->data_len = 0;
6660		cp->segments = 0;
6661	}
6662
6663	/*---------------------------------------------------
6664	**
6665	**	negotiation required?
6666	**
6667	**	(nego_status is filled by ncr_prepare_nego())
6668	**
6669	**---------------------------------------------------
6670	*/
6671
6672	cp->nego_status = 0;
6673
6674#ifdef	SCSI_NCR_INTEGRITY_CHECKING
6675	if ((np->check_integrity && tp->ic_done) || !np->check_integrity) {
6676		 if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
6677			msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
6678		 }
6679	}
6680	else if (np->check_integrity && (cmd->ic_in_progress)) {
6681		msglen += ncr_ic_nego (np, cp, cmd, msgptr + msglen);
6682        }
6683	else if (np->check_integrity && cmd->ic_complete) {
6684		u_long current_period;
6685		u_char current_offset, current_width, current_factor;
6686
6687		ncr_get_xfer_info (np, tp, &current_factor,
6688					&current_offset, &current_width);
6689
6690		tp->ic_max_width = current_width;
6691		tp->ic_min_sync  = current_factor;
6692
6693		if      (current_factor == 9) 	current_period = 125;
6694		else if (current_factor == 10) 	current_period = 250;
6695		else if (current_factor == 11) 	current_period = 303;
6696		else if (current_factor == 12) 	current_period = 500;
6697		else  			current_period = current_factor * 40;
6698
6699		/*
6700                 * Negotiation for this target is complete. Update flags.
6701                 */
6702		tp->period = current_period;
6703		tp->widedone = 1;
6704		tp->ic_done = 1;
6705
6706		printk("%s: Integrity Check Complete: \n", ncr_name(np));
6707
6708		printk("%s: %s %s SCSI", ncr_name(np),
6709				current_offset?"SYNC":"ASYNC",
6710				tp->ic_max_width?"WIDE":"NARROW");
6711		if (current_offset) {
6712			u_long mbs = 10000 * (tp->ic_max_width + 1);
6713
6714			printk(" %d.%d  MB/s",
6715				(int) (mbs / current_period), (int) (mbs % current_period));
6716
6717			printk(" (%d ns, %d offset)\n",
6718				  (int) current_period/10, current_offset);
6719		}
6720		else
6721			printk(" %d MB/s. \n ", (tp->ic_max_width+1)*5);
6722        }
6723#else
6724	if ((!tp->widedone || !tp->period) && !tp->nego_cp && lp) {
6725		msglen += ncr_prepare_nego (np, cp, msgptr + msglen);
6726	}
6727#endif	/* SCSI_NCR_INTEGRITY_CHECKING */
6728
6729
6730	/*----------------------------------------------------
6731	**
6732	**	Determine xfer direction.
6733	**
6734	**----------------------------------------------------
6735	*/
6736	if (!cp->data_len)
6737		direction = SCSI_DATA_NONE;
6738
6739	/*
6740	**	If data direction is UNKNOWN, speculate DATA_READ
6741	**	but prepare alternate pointers for WRITE in case
6742	**	of our speculation will be just wrong.
6743	**	SCRIPTS will swap values if needed.
6744	*/
6745	switch(direction) {
6746	case SCSI_DATA_UNKNOWN:
6747	case SCSI_DATA_WRITE:
6748		goalp = NCB_SCRIPT_PHYS (np, data_out2) + 8;
6749		lastp = goalp - 8 - (cp->segments * (SCR_SG_SIZE*4));
6750		if (direction != SCSI_DATA_UNKNOWN)
6751			break;
6752		cp->phys.header.wgoalp	= cpu_to_scr(goalp);
6753		cp->phys.header.wlastp	= cpu_to_scr(lastp);
6754		/* fall through */
6755	case SCSI_DATA_READ:
6756		cp->host_flags |= HF_DATA_IN;
6757		goalp = NCB_SCRIPT_PHYS (np, data_in2) + 8;
6758		lastp = goalp - 8 - (cp->segments * (SCR_SG_SIZE*4));
6759		break;
6760	default:
6761	case SCSI_DATA_NONE:
6762		lastp = goalp = NCB_SCRIPTH_PHYS (np, no_data);
6763		break;
6764	}
6765
6766	/*
6767	**	Set all pointers values needed by SCRIPTS.
6768	**	If direction is unknown, start at data_io.
6769	*/
6770	cp->phys.header.lastp = cpu_to_scr(lastp);
6771	cp->phys.header.goalp = cpu_to_scr(goalp);
6772
6773	if (direction == SCSI_DATA_UNKNOWN)
6774		cp->phys.header.savep =
6775			cpu_to_scr(NCB_SCRIPTH_PHYS (np, data_io));
6776	else
6777		cp->phys.header.savep= cpu_to_scr(lastp);
6778
6779	/*
6780	**	Save the initial data pointer in order to be able
6781	**	to redo the command.
6782	**	We also have to save the initial lastp, since it
6783	**	will be changed to DATA_IO if we don't know the data
6784	**	direction and the device completes the command with
6785	**	QUEUE FULL status (without entering the data phase).
6786	*/
6787	cp->startp = cp->phys.header.savep;
6788	cp->lastp0 = cp->phys.header.lastp;
6789
6790	/*----------------------------------------------------
6791	**
6792	**	fill in ccb
6793	**
6794	**----------------------------------------------------
6795	**
6796	**
6797	**	physical -> virtual backlink
6798	**	Generic SCSI command
6799	*/
6800
6801	/*
6802	**	Startqueue
6803	*/
6804	cp->phys.header.go.start   = cpu_to_scr(NCB_SCRIPT_PHYS (np,select));
6805	cp->phys.header.go.restart = cpu_to_scr(NCB_SCRIPT_PHYS (np,resel_dsa));
6806	/*
6807	**	select
6808	*/
6809	cp->phys.select.sel_id		= cp->target;
6810	cp->phys.select.sel_scntl3	= tp->wval;
6811	cp->phys.select.sel_sxfer	= tp->sval;
6812	cp->phys.select.sel_scntl4	= tp->uval;
6813	/*
6814	**	message
6815	*/
6816	cp->phys.smsg.addr	= cpu_to_scr(CCB_PHYS (cp, scsi_smsg));
6817	cp->phys.smsg.size	= cpu_to_scr(msglen);
6818
6819	/*
6820	**	command
6821	*/
6822	memcpy(cp->cdb_buf, cmd->cmnd, MIN(cmd->cmd_len, sizeof(cp->cdb_buf)));
6823	cp->phys.cmd.addr	= cpu_to_scr(CCB_PHYS (cp, cdb_buf[0]));
6824	cp->phys.cmd.size	= cpu_to_scr(cmd->cmd_len);
6825
6826	/*
6827	**	status
6828	*/
6829	cp->actualquirks	= tp->quirks;
6830	cp->host_status		= cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
6831	cp->scsi_status		= S_ILLEGAL;
6832	cp->xerr_status		= 0;
6833	cp->extra_bytes		= 0;
6834
6835	/*
6836	**	extreme data pointer.
6837	**	shall be positive, so -1 is lower than lowest.:)
6838	*/
6839	cp->ext_sg  = -1;
6840	cp->ext_ofs = 0;
6841
6842	/*----------------------------------------------------
6843	**
6844	**	Critical region: start this job.
6845	**
6846	**----------------------------------------------------
6847	*/
6848
6849	/*
6850	**	activate this job.
6851	*/
6852
6853	/*
6854	**	insert next CCBs into start queue.
6855	**	2 max at a time is enough to flush the CCB wait queue.
6856	*/
6857	if (lp)
6858		ncr_start_next_ccb(np, lp, 2);
6859	else
6860		ncr_put_start_queue(np, cp);
6861
6862	/*
6863	**	Command is successfully queued.
6864	*/
6865
6866	return(DID_OK);
6867}
6868
6869
6870/*==========================================================
6871**
6872**
6873**	Insert a CCB into the start queue and wake up the
6874**	SCRIPTS processor.
6875**
6876**
6877**==========================================================
6878*/
6879
6880static void ncr_start_next_ccb(ncb_p np, lcb_p lp, int maxn)
6881{
6882	XPT_QUEHEAD *qp;
6883	ccb_p cp;
6884
6885	while (maxn-- && lp->queuedccbs < lp->queuedepth) {
6886		qp = xpt_remque_head(&lp->wait_ccbq);
6887		if (!qp)
6888			break;
6889		++lp->queuedccbs;
6890		cp = xpt_que_entry(qp, struct ccb, link_ccbq);
6891		xpt_insque_tail(qp, &lp->busy_ccbq);
6892		lp->tasktbl[cp->tag == NO_TAG ? 0 : cp->tag] =
6893			cpu_to_scr(cp->p_ccb);
6894		ncr_put_start_queue(np, cp);
6895	}
6896}
6897
6898static void ncr_put_start_queue(ncb_p np, ccb_p cp)
6899{
6900	u_short	qidx;
6901
6902#ifdef SCSI_NCR_IARB_SUPPORT
6903	/*
6904	**	If the previously queued CCB is not yet done,
6905	**	set the IARB hint. The SCRIPTS will go with IARB
6906	**	for this job when starting the previous one.
6907	**	We leave devices a chance to win arbitration by
6908	**	not using more than 'iarb_max' consecutive
6909	**	immediate arbitrations.
6910	*/
6911	if (np->last_cp && np->iarb_count < np->iarb_max) {
6912		np->last_cp->host_flags |= HF_HINT_IARB;
6913		++np->iarb_count;
6914	}
6915	else
6916		np->iarb_count = 0;
6917	np->last_cp = cp;
6918#endif
6919
6920	/*
6921	**	insert into start queue.
6922	*/
6923	qidx = np->squeueput + 2;
6924	if (qidx >= MAX_START*2) qidx = 0;
6925
6926	np->squeue [qidx]	   = cpu_to_scr(np->p_idletask);
6927	MEMORY_BARRIER();
6928	np->squeue [np->squeueput] = cpu_to_scr(cp->p_ccb);
6929
6930	np->squeueput = qidx;
6931	cp->queued = 1;
6932
6933	if (DEBUG_FLAGS & DEBUG_QUEUE)
6934		printk ("%s: queuepos=%d.\n", ncr_name (np), np->squeueput);
6935
6936	/*
6937	**	Script processor may be waiting for reselect.
6938	**	Wake it up.
6939	*/
6940	MEMORY_BARRIER();
6941	OUTB (nc_istat, SIGP|np->istat_sem);
6942}
6943
6944
6945/*==========================================================
6946**
6947**	Soft reset the chip.
6948**
6949**	Some 896 and 876 chip revisions may hang-up if we set
6950**	the SRST (soft reset) bit at the wrong time when SCRIPTS
6951**	are running.
6952**	So, we need to abort the current operation prior to
6953**	soft resetting the chip.
6954**
6955**==========================================================
6956*/
6957
6958static void ncr_chip_reset (ncb_p np)
6959{
6960	OUTB (nc_istat, SRST);
6961	UDELAY (10);
6962	OUTB (nc_istat, 0);
6963}
6964
6965static void ncr_soft_reset(ncb_p np)
6966{
6967	u_char istat;
6968	int i;
6969
6970	if (!(np->features & FE_ISTAT1) || !(INB (nc_istat1) & SRUN))
6971		goto do_chip_reset;
6972
6973	OUTB (nc_istat, CABRT);
6974	for (i = 100000 ; i ; --i) {
6975		istat = INB (nc_istat);
6976		if (istat & SIP) {
6977			INW (nc_sist);
6978		}
6979		else if (istat & DIP) {
6980			if (INB (nc_dstat) & ABRT);
6981				break;
6982		}
6983		UDELAY(5);
6984	}
6985	OUTB (nc_istat, 0);
6986	if (!i)
6987		printk("%s: unable to abort current chip operation, "
6988		       "ISTAT=0x%02x.\n", ncr_name(np), istat);
6989do_chip_reset:
6990	ncr_chip_reset(np);
6991}
6992
6993/*==========================================================
6994**
6995**
6996**	Start reset process.
6997**	The interrupt handler will reinitialize the chip.
6998**	The timeout handler will wait for settle_time before
6999**	clearing it and so resuming command processing.
7000**
7001**
7002**==========================================================
7003*/
7004static void ncr_start_reset(ncb_p np)
7005{
7006	(void) ncr_reset_scsi_bus(np, 1, driver_setup.settle_delay);
7007}
7008
7009static int ncr_reset_scsi_bus(ncb_p np, int enab_int, int settle_delay)
7010{
7011	u_int32 term;
7012	int retv = 0;
7013
7014	np->settle_time	= ktime_get(settle_delay * HZ);
7015
7016	if (bootverbose > 1)
7017		printk("%s: resetting, "
7018			"command processing suspended for %d seconds\n",
7019			ncr_name(np), settle_delay);
7020
7021	ncr_soft_reset(np);	/* Soft reset the chip */
7022	UDELAY (2000);	/* The 895/6 need time for the bus mode to settle */
7023	if (enab_int)
7024		OUTW (nc_sien, RST);
7025	/*
7026	**	Enable Tolerant, reset IRQD if present and
7027	**	properly set IRQ mode, prior to resetting the bus.
7028	*/
7029	OUTB (nc_stest3, TE);
7030	OUTB (nc_dcntl, (np->rv_dcntl & IRQM));
7031	OUTB (nc_scntl1, CRST);
7032	UDELAY (200);
7033
7034	if (!driver_setup.bus_check)
7035		goto out;
7036	/*
7037	**	Check for no terminators or SCSI bus shorts to ground.
7038	**	Read SCSI data bus, data parity bits and control signals.
7039	**	We are expecting RESET to be TRUE and other signals to be
7040	**	FALSE.
7041	*/
7042	term =	INB(nc_sstat0);
7043	term =	((term & 2) << 7) + ((term & 1) << 17);	/* rst sdp0 */
7044	term |= ((INB(nc_sstat2) & 0x01) << 26) |	/* sdp1     */
7045		((INW(nc_sbdl) & 0xff)   << 9)  |	/* d7-0     */
7046		((INW(nc_sbdl) & 0xff00) << 10) |	/* d15-8    */
7047		INB(nc_sbcl);	/* req ack bsy sel atn msg cd io    */
7048
7049	if (!(np->features & FE_WIDE))
7050		term &= 0x3ffff;
7051
7052	if (term != (2<<7)) {
7053		printk("%s: suspicious SCSI data while resetting the BUS.\n",
7054			ncr_name(np));
7055		printk("%s: %sdp0,d7-0,rst,req,ack,bsy,sel,atn,msg,c/d,i/o = "
7056			"0x%lx, expecting 0x%lx\n",
7057			ncr_name(np),
7058			(np->features & FE_WIDE) ? "dp1,d15-8," : "",
7059			(u_long)term, (u_long)(2<<7));
7060		if (driver_setup.bus_check == 1)
7061			retv = 1;
7062	}
7063out:
7064	OUTB (nc_scntl1, 0);
7065	return retv;
7066}
7067
7068/*==========================================================
7069**
7070**
7071**	Reset the SCSI BUS.
7072**	This is called from the generic SCSI driver.
7073**
7074**
7075**==========================================================
7076*/
7077static int ncr_reset_bus (ncb_p np, Scsi_Cmnd *cmd, int sync_reset)
7078{
7079/*	Scsi_Device        *device    = cmd->device; */
7080	ccb_p cp;
7081	int found;
7082
7083/*
7084 * Return immediately if reset is in progress.
7085 */
7086	if (np->settle_time) {
7087		return SCSI_RESET_PUNT;
7088	}
7089/*
7090 * Start the reset process.
7091 * The script processor is then assumed to be stopped.
7092 * Commands will now be queued in the waiting list until a settle
7093 * delay of 2 seconds will be completed.
7094 */
7095	ncr_start_reset(np);
7096/*
7097 * First, look in the wakeup list
7098 */
7099	for (found=0, cp=np->ccbc; cp; cp=cp->link_ccb) {
7100		/*
7101		**	look for the ccb of this command.
7102		*/
7103		if (cp->host_status == HS_IDLE) continue;
7104		if (cp->cmd == cmd) {
7105			found = 1;
7106			break;
7107		}
7108	}
7109/*
7110 * Then, look in the waiting list
7111 */
7112	if (!found && retrieve_from_waiting_list(0, np, cmd))
7113		found = 1;
7114/*
7115 * Wake-up all awaiting commands with DID_RESET.
7116 */
7117	reset_waiting_list(np);
7118/*
7119 * Wake-up all pending commands with HS_RESET -> DID_RESET.
7120 */
7121	ncr_wakeup(np, HS_RESET);
7122/*
7123 * If the involved command was not in a driver queue, and the
7124 * scsi driver told us reset is synchronous, and the command is not
7125 * currently in the waiting list, complete it with DID_RESET status,
7126 * in order to keep it alive.
7127 */
7128	if (!found && sync_reset && !retrieve_from_waiting_list(0, np, cmd)) {
7129		SetScsiResult(cmd, DID_RESET, 0);
7130		ncr_queue_done_cmd(np, cmd);
7131	}
7132
7133	return SCSI_RESET_SUCCESS;
7134}
7135
7136/*==========================================================
7137**
7138**
7139**	Abort an SCSI command.
7140**	This is called from the generic SCSI driver.
7141**
7142**
7143**==========================================================
7144*/
7145static int ncr_abort_command (ncb_p np, Scsi_Cmnd *cmd)
7146{
7147/*	Scsi_Device        *device    = cmd->device; */
7148	ccb_p cp;
7149
7150/*
7151 * First, look for the scsi command in the waiting list
7152 */
7153	if (remove_from_waiting_list(np, cmd)) {
7154		SetScsiAbortResult(cmd);
7155		ncr_queue_done_cmd(np, cmd);
7156		return SCSI_ABORT_SUCCESS;
7157	}
7158
7159/*
7160 * Then, look in the wakeup list
7161 */
7162	for (cp=np->ccbc; cp; cp=cp->link_ccb) {
7163		/*
7164		**	look for the ccb of this command.
7165		*/
7166		if (cp->host_status == HS_IDLE) continue;
7167		if (cp->cmd == cmd)
7168			break;
7169	}
7170
7171	if (!cp) {
7172		return SCSI_ABORT_NOT_RUNNING;
7173	}
7174
7175	/*
7176	**	Keep track we have to abort this job.
7177	*/
7178	cp->to_abort = 1;
7179
7180	/*
7181	**	Tell the SCRIPTS processor to stop
7182	**	and synchronize with us.
7183	*/
7184	np->istat_sem = SEM;
7185
7186	/*
7187	**      If there are no requests, the script
7188	**      processor will sleep on SEL_WAIT_RESEL.
7189	**      Let's wake it up, since it may have to work.
7190	*/
7191	OUTB (nc_istat, SIGP|SEM);
7192
7193	/*
7194	**	Tell user we are working for him.
7195	*/
7196	return SCSI_ABORT_PENDING;
7197}
7198
7199/*==========================================================
7200**
7201**	Linux release module stuff.
7202**
7203**	Called before unloading the module
7204**	Detach the host.
7205**	We have to free resources and halt the NCR chip
7206**
7207**==========================================================
7208*/
7209
7210#ifdef MODULE
7211static int ncr_detach(ncb_p np)
7212{
7213	int i;
7214
7215	printk("%s: detaching ...\n", ncr_name(np));
7216
7217/*
7218**	Stop the ncr_timeout process
7219**	Set release_stage to 1 and wait that ncr_timeout() set it to 2.
7220*/
7221	np->release_stage = 1;
7222	for (i = 50 ; i && np->release_stage != 2 ; i--) MDELAY (100);
7223	if (np->release_stage != 2)
7224		printk("%s: the timer seems to be already stopped\n",
7225			ncr_name(np));
7226	else np->release_stage = 2;
7227
7228/*
7229**	Reset NCR chip.
7230**	We should use ncr_soft_reset(), but we donnot want to do
7231**	so, since we may not be safe if interrupts occur.
7232*/
7233
7234	printk("%s: resetting chip\n", ncr_name(np));
7235	ncr_chip_reset(np);
7236
7237/*
7238**	Restore bios setting for automatic clock detection.
7239*/
7240	OUTB(nc_dmode,	np->sv_dmode);
7241	OUTB(nc_dcntl,	np->sv_dcntl);
7242	OUTB(nc_ctest3,	np->sv_ctest3);
7243	OUTB(nc_ctest4,	np->sv_ctest4);
7244	OUTB(nc_ctest5,	np->sv_ctest5);
7245	OUTB(nc_gpcntl,	np->sv_gpcntl);
7246	OUTB(nc_stest2,	np->sv_stest2);
7247
7248	ncr_selectclock(np, np->sv_scntl3);
7249/*
7250**	Free host resources
7251*/
7252	ncr_free_resources(np);
7253
7254	return 1;
7255}
7256#endif
7257
7258/*==========================================================
7259**
7260**
7261**	Complete execution of a SCSI command.
7262**	Signal completion to the generic SCSI driver.
7263**
7264**
7265**==========================================================
7266*/
7267
7268void ncr_complete (ncb_p np, ccb_p cp)
7269{
7270	Scsi_Cmnd *cmd;
7271	tcb_p tp;
7272	lcb_p lp;
7273
7274	/*
7275	**	Sanity check
7276	*/
7277	if (!cp || !cp->cmd)
7278		return;
7279
7280	/*
7281	**	Print some debugging info.
7282	*/
7283
7284	if (DEBUG_FLAGS & DEBUG_TINY)
7285		printk ("CCB=%lx STAT=%x/%x\n", (unsigned long)cp,
7286			cp->host_status,cp->scsi_status);
7287
7288	/*
7289	**	Get command, target and lun pointers.
7290	*/
7291
7292	cmd = cp->cmd;
7293	cp->cmd = NULL;
7294	tp = &np->target[cp->target];
7295	lp = ncr_lp(np, tp, cp->lun);
7296
7297	/*
7298	**	We donnot queue more than 1 ccb per target
7299	**	with negotiation at any time. If this ccb was
7300	**	used for negotiation, clear this info in the tcb.
7301	*/
7302
7303	if (cp == tp->nego_cp)
7304		tp->nego_cp = 0;
7305
7306#ifdef SCSI_NCR_IARB_SUPPORT
7307	/*
7308	**	We just complete the last queued CCB.
7309	**	Clear this info that is no more relevant.
7310	*/
7311	if (cp == np->last_cp)
7312		np->last_cp = 0;
7313#endif
7314
7315	/*
7316	**	If auto-sense performed, change scsi status,
7317	**	Otherwise, compute the residual.
7318	*/
7319	if (cp->host_flags & HF_AUTO_SENSE) {
7320		cp->scsi_status = cp->sv_scsi_status;
7321		cp->xerr_status = cp->sv_xerr_status;
7322	}
7323	else {
7324		cp->resid = 0;
7325		if (cp->xerr_status ||
7326		    cp->phys.header.lastp != cp->phys.header.goalp)
7327			cp->resid = ncr_compute_residual(np, cp);
7328	}
7329
7330	/*
7331	**	Check for extended errors.
7332	*/
7333
7334	if (cp->xerr_status) {
7335		if (cp->xerr_status & XE_PARITY_ERR) {
7336			PRINT_ADDR(cmd);
7337			printk ("unrecovered SCSI parity error.\n");
7338		}
7339		if (cp->xerr_status & XE_EXTRA_DATA) {
7340			PRINT_ADDR(cmd);
7341			printk ("extraneous data discarded.\n");
7342		}
7343		if (cp->xerr_status & XE_BAD_PHASE) {
7344			PRINT_ADDR(cmd);
7345			printk ("illegal scsi phase (4/5).\n");
7346		}
7347		if (cp->xerr_status & XE_SODL_UNRUN) {
7348			PRINT_ADDR(cmd);
7349			printk ("ODD transfer in DATA OUT phase.\n");
7350		}
7351		if (cp->xerr_status & XE_SWIDE_OVRUN){
7352			PRINT_ADDR(cmd);
7353			printk ("ODD transfer in DATA IN phase.\n");
7354		}
7355
7356		if (cp->host_status==HS_COMPLETE)
7357			cp->host_status = HS_FAIL;
7358	}
7359
7360	/*
7361	**	Print out any error for debugging purpose.
7362	*/
7363	if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
7364		if (cp->host_status!=HS_COMPLETE || cp->scsi_status!=S_GOOD ||
7365		    cp->resid) {
7366			PRINT_ADDR(cmd);
7367			printk ("ERROR: cmd=%x host_status=%x scsi_status=%x "
7368				"data_len=%d residual=%d\n",
7369				cmd->cmnd[0], cp->host_status, cp->scsi_status,
7370				cp->data_len, cp->resid);
7371		}
7372	}
7373
7374#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,99)
7375	/*
7376	**	Move residual byte count to user structure.
7377	*/
7378	cmd->resid = cp->resid;
7379#endif
7380	/*
7381	**	Check the status.
7382	*/
7383	if (   (cp->host_status == HS_COMPLETE)
7384		&& (cp->scsi_status == S_GOOD ||
7385		    cp->scsi_status == S_COND_MET)) {
7386                /*
7387		**	All went well (GOOD status).
7388		**	CONDITION MET status is returned on
7389                **	`Pre-Fetch' or `Search data' success.
7390                */
7391		SetScsiResult(cmd, DID_OK, cp->scsi_status);
7392
7393		/*
7394		**	Allocate the lcb if not yet.
7395		*/
7396		if (!lp)
7397			ncr_alloc_lcb (np, cp->target, cp->lun);
7398
7399		/*
7400		**	On standard INQUIRY response (EVPD and CmDt
7401		**	not set), setup logical unit according to
7402		**	announced capabilities (we need the 1rst 8 bytes).
7403		*/
7404		if (cmd->cmnd[0] == 0x12 && !(cmd->cmnd[1] & 0x3) &&
7405		    cmd->request_bufflen - cp->resid > 7 && !cmd->use_sg) {
7406			sync_scsi_data(np, cmd);	/* SYNC the data */
7407			ncr_setup_lcb (np, cp->target, cp->lun,
7408				       (char *) cmd->request_buffer);
7409		}
7410
7411		/*
7412		**	If tags was reduced due to queue full,
7413		**	increase tags if 1000 good status received.
7414		*/
7415		if (lp && lp->usetags && lp->numtags < lp->maxtags) {
7416			++lp->num_good;
7417			if (lp->num_good >= 1000) {
7418				lp->num_good = 0;
7419				++lp->numtags;
7420				ncr_setup_tags (np, cp->target, cp->lun);
7421			}
7422		}
7423	} else if ((cp->host_status == HS_COMPLETE)
7424		&& (cp->scsi_status == S_CHECK_COND)) {
7425		/*
7426		**   Check condition code
7427		*/
7428		SetScsiResult(cmd, DID_OK, S_CHECK_COND);
7429
7430		if (DEBUG_FLAGS & (DEBUG_RESULT|DEBUG_TINY)) {
7431			PRINT_ADDR(cmd);
7432			ncr_printl_hex("sense data:", cmd->sense_buffer, 14);
7433		}
7434	} else if ((cp->host_status == HS_COMPLETE)
7435		&& (cp->scsi_status == S_CONFLICT)) {
7436		/*
7437		**   Reservation Conflict condition code
7438		*/
7439		SetScsiResult(cmd, DID_OK, S_CONFLICT);
7440
7441	} else if ((cp->host_status == HS_COMPLETE)
7442		&& (cp->scsi_status == S_BUSY ||
7443		    cp->scsi_status == S_QUEUE_FULL)) {
7444
7445		/*
7446		**   Target is busy.
7447		*/
7448		SetScsiResult(cmd, DID_OK, cp->scsi_status);
7449
7450	} else if ((cp->host_status == HS_SEL_TIMEOUT)
7451		|| (cp->host_status == HS_TIMEOUT)) {
7452
7453		/*
7454		**   No response
7455		*/
7456		SetScsiResult(cmd, DID_TIME_OUT, cp->scsi_status);
7457
7458	} else if (cp->host_status == HS_RESET) {
7459
7460		/*
7461		**   SCSI bus reset
7462		*/
7463		SetScsiResult(cmd, DID_RESET, cp->scsi_status);
7464
7465	} else if (cp->host_status == HS_ABORTED) {
7466
7467		/*
7468		**   Transfer aborted
7469		*/
7470		SetScsiAbortResult(cmd);
7471
7472	} else {
7473		int did_status;
7474
7475		/*
7476		**  Other protocol messes
7477		*/
7478		PRINT_ADDR(cmd);
7479		printk ("COMMAND FAILED (%x %x) @%p.\n",
7480			cp->host_status, cp->scsi_status, cp);
7481
7482		did_status = DID_ERROR;
7483		if (cp->xerr_status & XE_PARITY_ERR)
7484			did_status = DID_PARITY;
7485
7486		SetScsiResult(cmd, did_status, cp->scsi_status);
7487	}
7488
7489	/*
7490	**	trace output
7491	*/
7492
7493	if (tp->usrflag & UF_TRACE) {
7494		PRINT_ADDR(cmd);
7495		printk (" CMD:");
7496		ncr_print_hex(cmd->cmnd, cmd->cmd_len);
7497
7498		if (cp->host_status==HS_COMPLETE) {
7499			switch (cp->scsi_status) {
7500			case S_GOOD:
7501				printk ("  GOOD");
7502				break;
7503			case S_CHECK_COND:
7504				printk ("  SENSE:");
7505				ncr_print_hex(cmd->sense_buffer, 14);
7506				break;
7507			default:
7508				printk ("  STAT: %x\n", cp->scsi_status);
7509				break;
7510			}
7511		} else printk ("  HOSTERROR: %x", cp->host_status);
7512		printk ("\n");
7513	}
7514
7515	/*
7516	**	Free this ccb
7517	*/
7518	ncr_free_ccb (np, cp);
7519
7520	/*
7521	**	requeue awaiting scsi commands for this lun.
7522	*/
7523	if (lp && lp->queuedccbs < lp->queuedepth &&
7524	    !xpt_que_empty(&lp->wait_ccbq))
7525		ncr_start_next_ccb(np, lp, 2);
7526
7527	/*
7528	**	requeue awaiting scsi commands for this controller.
7529	*/
7530	if (np->waiting_list)
7531		requeue_waiting_list(np);
7532
7533	/*
7534	**	signal completion to generic driver.
7535	*/
7536	ncr_queue_done_cmd(np, cmd);
7537}
7538
7539/*==========================================================
7540**
7541**
7542**	Signal all (or one) control block done.
7543**
7544**
7545**==========================================================
7546*/
7547
7548/*
7549**	The NCR has completed CCBs.
7550**	Look at the DONE QUEUE.
7551**
7552**	On architectures that may reorder LOAD/STORE operations,
7553**	a memory barrier may be needed after the reading of the
7554**	so-called `flag' and prior to dealing with the data.
7555*/
7556int ncr_wakeup_done (ncb_p np)
7557{
7558	ccb_p cp;
7559	int i, n;
7560	u_long dsa;
7561
7562	n = 0;
7563	i = np->dqueueget;
7564	while (1) {
7565		dsa = scr_to_cpu(np->dqueue[i]);
7566		if (!dsa)
7567			break;
7568		np->dqueue[i] = 0;
7569		if ((i = i+2) >= MAX_START*2)
7570			i = 0;
7571
7572		cp = ncr_ccb_from_dsa(np, dsa);
7573		if (cp) {
7574			MEMORY_BARRIER();
7575			ncr_complete (np, cp);
7576			++n;
7577		}
7578		else
7579			printk (KERN_ERR "%s: bad DSA (%lx) in done queue.\n",
7580				ncr_name(np), dsa);
7581	}
7582	np->dqueueget = i;
7583
7584	return n;
7585}
7586
7587/*
7588**	Complete all active CCBs.
7589*/
7590void ncr_wakeup (ncb_p np, u_long code)
7591{
7592	ccb_p cp = np->ccbc;
7593
7594	while (cp) {
7595		if (cp->host_status != HS_IDLE) {
7596			cp->host_status = code;
7597			ncr_complete (np, cp);
7598		}
7599		cp = cp->link_ccb;
7600	}
7601}
7602
7603/*==========================================================
7604**
7605**
7606**	Start NCR chip.
7607**
7608**
7609**==========================================================
7610*/
7611
7612void ncr_init (ncb_p np, int reset, char * msg, u_long code)
7613{
7614 	int	i;
7615	u_long	phys;
7616
7617 	/*
7618	**	Reset chip if asked, otherwise just clear fifos.
7619 	*/
7620
7621	if (reset)
7622		ncr_soft_reset(np);
7623	else {
7624		OUTB (nc_stest3, TE|CSF);
7625		OUTONB (nc_ctest3, CLF);
7626	}
7627
7628	/*
7629	**	Message.
7630	*/
7631
7632	if (msg) printk (KERN_INFO "%s: restart (%s).\n", ncr_name (np), msg);
7633
7634	/*
7635	**	Clear Start Queue
7636	*/
7637	phys = np->p_squeue;
7638	np->queuedepth = MAX_START - 1;	/* 1 entry needed as end marker */
7639	for (i = 0; i < MAX_START*2; i += 2) {
7640		np->squeue[i]   = cpu_to_scr(np->p_idletask);
7641		np->squeue[i+1] = cpu_to_scr(phys + (i+2)*4);
7642	}
7643	np->squeue[MAX_START*2-1] = cpu_to_scr(phys);
7644
7645
7646	/*
7647	**	Start at first entry.
7648	*/
7649	np->squeueput = 0;
7650	np->scripth0->startpos[0] = cpu_to_scr(phys);
7651
7652	/*
7653	**	Clear Done Queue
7654	*/
7655	phys = vtobus(np->dqueue);
7656	for (i = 0; i < MAX_START*2; i += 2) {
7657		np->dqueue[i]   = 0;
7658		np->dqueue[i+1] = cpu_to_scr(phys + (i+2)*4);
7659	}
7660	np->dqueue[MAX_START*2-1] = cpu_to_scr(phys);
7661
7662	/*
7663	**	Start at first entry.
7664	*/
7665	np->scripth0->done_pos[0] = cpu_to_scr(phys);
7666	np->dqueueget = 0;
7667
7668	/*
7669	**	Wakeup all pending jobs.
7670	*/
7671	ncr_wakeup (np, code);
7672
7673	/*
7674	**	Init chip.
7675	*/
7676
7677	OUTB (nc_istat,  0x00   );	/*  Remove Reset, abort */
7678	UDELAY (2000);	/* The 895 needs time for the bus mode to settle */
7679
7680	OUTB (nc_scntl0, np->rv_scntl0 | 0xc0);
7681					/*  full arb., ena parity, par->ATN  */
7682	OUTB (nc_scntl1, 0x00);		/*  odd parity, and remove CRST!! */
7683
7684	ncr_selectclock(np, np->rv_scntl3);	/* Select SCSI clock */
7685
7686	OUTB (nc_scid  , RRE|np->myaddr);	/* Adapter SCSI address */
7687	OUTW (nc_respid, 1ul<<np->myaddr);	/* Id to respond to */
7688	OUTB (nc_istat , SIGP	);		/*  Signal Process */
7689	OUTB (nc_dmode , np->rv_dmode);		/* Burst length, dma mode */
7690	OUTB (nc_ctest5, np->rv_ctest5);	/* Large fifo + large burst */
7691
7692	OUTB (nc_dcntl , NOCOM|np->rv_dcntl);	/* Protect SFBR */
7693	OUTB (nc_ctest3, np->rv_ctest3);	/* Write and invalidate */
7694	OUTB (nc_ctest4, np->rv_ctest4);	/* Master parity checking */
7695
7696	if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
7697		(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66)){
7698		OUTB (nc_stest2, EXT|np->rv_stest2);
7699		/* Extended Sreq/Sack filtering, not supported in C1010/C1010_66 */
7700	}
7701	OUTB (nc_stest3, TE);			/* TolerANT enable */
7702	OUTB (nc_stime0, 0x0c);			/* HTH disabled  STO 0.25 sec */
7703
7704	/*
7705	**	DEL 441 - 53C876 Rev 5 - Part Number 609-0392787/2788 - ITEM 2.
7706	**	Disable overlapped arbitration for all dual-function
7707	**	devices, regardless revision id.
7708	**	We may consider it is a post-chip-design feature. ;-)
7709 	**
7710 	**	Errata applies to all 896 and 1010 parts.
7711	*/
7712	if (np->device_id == PCI_DEVICE_ID_NCR_53C875)
7713		OUTB (nc_ctest0, (1<<5));
7714 	else if (np->device_id == PCI_DEVICE_ID_NCR_53C896  ||
7715 		 np->device_id == PCI_DEVICE_ID_LSI_53C1010 ||
7716 		 np->device_id == PCI_DEVICE_ID_LSI_53C1010_66 )
7717		np->rv_ccntl0 |= DPR;
7718
7719	/*
7720	**	C1010_66MHz rev 0 part requies AIPCNTL1 bit 3 to be set.
7721	*/
7722	if (np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)
7723		OUTB(nc_aipcntl1, (1<<3));
7724
7725	/*
7726	**  Write CCNTL0/CCNTL1 for chips capable of 64 bit addressing
7727	**  and/or hardware phase mismatch, since only such chips
7728	**  seem to support those IO registers.
7729	*/
7730	if (np->features & (FE_DAC | FE_NOPM)) {
7731		OUTB (nc_ccntl0, np->rv_ccntl0);
7732		OUTB (nc_ccntl1, np->rv_ccntl1);
7733	}
7734
7735	/*
7736 	**	If phase mismatch handled by scripts (53C895A or 53C896
7737 	**	or 53C1010 or 53C1010_66), set PM jump addresses.
7738	*/
7739
7740	if (np->features & FE_NOPM) {
7741		printk(KERN_INFO "%s: handling phase mismatch from SCRIPTS.\n",
7742		       ncr_name(np));
7743		OUTL (nc_pmjad1, NCB_SCRIPTH_PHYS (np, pm_handle));
7744		OUTL (nc_pmjad2, NCB_SCRIPTH_PHYS (np, pm_handle));
7745	}
7746
7747	/*
7748	**    Enable GPIO0 pin for writing if LED support from SCRIPTS.
7749	**    Also set GPIO5 and clear GPIO6 if hardware LED control.
7750	*/
7751
7752	if (np->features & FE_LED0)
7753		OUTB(nc_gpcntl, INB(nc_gpcntl) & ~0x01);
7754	else if (np->features & FE_LEDC)
7755		OUTB(nc_gpcntl, (INB(nc_gpcntl) & ~0x41) | 0x20);
7756
7757
7758	/*
7759	**      enable ints
7760	*/
7761
7762	OUTW (nc_sien , STO|HTH|MA|SGE|UDC|RST|PAR);
7763	OUTB (nc_dien , MDPE|BF|SSI|SIR|IID);
7764
7765	/*
7766	**	For 895/895A/896/c1010
7767	**	Enable SBMC interrupt and save current SCSI bus mode.
7768	*/
7769	if ( (np->features & FE_ULTRA2) || (np->features & FE_ULTRA3) ) {
7770		OUTONW (nc_sien, SBMC);
7771		np->scsi_mode = INB (nc_stest4) & SMODE;
7772	}
7773
7774	/*
7775	**	Fill in target structure.
7776	**	Reinitialize usrsync.
7777	**	Reinitialize usrwide.
7778	**	Prepare sync negotiation according to actual SCSI bus mode.
7779	*/
7780
7781	for (i=0;i<MAX_TARGET;i++) {
7782		tcb_p tp = &np->target[i];
7783
7784		tp->to_reset = 0;
7785
7786		tp->sval    = 0;
7787		tp->wval    = np->rv_scntl3;
7788		tp->uval    = np->rv_scntl4;
7789
7790		if (tp->usrsync != 255) {
7791			if (tp->usrsync <= np->maxsync) {
7792				if (tp->usrsync < np->minsync) {
7793					tp->usrsync = np->minsync;
7794				}
7795			}
7796			else
7797				tp->usrsync = 255;
7798		};
7799
7800		if (tp->usrwide > np->maxwide)
7801			tp->usrwide = np->maxwide;
7802
7803		ncr_negotiate (np, tp);
7804	}
7805
7806	/*
7807	**    Download SCSI SCRIPTS to on-chip RAM if present,
7808	**    and start script processor.
7809	**    We do the download preferently from the CPU.
7810	**    For platforms that may not support PCI memory mapping,
7811	**    we use a simple SCRIPTS that performs MEMORY MOVEs.
7812	*/
7813	if (np->base2_ba) {
7814		if (bootverbose)
7815			printk ("%s: Downloading SCSI SCRIPTS.\n",
7816				ncr_name(np));
7817#ifdef SCSI_NCR_PCI_MEM_NOT_SUPPORTED
7818		if (np->base2_ws == 8192)
7819			phys = NCB_SCRIPTH0_PHYS (np, start_ram64);
7820		else
7821			phys = NCB_SCRIPTH_PHYS (np, start_ram);
7822#else
7823		if (np->base2_ws == 8192) {
7824			memcpy_to_pci(np->base2_va + 4096,
7825					np->scripth0, sizeof(struct scripth));
7826			OUTL (nc_mmws, np->scr_ram_seg);
7827			OUTL (nc_mmrs, np->scr_ram_seg);
7828			OUTL (nc_sfs,  np->scr_ram_seg);
7829			phys = NCB_SCRIPTH_PHYS (np, start64);
7830		}
7831		else
7832			phys = NCB_SCRIPT_PHYS (np, init);
7833		memcpy_to_pci(np->base2_va, np->script0, sizeof(struct script));
7834#endif /* SCSI_NCR_PCI_MEM_NOT_SUPPORTED */
7835	}
7836	else
7837		phys = NCB_SCRIPT_PHYS (np, init);
7838
7839	np->istat_sem = 0;
7840
7841	OUTL (nc_dsa, np->p_ncb);
7842	OUTL_DSP (phys);
7843}
7844
7845/*==========================================================
7846**
7847**	Prepare the negotiation values for wide and
7848**	synchronous transfers.
7849**
7850**==========================================================
7851*/
7852
7853static void ncr_negotiate (struct ncb* np, struct tcb* tp)
7854{
7855	/*
7856	**	minsync unit is 4ns !
7857	*/
7858
7859	u_long minsync = tp->usrsync;
7860
7861	/*
7862	**	SCSI bus mode limit
7863	*/
7864
7865	if (np->scsi_mode && np->scsi_mode == SMODE_SE) {
7866		if (minsync < 12) minsync = 12;
7867	}
7868
7869	/*
7870	**	our limit ..
7871	*/
7872
7873	if (minsync < np->minsync)
7874		minsync = np->minsync;
7875
7876	/*
7877	**	divider limit
7878	*/
7879
7880	if (minsync > np->maxsync)
7881		minsync = 255;
7882
7883	tp->minsync = minsync;
7884	tp->maxoffs = (minsync<255 ? np->maxoffs : 0);
7885
7886	/*
7887	**	period=0: has to negotiate sync transfer
7888	*/
7889
7890	tp->period=0;
7891
7892	/*
7893	**	widedone=0: has to negotiate wide transfer
7894	*/
7895	tp->widedone=0;
7896}
7897
7898/*==========================================================
7899**
7900**	Get clock factor and sync divisor for a given
7901**	synchronous factor period.
7902**	Returns the clock factor (in sxfer) and scntl3
7903**	synchronous divisor field.
7904**
7905**==========================================================
7906*/
7907
7908static void ncr_getsync(ncb_p np, u_char sfac, u_char *fakp, u_char *scntl3p)
7909{
7910	u_long	clk = np->clock_khz;	/* SCSI clock frequency in kHz	*/
7911	int	div = np->clock_divn;	/* Number of divisors supported	*/
7912	u_long	fak;			/* Sync factor in sxfer		*/
7913	u_long	per;			/* Period in tenths of ns	*/
7914	u_long	kpc;			/* (per * clk)			*/
7915
7916	/*
7917	**	Compute the synchronous period in tenths of nano-seconds
7918	**	from sfac.
7919	**
7920	**	Note, if sfac == 9, DT is being used. Double the period of 125
7921	**	to 250.
7922	*/
7923	if	(sfac <= 10)	per = 250;
7924	else if	(sfac == 11)	per = 303;
7925	else if	(sfac == 12)	per = 500;
7926	else			per = 40 * sfac;
7927
7928	/*
7929	**	Look for the greatest clock divisor that allows an
7930	**	input speed faster than the period.
7931	*/
7932	kpc = per * clk;
7933	while (--div >= 0)
7934		if (kpc >= (div_10M[div] << 2)) break;
7935
7936	/*
7937	**	Calculate the lowest clock factor that allows an output
7938	**	speed not faster than the period.
7939	*/
7940	fak = (kpc - 1) / div_10M[div] + 1;
7941
7942
7943	if (fak < 4) fak = 4;	/* Should never happen, too bad ... */
7944
7945	/*
7946	**	Compute and return sync parameters for the ncr
7947	*/
7948	*fakp		= fak - 4;
7949
7950	/*
7951	** If sfac < 25, and 8xx parts, desire that the chip operate at
7952	** least at Ultra speeds.  Must set bit 7 of scntl3.
7953	** For C1010, do not set this bit. If operating at Ultra3 speeds,
7954	**	set the U3EN bit instead.
7955	*/
7956	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010)  ||
7957			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
7958		*scntl3p	= (div+1) << 4;
7959		*fakp		= 0;
7960	}
7961	else {
7962		*scntl3p	= ((div+1) << 4) + (sfac < 25 ? 0x80 : 0);
7963		*fakp		= fak - 4;
7964	}
7965}
7966
7967/*==========================================================
7968**
7969**	Utility routine to return the current bus width
7970**	synchronous period and offset.
7971**	Utilizes target sval, wval and uval
7972**
7973**==========================================================
7974*/
7975static void ncr_get_xfer_info(ncb_p np, tcb_p tp, u_char *factor,
7976			u_char *offset, u_char *width)
7977{
7978
7979	u_char idiv;
7980	u_long period;
7981
7982	*width = (tp->wval & EWS) ? 1 : 0;
7983
7984	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
7985		(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66))
7986		*offset  = (tp->sval & 0x3f);
7987	else
7988		*offset  = (tp->sval & 0x1f);
7989
7990        /*
7991	 * Midlayer signal to the driver that all of the scsi commands
7992	 * for the integrity check have completed. Save the negotiated
7993 	 * parameters (extracted from sval, wval and uval).
7994	 * See ncr_setsync for alg. details.
7995	 */
7996
7997	idiv = (tp->wval>>4) & 0x07;
7998
7999	if ( *offset && idiv ) {
8000	  	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8001	  		(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)){
8002		    if (tp->uval & 0x80)
8003			period = (2*div_10M[idiv-1])/np->clock_khz;
8004	    	    else
8005	    		period = (4*div_10M[idiv-1])/np->clock_khz;
8006	  	}
8007	  	else
8008	   	    period = (((tp->sval>>5)+4)*div_10M[idiv-1])/np->clock_khz;
8009	}
8010	else
8011		period = 0xffff;
8012
8013	if	(period <= 125)		*factor =   9;
8014	else if	(period <= 250)		*factor =  10;
8015	else if	(period <= 303)		*factor  = 11;
8016	else if	(period <= 500)		*factor  = 12;
8017	else				*factor  = (period + 40 - 1) / 40;
8018
8019}
8020
8021
8022/*==========================================================
8023**
8024**	Set actual values, sync status and patch all ccbs of
8025**	a target according to new sync/wide agreement.
8026**
8027**==========================================================
8028*/
8029
8030static void ncr_set_sync_wide_status (ncb_p np, u_char target)
8031{
8032	ccb_p cp = np->ccbc;
8033	tcb_p tp = &np->target[target];
8034
8035	/*
8036	**	set actual value and sync_status
8037	**
8038	**	TEMP register contains current scripts address
8039	**	which is data type/direction/dependent.
8040	*/
8041	OUTB (nc_sxfer, tp->sval);
8042	OUTB (nc_scntl3, tp->wval);
8043	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010)  ||
8044			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66))
8045		OUTB (nc_scntl4, tp->uval);
8046
8047	/*
8048	**	patch ALL ccbs of this target.
8049	*/
8050	for (cp = np->ccbc; cp; cp = cp->link_ccb) {
8051		if (cp->host_status == HS_IDLE)
8052			continue;
8053		if (cp->target != target)
8054			continue;
8055		cp->phys.select.sel_scntl3 = tp->wval;
8056		cp->phys.select.sel_sxfer  = tp->sval;
8057		if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8058				(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66))
8059			cp->phys.select.sel_scntl4 = tp->uval;
8060	};
8061}
8062
8063/*==========================================================
8064**
8065**	Switch sync mode for current job and it's target
8066**
8067**==========================================================
8068*/
8069
8070static void ncr_setsync (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer,
8071					u_char scntl4)
8072{
8073	tcb_p tp;
8074	u_char target = INB (nc_sdid) & 0x0f;
8075	u_char idiv;
8076	u_char offset;
8077
8078	assert (cp);
8079	if (!cp) return;
8080
8081	assert (target == (cp->target & 0xf));
8082
8083	tp = &np->target[target];
8084
8085	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8086			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
8087		offset = sxfer & 0x3f; /* bits 5-0 */
8088		scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS);
8089		scntl4 = (scntl4 & 0x80);
8090	}
8091	else {
8092		offset = sxfer & 0x1f; /* bits 4-0 */
8093		if (!scntl3 || !offset)
8094			scntl3 = np->rv_scntl3;
8095
8096		scntl3 = (scntl3 & 0xf0) | (tp->wval & EWS) |
8097				(np->rv_scntl3 & 0x07);
8098	}
8099
8100
8101	/*
8102	**	Deduce the value of controller sync period from scntl3.
8103	**	period is in tenths of nano-seconds.
8104	*/
8105
8106	idiv = ((scntl3 >> 4) & 0x7);
8107	if ( offset && idiv) {
8108		if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8109			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
8110			/* Note: If extra data hold clocks are used,
8111			 * the formulas below must be modified.
8112			 * When scntl4 == 0, ST mode.
8113			 */
8114			if (scntl4 & 0x80)
8115				tp->period = (2*div_10M[idiv-1])/np->clock_khz;
8116			else
8117				tp->period = (4*div_10M[idiv-1])/np->clock_khz;
8118		}
8119		else
8120			tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
8121	}
8122	else
8123		tp->period = 0xffff;
8124
8125
8126	/*
8127	**	 Stop there if sync parameters are unchanged
8128	*/
8129	if (tp->sval == sxfer && tp->wval == scntl3 && tp->uval == scntl4) return;
8130	tp->sval = sxfer;
8131	tp->wval = scntl3;
8132	tp->uval = scntl4;
8133
8134	/*
8135	**	Bells and whistles   ;-)
8136	**	Donnot announce negotiations due to auto-sense,
8137	**	unless user really want us to be verbose. :)
8138	*/
8139	if ( bootverbose < 2 && (cp->host_flags & HF_AUTO_SENSE))
8140		goto next;
8141	PRINT_TARGET(np, target);
8142	if (offset) {
8143		unsigned f10 = 100000 << (tp->widedone ? tp->widedone -1 : 0);
8144		unsigned mb10 = (f10 + tp->period/2) / tp->period;
8145		char *scsi;
8146
8147		/*
8148		**  Disable extended Sreq/Sack filtering
8149		*/
8150		if ((tp->period <= 2000) &&
8151			(np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
8152			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
8153				OUTOFFB (nc_stest2, EXT);
8154
8155		/*
8156		**	Bells and whistles   ;-)
8157		*/
8158		if	(tp->period < 250)	scsi = "FAST-80";
8159		else if	(tp->period < 500)	scsi = "FAST-40";
8160		else if	(tp->period < 1000)	scsi = "FAST-20";
8161		else if	(tp->period < 2000)	scsi = "FAST-10";
8162		else				scsi = "FAST-5";
8163
8164		printk ("%s %sSCSI %d.%d MB/s (%d.%d ns, offset %d)\n", scsi,
8165			tp->widedone > 1 ? "WIDE " : "",
8166			mb10 / 10, mb10 % 10, tp->period / 10, tp->period % 10,
8167			offset);
8168	} else
8169		printk ("%sasynchronous.\n", tp->widedone > 1 ? "wide " : "");
8170next:
8171	/*
8172	**	set actual value and sync_status
8173	**	patch ALL ccbs of this target.
8174	*/
8175	ncr_set_sync_wide_status(np, target);
8176}
8177
8178
8179/*==========================================================
8180**
8181**	Switch wide mode for current job and it's target
8182**	SCSI specs say: a SCSI device that accepts a WDTR
8183**	message shall reset the synchronous agreement to
8184**	asynchronous mode.
8185**
8186**==========================================================
8187*/
8188
8189static void ncr_setwide (ncb_p np, ccb_p cp, u_char wide, u_char ack)
8190{
8191	u_short target = INB (nc_sdid) & 0x0f;
8192	tcb_p tp;
8193	u_char	scntl3;
8194	u_char	sxfer;
8195
8196	assert (cp);
8197	if (!cp) return;
8198
8199	assert (target == (cp->target & 0xf));
8200
8201	tp = &np->target[target];
8202	tp->widedone  =  wide+1;
8203	scntl3 = (tp->wval & (~EWS)) | (wide ? EWS : 0);
8204
8205	sxfer = ack ? 0 : tp->sval;
8206
8207	/*
8208	**	 Stop there if sync/wide parameters are unchanged
8209	*/
8210	if (tp->sval == sxfer && tp->wval == scntl3) return;
8211	tp->sval = sxfer;
8212	tp->wval = scntl3;
8213
8214	/*
8215	**	Bells and whistles   ;-)
8216	*/
8217	if (bootverbose >= 2) {
8218		PRINT_TARGET(np, target);
8219		if (scntl3 & EWS)
8220			printk ("WIDE SCSI (16 bit) enabled.\n");
8221		else
8222			printk ("WIDE SCSI disabled.\n");
8223	}
8224
8225	/*
8226	**	set actual value and sync_status
8227	**	patch ALL ccbs of this target.
8228	*/
8229	ncr_set_sync_wide_status(np, target);
8230}
8231
8232
8233/*==========================================================
8234**
8235**	Switch sync/wide mode for current job and it's target
8236**	PPR negotiations only
8237**
8238**==========================================================
8239*/
8240
8241static void ncr_setsyncwide (ncb_p np, ccb_p cp, u_char scntl3, u_char sxfer,
8242				u_char scntl4, u_char wide)
8243{
8244	tcb_p tp;
8245	u_char target = INB (nc_sdid) & 0x0f;
8246	u_char idiv;
8247	u_char offset;
8248
8249	assert (cp);
8250	if (!cp) return;
8251
8252	assert (target == (cp->target & 0xf));
8253
8254	tp = &np->target[target];
8255	tp->widedone  =  wide+1;
8256
8257	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8258			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
8259		offset = sxfer & 0x3f; /* bits 5-0 */
8260		scntl3 = (scntl3 & 0xf0) | (wide ? EWS : 0);
8261		scntl4 = (scntl4 & 0x80);
8262	}
8263	else {
8264		offset = sxfer & 0x1f; /* bits 4-0 */
8265		if (!scntl3 || !offset)
8266			scntl3 = np->rv_scntl3;
8267
8268		scntl3 = (scntl3 & 0xf0) | (wide ? EWS : 0) |
8269				(np->rv_scntl3 & 0x07);
8270	}
8271
8272
8273	/*
8274	**	Deduce the value of controller sync period from scntl3.
8275	**	period is in tenths of nano-seconds.
8276	*/
8277
8278	idiv = ((scntl3 >> 4) & 0x7);
8279	if ( offset && idiv) {
8280		if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8281			(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
8282			/* Note: If extra data hold clocks are used,
8283			 * the formulas below must be modified.
8284			 * When scntl4 == 0, ST mode.
8285			 */
8286			if (scntl4 & 0x80)
8287				tp->period = (2*div_10M[idiv-1])/np->clock_khz;
8288			else
8289				tp->period = (4*div_10M[idiv-1])/np->clock_khz;
8290		}
8291		else
8292			tp->period = (((sxfer>>5)+4)*div_10M[idiv-1])/np->clock_khz;
8293	}
8294	else
8295		tp->period = 0xffff;
8296
8297
8298	/*
8299	**	 Stop there if sync parameters are unchanged
8300	*/
8301	if (tp->sval == sxfer && tp->wval == scntl3 && tp->uval == scntl4) return;
8302	tp->sval = sxfer;
8303	tp->wval = scntl3;
8304	tp->uval = scntl4;
8305
8306	/*
8307	**	Bells and whistles   ;-)
8308	**	Donnot announce negotiations due to auto-sense,
8309	**	unless user really want us to be verbose. :)
8310	*/
8311	if ( bootverbose < 2 && (cp->host_flags & HF_AUTO_SENSE))
8312		goto next;
8313	PRINT_TARGET(np, target);
8314	if (offset) {
8315		unsigned f10 = 100000 << (tp->widedone ? tp->widedone -1 : 0);
8316		unsigned mb10 = (f10 + tp->period/2) / tp->period;
8317		char *scsi;
8318
8319		/*
8320		**  Disable extended Sreq/Sack filtering
8321		*/
8322		if ((tp->period <= 2000) &&
8323			(np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
8324			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
8325				OUTOFFB (nc_stest2, EXT);
8326
8327		/*
8328		**	Bells and whistles   ;-)
8329		*/
8330		if	(tp->period < 250)	scsi = "FAST-80";
8331		else if	(tp->period < 500)	scsi = "FAST-40";
8332		else if	(tp->period < 1000)	scsi = "FAST-20";
8333		else if	(tp->period < 2000)	scsi = "FAST-10";
8334		else				scsi = "FAST-5";
8335
8336		printk ("%s %sSCSI %d.%d MB/s (%d.%d ns, offset %d)\n", scsi,
8337			tp->widedone > 1 ? "WIDE " : "",
8338			mb10 / 10, mb10 % 10, tp->period / 10, tp->period % 10,
8339			offset);
8340	} else
8341		printk ("%sasynchronous.\n", tp->widedone > 1 ? "wide " : "");
8342next:
8343	/*
8344	**	set actual value and sync_status
8345	**	patch ALL ccbs of this target.
8346	*/
8347	ncr_set_sync_wide_status(np, target);
8348}
8349
8350
8351
8352
8353/*==========================================================
8354**
8355**	Switch tagged mode for a target.
8356**
8357**==========================================================
8358*/
8359
8360static void ncr_setup_tags (ncb_p np, u_char tn, u_char ln)
8361{
8362	tcb_p tp = &np->target[tn];
8363	lcb_p lp = ncr_lp(np, tp, ln);
8364	u_short reqtags, maxdepth;
8365
8366	/*
8367	**	Just in case ...
8368	*/
8369	if ((!tp) || (!lp))
8370		return;
8371
8372	/*
8373	**	If SCSI device queue depth is not yet set, leave here.
8374	*/
8375	if (!lp->scdev_depth)
8376		return;
8377
8378	/*
8379	**	Donnot allow more tags than the SCSI driver can queue
8380	**	for this device.
8381	**	Donnot allow more tags than we can handle.
8382	*/
8383	maxdepth = lp->scdev_depth;
8384	if (maxdepth > lp->maxnxs)	maxdepth    = lp->maxnxs;
8385	if (lp->maxtags > maxdepth)	lp->maxtags = maxdepth;
8386	if (lp->numtags > maxdepth)	lp->numtags = maxdepth;
8387
8388	/*
8389	**	only devices conformant to ANSI Version >= 2
8390	**	only devices capable of tagged commands
8391	**	only if enabled by user ..
8392	*/
8393	if ((lp->inq_byte7 & INQ7_QUEUE) && lp->numtags > 1) {
8394		reqtags = lp->numtags;
8395	} else {
8396		reqtags = 1;
8397	};
8398
8399	/*
8400	**	Update max number of tags
8401	*/
8402	lp->numtags = reqtags;
8403	if (lp->numtags > lp->maxtags)
8404		lp->maxtags = lp->numtags;
8405
8406	/*
8407	**	If we want to switch tag mode, we must wait
8408	**	for no CCB to be active.
8409	*/
8410	if	(reqtags > 1 && lp->usetags) {	 /* Stay in tagged mode    */
8411		if (lp->queuedepth == reqtags)	 /* Already announced	   */
8412			return;
8413		lp->queuedepth	= reqtags;
8414	}
8415	else if	(reqtags <= 1 && !lp->usetags) { /* Stay in untagged mode  */
8416		lp->queuedepth	= reqtags;
8417		return;
8418	}
8419	else {					 /* Want to switch tag mode */
8420		if (lp->busyccbs)		 /* If not yet safe, return */
8421			return;
8422		lp->queuedepth	= reqtags;
8423		lp->usetags	= reqtags > 1 ? 1 : 0;
8424	}
8425
8426	/*
8427	**	Patch the lun mini-script, according to tag mode.
8428	*/
8429	lp->resel_task = lp->usetags?
8430			cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_tag)) :
8431			cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
8432
8433	/*
8434	**	Announce change to user.
8435	*/
8436	if (bootverbose) {
8437		PRINT_LUN(np, tn, ln);
8438		if (lp->usetags)
8439			printk("tagged command queue depth set to %d\n", reqtags);
8440		else
8441			printk("tagged command queueing disabled\n");
8442	}
8443}
8444
8445/*----------------------------------------------------
8446**
8447**	handle user commands
8448**
8449**----------------------------------------------------
8450*/
8451
8452#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
8453
8454static void ncr_usercmd (ncb_p np)
8455{
8456	u_char t;
8457	tcb_p tp;
8458	int ln;
8459	u_long size;
8460
8461	switch (np->user.cmd) {
8462	case 0: return;
8463
8464	case UC_SETDEBUG:
8465#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
8466		ncr_debug = np->user.data;
8467#endif
8468		break;
8469
8470	case UC_SETORDER:
8471		np->order = np->user.data;
8472		break;
8473
8474	case UC_SETVERBOSE:
8475		np->verbose = np->user.data;
8476		break;
8477
8478	default:
8479		/*
8480		**	We assume that other commands apply to targets.
8481		**	This should always be the case and avoid the below
8482		**	4 lines to be repeated 5 times.
8483		*/
8484		for (t = 0; t < MAX_TARGET; t++) {
8485			if (!((np->user.target >> t) & 1))
8486				continue;
8487			tp = &np->target[t];
8488
8489			switch (np->user.cmd) {
8490
8491			case UC_SETSYNC:
8492				tp->usrsync = np->user.data;
8493				ncr_negotiate (np, tp);
8494				break;
8495
8496			case UC_SETWIDE:
8497				size = np->user.data;
8498				if (size > np->maxwide)
8499					size=np->maxwide;
8500				tp->usrwide = size;
8501				ncr_negotiate (np, tp);
8502				break;
8503
8504			case UC_SETTAGS:
8505				tp->usrtags = np->user.data;
8506				for (ln = 0; ln < MAX_LUN; ln++) {
8507					lcb_p lp;
8508					lp = ncr_lp(np, tp, ln);
8509					if (!lp)
8510						continue;
8511					lp->numtags = np->user.data;
8512					lp->maxtags = lp->numtags;
8513					ncr_setup_tags (np, t, ln);
8514				}
8515				break;
8516
8517			case UC_RESETDEV:
8518				tp->to_reset = 1;
8519				np->istat_sem = SEM;
8520				OUTB (nc_istat, SIGP|SEM);
8521				break;
8522
8523			case UC_CLEARDEV:
8524				for (ln = 0; ln < MAX_LUN; ln++) {
8525					lcb_p lp;
8526					lp = ncr_lp(np, tp, ln);
8527					if (lp)
8528						lp->to_clear = 1;
8529				}
8530				np->istat_sem = SEM;
8531				OUTB (nc_istat, SIGP|SEM);
8532				break;
8533
8534			case UC_SETFLAG:
8535				tp->usrflag = np->user.data;
8536				break;
8537			}
8538		}
8539		break;
8540	}
8541	np->user.cmd=0;
8542}
8543#endif
8544
8545/*==========================================================
8546**
8547**
8548**	ncr timeout handler.
8549**
8550**
8551**==========================================================
8552**
8553**	Misused to keep the driver running when
8554**	interrupts are not configured correctly.
8555**
8556**----------------------------------------------------------
8557*/
8558
8559static void ncr_timeout (ncb_p np)
8560{
8561	u_long	thistime = ktime_get(0);
8562
8563	/*
8564	**	If release process in progress, let's go
8565	**	Set the release stage from 1 to 2 to synchronize
8566	**	with the release process.
8567	*/
8568
8569	if (np->release_stage) {
8570		if (np->release_stage == 1) np->release_stage = 2;
8571		return;
8572	}
8573
8574#ifdef SCSI_NCR_PCIQ_BROKEN_INTR
8575	np->timer.expires = ktime_get((HZ+9)/10);
8576#else
8577	np->timer.expires = ktime_get(SCSI_NCR_TIMER_INTERVAL);
8578#endif
8579	add_timer(&np->timer);
8580
8581	/*
8582	**	If we are resetting the ncr, wait for settle_time before
8583	**	clearing it. Then command processing will be resumed.
8584	*/
8585	if (np->settle_time) {
8586		if (np->settle_time <= thistime) {
8587			if (bootverbose > 1)
8588				printk("%s: command processing resumed\n", ncr_name(np));
8589			np->settle_time	= 0;
8590			requeue_waiting_list(np);
8591		}
8592		return;
8593	}
8594
8595	/*
8596	**	Nothing to do for now, but that may come.
8597	*/
8598	if (np->lasttime + 4*HZ < thistime) {
8599		np->lasttime = thistime;
8600	}
8601
8602#ifdef SCSI_NCR_PCIQ_MAY_MISS_COMPLETIONS
8603	/*
8604	**	Some way-broken PCI bridges may lead to
8605	**	completions being lost when the clearing
8606	**	of the INTFLY flag by the CPU occurs
8607	**	concurrently with the chip raising this flag.
8608	**	If this ever happen, lost completions will
8609	**	be reaped here.
8610	*/
8611	ncr_wakeup_done(np);
8612#endif
8613
8614#ifdef SCSI_NCR_PCIQ_BROKEN_INTR
8615	if (INB(nc_istat) & (INTF|SIP|DIP)) {
8616
8617		/*
8618		**	Process pending interrupts.
8619		*/
8620		if (DEBUG_FLAGS & DEBUG_TINY) printk ("{");
8621		ncr_exception (np);
8622		if (DEBUG_FLAGS & DEBUG_TINY) printk ("}");
8623	}
8624#endif /* SCSI_NCR_PCIQ_BROKEN_INTR */
8625}
8626
8627/*==========================================================
8628**
8629**	log message for real hard errors
8630**
8631**	"ncr0 targ 0?: ERROR (ds:si) (so-si-sd) (sxfer/scntl3) @ name (dsp:dbc)."
8632**	"	      reg: r0 r1 r2 r3 r4 r5 r6 ..... rf."
8633**
8634**	exception register:
8635**		ds:	dstat
8636**		si:	sist
8637**
8638**	SCSI bus lines:
8639**		so:	control lines as driver by NCR.
8640**		si:	control lines as seen by NCR.
8641**		sd:	scsi data lines as seen by NCR.
8642**
8643**	wide/fastmode:
8644**		sxfer:	(see the manual)
8645**		scntl3:	(see the manual)
8646**
8647**	current script command:
8648**		dsp:	script address (relative to start of script).
8649**		dbc:	first word of script command.
8650**
8651**	First 24 register of the chip:
8652**		r0..rf
8653**
8654**==========================================================
8655*/
8656
8657static void ncr_log_hard_error(ncb_p np, u_short sist, u_char dstat)
8658{
8659	u_int32	dsp;
8660	int	script_ofs;
8661	int	script_size;
8662	char	*script_name;
8663	u_char	*script_base;
8664	int	i;
8665
8666	dsp	= INL (nc_dsp);
8667
8668	if (dsp > np->p_script && dsp <= np->p_script + sizeof(struct script)) {
8669		script_ofs	= dsp - np->p_script;
8670		script_size	= sizeof(struct script);
8671		script_base	= (u_char *) np->script0;
8672		script_name	= "script";
8673	}
8674	else if (np->p_scripth < dsp &&
8675		 dsp <= np->p_scripth + sizeof(struct scripth)) {
8676		script_ofs	= dsp - np->p_scripth;
8677		script_size	= sizeof(struct scripth);
8678		script_base	= (u_char *) np->scripth0;
8679		script_name	= "scripth";
8680	} else {
8681		script_ofs	= dsp;
8682		script_size	= 0;
8683		script_base	= 0;
8684		script_name	= "mem";
8685	}
8686
8687	printk ("%s:%d: ERROR (%x:%x) (%x-%x-%x) (%x/%x) @ (%s %x:%08x).\n",
8688		ncr_name (np), (unsigned)INB (nc_sdid)&0x0f, dstat, sist,
8689		(unsigned)INB (nc_socl), (unsigned)INB (nc_sbcl), (unsigned)INB (nc_sbdl),
8690		(unsigned)INB (nc_sxfer),(unsigned)INB (nc_scntl3), script_name, script_ofs,
8691		(unsigned)INL (nc_dbc));
8692
8693	if (((script_ofs & 3) == 0) &&
8694	    (unsigned)script_ofs < script_size) {
8695		printk ("%s: script cmd = %08x\n", ncr_name(np),
8696			scr_to_cpu((int) *(ncrcmd *)(script_base + script_ofs)));
8697	}
8698
8699        printk ("%s: regdump:", ncr_name(np));
8700        for (i=0; i<24;i++)
8701            printk (" %02x", (unsigned)INB_OFF(i));
8702        printk (".\n");
8703}
8704
8705/*============================================================
8706**
8707**	ncr chip exception handler.
8708**
8709**============================================================
8710**
8711**	In normal situations, interrupt conditions occur one at
8712**	a time. But when something bad happens on the SCSI BUS,
8713**	the chip may raise several interrupt flags before
8714**	stopping and interrupting the CPU. The additionnal
8715**	interrupt flags are stacked in some extra registers
8716**	after the SIP and/or DIP flag has been raised in the
8717**	ISTAT. After the CPU has read the interrupt condition
8718**	flag from SIST or DSTAT, the chip unstacks the other
8719**	interrupt flags and sets the corresponding bits in
8720**	SIST or DSTAT. Since the chip starts stacking once the
8721**	SIP or DIP flag is set, there is a small window of time
8722**	where the stacking does not occur.
8723**
8724**	Typically, multiple interrupt conditions may happen in
8725**	the following situations:
8726**
8727**	- SCSI parity error + Phase mismatch  (PAR|MA)
8728**	  When an parity error is detected in input phase
8729**	  and the device switches to msg-in phase inside a
8730**	  block MOV.
8731**	- SCSI parity error + Unexpected disconnect (PAR|UDC)
8732**	  When a stupid device does not want to handle the
8733**	  recovery of an SCSI parity error.
8734**	- Some combinations of STO, PAR, UDC, ...
8735**	  When using non compliant SCSI stuff, when user is
8736**	  doing non compliant hot tampering on the BUS, when
8737**	  something really bad happens to a device, etc ...
8738**
8739**	The heuristic suggested by SYMBIOS to handle
8740**	multiple interrupts is to try unstacking all
8741**	interrupts conditions and to handle them on some
8742**	priority based on error severity.
8743**	This will work when the unstacking has been
8744**	successful, but we cannot be 100 % sure of that,
8745**	since the CPU may have been faster to unstack than
8746**	the chip is able to stack. Hmmm ... But it seems that
8747**	such a situation is very unlikely to happen.
8748**
8749**	If this happen, for example STO catched by the CPU
8750**	then UDC happenning before the CPU have restarted
8751**	the SCRIPTS, the driver may wrongly complete the
8752**	same command on UDC, since the SCRIPTS didn't restart
8753**	and the DSA still points to the same command.
8754**	We avoid this situation by setting the DSA to an
8755**	invalid value when the CCB is completed and before
8756**	restarting the SCRIPTS.
8757**
8758**	Another issue is that we need some section of our
8759**	recovery procedures to be somehow uninterruptible and
8760**	that the SCRIPTS processor does not provides such a
8761**	feature. For this reason, we handle recovery preferently
8762**	from the C code	and check against some SCRIPTS
8763**	critical sections from the C code.
8764**
8765**	Hopefully, the interrupt handling of the driver is now
8766**	able to resist to weird BUS error conditions, but donnot
8767**	ask me for any guarantee that it will never fail. :-)
8768**	Use at your own decision and risk.
8769**
8770**============================================================
8771*/
8772
8773void ncr_exception (ncb_p np)
8774{
8775	u_char	istat, istatc;
8776	u_char	dstat;
8777	u_short	sist;
8778	int	i;
8779
8780	/*
8781	**	interrupt on the fly ?
8782	**
8783	**	A `dummy read' is needed to ensure that the
8784	**	clear of the INTF flag reaches the device
8785	**	before the scanning of the DONE queue.
8786	*/
8787	istat = INB (nc_istat);
8788	if (istat & INTF) {
8789		OUTB (nc_istat, (istat & SIGP) | INTF | np->istat_sem);
8790		istat = INB (nc_istat);		/* DUMMY READ */
8791		if (DEBUG_FLAGS & DEBUG_TINY) printk ("F ");
8792		(void)ncr_wakeup_done (np);
8793	};
8794
8795	if (!(istat & (SIP|DIP)))
8796		return;
8797
8798
8799	/*
8800	**	Steinbach's Guideline for Systems Programming:
8801	**	Never test for an error condition you don't know how to handle.
8802	*/
8803
8804	/*========================================================
8805	**	PAR and MA interrupts may occur at the same time,
8806	**	and we need to know of both in order to handle
8807	**	this situation properly. We try to unstack SCSI
8808	**	interrupts for that reason. BTW, I dislike a LOT
8809	**	such a loop inside the interrupt routine.
8810	**	Even if DMA interrupt stacking is very unlikely to
8811	**	happen, we also try unstacking these ones, since
8812	**	this has no performance impact.
8813	**=========================================================
8814	*/
8815	sist	= 0;
8816	dstat	= 0;
8817	istatc	= istat;
8818	do {
8819		if (istatc & SIP)
8820			sist  |= INW (nc_sist);
8821		if (istatc & DIP)
8822			dstat |= INB (nc_dstat);
8823		istatc = INB (nc_istat);
8824		istat |= istatc;
8825	} while (istatc & (SIP|DIP));
8826
8827	if (DEBUG_FLAGS & DEBUG_TINY)
8828		printk ("<%d|%x:%x|%x:%x>",
8829			(int)INB(nc_scr0),
8830			dstat,sist,
8831			(unsigned)INL(nc_dsp),
8832			(unsigned)INL(nc_dbc));
8833
8834	/*
8835	**	On paper, a memory barrier may be needed here.
8836	**	And since we are paranoid ... :)
8837	*/
8838	MEMORY_BARRIER();
8839
8840	/*========================================================
8841	**	First, interrupts we want to service cleanly.
8842	**
8843	**	Phase mismatch (MA) is the most frequent interrupt
8844	**	for chip earlier than the 896 and so we have to service
8845	**	it as quickly as possible.
8846	**	A SCSI parity error (PAR) may be combined with a phase
8847	**	mismatch condition (MA).
8848	**	Programmed interrupts (SIR) are used to call the C code
8849	**	from SCRIPTS.
8850	**	The single step interrupt (SSI) is not used in this
8851	**	driver.
8852	**=========================================================
8853	*/
8854
8855	if (!(sist  & (STO|GEN|HTH|SGE|UDC|SBMC|RST)) &&
8856	    !(dstat & (MDPE|BF|ABRT|IID))) {
8857		if	(sist & PAR)	ncr_int_par (np, sist);
8858		else if (sist & MA)	ncr_int_ma (np);
8859		else if (dstat & SIR)	ncr_int_sir (np);
8860		else if (dstat & SSI)	OUTONB_STD ();
8861		else			goto unknown_int;
8862		return;
8863	};
8864
8865	/*========================================================
8866	**	Now, interrupts that donnot happen in normal
8867	**	situations and that we may need to recover from.
8868	**
8869	**	On SCSI RESET (RST), we reset everything.
8870	**	On SCSI BUS MODE CHANGE (SBMC), we complete all
8871	**	active CCBs with RESET status, prepare all devices
8872	**	for negotiating again and restart the SCRIPTS.
8873	**	On STO and UDC, we complete the CCB with the corres-
8874	**	ponding status and restart the SCRIPTS.
8875	**=========================================================
8876	*/
8877
8878	if (sist & RST) {
8879		ncr_init (np, 1, bootverbose ? "scsi reset" : NULL, HS_RESET);
8880		return;
8881	};
8882
8883	OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* clear dma fifo  */
8884	OUTB (nc_stest3, TE|CSF);		/* clear scsi fifo */
8885
8886	if (!(sist  & (GEN|HTH|SGE)) &&
8887	    !(dstat & (MDPE|BF|ABRT|IID))) {
8888		if	(sist & SBMC)	ncr_int_sbmc (np);
8889		else if (sist & STO)	ncr_int_sto (np);
8890		else if (sist & UDC)	ncr_int_udc (np);
8891		else			goto unknown_int;
8892		return;
8893	};
8894
8895	/*=========================================================
8896	**	Now, interrupts we are not able to recover cleanly.
8897	**
8898	**	Do the register dump.
8899	**	Log message for hard errors.
8900	**	Reset everything.
8901	**=========================================================
8902	*/
8903	if (ktime_exp(np->regtime)) {
8904		np->regtime = ktime_get(10*HZ);
8905		for (i = 0; i<sizeof(np->regdump); i++)
8906			((char*)&np->regdump)[i] = INB_OFF(i);
8907		np->regdump.nc_dstat = dstat;
8908		np->regdump.nc_sist  = sist;
8909	};
8910
8911	ncr_log_hard_error(np, sist, dstat);
8912
8913	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
8914		(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)) {
8915		u_char ctest4_o, ctest4_m;
8916		u_char shadow;
8917
8918		/*
8919		 * Get shadow register data
8920		 * Write 1 to ctest4
8921		 */
8922		ctest4_o = INB(nc_ctest4);
8923
8924		OUTB(nc_ctest4, ctest4_o | 0x10);
8925
8926		ctest4_m = INB(nc_ctest4);
8927		shadow = INW_OFF(0x42);
8928
8929		OUTB(nc_ctest4, ctest4_o);
8930
8931		printk("%s: ctest4/sist original 0x%x/0x%X  mod: 0x%X/0x%x\n",
8932			ncr_name(np), ctest4_o, sist, ctest4_m, shadow);
8933	}
8934
8935	if ((sist & (GEN|HTH|SGE)) ||
8936		(dstat & (MDPE|BF|ABRT|IID))) {
8937		ncr_start_reset(np);
8938		return;
8939	};
8940
8941unknown_int:
8942	/*=========================================================
8943	**	We just miss the cause of the interrupt. :(
8944	**	Print a message. The timeout will do the real work.
8945	**=========================================================
8946	*/
8947	printk(	"%s: unknown interrupt(s) ignored, "
8948		"ISTAT=0x%x DSTAT=0x%x SIST=0x%x\n",
8949		ncr_name(np), istat, dstat, sist);
8950}
8951
8952
8953/*==========================================================
8954**
8955**	generic recovery from scsi interrupt
8956**
8957**==========================================================
8958**
8959**	The doc says that when the chip gets an SCSI interrupt,
8960**	it tries to stop in an orderly fashion, by completing
8961**	an instruction fetch that had started or by flushing
8962**	the DMA fifo for a write to memory that was executing.
8963**	Such a fashion is not enough to know if the instruction
8964**	that was just before the current DSP value has been
8965**	executed or not.
8966**
8967**	There are 3 small SCRIPTS sections that deal with the
8968**	start queue and the done queue that may break any
8969**	assomption from the C code if we are interrupted
8970**	inside, so we reset if it happens. Btw, since these
8971**	SCRIPTS sections are executed while the SCRIPTS hasn't
8972**	started SCSI operations, it is very unlikely to happen.
8973**
8974**	All the driver data structures are supposed to be
8975**	allocated from the same 4 GB memory window, so there
8976**	is a 1 to 1 relationship between DSA and driver data
8977**	structures. Since we are careful :) to invalidate the
8978**	DSA when we complete a command or when the SCRIPTS
8979**	pushes a DSA into a queue, we can trust it when it
8980**	points to a CCB.
8981**
8982**----------------------------------------------------------
8983*/
8984static void ncr_recover_scsi_int (ncb_p np, u_char hsts)
8985{
8986	u_int32	dsp	= INL (nc_dsp);
8987	u_int32	dsa	= INL (nc_dsa);
8988	ccb_p cp	= ncr_ccb_from_dsa(np, dsa);
8989
8990	/*
8991	**	If we haven't been interrupted inside the SCRIPTS
8992	**	critical pathes, we can safely restart the SCRIPTS
8993	**	and trust the DSA value if it matches a CCB.
8994	*/
8995	if ((!(dsp > NCB_SCRIPT_PHYS (np, getjob_begin) &&
8996	       dsp < NCB_SCRIPT_PHYS (np, getjob_end) + 1)) &&
8997	    (!(dsp > NCB_SCRIPT_PHYS (np, ungetjob) &&
8998	       dsp < NCB_SCRIPT_PHYS (np, reselect) + 1)) &&
8999	    (!(dsp > NCB_SCRIPTH_PHYS (np, sel_for_abort) &&
9000	       dsp < NCB_SCRIPTH_PHYS (np, sel_for_abort_1) + 1)) &&
9001	    (!(dsp > NCB_SCRIPT_PHYS (np, done) &&
9002	       dsp < NCB_SCRIPT_PHYS (np, done_end) + 1))) {
9003		if (cp) {
9004			cp->host_status = hsts;
9005			ncr_complete (np, cp);
9006		}
9007		OUTL (nc_dsa, DSA_INVALID);
9008		OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* clear dma fifo  */
9009		OUTB (nc_stest3, TE|CSF);		/* clear scsi fifo */
9010		OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
9011	}
9012	else
9013		goto reset_all;
9014
9015	return;
9016
9017reset_all:
9018	ncr_start_reset(np);
9019}
9020
9021/*==========================================================
9022**
9023**	ncr chip exception handler for selection timeout
9024**
9025**==========================================================
9026**
9027**	There seems to be a bug in the 53c810.
9028**	Although a STO-Interrupt is pending,
9029**	it continues executing script commands.
9030**	But it will fail and interrupt (IID) on
9031**	the next instruction where it's looking
9032**	for a valid phase.
9033**
9034**----------------------------------------------------------
9035*/
9036
9037void ncr_int_sto (ncb_p np)
9038{
9039	u_int32	dsp	= INL (nc_dsp);
9040
9041	if (DEBUG_FLAGS & DEBUG_TINY) printk ("T");
9042
9043	if (dsp == NCB_SCRIPT_PHYS (np, wf_sel_done) + 8 ||
9044	    !(driver_setup.recovery & 1))
9045		ncr_recover_scsi_int(np, HS_SEL_TIMEOUT);
9046	else
9047		ncr_start_reset(np);
9048}
9049
9050/*==========================================================
9051**
9052**	ncr chip exception handler for unexpected disconnect
9053**
9054**==========================================================
9055**
9056**----------------------------------------------------------
9057*/
9058void ncr_int_udc (ncb_p np)
9059{
9060	u_int32 dsa = INL (nc_dsa);
9061	ccb_p   cp  = ncr_ccb_from_dsa(np, dsa);
9062
9063	/*
9064	 * Fix Up. Some disks respond to a PPR negotation with
9065	 * a bus free instead of a message reject.
9066	 * Disable ppr negotiation if this is first time
9067	 * tried ppr negotiation.
9068	 */
9069	if (cp) {
9070		tcb_p tp = &np->target[cp->target];
9071		if (tp->ppr_negotiation == 1)
9072			tp->ppr_negotiation = 0;
9073	}
9074
9075	printk ("%s: unexpected disconnect\n", ncr_name(np));
9076	ncr_recover_scsi_int(np, HS_UNEXPECTED);
9077}
9078
9079/*==========================================================
9080**
9081**	ncr chip exception handler for SCSI bus mode change
9082**
9083**==========================================================
9084**
9085**	spi2-r12 11.2.3 says a transceiver mode change must
9086**	generate a reset event and a device that detects a reset
9087**	event shall initiate a hard reset. It says also that a
9088**	device that detects a mode change shall set data transfer
9089**	mode to eight bit asynchronous, etc...
9090**	So, just resetting should be enough.
9091**
9092**
9093**----------------------------------------------------------
9094*/
9095
9096static void ncr_int_sbmc (ncb_p np)
9097{
9098	u_char scsi_mode = INB (nc_stest4) & SMODE;
9099
9100	printk("%s: SCSI bus mode change from %x to %x.\n",
9101		ncr_name(np), np->scsi_mode, scsi_mode);
9102
9103	np->scsi_mode = scsi_mode;
9104
9105
9106	/*
9107	**	Suspend command processing for 1 second and
9108	**	reinitialize all except the chip.
9109	*/
9110	np->settle_time	= ktime_get(1*HZ);
9111	ncr_init (np, 0, bootverbose ? "scsi mode change" : NULL, HS_RESET);
9112}
9113
9114/*==========================================================
9115**
9116**	ncr chip exception handler for SCSI parity error.
9117**
9118**==========================================================
9119**
9120**	When the chip detects a SCSI parity error and is
9121**	currently executing a (CH)MOV instruction, it does
9122**	not interrupt immediately, but tries to finish the
9123**	transfer of the current scatter entry before
9124**	interrupting. The following situations may occur:
9125**
9126**	- The complete scatter entry has been transferred
9127**	  without the device having changed phase.
9128**	  The chip will then interrupt with the DSP pointing
9129**	  to the instruction that follows the MOV.
9130**
9131**	- A phase mismatch occurs before the MOV finished
9132**	  and phase errors are to be handled by the C code.
9133**	  The chip will then interrupt with both PAR and MA
9134**	  conditions set.
9135**
9136**	- A phase mismatch occurs before the MOV finished and
9137**	  phase errors are to be handled by SCRIPTS (895A or 896).
9138**	  The chip will load the DSP with the phase mismatch
9139**	  JUMP address and interrupt the host processor.
9140**
9141**----------------------------------------------------------
9142*/
9143
9144static void ncr_int_par (ncb_p np, u_short sist)
9145{
9146	u_char	hsts	= INB (HS_PRT);
9147	u_int32	dsp	= INL (nc_dsp);
9148	u_int32	dbc	= INL (nc_dbc);
9149	u_int32	dsa	= INL (nc_dsa);
9150	u_char	sbcl	= INB (nc_sbcl);
9151	u_char	cmd	= dbc >> 24;
9152	int phase	= cmd & 7;
9153	ccb_p	cp	= ncr_ccb_from_dsa(np, dsa);
9154
9155	printk("%s: SCSI parity error detected: SCR1=%d DBC=%x SBCL=%x\n",
9156		ncr_name(np), hsts, dbc, sbcl);
9157
9158	/*
9159	**	Check that the chip is connected to the SCSI BUS.
9160	*/
9161	if (!(INB (nc_scntl1) & ISCON)) {
9162	    	if (!(driver_setup.recovery & 1)) {
9163			ncr_recover_scsi_int(np, HS_FAIL);
9164			return;
9165		}
9166		goto reset_all;
9167	}
9168
9169	/*
9170	**	If the nexus is not clearly identified, reset the bus.
9171	**	We will try to do better later.
9172	*/
9173	if (!cp)
9174		goto reset_all;
9175
9176	/*
9177	**	Check instruction was a MOV, direction was INPUT and
9178	**	ATN is asserted.
9179	*/
9180	if ((cmd & 0xc0) || !(phase & 1) || !(sbcl & 0x8))
9181		goto reset_all;
9182
9183	/*
9184	**	Keep track of the parity error.
9185	*/
9186	OUTONB (HF_PRT, HF_EXT_ERR);
9187	cp->xerr_status |= XE_PARITY_ERR;
9188
9189	/*
9190	**	Prepare the message to send to the device.
9191	*/
9192	np->msgout[0] = (phase == 7) ? M_PARITY : M_ID_ERROR;
9193
9194#ifdef	SCSI_NCR_INTEGRITY_CHECKING
9195	/*
9196	**	Save error message. For integrity check use only.
9197	*/
9198	if (np->check_integrity)
9199		np->check_integ_par = np->msgout[0];
9200#endif
9201
9202	/*
9203	**	If the old phase was DATA IN or DT DATA IN phase,
9204	** 	we have to deal with the 3 situations described above.
9205	**	For other input phases (MSG IN and STATUS), the device
9206	**	must resend the whole thing that failed parity checking
9207	**	or signal error. So, jumping to dispatcher should be OK.
9208	*/
9209	if ((phase == 1) || (phase == 5)) {
9210		/* Phase mismatch handled by SCRIPTS */
9211		if (dsp == NCB_SCRIPTH_PHYS (np, pm_handle))
9212			OUTL_DSP (dsp);
9213		/* Phase mismatch handled by the C code */
9214		else if (sist & MA)
9215			ncr_int_ma (np);
9216		/* No phase mismatch occurred */
9217		else {
9218			OUTL (nc_temp, dsp);
9219			OUTL_DSP (NCB_SCRIPT_PHYS (np, dispatch));
9220		}
9221	}
9222	else
9223		OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
9224	return;
9225
9226reset_all:
9227	ncr_start_reset(np);
9228	return;
9229}
9230
9231/*==========================================================
9232**
9233**
9234**	ncr chip exception handler for phase errors.
9235**
9236**
9237**==========================================================
9238**
9239**	We have to construct a new transfer descriptor,
9240**	to transfer the rest of the current block.
9241**
9242**----------------------------------------------------------
9243*/
9244
9245static void ncr_int_ma (ncb_p np)
9246{
9247	u_int32	dbc;
9248	u_int32	rest;
9249	u_int32	dsp;
9250	u_int32	dsa;
9251	u_int32	nxtdsp;
9252	u_int32	*vdsp;
9253	u_int32	oadr, olen;
9254	u_int32	*tblp;
9255        u_int32	newcmd;
9256	u_int	delta;
9257	u_char	cmd;
9258	u_char	hflags, hflags0;
9259	struct pm_ctx *pm;
9260	ccb_p	cp;
9261
9262	dsp	= INL (nc_dsp);
9263	dbc	= INL (nc_dbc);
9264	dsa	= INL (nc_dsa);
9265
9266	cmd	= dbc >> 24;
9267	rest	= dbc & 0xffffff;
9268	delta	= 0;
9269
9270	/*
9271	**	locate matching cp.
9272	*/
9273	cp = ncr_ccb_from_dsa(np, dsa);
9274
9275	if (DEBUG_FLAGS & DEBUG_PHASE)
9276		printk("CCB = %2x %2x %2x %2x %2x %2x\n",
9277			cp->cmd->cmnd[0], cp->cmd->cmnd[1], cp->cmd->cmnd[2],
9278			cp->cmd->cmnd[3], cp->cmd->cmnd[4], cp->cmd->cmnd[5]);
9279
9280	/*
9281	**	Donnot take into account dma fifo and various buffers in
9282	**	INPUT phase since the chip flushes everything before
9283	**	raising the MA interrupt for interrupted INPUT phases.
9284	**	For DATA IN phase, we will check for the SWIDE later.
9285	*/
9286	if ((cmd & 7) != 1 && (cmd & 7) != 5) {
9287		u_int32 dfifo;
9288		u_char ss0, ss2;
9289
9290		/*
9291		**  If C1010, DFBC contains number of bytes in DMA fifo.
9292		**  else read DFIFO, CTEST[4-6] using 1 PCI bus ownership.
9293		*/
9294		if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
9295				(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66))
9296			delta = INL(nc_dfbc) & 0xffff;
9297		else {
9298			dfifo = INL(nc_dfifo);
9299
9300			/*
9301			**	Calculate remaining bytes in DMA fifo.
9302			**	C1010 - always large fifo, value in dfbc
9303			**	Otherwise, (CTEST5 = dfifo >> 16)
9304			*/
9305			if (dfifo & (DFS << 16))
9306				delta = ((((dfifo >> 8) & 0x300) |
9307				          (dfifo & 0xff)) - rest) & 0x3ff;
9308			else
9309				delta = ((dfifo & 0xff) - rest) & 0x7f;
9310
9311			/*
9312			**	The data in the dma fifo has not been
9313			**	transferred to the target -> add the amount
9314			**	to the rest and clear the data.
9315			**	Check the sstat2 register in case of wide
9316			**	transfer.
9317			*/
9318
9319		}
9320
9321		rest += delta;
9322		ss0  = INB (nc_sstat0);
9323		if (ss0 & OLF) rest++;
9324		if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
9325				(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66) && (ss0 & ORF))
9326			rest++;
9327		if (cp && (cp->phys.select.sel_scntl3 & EWS)) {
9328			ss2 = INB (nc_sstat2);
9329			if (ss2 & OLF1) rest++;
9330			if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
9331					(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66) && (ss2 & ORF))
9332				rest++;
9333		};
9334
9335		/*
9336		**	Clear fifos.
9337		*/
9338		OUTB (nc_ctest3, np->rv_ctest3 | CLF);	/* dma fifo  */
9339		OUTB (nc_stest3, TE|CSF);		/* scsi fifo */
9340	}
9341
9342	/*
9343	**	log the information
9344	*/
9345
9346	if (DEBUG_FLAGS & (DEBUG_TINY|DEBUG_PHASE))
9347		printk ("P%x%x RL=%d D=%d ", cmd&7, INB(nc_sbcl)&7,
9348			(unsigned) rest, (unsigned) delta);
9349
9350	/*
9351	**	try to find the interrupted script command,
9352	**	and the address at which to continue.
9353	*/
9354	vdsp	= 0;
9355	nxtdsp	= 0;
9356	if	(dsp >  np->p_script &&
9357		 dsp <= np->p_script + sizeof(struct script)) {
9358		vdsp = (u_int32 *)((char*)np->script0 + (dsp-np->p_script-8));
9359		nxtdsp = dsp;
9360	}
9361	else if	(dsp >  np->p_scripth &&
9362		 dsp <= np->p_scripth + sizeof(struct scripth)) {
9363		vdsp = (u_int32 *)((char*)np->scripth0 + (dsp-np->p_scripth-8));
9364		nxtdsp = dsp;
9365	}
9366
9367	/*
9368	**	log the information
9369	*/
9370	if (DEBUG_FLAGS & DEBUG_PHASE) {
9371		printk ("\nCP=%p DSP=%x NXT=%x VDSP=%p CMD=%x ",
9372			cp, (unsigned)dsp, (unsigned)nxtdsp, vdsp, cmd);
9373	};
9374
9375	if (!vdsp) {
9376		printk ("%s: interrupted SCRIPT address not found.\n",
9377			ncr_name (np));
9378		goto reset_all;
9379	}
9380
9381	if (!cp) {
9382		printk ("%s: SCSI phase error fixup: CCB already dequeued.\n",
9383			ncr_name (np));
9384		goto reset_all;
9385	}
9386
9387	/*
9388	**	get old startaddress and old length.
9389	*/
9390
9391	oadr = scr_to_cpu(vdsp[1]);
9392
9393	if (cmd & 0x10) {	/* Table indirect */
9394		tblp = (u_int32 *) ((char*) &cp->phys + oadr);
9395		olen = scr_to_cpu(tblp[0]);
9396		oadr = scr_to_cpu(tblp[1]);
9397	} else {
9398		tblp = (u_int32 *) 0;
9399		olen = scr_to_cpu(vdsp[0]) & 0xffffff;
9400	};
9401
9402	if (DEBUG_FLAGS & DEBUG_PHASE) {
9403		printk ("OCMD=%x\nTBLP=%p OLEN=%x OADR=%x\n",
9404			(unsigned) (scr_to_cpu(vdsp[0]) >> 24),
9405			tblp,
9406			(unsigned) olen,
9407			(unsigned) oadr);
9408	};
9409
9410	/*
9411	**	check cmd against assumed interrupted script command.
9412	**	If dt data phase, the MOVE instruction hasn't bit 4 of
9413	**	the phase.
9414	*/
9415
9416	if (((cmd & 2) ? cmd : (cmd & ~4)) != (scr_to_cpu(vdsp[0]) >> 24)) {
9417		PRINT_ADDR(cp->cmd);
9418		printk ("internal error: cmd=%02x != %02x=(vdsp[0] >> 24)\n",
9419			(unsigned)cmd, (unsigned)scr_to_cpu(vdsp[0]) >> 24);
9420
9421		goto reset_all;
9422	};
9423
9424	/*
9425	**	if old phase not dataphase, leave here.
9426	**	C/D line is low if data.
9427	*/
9428
9429	if (cmd & 0x02) {
9430		PRINT_ADDR(cp->cmd);
9431		printk ("phase change %x-%x %d@%08x resid=%d.\n",
9432			cmd&7, INB(nc_sbcl)&7, (unsigned)olen,
9433			(unsigned)oadr, (unsigned)rest);
9434		goto unexpected_phase;
9435	};
9436
9437	/*
9438	**	Choose the correct PM save area.
9439	**
9440	**	Look at the PM_SAVE SCRIPT if you want to understand
9441	**	this stuff. The equivalent code is implemented in
9442	**	SCRIPTS for the 895A and 896 that are able to handle
9443	**	PM from the SCRIPTS processor.
9444	*/
9445
9446	hflags0 = INB (HF_PRT);
9447	hflags = hflags0;
9448
9449	if (hflags & (HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED)) {
9450		if (hflags & HF_IN_PM0)
9451			nxtdsp = scr_to_cpu(cp->phys.pm0.ret);
9452		else if	(hflags & HF_IN_PM1)
9453			nxtdsp = scr_to_cpu(cp->phys.pm1.ret);
9454
9455		if (hflags & HF_DP_SAVED)
9456			hflags ^= HF_ACT_PM;
9457	}
9458
9459	if (!(hflags & HF_ACT_PM)) {
9460		pm = &cp->phys.pm0;
9461		newcmd = NCB_SCRIPT_PHYS(np, pm0_data);
9462	}
9463	else {
9464		pm = &cp->phys.pm1;
9465		newcmd = NCB_SCRIPT_PHYS(np, pm1_data);
9466	}
9467
9468	hflags &= ~(HF_IN_PM0 | HF_IN_PM1 | HF_DP_SAVED);
9469	if (hflags != hflags0)
9470		OUTB (HF_PRT, hflags);
9471
9472	/*
9473	**	fillin the phase mismatch context
9474	*/
9475
9476	pm->sg.addr = cpu_to_scr(oadr + olen - rest);
9477	pm->sg.size = cpu_to_scr(rest);
9478	pm->ret     = cpu_to_scr(nxtdsp);
9479
9480	/*
9481	**	If we have a SWIDE,
9482	**	- prepare the address to write the SWIDE from SCRIPTS,
9483	**	- compute the SCRIPTS address to restart from,
9484	**	- move current data pointer context by one byte.
9485	*/
9486	nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
9487	if ( ((cmd & 7) == 1  || (cmd & 7) == 5)
9488		&& cp && (cp->phys.select.sel_scntl3 & EWS) &&
9489	    (INB (nc_scntl2) & WSR)) {
9490		u32 tmp;
9491
9492#ifdef  SYM_DEBUG_PM_WITH_WSR
9493		PRINT_ADDR(cp);
9494		printk ("MA interrupt with WSR set - "
9495			"pm->sg.addr=%x - pm->sg.size=%d\n",
9496			pm->sg.addr, pm->sg.size);
9497#endif
9498		/*
9499		 *  Set up the table indirect for the MOVE
9500		 *  of the residual byte and adjust the data
9501		 *  pointer context.
9502		 */
9503		tmp = scr_to_cpu(pm->sg.addr);
9504		cp->phys.wresid.addr = cpu_to_scr(tmp);
9505		pm->sg.addr = cpu_to_scr(tmp + 1);
9506 		tmp = scr_to_cpu(pm->sg.size);
9507		cp->phys.wresid.size = cpu_to_scr((tmp&0xff000000) | 1);
9508		pm->sg.size = cpu_to_scr(tmp - 1);
9509
9510		/*
9511		 *  If only the residual byte is to be moved,
9512		 *  no PM context is needed.
9513		 */
9514		if ((tmp&0xffffff) == 1)
9515                        newcmd = pm->ret;
9516
9517		/*
9518		 *  Prepare the address of SCRIPTS that will
9519		 *  move the residual byte to memory.
9520		 */
9521		nxtdsp = NCB_SCRIPTH_PHYS (np, wsr_ma_helper);
9522        }
9523
9524	if (DEBUG_FLAGS & DEBUG_PHASE) {
9525		PRINT_ADDR(cp->cmd);
9526		printk ("PM %x %x %x / %x %x %x.\n",
9527			hflags0, hflags, newcmd,
9528			(unsigned)scr_to_cpu(pm->sg.addr),
9529			(unsigned)scr_to_cpu(pm->sg.size),
9530			(unsigned)scr_to_cpu(pm->ret));
9531	}
9532
9533	/*
9534	**	Restart the SCRIPTS processor.
9535	*/
9536
9537	OUTL (nc_temp, newcmd);
9538	OUTL_DSP (nxtdsp);
9539	return;
9540
9541	/*
9542	**	Unexpected phase changes that occurs when the current phase
9543	**	is not a DATA IN or DATA OUT phase are due to error conditions.
9544	**	Such event may only happen when the SCRIPTS is using a
9545	**	multibyte SCSI MOVE.
9546	**
9547	**	Phase change		Some possible cause
9548	**
9549	**	COMMAND  --> MSG IN	SCSI parity error detected by target.
9550	**	COMMAND  --> STATUS	Bad command or refused by target.
9551	**	MSG OUT  --> MSG IN     Message rejected by target.
9552	**	MSG OUT  --> COMMAND    Bogus target that discards extended
9553	**				negotiation messages.
9554	**
9555	**	The code below does not care of the new phase and so
9556	**	trusts the target. Why to annoy it ?
9557	**	If the interrupted phase is COMMAND phase, we restart at
9558	**	dispatcher.
9559	**	If a target does not get all the messages after selection,
9560	**	the code assumes blindly that the target discards extended
9561	**	messages and clears the negotiation status.
9562	**	If the target does not want all our response to negotiation,
9563	**	we force a SIR_NEGO_PROTO interrupt (it is a hack that avoids
9564	**	bloat for such a should_not_happen situation).
9565	**	In all other situation, we reset the BUS.
9566	**	Are these assumptions reasonnable ? (Wait and see ...)
9567	*/
9568unexpected_phase:
9569	dsp -= 8;
9570	nxtdsp = 0;
9571
9572	switch (cmd & 7) {
9573	case 2:	/* COMMAND phase */
9574		nxtdsp = NCB_SCRIPT_PHYS (np, dispatch);
9575		break;
9576	case 6:	/* MSG OUT phase */
9577		/*
9578		**	If the device may want to use untagged when we want
9579		**	tagged, we prepare an IDENTIFY without disc. granted,
9580		**	since we will not be able to handle reselect.
9581		**	Otherwise, we just don't care.
9582		*/
9583		if	(dsp == NCB_SCRIPT_PHYS (np, send_ident)) {
9584			if (cp->tag != NO_TAG && olen - rest <= 3) {
9585				cp->host_status = HS_BUSY;
9586				np->msgout[0] = M_IDENTIFY | cp->lun;
9587				nxtdsp = NCB_SCRIPTH_PHYS (np, ident_break_atn);
9588			}
9589			else
9590				nxtdsp = NCB_SCRIPTH_PHYS (np, ident_break);
9591		}
9592		else if	(dsp == NCB_SCRIPTH_PHYS (np, send_wdtr) ||
9593			 dsp == NCB_SCRIPTH_PHYS (np, send_sdtr) ||
9594			 dsp == NCB_SCRIPTH_PHYS (np, send_ppr)) {
9595			nxtdsp = NCB_SCRIPTH_PHYS (np, nego_bad_phase);
9596		}
9597		break;
9598	}
9599
9600	if (nxtdsp) {
9601		OUTL_DSP (nxtdsp);
9602		return;
9603	}
9604
9605reset_all:
9606	ncr_start_reset(np);
9607}
9608
9609/*==========================================================
9610**
9611**	ncr chip handler for QUEUE FULL and CHECK CONDITION
9612**
9613**==========================================================
9614**
9615**	On QUEUE FULL status, we set the actual tagged command
9616**	queue depth to the number of disconnected CCBs that is
9617**	hopefully a good value to avoid further QUEUE FULL.
9618**
9619**	On CHECK CONDITION or COMMAND TERMINATED, we use the
9620**	CCB of the failed command for performing a REQUEST
9621**	SENSE SCSI command.
9622**
9623**	We do not want to change the order commands will be
9624**	actually queued to the device after we received a
9625**	QUEUE FULL status. We also want to properly deal with
9626**	contingent allegiance condition. For these reasons,
9627**	we remove from the start queue all commands for this
9628**	LUN that haven't been yet queued to the device and
9629**	put them back in the correponding LUN queue, then
9630**	requeue the CCB that failed in front of the LUN queue.
9631**	I just hope this not to be performed too often. :)
9632**
9633**	If we are using IMMEDIATE ARBITRATION, we clear the
9634**	IARB hint for every commands we encounter in order not
9635**	to be stuck with a won arbitration and no job to queue
9636**	to a device.
9637**----------------------------------------------------------
9638*/
9639
9640static void ncr_sir_to_redo(ncb_p np, int num, ccb_p cp)
9641{
9642	Scsi_Cmnd *cmd	= cp->cmd;
9643	tcb_p tp	= &np->target[cp->target];
9644	lcb_p lp	= ncr_lp(np, tp, cp->lun);
9645	ccb_p		cp2;
9646	int		busyccbs = 1;
9647	u_int32		startp;
9648	u_char		s_status = INB (SS_PRT);
9649	int		msglen;
9650	int		i, j;
9651
9652
9653	/*
9654	**	If the LCB is not yet available, then only
9655	**	1 IO is accepted, so we should have it.
9656	*/
9657	if (!lp)
9658		goto next;
9659	/*
9660	**	Remove all CCBs queued to the chip for that LUN and put
9661	**	them back in the LUN CCB wait queue.
9662	*/
9663	busyccbs = lp->queuedccbs;
9664	i = (INL (nc_scratcha) - np->p_squeue) / 4;
9665	j = i;
9666	while (i != np->squeueput) {
9667		cp2 = ncr_ccb_from_dsa(np, scr_to_cpu(np->squeue[i]));
9668		assert(cp2);
9669#ifdef SCSI_NCR_IARB_SUPPORT
9670		/* IARB hints may not be relevant any more. Forget them. */
9671		cp2->host_flags &= ~HF_HINT_IARB;
9672#endif
9673		if (cp2 && cp2->target == cp->target && cp2->lun == cp->lun) {
9674			xpt_remque(&cp2->link_ccbq);
9675			xpt_insque_head(&cp2->link_ccbq, &lp->wait_ccbq);
9676			--lp->queuedccbs;
9677			cp2->queued = 0;
9678		}
9679		else {
9680			if (i != j)
9681				np->squeue[j] = np->squeue[i];
9682			if ((j += 2) >= MAX_START*2) j = 0;
9683		}
9684		if ((i += 2) >= MAX_START*2) i = 0;
9685	}
9686	if (i != j)		/* Copy back the idle task if needed */
9687		np->squeue[j] = np->squeue[i];
9688	np->squeueput = j;	/* Update our current start queue pointer */
9689
9690	/*
9691	**	Requeue the interrupted CCB in front of the
9692	**	LUN CCB wait queue to preserve ordering.
9693	*/
9694	xpt_remque(&cp->link_ccbq);
9695	xpt_insque_head(&cp->link_ccbq, &lp->wait_ccbq);
9696	--lp->queuedccbs;
9697	cp->queued = 0;
9698
9699next:
9700
9701#ifdef SCSI_NCR_IARB_SUPPORT
9702	/* IARB hint may not be relevant any more. Forget it. */
9703	cp->host_flags &= ~HF_HINT_IARB;
9704	if (np->last_cp)
9705		np->last_cp = 0;
9706#endif
9707
9708	/*
9709	**	Now we can restart the SCRIPTS processor safely.
9710	*/
9711	OUTL_DSP (NCB_SCRIPT_PHYS (np, start));
9712
9713	switch(s_status) {
9714	default:
9715	case S_BUSY:
9716		ncr_complete(np, cp);
9717		break;
9718	case S_QUEUE_FULL:
9719		if (!lp || !lp->queuedccbs) {
9720			ncr_complete(np, cp);
9721			break;
9722		}
9723		if (bootverbose >= 1) {
9724			PRINT_ADDR(cmd);
9725			printk ("QUEUE FULL! %d busy, %d disconnected CCBs\n",
9726				busyccbs, lp->queuedccbs);
9727		}
9728		/*
9729		**	Decrease number of tags to the number of
9730		**	disconnected commands.
9731		*/
9732		if (lp->queuedccbs < lp->numtags) {
9733			lp->numtags	= lp->queuedccbs;
9734			lp->num_good	= 0;
9735			ncr_setup_tags (np, cp->target, cp->lun);
9736		}
9737		/*
9738		**	Repair the offending CCB.
9739		*/
9740		cp->phys.header.savep	= cp->startp;
9741		cp->phys.header.lastp	= cp->lastp0;
9742		cp->host_status 	= HS_BUSY;
9743		cp->scsi_status 	= S_ILLEGAL;
9744		cp->xerr_status		= 0;
9745		cp->extra_bytes		= 0;
9746		cp->host_flags		&= (HF_PM_TO_C|HF_DATA_IN);
9747
9748		break;
9749
9750	case S_TERMINATED:
9751	case S_CHECK_COND:
9752		/*
9753		**	If we were requesting sense, give up.
9754		*/
9755		if (cp->host_flags & HF_AUTO_SENSE) {
9756			ncr_complete(np, cp);
9757			break;
9758		}
9759
9760		/*
9761		**	Save SCSI status and extended error.
9762		**	Compute the data residual now.
9763		*/
9764		cp->sv_scsi_status = cp->scsi_status;
9765		cp->sv_xerr_status = cp->xerr_status;
9766		cp->resid = ncr_compute_residual(np, cp);
9767
9768		/*
9769		**	Device returned CHECK CONDITION status.
9770		**	Prepare all needed data strutures for getting
9771		**	sense data.
9772		*/
9773
9774		/*
9775		**	identify message
9776		*/
9777		cp->scsi_smsg2[0]	= M_IDENTIFY | cp->lun;
9778		msglen = 1;
9779
9780		/*
9781		**	If we are currently using anything different from
9782		**	async. 8 bit data transfers with that target,
9783		**	start a negotiation, since the device may want
9784		**	to report us a UNIT ATTENTION condition due to
9785		**	a cause we currently ignore, and we donnot want
9786		**	to be stuck with WIDE and/or SYNC data transfer.
9787		**
9788		**	cp->nego_status is filled by ncr_prepare_nego().
9789		**
9790		**	Do NOT negotiate if performing integrity check
9791		**	or if integrity check has completed, all check
9792		**	conditions will have been cleared.
9793		*/
9794
9795#ifdef	SCSI_NCR_INTEGRITY_CHECKING
9796		if (DEBUG_FLAGS & DEBUG_IC) {
9797		printk("%s: ncr_sir_to_redo: ic_done %2X, in_progress %2X\n",
9798			ncr_name(np), tp->ic_done, cp->cmd->ic_in_progress);
9799		}
9800
9801		/*
9802		**	If parity error during integrity check,
9803		**	set the target width to narrow. Otherwise,
9804		**	do not negotiate on a request sense.
9805		*/
9806		if ( np->check_integ_par && np->check_integrity
9807						&& cp->cmd->ic_in_progress ) {
9808			cp->nego_status = 0;
9809			msglen +=
9810			    ncr_ic_nego (np, cp, cmd ,&cp->scsi_smsg2[msglen]);
9811		}
9812
9813		if (!np->check_integrity ||
9814		   	(np->check_integrity &&
9815				(!cp->cmd->ic_in_progress && !tp->ic_done)) ) {
9816		    ncr_negotiate(np, tp);
9817		    cp->nego_status = 0;
9818		    {
9819			u_char sync_offset;
9820			if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
9821					(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66))
9822				sync_offset = tp->sval & 0x3f;
9823			else
9824				sync_offset = tp->sval & 0x1f;
9825
9826		        if ((tp->wval & EWS) || sync_offset)
9827			  msglen +=
9828			    ncr_prepare_nego (np, cp, &cp->scsi_smsg2[msglen]);
9829		    }
9830
9831		}
9832#else
9833		ncr_negotiate(np, tp);
9834		cp->nego_status = 0;
9835		if ((tp->wval & EWS) || (tp->sval & 0x1f))
9836			msglen +=
9837			    ncr_prepare_nego (np, cp, &cp->scsi_smsg2[msglen]);
9838#endif	/* SCSI_NCR_INTEGRITY_CHECKING */
9839
9840		/*
9841		**	Message table indirect structure.
9842		*/
9843		cp->phys.smsg.addr	= cpu_to_scr(CCB_PHYS (cp, scsi_smsg2));
9844		cp->phys.smsg.size	= cpu_to_scr(msglen);
9845
9846		/*
9847		**	sense command
9848		*/
9849		cp->phys.cmd.addr	= cpu_to_scr(CCB_PHYS (cp, sensecmd));
9850		cp->phys.cmd.size	= cpu_to_scr(6);
9851
9852		/*
9853		**	patch requested size into sense command
9854		*/
9855		cp->sensecmd[0]		= 0x03;
9856		cp->sensecmd[1]		= cp->lun << 5;
9857		cp->sensecmd[4]		= sizeof(cp->sense_buf);
9858
9859		/*
9860		**	sense data
9861		*/
9862		bzero(cp->sense_buf, sizeof(cp->sense_buf));
9863		cp->phys.sense.addr	= cpu_to_scr(CCB_PHYS(cp,sense_buf[0]));
9864		cp->phys.sense.size	= cpu_to_scr(sizeof(cp->sense_buf));
9865
9866		/*
9867		**	requeue the command.
9868		*/
9869		startp = NCB_SCRIPTH_PHYS (np, sdata_in);
9870
9871		cp->phys.header.savep	= cpu_to_scr(startp);
9872		cp->phys.header.goalp	= cpu_to_scr(startp + 16);
9873		cp->phys.header.lastp	= cpu_to_scr(startp);
9874		cp->phys.header.wgoalp	= cpu_to_scr(startp + 16);
9875		cp->phys.header.wlastp	= cpu_to_scr(startp);
9876
9877		cp->host_status	= cp->nego_status ? HS_NEGOTIATE : HS_BUSY;
9878		cp->scsi_status = S_ILLEGAL;
9879		cp->host_flags	= (HF_AUTO_SENSE|HF_DATA_IN);
9880
9881		cp->phys.header.go.start =
9882			cpu_to_scr(NCB_SCRIPT_PHYS (np, select));
9883
9884		/*
9885		**	If lp not yet allocated, requeue the command.
9886		*/
9887		if (!lp)
9888			ncr_put_start_queue(np, cp);
9889		break;
9890	}
9891
9892	/*
9893	**	requeue awaiting scsi commands for this lun.
9894	*/
9895	if (lp)
9896		ncr_start_next_ccb(np, lp, 1);
9897
9898	return;
9899}
9900
9901/*----------------------------------------------------------
9902**
9903**	After a device has accepted some management message
9904**	as BUS DEVICE RESET, ABORT TASK, etc ..., or when
9905**	a device signals a UNIT ATTENTION condition, some
9906**	tasks are thrown away by the device. We are required
9907**	to reflect that on our tasks list since the device
9908**	will never complete these tasks.
9909**
9910**	This function completes all disconnected CCBs for a
9911**	given target that matches the following criteria:
9912**	- lun=-1  means any logical UNIT otherwise a given one.
9913**	- task=-1 means any task, otherwise a given one.
9914**----------------------------------------------------------
9915*/
9916static int ncr_clear_tasks(ncb_p np, u_char hsts,
9917			   int target, int lun, int task)
9918{
9919	int i = 0;
9920	ccb_p cp;
9921
9922	for (cp = np->ccbc; cp; cp = cp->link_ccb) {
9923		if (cp->host_status != HS_DISCONNECT)
9924			continue;
9925		if (cp->target != target)
9926			continue;
9927		if (lun != -1 && cp->lun != lun)
9928			continue;
9929		if (task != -1 && cp->tag != NO_TAG && cp->scsi_smsg[2] != task)
9930			continue;
9931		cp->host_status = hsts;
9932		cp->scsi_status = S_ILLEGAL;
9933		ncr_complete(np, cp);
9934		++i;
9935	}
9936	return i;
9937}
9938
9939/*==========================================================
9940**
9941**	ncr chip handler for TASKS recovery.
9942**
9943**==========================================================
9944**
9945**	We cannot safely abort a command, while the SCRIPTS
9946**	processor is running, since we just would be in race
9947**	with it.
9948**
9949**	As long as we have tasks to abort, we keep the SEM
9950**	bit set in the ISTAT. When this bit is set, the
9951**	SCRIPTS processor interrupts (SIR_SCRIPT_STOPPED)
9952**	each time it enters the scheduler.
9953**
9954**	If we have to reset a target, clear tasks of a unit,
9955**	or to perform the abort of a disconnected job, we
9956**	restart the SCRIPTS for selecting the target. Once
9957**	selected, the SCRIPTS interrupts (SIR_TARGET_SELECTED).
9958**	If it loses arbitration, the SCRIPTS will interrupt again
9959**	the next time it will enter its scheduler, and so on ...
9960**
9961**	On SIR_TARGET_SELECTED, we scan for the more
9962**	appropriate thing to do:
9963**
9964**	- If nothing, we just sent a M_ABORT message to the
9965**	  target to get rid of the useless SCSI bus ownership.
9966**	  According to the specs, no tasks shall be affected.
9967**	- If the target is to be reset, we send it a M_RESET
9968**	  message.
9969**	- If a logical UNIT is to be cleared , we send the
9970**	  IDENTIFY(lun) + M_ABORT.
9971**	- If an untagged task is to be aborted, we send the
9972**	  IDENTIFY(lun) + M_ABORT.
9973**	- If a tagged task is to be aborted, we send the
9974**	  IDENTIFY(lun) + task attributes + M_ABORT_TAG.
9975**
9976**	Once our 'kiss of death' :) message has been accepted
9977**	by the target, the SCRIPTS interrupts again
9978**	(SIR_ABORT_SENT). On this interrupt, we complete
9979**	all the CCBs that should have been aborted by the
9980**	target according to our message.
9981**
9982**----------------------------------------------------------
9983*/
9984static void ncr_sir_task_recovery(ncb_p np, int num)
9985{
9986	ccb_p cp;
9987	tcb_p tp;
9988	int target=-1, lun=-1, task;
9989	int i, k;
9990	u_char *p;
9991
9992	switch(num) {
9993	/*
9994	**	The SCRIPTS processor stopped before starting
9995	**	the next command in order to allow us to perform
9996	**	some task recovery.
9997	*/
9998	case SIR_SCRIPT_STOPPED:
9999
10000		/*
10001		**	Do we have any target to reset or unit to clear ?
10002		*/
10003		for (i = 0 ; i < MAX_TARGET ; i++) {
10004			tp = &np->target[i];
10005			if (tp->to_reset || (tp->l0p && tp->l0p->to_clear)) {
10006				target = i;
10007				break;
10008			}
10009			if (!tp->lmp)
10010				continue;
10011			for (k = 1 ; k < MAX_LUN ; k++) {
10012				if (tp->lmp[k] && tp->lmp[k]->to_clear) {
10013					target	= i;
10014					break;
10015				}
10016			}
10017			if (target != -1)
10018				break;
10019		}
10020
10021		/*
10022		**	If not, look at the CCB list for any
10023		**	disconnected CCB to be aborted.
10024		*/
10025		if (target == -1) {
10026			for (cp = np->ccbc; cp; cp = cp->link_ccb) {
10027				if (cp->host_status != HS_DISCONNECT)
10028					continue;
10029				if (cp->to_abort) {
10030					target = cp->target;
10031					break;
10032				}
10033			}
10034		}
10035
10036		/*
10037		**	If some target is to be selected,
10038		**	prepare and start the selection.
10039		*/
10040		if (target != -1) {
10041			tp = &np->target[target];
10042			np->abrt_sel.sel_id	= target;
10043			np->abrt_sel.sel_scntl3 = tp->wval;
10044			np->abrt_sel.sel_sxfer  = tp->sval;
10045			np->abrt_sel.sel_scntl4 = tp->uval;
10046			OUTL(nc_dsa, np->p_ncb);
10047			OUTL_DSP (NCB_SCRIPTH_PHYS (np, sel_for_abort));
10048			return;
10049		}
10050
10051		/*
10052		**	Nothing is to be selected, so we donnot need
10053		**	to synchronize with the SCRIPTS anymore.
10054		**	Remove the SEM flag from the ISTAT.
10055		*/
10056		np->istat_sem = 0;
10057		OUTB (nc_istat, SIGP);
10058
10059		/*
10060		**	Now look at CCBs to abort that haven't started yet.
10061		**	Remove all those CCBs from the start queue and
10062		**	complete them with appropriate status.
10063		**	Btw, the SCRIPTS processor is still stopped, so
10064		**	we are not in race.
10065		*/
10066		for (cp = np->ccbc; cp; cp = cp->link_ccb) {
10067			if (cp->host_status != HS_BUSY &&
10068			    cp->host_status != HS_NEGOTIATE)
10069				continue;
10070			if (!cp->to_abort)
10071				continue;
10072#ifdef SCSI_NCR_IARB_SUPPORT
10073			/*
10074			**    If we are using IMMEDIATE ARBITRATION, we donnot
10075			**    want to cancel the last queued CCB, since the
10076			**    SCRIPTS may have anticipated the selection.
10077			*/
10078			if (cp == np->last_cp) {
10079				cp->to_abort = 0;
10080				continue;
10081			}
10082#endif
10083			/*
10084			**	Compute index of next position in the start
10085			**	queue the SCRIPTS will schedule.
10086			*/
10087			i = (INL (nc_scratcha) - np->p_squeue) / 4;
10088
10089			/*
10090			**	Remove the job from the start queue.
10091			*/
10092			k = -1;
10093			while (1) {
10094				if (i == np->squeueput)
10095					break;
10096				if (k == -1) {		/* Not found yet */
10097					if (cp == ncr_ccb_from_dsa(np,
10098						     scr_to_cpu(np->squeue[i])))
10099						k = i;	/* Found */
10100				}
10101				else {
10102					/*
10103					**    Once found, we have to move
10104					**    back all jobs by 1 position.
10105					*/
10106					np->squeue[k] = np->squeue[i];
10107					k += 2;
10108					if (k >= MAX_START*2)
10109						k = 0;
10110				}
10111
10112				i += 2;
10113				if (i >= MAX_START*2)
10114					i = 0;
10115			}
10116			/*
10117			**	If job removed, repair the start queue.
10118			*/
10119			if (k != -1) {
10120				np->squeue[k] = np->squeue[i]; /* Idle task */
10121				np->squeueput = k; /* Start queue pointer */
10122			}
10123			cp->host_status = HS_ABORTED;
10124			cp->scsi_status = S_ILLEGAL;
10125			ncr_complete(np, cp);
10126		}
10127		break;
10128	/*
10129	**	The SCRIPTS processor has selected a target
10130	**	we may have some manual recovery to perform for.
10131	*/
10132	case SIR_TARGET_SELECTED:
10133		target = (INB (nc_sdid) & 0xf);
10134		tp = &np->target[target];
10135
10136		np->abrt_tbl.addr = cpu_to_scr(vtobus(np->abrt_msg));
10137
10138		/*
10139		**	If the target is to be reset, prepare a
10140		**	M_RESET message and clear the to_reset flag
10141		**	since we donnot expect this operation to fail.
10142		*/
10143		if (tp->to_reset) {
10144			np->abrt_msg[0] = M_RESET;
10145			np->abrt_tbl.size = 1;
10146			tp->to_reset = 0;
10147			break;
10148		}
10149
10150		/*
10151		**	Otherwise, look for some logical unit to be cleared.
10152		*/
10153		if (tp->l0p && tp->l0p->to_clear)
10154			lun = 0;
10155		else if (tp->lmp) {
10156			for (k = 1 ; k < MAX_LUN ; k++) {
10157				if (tp->lmp[k] && tp->lmp[k]->to_clear) {
10158					lun = k;
10159					break;
10160				}
10161			}
10162		}
10163
10164		/*
10165		**	If a logical unit is to be cleared, prepare
10166		**	an IDENTIFY(lun) + ABORT MESSAGE.
10167		*/
10168		if (lun != -1) {
10169			lcb_p lp = ncr_lp(np, tp, lun);
10170			lp->to_clear = 0; /* We donnot expect to fail here */
10171			np->abrt_msg[0] = M_IDENTIFY | lun;
10172			np->abrt_msg[1] = M_ABORT;
10173			np->abrt_tbl.size = 2;
10174			break;
10175		}
10176
10177		/*
10178		**	Otherwise, look for some disconnected job to
10179		**	abort for this target.
10180		*/
10181		for (cp = np->ccbc; cp; cp = cp->link_ccb) {
10182			if (cp->host_status != HS_DISCONNECT)
10183				continue;
10184			if (cp->target != target)
10185				continue;
10186			if (cp->to_abort)
10187				break;
10188		}
10189
10190		/*
10191		**	If we have none, probably since the device has
10192		**	completed the command before we won abitration,
10193		**	send a M_ABORT message without IDENTIFY.
10194		**	According to the specs, the device must just
10195		**	disconnect the BUS and not abort any task.
10196		*/
10197		if (!cp) {
10198			np->abrt_msg[0] = M_ABORT;
10199			np->abrt_tbl.size = 1;
10200			break;
10201		}
10202
10203		/*
10204		**	We have some task to abort.
10205		**	Set the IDENTIFY(lun)
10206		*/
10207		np->abrt_msg[0] = M_IDENTIFY | cp->lun;
10208
10209		/*
10210		**	If we want to abort an untagged command, we
10211		**	will send a IDENTIFY + M_ABORT.
10212		**	Otherwise (tagged command), we will send
10213		**	a IDENTITFY + task attributes + ABORT TAG.
10214		*/
10215		if (cp->tag == NO_TAG) {
10216			np->abrt_msg[1] = M_ABORT;
10217			np->abrt_tbl.size = 2;
10218		}
10219		else {
10220			np->abrt_msg[1] = cp->scsi_smsg[1];
10221			np->abrt_msg[2] = cp->scsi_smsg[2];
10222			np->abrt_msg[3] = M_ABORT_TAG;
10223			np->abrt_tbl.size = 4;
10224		}
10225		cp->to_abort = 0; /* We donnot expect to fail here */
10226		break;
10227
10228	/*
10229	**	The target has accepted our message and switched
10230	**	to BUS FREE phase as we expected.
10231	*/
10232	case SIR_ABORT_SENT:
10233		target = (INB (nc_sdid) & 0xf);
10234		tp = &np->target[target];
10235
10236		/*
10237		**	If we didn't abort anything, leave here.
10238		*/
10239		if (np->abrt_msg[0] == M_ABORT)
10240			break;
10241
10242		/*
10243		**	If we sent a M_RESET, then a hardware reset has
10244		**	been performed by the target.
10245		**	- Reset everything to async 8 bit
10246		**	- Tell ourself to negotiate next time :-)
10247		**	- Prepare to clear all disconnected CCBs for
10248		**	  this target from our task list (lun=task=-1)
10249		*/
10250		lun = -1;
10251		task = -1;
10252		if (np->abrt_msg[0] == M_RESET) {
10253			tp->sval = 0;
10254			tp->wval = np->rv_scntl3;
10255			tp->uval = np->rv_scntl4;
10256			ncr_set_sync_wide_status(np, target);
10257			ncr_negotiate(np, tp);
10258		}
10259
10260		/*
10261		**	Otherwise, check for the LUN and TASK(s)
10262		**	concerned by the cancelation.
10263		**	If it is not ABORT_TAG then it is CLEAR_QUEUE
10264		**	or an ABORT message :-)
10265		*/
10266		else {
10267			lun = np->abrt_msg[0] & 0x3f;
10268			if (np->abrt_msg[1] == M_ABORT_TAG)
10269				task = np->abrt_msg[2];
10270		}
10271
10272		/*
10273		**	Complete all the CCBs the device should have
10274		**	aborted due to our 'kiss of death' message.
10275		*/
10276		(void) ncr_clear_tasks(np, HS_ABORTED, target, lun, task);
10277		break;
10278
10279	/*
10280	**	We have performed a auto-sense that succeeded.
10281	**	If the device reports a UNIT ATTENTION condition
10282	**	due to a RESET condition, we must complete all
10283	**	disconnect CCBs for this unit since the device
10284	**	shall have thrown them away.
10285	**	Since I haven't time to guess what the specs are
10286	**	expecting for other UNIT ATTENTION conditions, I
10287	**	decided to only care about RESET conditions. :)
10288	*/
10289	case SIR_AUTO_SENSE_DONE:
10290		cp = ncr_ccb_from_dsa(np, INL (nc_dsa));
10291		if (!cp)
10292			break;
10293		memcpy(cp->cmd->sense_buffer, cp->sense_buf,
10294		       sizeof(cp->cmd->sense_buffer));
10295		p  = &cp->cmd->sense_buffer[0];
10296
10297		if (p[0] != 0x70 || p[2] != 0x6 || p[12] != 0x29)
10298			break;
10299		break;
10300	}
10301
10302	/*
10303	**	Print to the log the message we intend to send.
10304	*/
10305	if (num == SIR_TARGET_SELECTED) {
10306		PRINT_TARGET(np, target);
10307		ncr_printl_hex("control msgout:", np->abrt_msg,
10308			      np->abrt_tbl.size);
10309		np->abrt_tbl.size = cpu_to_scr(np->abrt_tbl.size);
10310	}
10311
10312	/*
10313	**	Let the SCRIPTS processor continue.
10314	*/
10315	OUTONB_STD ();
10316}
10317
10318
10319/*==========================================================
10320**
10321**	G�rard's alchemy:) that deals with with the data
10322**	pointer for both MDP and the residual calculation.
10323**
10324**==========================================================
10325**
10326**	I didn't want to bloat the code by more than 200
10327**	lignes for the handling of both MDP and the residual.
10328**	This has been achieved by using a data pointer
10329**	representation consisting in an index in the data
10330**	array (dp_sg) and a negative offset (dp_ofs) that
10331**	have the following meaning:
10332**
10333**	- dp_sg = MAX_SCATTER
10334**	  we are at the end of the data script.
10335**	- dp_sg < MAX_SCATTER
10336**	  dp_sg points to the next entry of the scatter array
10337**	  we want to transfer.
10338**	- dp_ofs < 0
10339**	  dp_ofs represents the residual of bytes of the
10340**	  previous entry scatter entry we will send first.
10341**	- dp_ofs = 0
10342**	  no residual to send first.
10343**
10344**	The function ncr_evaluate_dp() accepts an arbitray
10345**	offset (basically from the MDP message) and returns
10346**	the corresponding values of dp_sg and dp_ofs.
10347**
10348**----------------------------------------------------------
10349*/
10350
10351static int ncr_evaluate_dp(ncb_p np, ccb_p cp, u_int32 scr, int *ofs)
10352{
10353	u_int32	dp_scr;
10354	int	dp_ofs, dp_sg, dp_sgmin;
10355	int	tmp;
10356	struct pm_ctx *pm;
10357
10358	/*
10359	**	Compute the resulted data pointer in term of a script
10360	**	address within some DATA script and a signed byte offset.
10361	*/
10362	dp_scr = scr;
10363	dp_ofs = *ofs;
10364	if	(dp_scr == NCB_SCRIPT_PHYS (np, pm0_data))
10365		pm = &cp->phys.pm0;
10366	else if (dp_scr == NCB_SCRIPT_PHYS (np, pm1_data))
10367		pm = &cp->phys.pm1;
10368	else
10369		pm = 0;
10370
10371	if (pm) {
10372		dp_scr  = scr_to_cpu(pm->ret);
10373		dp_ofs -= scr_to_cpu(pm->sg.size);
10374	}
10375
10376	/*
10377	**	Deduce the index of the sg entry.
10378	**	Keep track of the index of the first valid entry.
10379	**	If result is dp_sg = MAX_SCATTER, then we are at the
10380	**	end of the data and vice-versa.
10381	*/
10382	tmp = scr_to_cpu(cp->phys.header.goalp);
10383	dp_sg = MAX_SCATTER;
10384	if (dp_scr != tmp)
10385		dp_sg -= (tmp - 8 - (int)dp_scr) / (SCR_SG_SIZE*4);
10386	dp_sgmin = MAX_SCATTER - cp->segments;
10387
10388	/*
10389	**	Move to the sg entry the data pointer belongs to.
10390	**
10391	**	If we are inside the data area, we expect result to be:
10392	**
10393	**	Either,
10394	**	    dp_ofs = 0 and dp_sg is the index of the sg entry
10395	**	    the data pointer belongs to (or the end of the data)
10396	**	Or,
10397	**	    dp_ofs < 0 and dp_sg is the index of the sg entry
10398	**	    the data pointer belongs to + 1.
10399	*/
10400	if (dp_ofs < 0) {
10401		int n;
10402		while (dp_sg > dp_sgmin) {
10403			--dp_sg;
10404			tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
10405			n = dp_ofs + (tmp & 0xffffff);
10406			if (n > 0) {
10407				++dp_sg;
10408				break;
10409			}
10410			dp_ofs = n;
10411		}
10412	}
10413	else if (dp_ofs > 0) {
10414		while (dp_sg < MAX_SCATTER) {
10415			tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
10416			dp_ofs -= (tmp & 0xffffff);
10417			++dp_sg;
10418			if (dp_ofs <= 0)
10419				break;
10420		}
10421	}
10422
10423	/*
10424	**	Make sure the data pointer is inside the data area.
10425	**	If not, return some error.
10426	*/
10427	if	(dp_sg < dp_sgmin || (dp_sg == dp_sgmin && dp_ofs < 0))
10428		goto out_err;
10429	else if	(dp_sg > MAX_SCATTER || (dp_sg == MAX_SCATTER && dp_ofs > 0))
10430		goto out_err;
10431
10432	/*
10433	**	Save the extreme pointer if needed.
10434	*/
10435	if (dp_sg > cp->ext_sg ||
10436            (dp_sg == cp->ext_sg && dp_ofs > cp->ext_ofs)) {
10437		cp->ext_sg  = dp_sg;
10438		cp->ext_ofs = dp_ofs;
10439	}
10440
10441	/*
10442	**	Return data.
10443	*/
10444	*ofs = dp_ofs;
10445	return dp_sg;
10446
10447out_err:
10448	return -1;
10449}
10450
10451/*==========================================================
10452**
10453**	ncr chip handler for MODIFY DATA POINTER MESSAGE
10454**
10455**==========================================================
10456**
10457**	We also call this function on IGNORE WIDE RESIDUE
10458**	messages that do not match a SWIDE full condition.
10459**	Btw, we assume in that situation that such a message
10460**	is equivalent to a MODIFY DATA POINTER (offset=-1).
10461**
10462**----------------------------------------------------------
10463*/
10464
10465static void ncr_modify_dp(ncb_p np, tcb_p tp, ccb_p cp, int ofs)
10466{
10467	int dp_ofs	= ofs;
10468	u_int32 dp_scr	= INL (nc_temp);
10469	u_int32	dp_ret;
10470	u_int32	tmp;
10471	u_char	hflags;
10472	int	dp_sg;
10473	struct pm_ctx *pm;
10474
10475	/*
10476	**	Not supported for auto_sense;
10477	*/
10478	if (cp->host_flags & HF_AUTO_SENSE)
10479		goto out_reject;
10480
10481	/*
10482	**	Apply our alchemy:) (see comments in ncr_evaluate_dp()),
10483	**	to the resulted data pointer.
10484	*/
10485	dp_sg = ncr_evaluate_dp(np, cp, dp_scr, &dp_ofs);
10486	if (dp_sg < 0)
10487		goto out_reject;
10488
10489	/*
10490	**	And our alchemy:) allows to easily calculate the data
10491	**	script address we want to return for the next data phase.
10492	*/
10493	dp_ret = cpu_to_scr(cp->phys.header.goalp);
10494	dp_ret = dp_ret - 8 - (MAX_SCATTER - dp_sg) * (SCR_SG_SIZE*4);
10495
10496	/*
10497	**	If offset / scatter entry is zero we donnot need
10498	**	a context for the new current data pointer.
10499	*/
10500	if (dp_ofs == 0) {
10501		dp_scr = dp_ret;
10502		goto out_ok;
10503	}
10504
10505	/*
10506	**	Get a context for the new current data pointer.
10507	*/
10508	hflags = INB (HF_PRT);
10509
10510	if (hflags & HF_DP_SAVED)
10511		hflags ^= HF_ACT_PM;
10512
10513	if (!(hflags & HF_ACT_PM)) {
10514		pm  = &cp->phys.pm0;
10515		dp_scr = NCB_SCRIPT_PHYS (np, pm0_data);
10516	}
10517	else {
10518		pm = &cp->phys.pm1;
10519		dp_scr = NCB_SCRIPT_PHYS (np, pm1_data);
10520	}
10521
10522	hflags &= ~(HF_DP_SAVED);
10523
10524	OUTB (HF_PRT, hflags);
10525
10526	/*
10527	**	Set up the new current data pointer.
10528	**	ofs < 0 there, and for the next data phase, we
10529	**	want to transfer part of the data of the sg entry
10530	**	corresponding to index dp_sg-1 prior to returning
10531	**	to the main data script.
10532	*/
10533	pm->ret = cpu_to_scr(dp_ret);
10534	tmp  = scr_to_cpu(cp->phys.data[dp_sg-1].addr);
10535	tmp += scr_to_cpu(cp->phys.data[dp_sg-1].size) + dp_ofs;
10536	pm->sg.addr = cpu_to_scr(tmp);
10537	pm->sg.size = cpu_to_scr(-dp_ofs);
10538
10539out_ok:
10540	OUTL (nc_temp, dp_scr);
10541	OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
10542	return;
10543
10544out_reject:
10545	OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
10546}
10547
10548
10549/*==========================================================
10550**
10551**	ncr chip calculation of the data residual.
10552**
10553**==========================================================
10554**
10555**	As I used to say, the requirement of data residual
10556**	in SCSI is broken, useless and cannot be achieved
10557**	without huge complexity.
10558**	But most OSes and even the official CAM require it.
10559**	When stupidity happens to be so widely spread inside
10560**	a community, it gets hard to convince.
10561**
10562**	Anyway, I don't care, since I am not going to use
10563**	any software that considers this data residual as
10564**	a relevant information. :)
10565**
10566**----------------------------------------------------------
10567*/
10568
10569static int ncr_compute_residual(ncb_p np, ccb_p cp)
10570{
10571	int dp_sg, dp_sgmin, tmp;
10572	int resid=0;
10573	int dp_ofs = 0;
10574
10575	/*
10576	 *	Check for some data lost or just thrown away.
10577	 *	We are not required to be quite accurate in this
10578	 *	situation. Btw, if we are odd for output and the
10579	 *	device claims some more data, it may well happen
10580	 *	than our residual be zero. :-)
10581	 */
10582	if (cp->xerr_status & (XE_EXTRA_DATA|XE_SODL_UNRUN|XE_SWIDE_OVRUN)) {
10583		if (cp->xerr_status & XE_EXTRA_DATA)
10584			resid -= cp->extra_bytes;
10585		if (cp->xerr_status & XE_SODL_UNRUN)
10586			++resid;
10587		if (cp->xerr_status & XE_SWIDE_OVRUN)
10588			--resid;
10589	}
10590
10591
10592	/*
10593	**	If SCRIPTS reaches its goal point, then
10594	**	there is no additionnal residual.
10595	*/
10596	if (cp->phys.header.lastp == cp->phys.header.goalp)
10597		return resid;
10598
10599	/*
10600	**	If the last data pointer is data_io (direction
10601	**	unknown), then no data transfer should have
10602	**	taken place.
10603	*/
10604	if (cp->phys.header.lastp == NCB_SCRIPTH_PHYS (np, data_io))
10605		return cp->data_len;
10606
10607	/*
10608	**	If no data transfer occurs, or if the data
10609	**	pointer is weird, return full residual.
10610	*/
10611	if (cp->startp == cp->phys.header.lastp ||
10612	    ncr_evaluate_dp(np, cp, scr_to_cpu(cp->phys.header.lastp),
10613			    &dp_ofs) < 0) {
10614		return cp->data_len;
10615	}
10616
10617	/*
10618	**	We are now full comfortable in the computation
10619	**	of the data residual (2's complement).
10620	*/
10621	dp_sgmin = MAX_SCATTER - cp->segments;
10622	resid = -cp->ext_ofs;
10623	for (dp_sg = cp->ext_sg; dp_sg < MAX_SCATTER; ++dp_sg) {
10624		tmp = scr_to_cpu(cp->phys.data[dp_sg].size);
10625		resid += (tmp & 0xffffff);
10626	}
10627
10628	/*
10629	**	Hopefully, the result is not too wrong.
10630	*/
10631	return resid;
10632}
10633
10634/*==========================================================
10635**
10636**	Print out the containt of a SCSI message.
10637**
10638**==========================================================
10639*/
10640
10641static int ncr_show_msg (u_char * msg)
10642{
10643	u_char i;
10644	printk ("%x",*msg);
10645	if (*msg==M_EXTENDED) {
10646		for (i=1;i<8;i++) {
10647			if (i-1>msg[1]) break;
10648			printk ("-%x",msg[i]);
10649		};
10650		return (i+1);
10651	} else if ((*msg & 0xf0) == 0x20) {
10652		printk ("-%x",msg[1]);
10653		return (2);
10654	};
10655	return (1);
10656}
10657
10658static void ncr_print_msg (ccb_p cp, char *label, u_char *msg)
10659{
10660	if (cp)
10661		PRINT_ADDR(cp->cmd);
10662	if (label)
10663		printk ("%s: ", label);
10664
10665	(void) ncr_show_msg (msg);
10666	printk (".\n");
10667}
10668
10669/*===================================================================
10670**
10671**	Negotiation for WIDE and SYNCHRONOUS DATA TRANSFER.
10672**
10673**===================================================================
10674**
10675**	Was Sie schon immer ueber transfermode negotiation wissen wollten ...
10676**
10677**	We try to negotiate sync and wide transfer only after
10678**	a successful inquire command. We look at byte 7 of the
10679**	inquire data to determine the capabilities of the target.
10680**
10681**	When we try to negotiate, we append the negotiation message
10682**	to the identify and (maybe) simple tag message.
10683**	The host status field is set to HS_NEGOTIATE to mark this
10684**	situation.
10685**
10686**	If the target doesn't answer this message immediately
10687**	(as required by the standard), the SIR_NEGO_FAILED interrupt
10688**	will be raised eventually.
10689**	The handler removes the HS_NEGOTIATE status, and sets the
10690**	negotiated value to the default (async / nowide).
10691**
10692**	If we receive a matching answer immediately, we check it
10693**	for validity, and set the values.
10694**
10695**	If we receive a Reject message immediately, we assume the
10696**	negotiation has failed, and fall back to standard values.
10697**
10698**	If we receive a negotiation message while not in HS_NEGOTIATE
10699**	state, it's a target initiated negotiation. We prepare a
10700**	(hopefully) valid answer, set our parameters, and send back
10701**	this answer to the target.
10702**
10703**	If the target doesn't fetch the answer (no message out phase),
10704**	we assume the negotiation has failed, and fall back to default
10705**	settings (SIR_NEGO_PROTO interrupt).
10706**
10707**	When we set the values, we adjust them in all ccbs belonging
10708**	to this target, in the controller's register, and in the "phys"
10709**	field of the controller's struct ncb.
10710**
10711**---------------------------------------------------------------------
10712*/
10713
10714/*==========================================================
10715**
10716**	ncr chip handler for SYNCHRONOUS DATA TRANSFER
10717**	REQUEST (SDTR) message.
10718**
10719**==========================================================
10720**
10721**	Read comments above.
10722**
10723**----------------------------------------------------------
10724*/
10725static void ncr_sync_nego(ncb_p np, tcb_p tp, ccb_p cp)
10726{
10727	u_char	scntl3, scntl4;
10728	u_char	chg, ofs, per, fak;
10729
10730	/*
10731	**	Synchronous request message received.
10732	*/
10733
10734	if (DEBUG_FLAGS & DEBUG_NEGO) {
10735		ncr_print_msg(cp, "sync msg in", np->msgin);
10736	};
10737
10738	/*
10739	**	get requested values.
10740	*/
10741
10742	chg = 0;
10743	per = np->msgin[3];
10744	ofs = np->msgin[4];
10745	if (ofs==0) per=255;
10746
10747	/*
10748	**      if target sends SDTR message,
10749	**	      it CAN transfer synch.
10750	*/
10751
10752	if (ofs)
10753		tp->inq_byte7 |= INQ7_SYNC;
10754
10755	/*
10756	**	check values against driver limits.
10757	*/
10758
10759	if (per < np->minsync)
10760		{chg = 1; per = np->minsync;}
10761	if (per < tp->minsync)
10762		{chg = 1; per = tp->minsync;}
10763	if (ofs > np->maxoffs_st)
10764		{chg = 1; ofs = np->maxoffs_st;}
10765	if (ofs > tp->maxoffs)
10766		{chg = 1; ofs = tp->maxoffs;}
10767
10768	/*
10769	**	Check against controller limits.
10770	*/
10771	fak	= 7;
10772	scntl3	= 0;
10773	scntl4  = 0;
10774	if (ofs != 0) {
10775		ncr_getsync(np, per, &fak, &scntl3);
10776		if (fak > 7) {
10777			chg = 1;
10778			ofs = 0;
10779		}
10780	}
10781	if (ofs == 0) {
10782		fak	= 7;
10783		per	= 0;
10784		scntl3	= 0;
10785		scntl4  = 0;
10786		tp->minsync = 0;
10787	}
10788
10789	if (DEBUG_FLAGS & DEBUG_NEGO) {
10790		PRINT_ADDR(cp->cmd);
10791		printk ("sync: per=%d scntl3=0x%x scntl4=0x%x ofs=%d fak=%d chg=%d.\n",
10792			per, scntl3, scntl4, ofs, fak, chg);
10793	}
10794
10795	if (INB (HS_PRT) == HS_NEGOTIATE) {
10796		OUTB (HS_PRT, HS_BUSY);
10797		switch (cp->nego_status) {
10798		case NS_SYNC:
10799			/*
10800			**      This was an answer message
10801			*/
10802			if (chg) {
10803				/*
10804				**	Answer wasn't acceptable.
10805				*/
10806				ncr_setsync (np, cp, 0, 0xe0, 0);
10807				OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
10808			} else {
10809				/*
10810				**	Answer is ok.
10811				*/
10812				if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
10813					(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
10814				  ncr_setsync (np, cp, scntl3, (fak<<5)|ofs,0);
10815				else
10816				  ncr_setsync (np, cp, scntl3, ofs, scntl4);
10817
10818				OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
10819			};
10820			return;
10821
10822		case NS_WIDE:
10823			ncr_setwide (np, cp, 0, 0);
10824			break;
10825		};
10826	};
10827
10828	/*
10829	**	It was a request. Set value and
10830	**      prepare an answer message
10831	*/
10832
10833	if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
10834			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
10835		ncr_setsync (np, cp, scntl3, (fak<<5)|ofs,0);
10836	else
10837		ncr_setsync (np, cp, scntl3, ofs, scntl4);
10838
10839	np->msgout[0] = M_EXTENDED;
10840	np->msgout[1] = 3;
10841	np->msgout[2] = M_X_SYNC_REQ;
10842	np->msgout[3] = per;
10843	np->msgout[4] = ofs;
10844
10845	cp->nego_status = NS_SYNC;
10846
10847	if (DEBUG_FLAGS & DEBUG_NEGO) {
10848		ncr_print_msg(cp, "sync msgout", np->msgout);
10849	}
10850
10851	np->msgin [0] = M_NOOP;
10852
10853	if (!ofs)
10854		OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
10855	else
10856		OUTL_DSP (NCB_SCRIPTH_PHYS (np, sdtr_resp));
10857}
10858
10859/*==========================================================
10860**
10861**	ncr chip handler for WIDE DATA TRANSFER REQUEST
10862**	(WDTR) message.
10863**
10864**==========================================================
10865**
10866**	Read comments above.
10867**
10868**----------------------------------------------------------
10869*/
10870static void ncr_wide_nego(ncb_p np, tcb_p tp, ccb_p cp)
10871{
10872	u_char	chg, wide;
10873
10874	/*
10875	**	Wide request message received.
10876	*/
10877	if (DEBUG_FLAGS & DEBUG_NEGO) {
10878		ncr_print_msg(cp, "wide msgin", np->msgin);
10879	};
10880
10881	/*
10882	**	get requested values.
10883	*/
10884
10885	chg  = 0;
10886	wide = np->msgin[3];
10887
10888	/*
10889	**      if target sends WDTR message,
10890	**	      it CAN transfer wide.
10891	*/
10892
10893	if (wide)
10894		tp->inq_byte7 |= INQ7_WIDE16;
10895
10896	/*
10897	**	check values against driver limits.
10898	*/
10899
10900	if (wide > tp->usrwide)
10901		{chg = 1; wide = tp->usrwide;}
10902
10903	if (DEBUG_FLAGS & DEBUG_NEGO) {
10904		PRINT_ADDR(cp->cmd);
10905		printk ("wide: wide=%d chg=%d.\n", wide, chg);
10906	}
10907
10908	if (INB (HS_PRT) == HS_NEGOTIATE) {
10909		OUTB (HS_PRT, HS_BUSY);
10910		switch (cp->nego_status) {
10911		case NS_WIDE:
10912			/*
10913			**      This was an answer message
10914			*/
10915			if (chg) {
10916				/*
10917				**	Answer wasn't acceptable.
10918				*/
10919				ncr_setwide (np, cp, 0, 1);
10920				OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
10921			} else {
10922				/*
10923				**	Answer is ok.
10924				*/
10925				ncr_setwide (np, cp, wide, 1);
10926				OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
10927			};
10928			return;
10929
10930		case NS_SYNC:
10931			ncr_setsync (np, cp, 0, 0xe0, 0);
10932			break;
10933		};
10934	};
10935
10936	/*
10937	**	It was a request, set value and
10938	**      prepare an answer message
10939	*/
10940
10941	ncr_setwide (np, cp, wide, 1);
10942
10943	np->msgout[0] = M_EXTENDED;
10944	np->msgout[1] = 2;
10945	np->msgout[2] = M_X_WIDE_REQ;
10946	np->msgout[3] = wide;
10947
10948	np->msgin [0] = M_NOOP;
10949
10950	cp->nego_status = NS_WIDE;
10951
10952	if (DEBUG_FLAGS & DEBUG_NEGO) {
10953		ncr_print_msg(cp, "wide msgout", np->msgout);
10954	}
10955
10956	OUTL_DSP (NCB_SCRIPTH_PHYS (np, wdtr_resp));
10957}
10958/*==========================================================
10959**
10960**	ncr chip handler for PARALLEL PROTOCOL REQUEST
10961**	(PPR) message.
10962**
10963**==========================================================
10964**
10965**	Read comments above.
10966**
10967**----------------------------------------------------------
10968*/
10969static void ncr_ppr_nego(ncb_p np, tcb_p tp, ccb_p cp)
10970{
10971	u_char	scntl3, scntl4;
10972	u_char	chg, ofs, per, fak, wth, dt;
10973
10974	/*
10975	**	PPR message received.
10976	*/
10977
10978	if (DEBUG_FLAGS & DEBUG_NEGO) {
10979		ncr_print_msg(cp, "ppr msg in", np->msgin);
10980	};
10981
10982	/*
10983	**	get requested values.
10984	*/
10985
10986	chg = 0;
10987	per = np->msgin[3];
10988	ofs = np->msgin[5];
10989	wth = np->msgin[6];
10990	dt  = np->msgin[7];
10991	if (ofs==0) per=255;
10992
10993	/*
10994	**      if target sends sync (wide),
10995	**	      it CAN transfer synch (wide).
10996	*/
10997
10998	if (ofs)
10999		tp->inq_byte7 |= INQ7_SYNC;
11000
11001	if (wth)
11002		tp->inq_byte7 |= INQ7_WIDE16;
11003
11004	/*
11005	**	check values against driver limits.
11006	*/
11007
11008	if (wth > tp->usrwide)
11009		{chg = 1; wth = tp->usrwide;}
11010	if (per < np->minsync)
11011		{chg = 1; per = np->minsync;}
11012	if (per < tp->minsync)
11013		{chg = 1; per = tp->minsync;}
11014	if (ofs > tp->maxoffs)
11015		{chg = 1; ofs = tp->maxoffs;}
11016
11017	/*
11018	**	Check against controller limits.
11019	*/
11020	fak	= 7;
11021	scntl3	= 0;
11022	scntl4  = 0;
11023	if (ofs != 0) {
11024		scntl4 = dt ? 0x80 : 0;
11025		ncr_getsync(np, per, &fak, &scntl3);
11026		if (fak > 7) {
11027			chg = 1;
11028			ofs = 0;
11029		}
11030	}
11031	if (ofs == 0) {
11032		fak	= 7;
11033		per	= 0;
11034		scntl3	= 0;
11035		scntl4  = 0;
11036		tp->minsync = 0;
11037	}
11038
11039	/*
11040	**	If target responds with Ultra 3 speed
11041	**	but narrow or not DT, reject.
11042	**	If target responds with DT request
11043	**	but not Ultra3 speeds, reject message,
11044	**	reset min sync for target to 0x0A and
11045	**	set flags to re-negotiate.
11046	*/
11047
11048	if   ((per == 0x09) && ofs && (!wth || !dt))
11049		chg = 1;
11050	else if (( (per > 0x09) && dt) )
11051		chg = 2;
11052
11053	/* Not acceptable since beyond controller limit */
11054	if (!dt && ofs > np->maxoffs_st)
11055		{chg = 2; ofs = np->maxoffs_st;}
11056
11057	if (DEBUG_FLAGS & DEBUG_NEGO) {
11058		PRINT_ADDR(cp->cmd);
11059		printk ("ppr: wth=%d per=%d scntl3=0x%x scntl4=0x%x ofs=%d fak=%d chg=%d.\n",
11060			wth, per, scntl3, scntl4, ofs, fak, chg);
11061	}
11062
11063	if (INB (HS_PRT) == HS_NEGOTIATE) {
11064		OUTB (HS_PRT, HS_BUSY);
11065		switch (cp->nego_status) {
11066		case NS_PPR:
11067			/*
11068			**      This was an answer message
11069			*/
11070			if (chg) {
11071				/*
11072				**	Answer wasn't acceptable.
11073				*/
11074				if (chg == 2) {
11075					/* Send message reject and reset flags for
11076					** host to re-negotiate with min period 0x0A.
11077					*/
11078					tp->minsync = 0x0A;
11079					tp->period = 0;
11080					tp->widedone = 0;
11081				}
11082				ncr_setsyncwide (np, cp, 0, 0xe0, 0, 0);
11083				OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
11084			} else {
11085				/*
11086				**	Answer is ok.
11087				*/
11088
11089				if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
11090					(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
11091				  ncr_setsyncwide (np, cp, scntl3, (fak<<5)|ofs,0, wth);
11092				else
11093				  ncr_setsyncwide (np, cp, scntl3, ofs, scntl4, wth);
11094
11095				OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
11096
11097			};
11098			return;
11099
11100		case NS_SYNC:
11101			ncr_setsync (np, cp, 0, 0xe0, 0);
11102			break;
11103
11104		case NS_WIDE:
11105			ncr_setwide (np, cp, 0, 0);
11106			break;
11107		};
11108	};
11109
11110	/*
11111	**	It was a request. Set value and
11112	**      prepare an answer message
11113	**
11114	**	If narrow or not DT and requesting Ultra3
11115	**	slow the bus down and force ST. If not
11116	**	requesting Ultra3, force ST.
11117	**	Max offset is 31=0x1f if ST mode.
11118	*/
11119
11120	if  ((per == 0x09) && ofs && (!wth || !dt)) {
11121		per = 0x0A;
11122		dt = 0;
11123	}
11124	else if ( (per > 0x09) && dt) {
11125		dt = 0;
11126	}
11127	if (!dt && ofs > np->maxoffs_st)
11128		ofs = np->maxoffs_st;
11129
11130	if ((np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
11131			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66))
11132		ncr_setsyncwide (np, cp, scntl3, (fak<<5)|ofs,0, wth);
11133	else
11134		ncr_setsyncwide (np, cp, scntl3, ofs, scntl4, wth);
11135
11136	np->msgout[0] = M_EXTENDED;
11137	np->msgout[1] = 6;
11138	np->msgout[2] = M_X_PPR_REQ;
11139	np->msgout[3] = per;
11140	np->msgout[4] = 0;
11141	np->msgout[5] = ofs;
11142	np->msgout[6] = wth;
11143	np->msgout[7] = dt;
11144
11145	cp->nego_status = NS_PPR;
11146
11147	if (DEBUG_FLAGS & DEBUG_NEGO) {
11148		ncr_print_msg(cp, "ppr msgout", np->msgout);
11149	}
11150
11151	np->msgin [0] = M_NOOP;
11152
11153	if (!ofs)
11154		OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
11155	else
11156		OUTL_DSP (NCB_SCRIPTH_PHYS (np, ppr_resp));
11157}
11158
11159
11160
11161/*
11162**	Reset SYNC or WIDE to default settings.
11163**	Called when a negotiation does not succeed either
11164**	on rejection or on protocol error.
11165*/
11166static void ncr_nego_default(ncb_p np, tcb_p tp, ccb_p cp)
11167{
11168	/*
11169	**	any error in negotiation:
11170	**	fall back to default mode.
11171	*/
11172	switch (cp->nego_status) {
11173
11174	case NS_SYNC:
11175		ncr_setsync (np, cp, 0, 0xe0, 0);
11176		break;
11177
11178	case NS_WIDE:
11179		ncr_setwide (np, cp, 0, 0);
11180		break;
11181
11182	case NS_PPR:
11183		/*
11184		 * ppr_negotiation is set to 1 on the first ppr nego command.
11185		 * If ppr is successful, it is reset to 2.
11186		 * If unsuccessful it is reset to 0.
11187		 */
11188		if (DEBUG_FLAGS & DEBUG_NEGO) {
11189			tcb_p tp=&np->target[cp->target];
11190			u_char factor, offset, width;
11191
11192			ncr_get_xfer_info ( np, tp, &factor, &offset, &width);
11193
11194			printk("Current factor %d offset %d width %d\n",
11195				factor, offset, width);
11196		}
11197		if (tp->ppr_negotiation == 2)
11198			ncr_setsyncwide (np, cp, 0, 0xe0, 0, 0);
11199		else if (tp->ppr_negotiation == 1) {
11200
11201			/* First ppr command has received a  M REJECT.
11202			 * Do not change the existing wide/sync parameter
11203			 * values (asyn/narrow if this as the first nego;
11204			 * may be different if target initiates nego.).
11205			 */
11206			tp->ppr_negotiation = 0;
11207		}
11208		else
11209		{
11210			tp->ppr_negotiation = 0;
11211			ncr_setwide (np, cp, 0, 0);
11212		}
11213		break;
11214	};
11215	np->msgin [0] = M_NOOP;
11216	np->msgout[0] = M_NOOP;
11217	cp->nego_status = 0;
11218}
11219
11220/*==========================================================
11221**
11222**	ncr chip handler for MESSAGE REJECT received for
11223**	a WIDE or SYNCHRONOUS negotiation.
11224**
11225**	clear the PPR negotiation flag, all future nego.
11226**	will be SDTR and WDTR
11227**
11228**==========================================================
11229**
11230**	Read comments above.
11231**
11232**----------------------------------------------------------
11233*/
11234static void ncr_nego_rejected(ncb_p np, tcb_p tp, ccb_p cp)
11235{
11236	ncr_nego_default(np, tp, cp);
11237	OUTB (HS_PRT, HS_BUSY);
11238}
11239
11240
11241/*==========================================================
11242**
11243**
11244**      ncr chip exception handler for programmed interrupts.
11245**
11246**
11247**==========================================================
11248*/
11249
11250void ncr_int_sir (ncb_p np)
11251{
11252	u_char	num	= INB (nc_dsps);
11253	u_long	dsa	= INL (nc_dsa);
11254	ccb_p	cp	= ncr_ccb_from_dsa(np, dsa);
11255	u_char	target	= INB (nc_sdid) & 0x0f;
11256	tcb_p	tp	= &np->target[target];
11257	int	tmp;
11258
11259	if (DEBUG_FLAGS & DEBUG_TINY) printk ("I#%d", num);
11260
11261	switch (num) {
11262	/*
11263	**	See comments in the SCRIPTS code.
11264	*/
11265#ifdef SCSI_NCR_PCIQ_SYNC_ON_INTR
11266	case SIR_DUMMY_INTERRUPT:
11267		goto out;
11268#endif
11269
11270	/*
11271	**	The C code is currently trying to recover from something.
11272	**	Typically, user want to abort some command.
11273	*/
11274	case SIR_SCRIPT_STOPPED:
11275	case SIR_TARGET_SELECTED:
11276	case SIR_ABORT_SENT:
11277	case SIR_AUTO_SENSE_DONE:
11278		ncr_sir_task_recovery(np, num);
11279		return;
11280	/*
11281	**	The device didn't go to MSG OUT phase after having
11282	**	been selected with ATN. We donnot want to handle
11283	**	that.
11284	*/
11285	case SIR_SEL_ATN_NO_MSG_OUT:
11286		printk ("%s:%d: No MSG OUT phase after selection with ATN.\n",
11287			ncr_name (np), target);
11288		goto out_stuck;
11289	/*
11290	**	The device didn't switch to MSG IN phase after
11291	**	having reseleted the initiator.
11292	*/
11293	case SIR_RESEL_NO_MSG_IN:
11294	/*
11295	**	After reselection, the device sent a message that wasn't
11296	**	an IDENTIFY.
11297	*/
11298	case SIR_RESEL_NO_IDENTIFY:
11299		/*
11300		**	If devices reselecting without sending an IDENTIFY
11301		**	message still exist, this should help.
11302		**	We just assume lun=0, 1 CCB, no tag.
11303		*/
11304		if (tp->l0p) {
11305			OUTL (nc_dsa, scr_to_cpu(tp->l0p->tasktbl[0]));
11306			OUTL_DSP (NCB_SCRIPT_PHYS (np, resel_go));
11307			return;
11308		}
11309	/*
11310	**	The device reselected a LUN we donnot know of.
11311	*/
11312	case SIR_RESEL_BAD_LUN:
11313		np->msgout[0] = M_RESET;
11314		goto out;
11315	/*
11316	**	The device reselected for an untagged nexus and we
11317	**	haven't any.
11318	*/
11319	case SIR_RESEL_BAD_I_T_L:
11320		np->msgout[0] = M_ABORT;
11321		goto out;
11322	/*
11323	**	The device reselected for a tagged nexus that we donnot
11324	**	have.
11325	*/
11326	case SIR_RESEL_BAD_I_T_L_Q:
11327		np->msgout[0] = M_ABORT_TAG;
11328		goto out;
11329	/*
11330	**	The SCRIPTS let us know that the device has grabbed
11331	**	our message and will abort the job.
11332	*/
11333	case SIR_RESEL_ABORTED:
11334		np->lastmsg = np->msgout[0];
11335		np->msgout[0] = M_NOOP;
11336		printk ("%s:%d: message %x sent on bad reselection.\n",
11337			ncr_name (np), target, np->lastmsg);
11338		goto out;
11339	/*
11340	**	The SCRIPTS let us know that a message has been
11341	**	successfully sent to the device.
11342	*/
11343	case SIR_MSG_OUT_DONE:
11344		np->lastmsg = np->msgout[0];
11345		np->msgout[0] = M_NOOP;
11346		/* Should we really care of that */
11347		if (np->lastmsg == M_PARITY || np->lastmsg == M_ID_ERROR) {
11348			if (cp) {
11349				cp->xerr_status &= ~XE_PARITY_ERR;
11350                                if (!cp->xerr_status)
11351					OUTOFFB (HF_PRT, HF_EXT_ERR);
11352			}
11353		}
11354		goto out;
11355	/*
11356	**	The device didn't send a GOOD SCSI status.
11357	**	We may have some work to do prior to allow
11358	**	the SCRIPTS processor to continue.
11359	*/
11360	case SIR_BAD_STATUS:
11361		if (!cp)
11362			goto out;
11363		ncr_sir_to_redo(np, num, cp);
11364		return;
11365	/*
11366	**	We are asked by the SCRIPTS to prepare a
11367	**	REJECT message.
11368	*/
11369	case SIR_REJECT_TO_SEND:
11370		ncr_print_msg(cp, "M_REJECT to send for ", np->msgin);
11371		np->msgout[0] = M_REJECT;
11372		goto out;
11373	/*
11374	**	We have been ODD at the end of a DATA IN
11375	**	transfer and the device didn't send a
11376	**	IGNORE WIDE RESIDUE message.
11377	**	It is a data overrun condition.
11378	*/
11379	case SIR_SWIDE_OVERRUN:
11380                if (cp) {
11381                        OUTONB (HF_PRT, HF_EXT_ERR);
11382                        cp->xerr_status |= XE_SWIDE_OVRUN;
11383                }
11384		goto out;
11385	/*
11386	**	We have been ODD at the end of a DATA OUT
11387	**	transfer.
11388	**	It is a data underrun condition.
11389	*/
11390	case SIR_SODL_UNDERRUN:
11391                if (cp) {
11392                        OUTONB (HF_PRT, HF_EXT_ERR);
11393                        cp->xerr_status |= XE_SODL_UNRUN;
11394                }
11395		goto out;
11396	/*
11397	**	The device wants us to tranfer more data than
11398	**	expected or in the wrong direction.
11399	**	The number of extra bytes is in scratcha.
11400	**	It is a data overrun condition.
11401	*/
11402	case SIR_DATA_OVERRUN:
11403		if (cp) {
11404			OUTONB (HF_PRT, HF_EXT_ERR);
11405			cp->xerr_status |= XE_EXTRA_DATA;
11406			cp->extra_bytes += INL (nc_scratcha);
11407		}
11408		goto out;
11409	/*
11410	**	The device switched to an illegal phase (4/5).
11411	*/
11412	case SIR_BAD_PHASE:
11413		if (cp) {
11414			OUTONB (HF_PRT, HF_EXT_ERR);
11415			cp->xerr_status |= XE_BAD_PHASE;
11416		}
11417		goto out;
11418	/*
11419	**	We received a message.
11420	*/
11421	case SIR_MSG_RECEIVED:
11422		if (!cp)
11423			goto out_stuck;
11424		switch (np->msgin [0]) {
11425		/*
11426		**	We received an extended message.
11427		**	We handle MODIFY DATA POINTER, SDTR, WDTR
11428		**	and reject all other extended messages.
11429		*/
11430		case M_EXTENDED:
11431			switch (np->msgin [2]) {
11432			case M_X_MODIFY_DP:
11433				if (DEBUG_FLAGS & DEBUG_POINTER)
11434					ncr_print_msg(cp,"modify DP",np->msgin);
11435				tmp = (np->msgin[3]<<24) + (np->msgin[4]<<16) +
11436				      (np->msgin[5]<<8)  + (np->msgin[6]);
11437				ncr_modify_dp(np, tp, cp, tmp);
11438				return;
11439			case M_X_SYNC_REQ:
11440				ncr_sync_nego(np, tp, cp);
11441				return;
11442			case M_X_WIDE_REQ:
11443				ncr_wide_nego(np, tp, cp);
11444				return;
11445			case M_X_PPR_REQ:
11446				ncr_ppr_nego(np, tp, cp);
11447				return;
11448			default:
11449				goto out_reject;
11450			}
11451			break;
11452		/*
11453		**	We received a 1/2 byte message not handled from SCRIPTS.
11454		**	We are only expecting MESSAGE REJECT and IGNORE WIDE
11455		**	RESIDUE messages that haven't been anticipated by
11456		**	SCRIPTS on SWIDE full condition. Unanticipated IGNORE
11457		**	WIDE RESIDUE messages are aliased as MODIFY DP (-1).
11458		*/
11459		case M_IGN_RESIDUE:
11460			if (DEBUG_FLAGS & DEBUG_POINTER)
11461				ncr_print_msg(cp,"ign wide residue", np->msgin);
11462			ncr_modify_dp(np, tp, cp, -1);
11463			return;
11464		case M_REJECT:
11465			if (INB (HS_PRT) == HS_NEGOTIATE)
11466				ncr_nego_rejected(np, tp, cp);
11467			else {
11468				PRINT_ADDR(cp->cmd);
11469				printk ("M_REJECT received (%x:%x).\n",
11470					scr_to_cpu(np->lastmsg), np->msgout[0]);
11471			}
11472			goto out_clrack;
11473			break;
11474		default:
11475			goto out_reject;
11476		}
11477		break;
11478	/*
11479	**	We received an unknown message.
11480	**	Ignore all MSG IN phases and reject it.
11481	*/
11482	case SIR_MSG_WEIRD:
11483		ncr_print_msg(cp, "WEIRD message received", np->msgin);
11484		OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_weird));
11485		return;
11486	/*
11487	**	Negotiation failed.
11488	**	Target does not send us the reply.
11489	**	Remove the HS_NEGOTIATE status.
11490	*/
11491	case SIR_NEGO_FAILED:
11492		OUTB (HS_PRT, HS_BUSY);
11493	/*
11494	**	Negotiation failed.
11495	**	Target does not want answer message.
11496	*/
11497	case SIR_NEGO_PROTO:
11498		ncr_nego_default(np, tp, cp);
11499		goto out;
11500	};
11501
11502out:
11503	OUTONB_STD ();
11504	return;
11505out_reject:
11506	OUTL_DSP (NCB_SCRIPTH_PHYS (np, msg_bad));
11507	return;
11508out_clrack:
11509	OUTL_DSP (NCB_SCRIPT_PHYS (np, clrack));
11510	return;
11511out_stuck:
11512	return;
11513}
11514
11515
11516/*==========================================================
11517**
11518**
11519**	Acquire a control block
11520**
11521**
11522**==========================================================
11523*/
11524
11525static	ccb_p ncr_get_ccb (ncb_p np, u_char tn, u_char ln)
11526{
11527	tcb_p tp = &np->target[tn];
11528	lcb_p lp = ncr_lp(np, tp, ln);
11529	u_short tag = NO_TAG;
11530	XPT_QUEHEAD *qp;
11531	ccb_p cp = (ccb_p) 0;
11532
11533	/*
11534	**	Allocate a new CCB if needed.
11535	*/
11536	if (xpt_que_empty(&np->free_ccbq))
11537		(void) ncr_alloc_ccb(np);
11538
11539	/*
11540	**	Look for a free CCB
11541	*/
11542	qp = xpt_remque_head(&np->free_ccbq);
11543	if (!qp)
11544		goto out;
11545	cp = xpt_que_entry(qp, struct ccb, link_ccbq);
11546
11547	/*
11548	**	If the LCB is not yet available and we already
11549	**	have queued a CCB for a LUN without LCB,
11550	**	give up. Otherwise all is fine. :-)
11551	*/
11552	if (!lp) {
11553		if (xpt_que_empty(&np->b0_ccbq))
11554			xpt_insque_head(&cp->link_ccbq, &np->b0_ccbq);
11555		else
11556			goto out_free;
11557	} else {
11558		/*
11559		**	Tune tag mode if asked by user.
11560		*/
11561		if (lp->queuedepth != lp->numtags) {
11562			ncr_setup_tags(np, tn, ln);
11563		}
11564
11565		/*
11566		**	Get a tag for this nexus if required.
11567		**	Keep from using more tags than we can handle.
11568		*/
11569		if (lp->usetags) {
11570			if (lp->busyccbs < lp->maxnxs) {
11571				tag = lp->cb_tags[lp->ia_tag];
11572				++lp->ia_tag;
11573				if (lp->ia_tag == MAX_TAGS)
11574					lp->ia_tag = 0;
11575				cp->tags_si = lp->tags_si;
11576				++lp->tags_sum[cp->tags_si];
11577			}
11578			else
11579				goto out_free;
11580		}
11581
11582		/*
11583		**	Put the CCB in the LUN wait queue and
11584		**	count it as busy.
11585		*/
11586		xpt_insque_tail(&cp->link_ccbq, &lp->wait_ccbq);
11587		++lp->busyccbs;
11588	}
11589
11590	/*
11591	**	Remember all informations needed to free this CCB.
11592	*/
11593	cp->to_abort = 0;
11594	cp->tag	   = tag;
11595	cp->target = tn;
11596	cp->lun    = ln;
11597
11598	if (DEBUG_FLAGS & DEBUG_TAGS) {
11599		PRINT_LUN(np, tn, ln);
11600		printk ("ccb @%p using tag %d.\n", cp, tag);
11601	}
11602
11603out:
11604	return cp;
11605out_free:
11606	xpt_insque_head(&cp->link_ccbq, &np->free_ccbq);
11607	return (ccb_p) 0;
11608}
11609
11610/*==========================================================
11611**
11612**
11613**	Release one control block
11614**
11615**
11616**==========================================================
11617*/
11618
11619static void ncr_free_ccb (ncb_p np, ccb_p cp)
11620{
11621	tcb_p tp = &np->target[cp->target];
11622	lcb_p lp = ncr_lp(np, tp, cp->lun);
11623
11624	if (DEBUG_FLAGS & DEBUG_TAGS) {
11625		PRINT_LUN(np, cp->target, cp->lun);
11626		printk ("ccb @%p freeing tag %d.\n", cp, cp->tag);
11627	}
11628
11629	/*
11630	**	If lun control block available, make available
11631	**	the task slot and the tag if any.
11632	**	Decrement counters.
11633	*/
11634	if (lp) {
11635		if (cp->tag != NO_TAG) {
11636			lp->cb_tags[lp->if_tag++] = cp->tag;
11637			if (lp->if_tag == MAX_TAGS)
11638				lp->if_tag = 0;
11639			--lp->tags_sum[cp->tags_si];
11640			lp->tasktbl[cp->tag] = cpu_to_scr(np->p_bad_i_t_l_q);
11641		} else {
11642			lp->tasktbl[0] = cpu_to_scr(np->p_bad_i_t_l);
11643		}
11644		--lp->busyccbs;
11645		if (cp->queued) {
11646			--lp->queuedccbs;
11647		}
11648	}
11649
11650	/*
11651	**	Make this CCB available.
11652	*/
11653	xpt_remque(&cp->link_ccbq);
11654	xpt_insque_head(&cp->link_ccbq, &np->free_ccbq);
11655	cp -> host_status = HS_IDLE;
11656	cp -> queued = 0;
11657}
11658
11659/*------------------------------------------------------------------------
11660**	Allocate a CCB and initialize its fixed part.
11661**------------------------------------------------------------------------
11662**------------------------------------------------------------------------
11663*/
11664static ccb_p ncr_alloc_ccb(ncb_p np)
11665{
11666	ccb_p cp = 0;
11667	int hcode;
11668
11669	/*
11670	**	Allocate memory for this CCB.
11671	*/
11672	cp = m_calloc_dma(sizeof(struct ccb), "CCB");
11673	if (!cp)
11674		return 0;
11675
11676	/*
11677	**	Count it and initialyze it.
11678	*/
11679	np->actccbs++;
11680
11681	/*
11682	**	Remember virtual and bus address of this ccb.
11683	*/
11684	cp->p_ccb 	   = vtobus(cp);
11685
11686	/*
11687	**	Insert this ccb into the hashed list.
11688	*/
11689	hcode = CCB_HASH_CODE(cp->p_ccb);
11690	cp->link_ccbh = np->ccbh[hcode];
11691	np->ccbh[hcode] = cp;
11692
11693	/*
11694	**	Initialyze the start and restart actions.
11695	*/
11696	cp->phys.header.go.start   = cpu_to_scr(NCB_SCRIPT_PHYS (np, idle));
11697	cp->phys.header.go.restart = cpu_to_scr(NCB_SCRIPTH_PHYS(np,bad_i_t_l));
11698
11699	/*
11700	**	Initilialyze some other fields.
11701	*/
11702	cp->phys.smsg_ext.addr = cpu_to_scr(NCB_PHYS(np, msgin[2]));
11703
11704	/*
11705	**	Chain into wakeup list and free ccb queue.
11706	*/
11707	cp->link_ccb	= np->ccbc;
11708	np->ccbc	= cp;
11709
11710	xpt_insque_head(&cp->link_ccbq, &np->free_ccbq);
11711
11712	return cp;
11713}
11714
11715/*------------------------------------------------------------------------
11716**	Look up a CCB from a DSA value.
11717**------------------------------------------------------------------------
11718**------------------------------------------------------------------------
11719*/
11720static ccb_p ncr_ccb_from_dsa(ncb_p np, u_long dsa)
11721{
11722	int hcode;
11723	ccb_p cp;
11724
11725	hcode = CCB_HASH_CODE(dsa);
11726	cp = np->ccbh[hcode];
11727	while (cp) {
11728		if (cp->p_ccb == dsa)
11729			break;
11730		cp = cp->link_ccbh;
11731	}
11732
11733	return cp;
11734}
11735
11736/*==========================================================
11737**
11738**
11739**      Allocation of resources for Targets/Luns/Tags.
11740**
11741**
11742**==========================================================
11743*/
11744
11745
11746/*------------------------------------------------------------------------
11747**	Target control block initialisation.
11748**------------------------------------------------------------------------
11749**	This data structure is fully initialized after a SCSI command
11750**	has been successfully completed for this target.
11751**------------------------------------------------------------------------
11752*/
11753static void ncr_init_tcb (ncb_p np, u_char tn)
11754{
11755	/*
11756	**	Check some alignments required by the chip.
11757	*/
11758	assert (( (offsetof(struct ncr_reg, nc_sxfer) ^
11759		offsetof(struct tcb    , sval    )) &3) == 0);
11760	assert (( (offsetof(struct ncr_reg, nc_scntl3) ^
11761		offsetof(struct tcb    , wval    )) &3) == 0);
11762	if ((np->device_id == PCI_DEVICE_ID_LSI_53C1010) ||
11763		(np->device_id == PCI_DEVICE_ID_LSI_53C1010_66)){
11764		assert (( (offsetof(struct ncr_reg, nc_scntl4) ^
11765			offsetof(struct tcb    , uval    )) &3) == 0);
11766	}
11767}
11768
11769/*------------------------------------------------------------------------
11770**	Lun control block allocation and initialization.
11771**------------------------------------------------------------------------
11772**	This data structure is allocated and initialized after a SCSI
11773**	command has been successfully completed for this target/lun.
11774**------------------------------------------------------------------------
11775*/
11776static lcb_p ncr_alloc_lcb (ncb_p np, u_char tn, u_char ln)
11777{
11778	tcb_p tp = &np->target[tn];
11779	lcb_p lp = ncr_lp(np, tp, ln);
11780
11781	/*
11782	**	Already done, return.
11783	*/
11784	if (lp)
11785		return lp;
11786
11787	/*
11788	**	Initialize the target control block if not yet.
11789	*/
11790	ncr_init_tcb(np, tn);
11791
11792	/*
11793	**	Allocate the lcb bus address array.
11794	**	Compute the bus address of this table.
11795	*/
11796	if (ln && !tp->luntbl) {
11797		int i;
11798
11799		tp->luntbl = m_calloc_dma(256, "LUNTBL");
11800		if (!tp->luntbl)
11801			goto fail;
11802		for (i = 0 ; i < 64 ; i++)
11803			tp->luntbl[i] = cpu_to_scr(NCB_PHYS(np, resel_badlun));
11804		tp->b_luntbl = cpu_to_scr(vtobus(tp->luntbl));
11805	}
11806
11807	/*
11808	**	Allocate the table of pointers for LUN(s) > 0, if needed.
11809	*/
11810	if (ln && !tp->lmp) {
11811		tp->lmp = m_calloc(MAX_LUN * sizeof(lcb_p), "LMP");
11812		if (!tp->lmp)
11813			goto fail;
11814	}
11815
11816	/*
11817	**	Allocate the lcb.
11818	**	Make it available to the chip.
11819	*/
11820	lp = m_calloc_dma(sizeof(struct lcb), "LCB");
11821	if (!lp)
11822		goto fail;
11823	if (ln) {
11824		tp->lmp[ln] = lp;
11825		tp->luntbl[ln] = cpu_to_scr(vtobus(lp));
11826	}
11827	else {
11828		tp->l0p = lp;
11829		tp->b_lun0 = cpu_to_scr(vtobus(lp));
11830	}
11831
11832	/*
11833	**	Initialize the CCB queue headers.
11834	*/
11835	xpt_que_init(&lp->busy_ccbq);
11836	xpt_que_init(&lp->wait_ccbq);
11837
11838	/*
11839	**	Set max CCBs to 1 and use the default task array
11840	**	by default.
11841	*/
11842	lp->maxnxs	= 1;
11843	lp->tasktbl	= &lp->tasktbl_0;
11844	lp->b_tasktbl	= cpu_to_scr(vtobus(lp->tasktbl));
11845	lp->tasktbl[0]	= cpu_to_scr(np->p_notask);
11846	lp->resel_task	= cpu_to_scr(NCB_SCRIPT_PHYS(np, resel_notag));
11847
11848	/*
11849	**	Initialize command queuing control.
11850	*/
11851	lp->busyccbs	= 1;
11852	lp->queuedccbs	= 1;
11853	lp->queuedepth	= 1;
11854fail:
11855	return lp;
11856}
11857
11858
11859/*------------------------------------------------------------------------
11860**	Lun control block setup on INQUIRY data received.
11861**------------------------------------------------------------------------
11862**	We only support WIDE, SYNC for targets and CMDQ for logical units.
11863**	This setup is done on each INQUIRY since we are expecting user
11864**	will play with CHANGE DEFINITION commands. :-)
11865**------------------------------------------------------------------------
11866*/
11867static lcb_p ncr_setup_lcb (ncb_p np, u_char tn, u_char ln, u_char *inq_data)
11868{
11869	tcb_p tp = &np->target[tn];
11870	lcb_p lp = ncr_lp(np, tp, ln);
11871	u_char inq_byte7;
11872	int i;
11873
11874	/*
11875	**	If no lcb, try to allocate it.
11876	*/
11877	if (!lp && !(lp = ncr_alloc_lcb(np, tn, ln)))
11878		goto fail;
11879
11880
11881	/*
11882	**	Evaluate trustable target/unit capabilities.
11883	**	We only believe device version >= SCSI-2 that
11884	**	use appropriate response data format (2).
11885	**	But it seems that some CCS devices also
11886	**	support SYNC and I donnot want to frustrate
11887	**	anybody. ;-)
11888	*/
11889	inq_byte7 = 0;
11890	if	((inq_data[2] & 0x7) >= 2 && (inq_data[3] & 0xf) == 2)
11891		inq_byte7 = inq_data[7];
11892	else if ((inq_data[2] & 0x7) == 1 && (inq_data[3] & 0xf) == 1)
11893		inq_byte7 = INQ7_SYNC;
11894
11895	/*
11896	**	Throw away announced LUN capabilities if we are told
11897	**	that there is no real device supported by the logical unit.
11898	*/
11899	if ((inq_data[0] & 0xe0) > 0x20 || (inq_data[0] & 0x1f) == 0x1f)
11900		inq_byte7 &= (INQ7_SYNC | INQ7_WIDE16);
11901
11902	/*
11903	**	If user is wanting SYNC, force this feature.
11904	*/
11905	if (driver_setup.force_sync_nego)
11906		inq_byte7 |= INQ7_SYNC;
11907
11908	/*
11909	**	Prepare negotiation if SIP capabilities have changed.
11910	*/
11911	tp->inq_done = 1;
11912	if ((inq_byte7 ^ tp->inq_byte7) & (INQ7_SYNC | INQ7_WIDE16)) {
11913		tp->inq_byte7 = inq_byte7;
11914		ncr_negotiate(np, tp);
11915	}
11916
11917	/*
11918	**	If unit supports tagged commands, allocate and
11919	**	initialyze the task table if not yet.
11920	*/
11921	if ((inq_byte7 & INQ7_QUEUE) && lp->tasktbl == &lp->tasktbl_0) {
11922		lp->tasktbl = m_calloc_dma(MAX_TASKS*4, "TASKTBL");
11923		if (!lp->tasktbl) {
11924			lp->tasktbl = &lp->tasktbl_0;
11925			goto fail;
11926		}
11927		lp->b_tasktbl = cpu_to_scr(vtobus(lp->tasktbl));
11928		for (i = 0 ; i < MAX_TASKS ; i++)
11929			lp->tasktbl[i] = cpu_to_scr(np->p_notask);
11930
11931		lp->cb_tags = m_calloc(MAX_TAGS, "CB_TAGS");
11932		if (!lp->cb_tags)
11933			goto fail;
11934		for (i = 0 ; i < MAX_TAGS ; i++)
11935			lp->cb_tags[i] = i;
11936
11937		lp->maxnxs = MAX_TAGS;
11938		lp->tags_stime = ktime_get(3*HZ);
11939	}
11940
11941	/*
11942	**	Adjust tagged queueing status if needed.
11943	*/
11944	if ((inq_byte7 ^ lp->inq_byte7) & INQ7_QUEUE) {
11945		lp->inq_byte7 = inq_byte7;
11946		lp->numtags   = lp->maxtags;
11947		ncr_setup_tags (np, tn, ln);
11948	}
11949
11950fail:
11951	return lp;
11952}
11953
11954/*==========================================================
11955**
11956**
11957**	Build Scatter Gather Block
11958**
11959**
11960**==========================================================
11961**
11962**	The transfer area may be scattered among
11963**	several non adjacent physical pages.
11964**
11965**	We may use MAX_SCATTER blocks.
11966**
11967**----------------------------------------------------------
11968*/
11969
11970/*
11971**	We try to reduce the number of interrupts caused
11972**	by unexpected phase changes due to disconnects.
11973**	A typical harddisk may disconnect before ANY block.
11974**	If we wanted to avoid unexpected phase changes at all
11975**	we had to use a break point every 512 bytes.
11976**	Of course the number of scatter/gather blocks is
11977**	limited.
11978**	Under Linux, the scatter/gatter blocks are provided by
11979**	the generic driver. We just have to copy addresses and
11980**	sizes to the data segment array.
11981*/
11982
11983/*
11984**	For 64 bit systems, we use the 8 upper bits of the size field
11985**	to provide bus address bits 32-39 to the SCRIPTS processor.
11986**	This allows the 895A and 896 to address up to 1 TB of memory.
11987**	For 32 bit chips on 64 bit systems, we must be provided with
11988**	memory addresses that fit into the first 32 bit bus address
11989**	range and so, this does not matter and we expect an error from
11990**	the chip if this ever happen.
11991**
11992**	We use a separate function for the case Linux does not provide
11993**	a scatter list in order to allow better code optimization
11994**	for the case we have a scatter list (BTW, for now this just wastes
11995**	about 40 bytes of code for x86, but my guess is that the scatter
11996**	code will get more complex later).
11997*/
11998
11999#define SCATTER_ONE(data, badd, len)					\
12000	(data)->addr = cpu_to_scr(badd);				\
12001	(data)->size = cpu_to_scr((((badd) >> 8) & 0xff000000) + len);
12002
12003#define CROSS_16MB(p, n) (((((u_long) p) + n - 1) ^ ((u_long) p)) & ~0xffffff)
12004
12005static	int ncr_scatter_no_sglist(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd)
12006{
12007	struct scr_tblmove *data = &cp->phys.data[MAX_SCATTER-1];
12008	int segment;
12009
12010	cp->data_len = cmd->request_bufflen;
12011
12012	if (cmd->request_bufflen) {
12013		dma_addr_t baddr = map_scsi_single_data(np, cmd);
12014
12015		SCATTER_ONE(data, baddr, cmd->request_bufflen);
12016		if (CROSS_16MB(baddr, cmd->request_bufflen)) {
12017			cp->host_flags |= HF_PM_TO_C;
12018#ifdef DEBUG_896R1
12019printk("He! we are crossing a 16 MB boundary (0x%lx, 0x%x)\n",
12020	baddr, cmd->request_bufflen);
12021#endif
12022		}
12023		segment = 1;
12024	}
12025	else
12026		segment = 0;
12027
12028	return segment;
12029}
12030
12031/*
12032**	DEL 472 - 53C896 Rev 1 - Part Number 609-0393055 - ITEM 5.
12033**
12034**	We disable data phase mismatch handling from SCRIPTS for data
12035**	transfers that contains scatter/gather entries that cross
12036**	a 16 MB boundary.
12037**	We use a different scatter function for 896 rev. 1 that needs
12038**	such a work-around. Doing so, we do not affect performance for
12039**	other chips.
12040**	This problem should not be triggered for disk IOs under Linux,
12041**	since such IOs are performed using pages and buffers that are
12042**	nicely power-of-two sized and aligned. But, since this may change
12043**	at any time, a work-around was required.
12044*/
12045static int ncr_scatter_896R1(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd)
12046{
12047	int segn;
12048	int use_sg = (int) cmd->use_sg;
12049
12050	cp->data_len = 0;
12051
12052	if (!use_sg)
12053		segn = ncr_scatter_no_sglist(np, cp, cmd);
12054	else if (use_sg > MAX_SCATTER)
12055		segn = -1;
12056	else {
12057		struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
12058		struct scr_tblmove *data;
12059
12060		use_sg = map_scsi_sg_data(np, cmd);
12061		data = &cp->phys.data[MAX_SCATTER - use_sg];
12062
12063		for (segn = 0; segn < use_sg; segn++) {
12064			dma_addr_t baddr = scsi_sg_dma_address(&scatter[segn]);
12065			unsigned int len = scsi_sg_dma_len(&scatter[segn]);
12066
12067			SCATTER_ONE(&data[segn],
12068				    baddr,
12069				    len);
12070			if (CROSS_16MB(baddr, scatter[segn].length)) {
12071				cp->host_flags |= HF_PM_TO_C;
12072#ifdef DEBUG_896R1
12073printk("He! we are crossing a 16 MB boundary (0x%lx, 0x%x)\n",
12074	baddr, scatter[segn].length);
12075#endif
12076			}
12077			cp->data_len += len;
12078		}
12079	}
12080
12081	return segn;
12082}
12083
12084static int ncr_scatter(ncb_p np, ccb_p cp, Scsi_Cmnd *cmd)
12085{
12086	int segment;
12087	int use_sg = (int) cmd->use_sg;
12088
12089	cp->data_len = 0;
12090
12091	if (!use_sg)
12092		segment = ncr_scatter_no_sglist(np, cp, cmd);
12093	else if (use_sg > MAX_SCATTER)
12094		segment = -1;
12095	else {
12096		struct scatterlist *scatter = (struct scatterlist *)cmd->buffer;
12097		struct scr_tblmove *data;
12098
12099		use_sg = map_scsi_sg_data(np, cmd);
12100		data = &cp->phys.data[MAX_SCATTER - use_sg];
12101
12102		for (segment = 0; segment < use_sg; segment++) {
12103			dma_addr_t baddr = scsi_sg_dma_address(&scatter[segment]);
12104			unsigned int len = scsi_sg_dma_len(&scatter[segment]);
12105
12106			SCATTER_ONE(&data[segment],
12107				    baddr,
12108				    len);
12109			cp->data_len += len;
12110		}
12111	}
12112
12113	return segment;
12114}
12115
12116/*==========================================================
12117**
12118**
12119**	Test the pci bus snoop logic :-(
12120**
12121**	Has to be called with interrupts disabled.
12122**
12123**
12124**==========================================================
12125*/
12126
12127#ifndef SCSI_NCR_IOMAPPED
12128static int __init ncr_regtest (struct ncb* np)
12129{
12130	register volatile u_int32 data;
12131	/*
12132	**	ncr registers may NOT be cached.
12133	**	write 0xffffffff to a read only register area,
12134	**	and try to read it back.
12135	*/
12136	data = 0xffffffff;
12137	OUTL_OFF(offsetof(struct ncr_reg, nc_dstat), data);
12138	data = INL_OFF(offsetof(struct ncr_reg, nc_dstat));
12139	if (data == 0xffffffff) {
12140		printk ("CACHE TEST FAILED: reg dstat-sstat2 readback %x.\n",
12141			(unsigned) data);
12142		return (0x10);
12143	};
12144	return (0);
12145}
12146#endif
12147
12148static int __init ncr_snooptest (struct ncb* np)
12149{
12150	u_int32	ncr_rd, ncr_wr, ncr_bk, host_rd, host_wr, pc;
12151	u_char  dstat;
12152	int	i, err=0;
12153#ifndef SCSI_NCR_IOMAPPED
12154	if (np->reg) {
12155            err |= ncr_regtest (np);
12156            if (err) return (err);
12157	}
12158#endif
12159restart_test:
12160	/*
12161	**	Enable Master Parity Checking as we intend
12162	**	to enable it for normal operations.
12163	*/
12164	OUTB (nc_ctest4, (np->rv_ctest4 & MPEE));
12165	/*
12166	**	init
12167	*/
12168	pc  = NCB_SCRIPTH0_PHYS (np, snooptest);
12169	host_wr = 1;
12170	ncr_wr  = 2;
12171	/*
12172	**	Set memory and register.
12173	*/
12174	np->ncr_cache = cpu_to_scr(host_wr);
12175	OUTL (nc_temp, ncr_wr);
12176	/*
12177	**	Start script (exchange values)
12178	*/
12179	OUTL (nc_dsa, np->p_ncb);
12180	OUTL_DSP (pc);
12181	/*
12182	**	Wait 'til done (with timeout)
12183	*/
12184	for (i=0; i<NCR_SNOOP_TIMEOUT; i++)
12185		if (INB(nc_istat) & (INTF|SIP|DIP))
12186			break;
12187	if (i>=NCR_SNOOP_TIMEOUT) {
12188		printk ("CACHE TEST FAILED: timeout.\n");
12189		return (0x20);
12190	};
12191	/*
12192	**	Check for fatal DMA errors.
12193	*/
12194	dstat = INB (nc_dstat);
12195	if ((dstat & MDPE) && (np->rv_ctest4 & MPEE)) {
12196		printk ("%s: PCI DATA PARITY ERROR DETECTED - "
12197			"DISABLING MASTER DATA PARITY CHECKING.\n",
12198			ncr_name(np));
12199		np->rv_ctest4 &= ~MPEE;
12200		goto restart_test;
12201	}
12202	if (dstat & (MDPE|BF|IID)) {
12203		printk ("CACHE TEST FAILED: DMA error (dstat=0x%02x).", dstat);
12204		return (0x80);
12205	}
12206	/*
12207	**	Save termination position.
12208	*/
12209	pc = INL (nc_dsp);
12210	/*
12211	**	Read memory and register.
12212	*/
12213	host_rd = scr_to_cpu(np->ncr_cache);
12214	ncr_rd  = INL (nc_scratcha);
12215	ncr_bk  = INL (nc_temp);
12216	/*
12217	**	Check termination position.
12218	*/
12219	if (pc != NCB_SCRIPTH0_PHYS (np, snoopend)+8) {
12220		printk ("CACHE TEST FAILED: script execution failed.\n");
12221		printk ("start=%08lx, pc=%08lx, end=%08lx\n",
12222			(u_long) NCB_SCRIPTH0_PHYS (np, snooptest), (u_long) pc,
12223			(u_long) NCB_SCRIPTH0_PHYS (np, snoopend) +8);
12224		return (0x40);
12225	};
12226	/*
12227	**	Show results.
12228	*/
12229	if (host_wr != ncr_rd) {
12230		printk ("CACHE TEST FAILED: host wrote %d, ncr read %d.\n",
12231			(int) host_wr, (int) ncr_rd);
12232		err |= 1;
12233	};
12234	if (host_rd != ncr_wr) {
12235		printk ("CACHE TEST FAILED: ncr wrote %d, host read %d.\n",
12236			(int) ncr_wr, (int) host_rd);
12237		err |= 2;
12238	};
12239	if (ncr_bk != ncr_wr) {
12240		printk ("CACHE TEST FAILED: ncr wrote %d, read back %d.\n",
12241			(int) ncr_wr, (int) ncr_bk);
12242		err |= 4;
12243	};
12244	return (err);
12245}
12246
12247/*==========================================================
12248**
12249**	Determine the ncr's clock frequency.
12250**	This is essential for the negotiation
12251**	of the synchronous transfer rate.
12252**
12253**==========================================================
12254**
12255**	Note: we have to return the correct value.
12256**	THERE IS NO SAFE DEFAULT VALUE.
12257**
12258**	Most NCR/SYMBIOS boards are delivered with a 40 Mhz clock.
12259**	53C860 and 53C875 rev. 1 support fast20 transfers but
12260**	do not have a clock doubler and so are provided with a
12261**	80 MHz clock. All other fast20 boards incorporate a doubler
12262**	and so should be delivered with a 40 MHz clock.
12263**	The recent fast40 chips  (895/896/895A) and the
12264**	fast80 chip (C1010) use a 40 Mhz base clock
12265**	and provide a clock quadrupler (160 Mhz). The code below
12266**	tries to deal as cleverly as possible with all this stuff.
12267**
12268**----------------------------------------------------------
12269*/
12270
12271/*
12272 *	Select NCR SCSI clock frequency
12273 */
12274static void ncr_selectclock(ncb_p np, u_char scntl3)
12275{
12276	if (np->multiplier < 2) {
12277		OUTB(nc_scntl3,	scntl3);
12278		return;
12279	}
12280
12281	if (bootverbose >= 2)
12282		printk ("%s: enabling clock multiplier\n", ncr_name(np));
12283
12284	OUTB(nc_stest1, DBLEN);	   /* Enable clock multiplier		  */
12285
12286	if ( (np->device_id != PCI_DEVICE_ID_LSI_53C1010) &&
12287			(np->device_id != PCI_DEVICE_ID_LSI_53C1010_66) &&
12288						(np->multiplier > 2)) {
12289		int i = 20;	 /* Poll bit 5 of stest4 for quadrupler */
12290		while (!(INB(nc_stest4) & LCKFRQ) && --i > 0)
12291			UDELAY (20);
12292		if (!i)
12293		    printk("%s: the chip cannot lock the frequency\n",
12294						 ncr_name(np));
12295
12296	} else			/* Wait 120 micro-seconds for multiplier*/
12297		UDELAY (120);
12298
12299	OUTB(nc_stest3, HSC);		/* Halt the scsi clock		*/
12300	OUTB(nc_scntl3,	scntl3);
12301	OUTB(nc_stest1, (DBLEN|DBLSEL));/* Select clock multiplier	*/
12302	OUTB(nc_stest3, 0x00);		/* Restart scsi clock 		*/
12303}
12304
12305
12306/*
12307 *	calculate NCR SCSI clock frequency (in KHz)
12308 */
12309static unsigned __init ncrgetfreq (ncb_p np, int gen)
12310{
12311	unsigned int ms = 0;
12312	unsigned int f;
12313	int count;
12314
12315	/*
12316	 * Measure GEN timer delay in order
12317	 * to calculate SCSI clock frequency
12318	 *
12319	 * This code will never execute too
12320	 * many loop iterations (if DELAY is
12321	 * reasonably correct). It could get
12322	 * too low a delay (too high a freq.)
12323	 * if the CPU is slow executing the
12324	 * loop for some reason (an NMI, for
12325	 * example). For this reason we will
12326	 * if multiple measurements are to be
12327	 * performed trust the higher delay
12328	 * (lower frequency returned).
12329	 */
12330	OUTW (nc_sien , 0x0);/* mask all scsi interrupts */
12331				/* enable general purpose timer */
12332	(void) INW (nc_sist);	/* clear pending scsi interrupt */
12333	OUTB (nc_dien , 0);	/* mask all dma interrupts */
12334	(void) INW (nc_sist);	/* another one, just to be sure :) */
12335	OUTB (nc_scntl3, 4);	/* set pre-scaler to divide by 3 */
12336	OUTB (nc_stime1, 0);	/* disable general purpose timer */
12337	OUTB (nc_stime1, gen);	/* set to nominal delay of 1<<gen * 125us */
12338				/* Temporary fix for udelay issue with Alpha
12339					platform */
12340	while (!(INW(nc_sist) & GEN) && ms++ < 100000) {
12341		/* count 1ms */
12342		for (count = 0; count < 10; count++)
12343			UDELAY (100);
12344	}
12345	OUTB (nc_stime1, 0);	/* disable general purpose timer */
12346 	/*
12347 	 * set prescaler to divide by whatever 0 means
12348 	 * 0 ought to choose divide by 2, but appears
12349 	 * to set divide by 3.5 mode in my 53c810 ...
12350 	 */
12351 	OUTB (nc_scntl3, 0);
12352
12353  	/*
12354 	 * adjust for prescaler, and convert into KHz
12355	 * scale values derived empirically.
12356  	 */
12357	f = ms ? ((1 << gen) * 4340) / ms : 0;
12358
12359	if (bootverbose >= 2)
12360		printk ("%s: Delay (GEN=%d): %u msec, %u KHz\n",
12361			ncr_name(np), gen, ms, f);
12362
12363	return f;
12364}
12365
12366static unsigned __init ncr_getfreq (ncb_p np)
12367{
12368	u_int f1, f2;
12369	int gen = 11;
12370
12371	(void) ncrgetfreq (np, gen);	/* throw away first result */
12372	f1 = ncrgetfreq (np, gen);
12373	f2 = ncrgetfreq (np, gen);
12374	if (f1 > f2) f1 = f2;		/* trust lower result	*/
12375	return f1;
12376}
12377
12378/*
12379 *	Get/probe NCR SCSI clock frequency
12380 */
12381static void __init ncr_getclock (ncb_p np, int mult)
12382{
12383	unsigned char scntl3 = np->sv_scntl3;
12384	unsigned char stest1 = np->sv_stest1;
12385	unsigned f1;
12386
12387	np->multiplier = 1;
12388	f1 = 40000;
12389
12390	/*
12391	**	True with 875/895/896/895A with clock multiplier selected
12392	*/
12393	if (mult > 1 && (stest1 & (DBLEN+DBLSEL)) == DBLEN+DBLSEL) {
12394		if (bootverbose >= 2)
12395			printk ("%s: clock multiplier found\n", ncr_name(np));
12396		np->multiplier = mult;
12397	}
12398
12399	/*
12400	**	If multiplier not found or scntl3 not 7,5,3,
12401	**	reset chip and get frequency from general purpose timer.
12402	**	Otherwise trust scntl3 BIOS setting.
12403	*/
12404	if (np->multiplier != mult || (scntl3 & 7) < 3 || !(scntl3 & 1)) {
12405		OUTB (nc_stest1, 0);		/* make sure doubler is OFF */
12406		f1 = ncr_getfreq (np);
12407
12408		if (bootverbose)
12409			printk ("%s: NCR clock is %uKHz\n", ncr_name(np), f1);
12410
12411		if	(f1 < 55000)		f1 =  40000;
12412		else				f1 =  80000;
12413
12414		/*
12415		**	Suggest to also check the PCI clock frequency
12416		**	to make sure our frequency calculation algorithm
12417		**	is not too biased.
12418		*/
12419		if (np->features & FE_66MHZ) {
12420			np->pciclock_min = (66000*55+80-1)/80;
12421			np->pciclock_max = (66000*55)/40;
12422		}
12423		else {
12424			np->pciclock_min = (33000*55+80-1)/80;
12425			np->pciclock_max = (33000*55)/40;
12426		}
12427
12428		if (f1 == 40000 && mult > 1) {
12429			if (bootverbose >= 2)
12430				printk ("%s: clock multiplier assumed\n", ncr_name(np));
12431			np->multiplier	= mult;
12432		}
12433	} else {
12434		if	((scntl3 & 7) == 3)	f1 =  40000;
12435		else if	((scntl3 & 7) == 5)	f1 =  80000;
12436		else 				f1 = 160000;
12437
12438		f1 /= np->multiplier;
12439	}
12440
12441	/*
12442	**	Compute controller synchronous parameters.
12443	*/
12444	f1		*= np->multiplier;
12445	np->clock_khz	= f1;
12446}
12447
12448/*
12449 *	Get/probe PCI clock frequency
12450 */
12451static u_int __init ncr_getpciclock (ncb_p np)
12452{
12453	static u_int f;
12454
12455	OUTB (nc_stest1, SCLK);	/* Use the PCI clock as SCSI clock */
12456	f = ncr_getfreq (np);
12457	OUTB (nc_stest1, 0);
12458
12459	return f;
12460}
12461
12462/*===================== LINUX ENTRY POINTS SECTION ==========================*/
12463
12464#ifndef uchar
12465#define uchar unsigned char
12466#endif
12467
12468#ifndef ushort
12469#define ushort unsigned short
12470#endif
12471
12472#ifndef ulong
12473#define ulong unsigned long
12474#endif
12475
12476/* ---------------------------------------------------------------------
12477**
12478**	Driver setup from the boot command line
12479**
12480** ---------------------------------------------------------------------
12481*/
12482
12483#ifdef MODULE
12484#define	ARG_SEP	' '
12485#else
12486#define	ARG_SEP	','
12487#endif
12488
12489#define OPT_TAGS		1
12490#define OPT_MASTER_PARITY	2
12491#define OPT_SCSI_PARITY		3
12492#define OPT_DISCONNECTION	4
12493#define OPT_SPECIAL_FEATURES	5
12494#define OPT_RESERVED_1		6
12495#define OPT_FORCE_SYNC_NEGO	7
12496#define OPT_REVERSE_PROBE	8
12497#define OPT_DEFAULT_SYNC	9
12498#define OPT_VERBOSE		10
12499#define OPT_DEBUG		11
12500#define OPT_BURST_MAX		12
12501#define OPT_LED_PIN		13
12502#define OPT_MAX_WIDE		14
12503#define OPT_SETTLE_DELAY	15
12504#define OPT_DIFF_SUPPORT	16
12505#define OPT_IRQM		17
12506#define OPT_PCI_FIX_UP		18
12507#define OPT_BUS_CHECK		19
12508#define OPT_OPTIMIZE		20
12509#define OPT_RECOVERY		21
12510#define OPT_SAFE_SETUP		22
12511#define OPT_USE_NVRAM		23
12512#define OPT_EXCLUDE		24
12513#define OPT_HOST_ID		25
12514
12515#ifdef SCSI_NCR_IARB_SUPPORT
12516#define OPT_IARB		26
12517#endif
12518
12519static char setup_token[] __initdata =
12520	"tags:"   "mpar:"
12521	"spar:"   "disc:"
12522	"specf:"  "_rsvd1:"
12523	"fsn:"    "revprob:"
12524	"sync:"   "verb:"
12525	"debug:"  "burst:"
12526	"led:"    "wide:"
12527	"settle:" "diff:"
12528	"irqm:"   "pcifix:"
12529	"buschk:" "optim:"
12530	"recovery:"
12531	"safe:"   "nvram:"
12532	"excl:"   "hostid:"
12533#ifdef SCSI_NCR_IARB_SUPPORT
12534	"iarb:"
12535#endif
12536	;	/* DONNOT REMOVE THIS ';' */
12537
12538#ifdef MODULE
12539#define	ARG_SEP	' '
12540#else
12541#define	ARG_SEP	','
12542#endif
12543
12544static int __init get_setup_token(char *p)
12545{
12546	char *cur = setup_token;
12547	char *pc;
12548	int i = 0;
12549
12550	while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
12551		++pc;
12552		++i;
12553		if (!strncmp(p, cur, pc - cur))
12554			return i;
12555		cur = pc;
12556	}
12557	return 0;
12558}
12559
12560
12561int __init sym53c8xx_setup(char *str)
12562{
12563#ifdef SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT
12564	char *cur = str;
12565	char *pc, *pv;
12566	unsigned long val;
12567	int i,  c;
12568	int xi = 0;
12569
12570	while (cur != NULL && (pc = strchr(cur, ':')) != NULL) {
12571		char *pe;
12572
12573		val = 0;
12574		pv = pc;
12575		c = *++pv;
12576
12577		if	(c == 'n')
12578			val = 0;
12579		else if	(c == 'y')
12580			val = 1;
12581		else
12582			val = (int) simple_strtoul(pv, &pe, 0);
12583
12584		switch (get_setup_token(cur)) {
12585		case OPT_TAGS:
12586			driver_setup.default_tags = val;
12587			if (pe && *pe == '/') {
12588				i = 0;
12589				while (*pe && *pe != ARG_SEP &&
12590					i < sizeof(driver_setup.tag_ctrl)-1) {
12591					driver_setup.tag_ctrl[i++] = *pe++;
12592				}
12593				driver_setup.tag_ctrl[i] = '\0';
12594			}
12595			break;
12596		case OPT_MASTER_PARITY:
12597			driver_setup.master_parity = val;
12598			break;
12599		case OPT_SCSI_PARITY:
12600			driver_setup.scsi_parity = val;
12601			break;
12602		case OPT_DISCONNECTION:
12603			driver_setup.disconnection = val;
12604			break;
12605		case OPT_SPECIAL_FEATURES:
12606			driver_setup.special_features = val;
12607			break;
12608		case OPT_FORCE_SYNC_NEGO:
12609			driver_setup.force_sync_nego = val;
12610			break;
12611		case OPT_REVERSE_PROBE:
12612			driver_setup.reverse_probe = val;
12613			break;
12614		case OPT_DEFAULT_SYNC:
12615			driver_setup.default_sync = val;
12616			break;
12617		case OPT_VERBOSE:
12618			driver_setup.verbose = val;
12619			break;
12620		case OPT_DEBUG:
12621			driver_setup.debug = val;
12622			break;
12623		case OPT_BURST_MAX:
12624			driver_setup.burst_max = val;
12625			break;
12626		case OPT_LED_PIN:
12627			driver_setup.led_pin = val;
12628			break;
12629		case OPT_MAX_WIDE:
12630			driver_setup.max_wide = val? 1:0;
12631			break;
12632		case OPT_SETTLE_DELAY:
12633			driver_setup.settle_delay = val;
12634			break;
12635		case OPT_DIFF_SUPPORT:
12636			driver_setup.diff_support = val;
12637			break;
12638		case OPT_IRQM:
12639			driver_setup.irqm = val;
12640			break;
12641		case OPT_PCI_FIX_UP:
12642			driver_setup.pci_fix_up	= val;
12643			break;
12644		case OPT_BUS_CHECK:
12645			driver_setup.bus_check = val;
12646			break;
12647		case OPT_OPTIMIZE:
12648			driver_setup.optimize = val;
12649			break;
12650		case OPT_RECOVERY:
12651			driver_setup.recovery = val;
12652			break;
12653		case OPT_USE_NVRAM:
12654			driver_setup.use_nvram = val;
12655			break;
12656		case OPT_SAFE_SETUP:
12657			memcpy(&driver_setup, &driver_safe_setup,
12658				sizeof(driver_setup));
12659			break;
12660		case OPT_EXCLUDE:
12661			if (xi < SCSI_NCR_MAX_EXCLUDES)
12662				driver_setup.excludes[xi++] = val;
12663			break;
12664		case OPT_HOST_ID:
12665			driver_setup.host_id = val;
12666			break;
12667#ifdef SCSI_NCR_IARB_SUPPORT
12668		case OPT_IARB:
12669			driver_setup.iarb = val;
12670			break;
12671#endif
12672		default:
12673			printk("sym53c8xx_setup: unexpected boot option '%.*s' ignored\n", (int)(pc-cur+1), cur);
12674			break;
12675		}
12676
12677		if ((cur = strchr(cur, ARG_SEP)) != NULL)
12678			++cur;
12679	}
12680#endif /* SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT */
12681	return 1;
12682}
12683
12684#if LINUX_VERSION_CODE >= LinuxVersionCode(2,3,13)
12685#ifndef MODULE
12686__setup("sym53c8xx=", sym53c8xx_setup);
12687#endif
12688#endif
12689
12690static int
12691sym53c8xx_pci_init(Scsi_Host_Template *tpnt, pcidev_t pdev, ncr_device *device);
12692
12693/*
12694**   Linux entry point for SYM53C8XX devices detection routine.
12695**
12696**   Called by the middle-level scsi drivers at initialization time,
12697**   or at module installation.
12698**
12699**   Read the PCI configuration and try to attach each
12700**   detected NCR board.
12701**
12702**   If NVRAM is present, try to attach boards according to
12703**   the used defined boot order.
12704**
12705**   Returns the number of boards successfully attached.
12706*/
12707
12708static void __init ncr_print_driver_setup(void)
12709{
12710#define YesNo(y)	y ? 'y' : 'n'
12711	printk (NAME53C8XX ": setup=disc:%c,specf:%d,tags:%d,sync:%d,"
12712		"burst:%d,wide:%c,diff:%d,revprob:%c,buschk:0x%x\n",
12713		YesNo(driver_setup.disconnection),
12714		driver_setup.special_features,
12715		driver_setup.default_tags,
12716		driver_setup.default_sync,
12717		driver_setup.burst_max,
12718		YesNo(driver_setup.max_wide),
12719		driver_setup.diff_support,
12720		YesNo(driver_setup.reverse_probe),
12721		driver_setup.bus_check);
12722
12723	printk (NAME53C8XX ": setup=mpar:%c,spar:%c,fsn=%c,verb:%d,debug:0x%x,"
12724		"led:%c,settle:%d,irqm:0x%x,nvram:0x%x,pcifix:0x%x\n",
12725		YesNo(driver_setup.master_parity),
12726		YesNo(driver_setup.scsi_parity),
12727		YesNo(driver_setup.force_sync_nego),
12728		driver_setup.verbose,
12729		driver_setup.debug,
12730		YesNo(driver_setup.led_pin),
12731		driver_setup.settle_delay,
12732		driver_setup.irqm,
12733		driver_setup.use_nvram,
12734		driver_setup.pci_fix_up);
12735#undef YesNo
12736}
12737
12738/*===================================================================
12739**   SYM53C8XX devices description table and chip ids list.
12740**===================================================================
12741*/
12742
12743static ncr_chip	ncr_chip_table[] __initdata	= SCSI_NCR_CHIP_TABLE;
12744static ushort	ncr_chip_ids[]   __initdata	= SCSI_NCR_CHIP_IDS;
12745
12746#ifdef	SCSI_NCR_PQS_PDS_SUPPORT
12747/*===================================================================
12748**    Detect all NCR PQS/PDS boards and keep track of their bus nr.
12749**
12750**    The NCR PQS or PDS card is constructed as a DEC bridge
12751**    behind which sit a proprietary NCR memory controller and
12752**    four or two 53c875s as separate devices.  In its usual mode
12753**    of operation, the 875s are slaved to the memory controller
12754**    for all transfers.  We can tell if an 875 is part of a
12755**    PQS/PDS or not since if it is, it will be on the same bus
12756**    as the memory controller.  To operate with the Linux
12757**    driver, the memory controller is disabled and the 875s
12758**    freed to function independently.  The only wrinkle is that
12759**    the preset SCSI ID (which may be zero) must be read in from
12760**    a special configuration space register of the 875
12761**===================================================================
12762*/
12763#define	SCSI_NCR_MAX_PQS_BUS	16
12764static int pqs_bus[SCSI_NCR_MAX_PQS_BUS] __initdata = { 0 };
12765
12766static void __init ncr_detect_pqs_pds(void)
12767{
12768	short index;
12769	pcidev_t dev = PCIDEV_NULL;
12770
12771	for(index=0; index < SCSI_NCR_MAX_PQS_BUS; index++) {
12772		u_char tmp;
12773
12774		dev = pci_find_device(0x101a, 0x0009, dev);
12775		if (dev == PCIDEV_NULL) {
12776			pqs_bus[index] = -1;
12777			break;
12778		}
12779		printk(KERN_INFO NAME53C8XX ": NCR PQS/PDS memory controller detected on bus %d\n", PciBusNumber(dev));
12780		pci_read_config_byte(dev, 0x44, &tmp);
12781		/* bit 1: allow individual 875 configuration */
12782		tmp |= 0x2;
12783		pci_write_config_byte(dev, 0x44, tmp);
12784		pci_read_config_byte(dev, 0x45, &tmp);
12785		/* bit 2: drive individual 875 interrupts to the bus */
12786		tmp |= 0x4;
12787		pci_write_config_byte(dev, 0x45, tmp);
12788
12789		pqs_bus[index] = PciBusNumber(dev);
12790	}
12791}
12792#endif /* SCSI_NCR_PQS_PDS_SUPPORT */
12793
12794/*===================================================================
12795**    Detect all 53c8xx hosts and then attach them.
12796**
12797**    If we are using NVRAM, once all hosts are detected, we need to
12798**    check any NVRAM for boot order in case detect and boot order
12799**    differ and attach them using the order in the NVRAM.
12800**
12801**    If no NVRAM is found or data appears invalid attach boards in
12802**    the order they are detected.
12803**===================================================================
12804*/
12805int __init sym53c8xx_detect(Scsi_Host_Template *tpnt)
12806{
12807	pcidev_t pcidev;
12808	int i, j, chips, hosts, count;
12809	int attach_count = 0;
12810	ncr_device *devtbl, *devp;
12811#ifdef SCSI_NCR_NVRAM_SUPPORT
12812	ncr_nvram  nvram0, nvram, *nvp;
12813#endif
12814
12815	/*
12816	**    PCI is required.
12817	*/
12818	if (!pci_present())
12819		return 0;
12820
12821	/*
12822	**    Initialize driver general stuff.
12823	*/
12824#ifdef SCSI_NCR_PROC_INFO_SUPPORT
12825#if LINUX_VERSION_CODE < LinuxVersionCode(2,3,27)
12826     tpnt->proc_dir  = &proc_scsi_sym53c8xx;
12827#else
12828     tpnt->proc_name = NAME53C8XX;
12829#endif
12830     tpnt->proc_info = sym53c8xx_proc_info;
12831#endif
12832
12833#if	defined(SCSI_NCR_BOOT_COMMAND_LINE_SUPPORT) && defined(MODULE)
12834if (sym53c8xx)
12835	sym53c8xx_setup(sym53c8xx);
12836#endif
12837#ifdef SCSI_NCR_DEBUG_INFO_SUPPORT
12838	ncr_debug = driver_setup.debug;
12839#endif
12840
12841	if (initverbose >= 2)
12842		ncr_print_driver_setup();
12843
12844	/*
12845	**	Allocate the device table since we donnot want to
12846	**	overflow the kernel stack.
12847	**	1 x 4K PAGE is enough for more than 40 devices for i386.
12848	*/
12849	devtbl = m_calloc(PAGE_SIZE, "devtbl");
12850	if (!devtbl)
12851		return 0;
12852
12853	/*
12854	**    Detect all NCR PQS/PDS memory controllers.
12855	*/
12856#ifdef	SCSI_NCR_PQS_PDS_SUPPORT
12857	ncr_detect_pqs_pds();
12858#endif
12859
12860	/*
12861	**    Detect all 53c8xx hosts.
12862	**    Save the first Symbios NVRAM content if any
12863	**    for the boot order.
12864	*/
12865	chips	= sizeof(ncr_chip_ids)	/ sizeof(ncr_chip_ids[0]);
12866	hosts	= PAGE_SIZE		/ sizeof(*devtbl);
12867#ifdef SCSI_NCR_NVRAM_SUPPORT
12868	nvp = (driver_setup.use_nvram & 0x1) ? &nvram0 : 0;
12869#endif
12870	j = 0;
12871	count = 0;
12872	pcidev = PCIDEV_NULL;
12873	while (1) {
12874		char *msg = "";
12875		if (count >= hosts)
12876			break;
12877		if (j >= chips)
12878			break;
12879		i = driver_setup.reverse_probe ? chips - 1 - j : j;
12880		pcidev = pci_find_device(PCI_VENDOR_ID_NCR, ncr_chip_ids[i],
12881					 pcidev);
12882		if (pcidev == PCIDEV_NULL) {
12883			++j;
12884			continue;
12885		}
12886		if (pci_enable_device(pcidev)) /* @!*!$&*!%-*#;! */
12887			continue;
12888		/* Some HW as the HP LH4 may report twice PCI devices */
12889		for (i = 0; i < count ; i++) {
12890			if (devtbl[i].slot.bus	     == PciBusNumber(pcidev) &&
12891			    devtbl[i].slot.device_fn == PciDeviceFn(pcidev))
12892				break;
12893		}
12894		if (i != count)	/* Ignore this device if we already have it */
12895			continue;
12896		devp = &devtbl[count];
12897		devp->host_id = driver_setup.host_id;
12898		devp->attach_done = 0;
12899		if (sym53c8xx_pci_init(tpnt, pcidev, devp)) {
12900			continue;
12901		}
12902		++count;
12903#ifdef SCSI_NCR_NVRAM_SUPPORT
12904		if (nvp) {
12905			ncr_get_nvram(devp, nvp);
12906			switch(nvp->type) {
12907			case SCSI_NCR_SYMBIOS_NVRAM:
12908				/*
12909				 *   Switch to the other nvram buffer, so that
12910				 *   nvram0 will contain the first Symbios
12911				 *   format NVRAM content with boot order.
12912				 */
12913				nvp = &nvram;
12914				msg = "with Symbios NVRAM";
12915				break;
12916			case SCSI_NCR_TEKRAM_NVRAM:
12917				msg = "with Tekram NVRAM";
12918				break;
12919			}
12920		}
12921#endif
12922#ifdef	SCSI_NCR_PQS_PDS_SUPPORT
12923		if (devp->pqs_pds)
12924			msg = "(NCR PQS/PDS)";
12925#endif
12926		printk(KERN_INFO NAME53C8XX ": 53c%s detected %s\n",
12927		       devp->chip.name, msg);
12928	}
12929
12930	/*
12931	**    If we have found a SYMBIOS NVRAM, use first the NVRAM boot
12932	**    sequence as device boot order.
12933	**    check devices in the boot record against devices detected.
12934	**    attach devices if we find a match. boot table records that
12935	**    do not match any detected devices will be ignored.
12936	**    devices that do not match any boot table will not be attached
12937	**    here but will attempt to be attached during the device table
12938	**    rescan.
12939	*/
12940#ifdef SCSI_NCR_NVRAM_SUPPORT
12941	if (!nvp || nvram0.type != SCSI_NCR_SYMBIOS_NVRAM)
12942		goto next;
12943	for (i = 0; i < 4; i++) {
12944		Symbios_host *h = &nvram0.data.Symbios.host[i];
12945		for (j = 0 ; j < count ; j++) {
12946			devp = &devtbl[j];
12947			if (h->device_fn != devp->slot.device_fn ||
12948			    h->bus_nr	 != devp->slot.bus	 ||
12949			    h->device_id != devp->chip.device_id)
12950				continue;
12951			if (devp->attach_done)
12952				continue;
12953			if (h->flags & SYMBIOS_INIT_SCAN_AT_BOOT) {
12954				ncr_get_nvram(devp, nvp);
12955				if (!ncr_attach (tpnt, attach_count, devp))
12956					attach_count++;
12957			}
12958			else if (!(driver_setup.use_nvram & 0x80))
12959				printk(KERN_INFO NAME53C8XX
12960				       ": 53c%s state OFF thus not attached\n",
12961				       devp->chip.name);
12962			else
12963				continue;
12964
12965			devp->attach_done = 1;
12966			break;
12967		}
12968	}
12969next:
12970#endif
12971
12972	/*
12973	**    Rescan device list to make sure all boards attached.
12974	**    Devices without boot records will not be attached yet
12975	**    so try to attach them here.
12976	*/
12977	for (i= 0; i < count; i++) {
12978		devp = &devtbl[i];
12979		if (!devp->attach_done) {
12980#ifdef SCSI_NCR_NVRAM_SUPPORT
12981			ncr_get_nvram(devp, nvp);
12982#endif
12983			if (!ncr_attach (tpnt, attach_count, devp))
12984				attach_count++;
12985		}
12986	}
12987
12988	m_free(devtbl, PAGE_SIZE, "devtbl");
12989
12990	return attach_count;
12991}
12992
12993/*===================================================================
12994**   Read and check the PCI configuration for any detected NCR
12995**   boards and save data for attaching after all boards have
12996**   been detected.
12997**===================================================================
12998*/
12999static int __init
13000sym53c8xx_pci_init(Scsi_Host_Template *tpnt, pcidev_t pdev, ncr_device *device)
13001{
13002	u_short vendor_id, device_id, command, status_reg;
13003	u_char cache_line_size, latency_timer;
13004	u_char suggested_cache_line_size = 0;
13005	u_char pci_fix_up = driver_setup.pci_fix_up;
13006	u_char revision;
13007	u_int irq;
13008	u_long base, base_c, base_2, base_2_c, io_port;
13009	int i;
13010	ncr_chip *chip;
13011
13012	printk(KERN_INFO NAME53C8XX ": at PCI bus %d, device %d, function %d\n",
13013		PciBusNumber(pdev),
13014		(int) (PciDeviceFn(pdev) & 0xf8) >> 3,
13015		(int) (PciDeviceFn(pdev) & 7));
13016
13017	/*
13018	**    Read info from the PCI config space.
13019	**    pci_read_config_xxx() functions are assumed to be used for
13020	**    successfully detected PCI devices.
13021	*/
13022	vendor_id = PciVendorId(pdev);
13023	device_id = PciDeviceId(pdev);
13024	irq	  = PciIrqLine(pdev);
13025
13026	i = pci_get_base_address(pdev, 0, &io_port);
13027	io_port = pci_get_base_cookie(pdev, 0);
13028
13029	base_c = pci_get_base_cookie(pdev, i);
13030	i = pci_get_base_address(pdev, i, &base);
13031
13032	base_2_c = pci_get_base_cookie(pdev, i);
13033	(void) pci_get_base_address(pdev, i, &base_2);
13034
13035	pci_read_config_word(pdev, PCI_COMMAND,		&command);
13036	pci_read_config_byte(pdev, PCI_CLASS_REVISION,	&revision);
13037	pci_read_config_byte(pdev, PCI_CACHE_LINE_SIZE,	&cache_line_size);
13038	pci_read_config_byte(pdev, PCI_LATENCY_TIMER,	&latency_timer);
13039	pci_read_config_word(pdev, PCI_STATUS,		&status_reg);
13040
13041#ifdef SCSI_NCR_PQS_PDS_SUPPORT
13042	/*
13043	**    Match the BUS number for PQS/PDS devices.
13044	**    Read the SCSI ID from a special register mapped
13045	**    into the configuration space of the individual
13046	**    875s.  This register is set up by the PQS bios
13047	*/
13048	for(i = 0; i < SCSI_NCR_MAX_PQS_BUS && pqs_bus[i] != -1; i++) {
13049		u_char tmp;
13050		if (pqs_bus[i] == PciBusNumber(pdev)) {
13051			pci_read_config_byte(pdev, 0x84, &tmp);
13052			device->pqs_pds = 1;
13053			device->host_id = tmp;
13054			break;
13055		}
13056	}
13057#endif /* SCSI_NCR_PQS_PDS_SUPPORT */
13058
13059	/*
13060	**	If user excludes this chip, donnot initialize it.
13061	*/
13062	for (i = 0 ; i < SCSI_NCR_MAX_EXCLUDES ; i++) {
13063		if (driver_setup.excludes[i] ==
13064				(io_port & PCI_BASE_ADDRESS_IO_MASK))
13065			return -1;
13066	}
13067	/*
13068	**    Check if the chip is supported
13069	*/
13070	chip = 0;
13071	for (i = 0; i < sizeof(ncr_chip_table)/sizeof(ncr_chip_table[0]); i++) {
13072		if (device_id != ncr_chip_table[i].device_id)
13073			continue;
13074		if (revision > ncr_chip_table[i].revision_id)
13075			continue;
13076		if (!(ncr_chip_table[i].features & FE_LDSTR))
13077			break;
13078		chip = &device->chip;
13079		memcpy(chip, &ncr_chip_table[i], sizeof(*chip));
13080		chip->revision_id = revision;
13081		break;
13082	}
13083
13084#ifdef SCSI_NCR_DYNAMIC_DMA_MAPPING
13085	/* Configure DMA attributes.  For DAC capable boards, we can encode
13086	** 32+8 bits for SCSI DMA data addresses with the extra bits used
13087	** in the size field.  We use normal 32-bit PCI addresses for
13088	** descriptors.
13089	*/
13090	if (chip && (chip->features & FE_DAC)) {
13091		if (pci_set_dma_mask(pdev, (u64) 0xffffffffff))
13092			chip->features &= ~FE_DAC_IN_USE;
13093		else
13094			chip->features |= FE_DAC_IN_USE;
13095	}
13096
13097	if (chip && !(chip->features & FE_DAC_IN_USE)) {
13098		if (pci_set_dma_mask(pdev, (u64) 0xffffffff)) {
13099			printk(KERN_WARNING NAME53C8XX
13100			       "32 BIT PCI BUS DMA ADDRESSING NOT SUPPORTED\n");
13101			return -1;
13102		}
13103	}
13104#endif
13105
13106	/*
13107	**	Ignore Symbios chips controlled by SISL RAID controller.
13108	**	This controller sets value 0x52414944 at RAM end - 16.
13109	*/
13110#if defined(__i386__) && !defined(SCSI_NCR_PCI_MEM_NOT_SUPPORTED)
13111	if (chip && (base_2_c & PCI_BASE_ADDRESS_MEM_MASK)) {
13112		unsigned int ram_size, ram_val;
13113		u_long ram_ptr;
13114
13115		if (chip->features & FE_RAM8K)
13116			ram_size = 8192;
13117		else
13118			ram_size = 4096;
13119
13120		ram_ptr = remap_pci_mem(base_2_c & PCI_BASE_ADDRESS_MEM_MASK,
13121					ram_size);
13122		if (ram_ptr) {
13123			ram_val = readl_raw(ram_ptr + ram_size - 16);
13124			unmap_pci_mem(ram_ptr, ram_size);
13125			if (ram_val == 0x52414944) {
13126				printk(NAME53C8XX": not initializing, "
13127				       "driven by SISL RAID controller.\n");
13128				return -1;
13129			}
13130		}
13131	}
13132#endif /* i386 and PCI MEMORY accessible */
13133
13134	if (!chip) {
13135		printk(NAME53C8XX ": not initializing, device not supported\n");
13136		return -1;
13137	}
13138
13139#ifdef __powerpc__
13140	/*
13141	**	Fix-up for power/pc.
13142	**	Should not be performed by the driver.
13143	*/
13144	if ((command & (PCI_COMMAND_IO | PCI_COMMAND_MEMORY))
13145		    != (PCI_COMMAND_IO | PCI_COMMAND_MEMORY)) {
13146		printk(NAME53C8XX ": setting%s%s...\n",
13147		(command & PCI_COMMAND_IO)     ? "" : " PCI_COMMAND_IO",
13148		(command & PCI_COMMAND_MEMORY) ? "" : " PCI_COMMAND_MEMORY");
13149		command |= (PCI_COMMAND_IO | PCI_COMMAND_MEMORY);
13150		pci_write_config_word(pdev, PCI_COMMAND, command);
13151	}
13152
13153#if LINUX_VERSION_CODE < LinuxVersionCode(2,2,0)
13154	if ( is_prep ) {
13155		if (io_port >= 0x10000000) {
13156			printk(NAME53C8XX ": reallocating io_port (Wacky IBM)");
13157			io_port = (io_port & 0x00FFFFFF) | 0x01000000;
13158			pci_write_config_dword(pdev,
13159					       PCI_BASE_ADDRESS_0, io_port);
13160		}
13161		if (base >= 0x10000000) {
13162			printk(NAME53C8XX ": reallocating base (Wacky IBM)");
13163			base = (base & 0x00FFFFFF) | 0x01000000;
13164			pci_write_config_dword(pdev,
13165					       PCI_BASE_ADDRESS_1, base);
13166		}
13167		if (base_2 >= 0x10000000) {
13168			printk(NAME53C8XX ": reallocating base2 (Wacky IBM)");
13169			base_2 = (base_2 & 0x00FFFFFF) | 0x01000000;
13170			pci_write_config_dword(pdev,
13171					       PCI_BASE_ADDRESS_2, base_2);
13172		}
13173	}
13174#endif
13175#endif	/* __powerpc__ */
13176
13177#if defined(__i386__) && !defined(MODULE)
13178	if (!cache_line_size) {
13179#if LINUX_VERSION_CODE < LinuxVersionCode(2,1,75)
13180		extern char x86;
13181		switch(x86) {
13182#else
13183		switch(boot_cpu_data.x86) {
13184#endif
13185		case 4:	suggested_cache_line_size = 4; break;
13186		case 6:
13187		case 5:	suggested_cache_line_size = 8; break;
13188		}
13189	}
13190#endif	/* __i386__ */
13191
13192	/*
13193	**    Check availability of IO space, memory space.
13194	**    Enable master capability if not yet.
13195	**
13196	**    We shouldn't have to care about the IO region when
13197	**    we are using MMIO. But calling check_region() from
13198	**    both the ncr53c8xx and the sym53c8xx drivers prevents
13199	**    from attaching devices from the both drivers.
13200	**    If you have a better idea, let me know.
13201	*/
13202/* #ifdef SCSI_NCR_IOMAPPED */
13203	if (!(command & PCI_COMMAND_IO)) {
13204		printk(NAME53C8XX ": I/O base address (0x%lx) disabled.\n",
13205			(long) io_port);
13206		io_port = 0;
13207	}
13208	if (!(command & PCI_COMMAND_MEMORY)) {
13209		printk(NAME53C8XX ": PCI_COMMAND_MEMORY not set.\n");
13210		base	= 0;
13211		base_2	= 0;
13212	}
13213	io_port &= PCI_BASE_ADDRESS_IO_MASK;
13214	base	&= PCI_BASE_ADDRESS_MEM_MASK;
13215	base_2	&= PCI_BASE_ADDRESS_MEM_MASK;
13216
13217/* #ifdef SCSI_NCR_IOMAPPED */
13218	if (io_port && check_region (io_port, 128)) {
13219		printk(NAME53C8XX ": IO region 0x%lx[0..127] is in use\n",
13220			(long) io_port);
13221		io_port = 0;
13222	}
13223	if (!io_port)
13224		return -1;
13225#ifndef SCSI_NCR_IOMAPPED
13226	if (!base) {
13227		printk(NAME53C8XX ": MMIO base address disabled.\n");
13228		return -1;
13229	}
13230#endif
13231
13232	/*
13233	**    Set MASTER capable and PARITY bit, if not yet.
13234	*/
13235	if ((command & (PCI_COMMAND_MASTER | PCI_COMMAND_PARITY))
13236		     != (PCI_COMMAND_MASTER | PCI_COMMAND_PARITY)) {
13237		printk(NAME53C8XX ": setting%s%s...(fix-up)\n",
13238		(command & PCI_COMMAND_MASTER) ? "" : " PCI_COMMAND_MASTER",
13239		(command & PCI_COMMAND_PARITY) ? "" : " PCI_COMMAND_PARITY");
13240		command |= (PCI_COMMAND_MASTER | PCI_COMMAND_PARITY);
13241		pci_write_config_word(pdev, PCI_COMMAND, command);
13242	}
13243
13244	/*
13245	**    Fix some features according to driver setup.
13246	*/
13247	if (!(driver_setup.special_features & 1))
13248		chip->features &= ~FE_SPECIAL_SET;
13249	else {
13250		if (driver_setup.special_features & 2)
13251			chip->features &= ~FE_WRIE;
13252		if (driver_setup.special_features & 4)
13253			chip->features &= ~FE_NOPM;
13254	}
13255
13256	/*
13257	** Work around for errant bit in 895A. The 66Mhz
13258	** capable bit is set erroneously. Clear this bit.
13259	** (Item 1 DEL 533)
13260	**
13261	** Make sure Config space and Features agree.
13262	**
13263	** Recall: writes are not normal to status register -
13264	** write a 1 to clear and a 0 to leave unchanged.
13265	** Can only reset bits.
13266	*/
13267	if (chip->features & FE_66MHZ) {
13268		if (!(status_reg & PCI_STATUS_66MHZ))
13269			chip->features &= ~FE_66MHZ;
13270	}
13271	else {
13272		if (status_reg & PCI_STATUS_66MHZ) {
13273			status_reg = PCI_STATUS_66MHZ;
13274			pci_write_config_word(pdev, PCI_STATUS, status_reg);
13275			pci_read_config_word(pdev, PCI_STATUS, &status_reg);
13276		}
13277	}
13278
13279	/*
13280	**	Some features are required to be enabled in order to
13281	**	work around some chip problems. :) ;)
13282	**	(ITEM 12 of a DEL about the 896 I haven't yet).
13283	**	We must ensure the chip will use WRITE AND INVALIDATE.
13284	**	The revision number limit is for now arbitrary.
13285	*/
13286	if (device_id == PCI_DEVICE_ID_NCR_53C896 && revision <= 0x10) {
13287		chip->features	|= (FE_WRIE | FE_CLSE);
13288		pci_fix_up	|=  3;	/* Force appropriate PCI fix-up */
13289	}
13290
13291#ifdef	SCSI_NCR_PCI_FIX_UP_SUPPORT
13292	/*
13293	**    Try to fix up PCI config according to wished features.
13294	*/
13295	if ((pci_fix_up & 1) && (chip->features & FE_CLSE) &&
13296	    !cache_line_size && suggested_cache_line_size) {
13297		cache_line_size = suggested_cache_line_size;
13298		pci_write_config_byte(pdev,
13299				      PCI_CACHE_LINE_SIZE, cache_line_size);
13300		printk(NAME53C8XX ": PCI_CACHE_LINE_SIZE set to %d (fix-up).\n",
13301			cache_line_size);
13302	}
13303
13304	if ((pci_fix_up & 2) && cache_line_size &&
13305	    (chip->features & FE_WRIE) && !(command & PCI_COMMAND_INVALIDATE)) {
13306		printk(NAME53C8XX": setting PCI_COMMAND_INVALIDATE (fix-up)\n");
13307		command |= PCI_COMMAND_INVALIDATE;
13308		pci_write_config_word(pdev, PCI_COMMAND, command);
13309	}
13310
13311	/*
13312	**    Tune PCI LATENCY TIMER according to burst max length transfer.
13313	**    (latency timer >= burst length + 6, we add 10 to be quite sure)
13314	*/
13315
13316	if (chip->burst_max && (latency_timer == 0 || (pci_fix_up & 4))) {
13317		uchar lt = (1 << chip->burst_max) + 6 + 10;
13318		if (latency_timer < lt) {
13319			printk(NAME53C8XX
13320			       ": changing PCI_LATENCY_TIMER from %d to %d.\n",
13321			       (int) latency_timer, (int) lt);
13322			latency_timer = lt;
13323			pci_write_config_byte(pdev,
13324					      PCI_LATENCY_TIMER, latency_timer);
13325		}
13326	}
13327
13328#endif	/* SCSI_NCR_PCI_FIX_UP_SUPPORT */
13329
13330 	/*
13331	**    Initialise ncr_device structure with items required by ncr_attach.
13332	*/
13333	device->pdev		= pdev;
13334	device->slot.bus	= PciBusNumber(pdev);
13335	device->slot.device_fn	= PciDeviceFn(pdev);
13336	device->slot.base	= base;
13337	device->slot.base_2	= base_2;
13338	device->slot.base_c	= base_c;
13339	device->slot.base_2_c	= base_2_c;
13340	device->slot.io_port	= io_port;
13341	device->slot.irq	= irq;
13342	device->attach_done	= 0;
13343
13344	return 0;
13345}
13346
13347
13348/*===================================================================
13349**    Detect and try to read SYMBIOS and TEKRAM NVRAM.
13350**
13351**    Data can be used to order booting of boards.
13352**
13353**    Data is saved in ncr_device structure if NVRAM found. This
13354**    is then used to find drive boot order for ncr_attach().
13355**
13356**    NVRAM data is passed to Scsi_Host_Template later during
13357**    ncr_attach() for any device set up.
13358*===================================================================
13359*/
13360#ifdef SCSI_NCR_NVRAM_SUPPORT
13361static void __init ncr_get_nvram(ncr_device *devp, ncr_nvram *nvp)
13362{
13363	devp->nvram = nvp;
13364	if (!nvp)
13365		return;
13366	/*
13367	**    Get access to chip IO registers
13368	*/
13369#ifdef SCSI_NCR_IOMAPPED
13370	request_region(devp->slot.io_port, 128, NAME53C8XX);
13371	devp->slot.base_io = devp->slot.io_port;
13372#else
13373	devp->slot.reg =
13374		(struct ncr_reg *) remap_pci_mem(devp->slot.base_c, 128);
13375	if (!devp->slot.reg)
13376		return;
13377#endif
13378
13379	/*
13380	**    Try to read SYMBIOS nvram.
13381	**    Try to read TEKRAM nvram if Symbios nvram not found.
13382	*/
13383	if	(!sym_read_Symbios_nvram(&devp->slot, &nvp->data.Symbios))
13384		nvp->type = SCSI_NCR_SYMBIOS_NVRAM;
13385	else if	(!sym_read_Tekram_nvram(&devp->slot, devp->chip.device_id,
13386					&nvp->data.Tekram))
13387		nvp->type = SCSI_NCR_TEKRAM_NVRAM;
13388	else {
13389		nvp->type = 0;
13390		devp->nvram = 0;
13391	}
13392
13393	/*
13394	** Release access to chip IO registers
13395	*/
13396#ifdef SCSI_NCR_IOMAPPED
13397	release_region(devp->slot.base_io, 128);
13398#else
13399	unmap_pci_mem((u_long) devp->slot.reg, 128ul);
13400#endif
13401
13402}
13403#endif	/* SCSI_NCR_NVRAM_SUPPORT */
13404
13405/*
13406**   Linux select queue depths function
13407*/
13408
13409#define DEF_DEPTH	(driver_setup.default_tags)
13410#define ALL_TARGETS	-2
13411#define NO_TARGET	-1
13412#define ALL_LUNS	-2
13413#define NO_LUN		-1
13414
13415static int device_queue_depth(ncb_p np, int target, int lun)
13416{
13417	int c, h, t, u, v;
13418	char *p = driver_setup.tag_ctrl;
13419	char *ep;
13420
13421	h = -1;
13422	t = NO_TARGET;
13423	u = NO_LUN;
13424	while ((c = *p++) != 0) {
13425		v = simple_strtoul(p, &ep, 0);
13426		switch(c) {
13427		case '/':
13428			++h;
13429			t = ALL_TARGETS;
13430			u = ALL_LUNS;
13431			break;
13432		case 't':
13433			if (t != target)
13434				t = (target == v) ? v : NO_TARGET;
13435			u = ALL_LUNS;
13436			break;
13437		case 'u':
13438			if (u != lun)
13439				u = (lun == v) ? v : NO_LUN;
13440			break;
13441		case 'q':
13442			if (h == np->unit &&
13443				(t == ALL_TARGETS || t == target) &&
13444				(u == ALL_LUNS    || u == lun))
13445				return v;
13446			break;
13447		case '-':
13448			t = ALL_TARGETS;
13449			u = ALL_LUNS;
13450			break;
13451		default:
13452			break;
13453		}
13454		p = ep;
13455	}
13456	return DEF_DEPTH;
13457}
13458
13459static void sym53c8xx_select_queue_depths(struct Scsi_Host *host, struct scsi_device *devlist)
13460{
13461	struct scsi_device *device;
13462
13463	for (device = devlist; device; device = device->next) {
13464		ncb_p np;
13465		tcb_p tp;
13466		lcb_p lp;
13467		int numtags;
13468
13469		if (device->host != host)
13470			continue;
13471
13472		np = ((struct host_data *) host->hostdata)->ncb;
13473		tp = &np->target[device->id];
13474		lp = ncr_lp(np, tp, device->lun);
13475
13476		/*
13477		**	Select queue depth from driver setup.
13478		**	Donnot use more than configured by user.
13479		**	Use at least 2.
13480		**	Donnot use more than our maximum.
13481		*/
13482		numtags = device_queue_depth(np, device->id, device->lun);
13483		if (numtags > tp->usrtags)
13484			numtags = tp->usrtags;
13485		if (!device->tagged_supported)
13486			numtags = 1;
13487		device->queue_depth = numtags;
13488		if (device->queue_depth < 2)
13489			device->queue_depth = 2;
13490		if (device->queue_depth > MAX_TAGS)
13491			device->queue_depth = MAX_TAGS;
13492
13493		/*
13494		**	Since the queue depth is not tunable under Linux,
13495		**	we need to know this value in order not to
13496		**	announce stupid things to user.
13497		*/
13498		if (lp) {
13499			lp->numtags = lp->maxtags = numtags;
13500			lp->scdev_depth = device->queue_depth;
13501		}
13502		ncr_setup_tags (np, device->id, device->lun);
13503
13504#ifdef DEBUG_SYM53C8XX
13505printk("sym53c8xx_select_queue_depth: host=%d, id=%d, lun=%d, depth=%d\n",
13506	np->unit, device->id, device->lun, device->queue_depth);
13507#endif
13508	}
13509}
13510
13511/*
13512**   Linux entry point for info() function
13513*/
13514const char *sym53c8xx_info (struct Scsi_Host *host)
13515{
13516	return SCSI_NCR_DRIVER_NAME;
13517}
13518
13519/*
13520**   Linux entry point of queuecommand() function
13521*/
13522
13523int sym53c8xx_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *))
13524{
13525     ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
13526     unsigned long flags;
13527     int sts;
13528
13529#ifdef DEBUG_SYM53C8XX
13530printk("sym53c8xx_queue_command\n");
13531#endif
13532
13533     cmd->scsi_done     = done;
13534     cmd->host_scribble = NULL;
13535     cmd->SCp.ptr       = NULL;
13536     cmd->SCp.buffer    = NULL;
13537#ifdef SCSI_NCR_DYNAMIC_DMA_MAPPING
13538     __data_mapped(cmd) = 0;
13539     __data_mapping(cmd) = 0;
13540#endif
13541
13542     NCR_LOCK_NCB(np, flags);
13543
13544     if ((sts = ncr_queue_command(np, cmd)) != DID_OK) {
13545	  SetScsiResult(cmd, sts, 0);
13546#ifdef DEBUG_SYM53C8XX
13547printk("sym53c8xx : command not queued - result=%d\n", sts);
13548#endif
13549     }
13550#ifdef DEBUG_SYM53C8XX
13551     else
13552printk("sym53c8xx : command successfully queued\n");
13553#endif
13554
13555     NCR_UNLOCK_NCB(np, flags);
13556
13557     if (sts != DID_OK) {
13558          unmap_scsi_data(np, cmd);
13559          done(cmd);
13560     }
13561
13562     return sts;
13563}
13564
13565/*
13566**   Linux entry point of the interrupt handler.
13567**   Since linux versions > 1.3.70, we trust the kernel for
13568**   passing the internal host descriptor as 'dev_id'.
13569**   Otherwise, we scan the host list and call the interrupt
13570**   routine for each host that uses this IRQ.
13571*/
13572
13573static void sym53c8xx_intr(int irq, void *dev_id, struct pt_regs * regs)
13574{
13575     unsigned long flags;
13576     ncb_p np = (ncb_p) dev_id;
13577     Scsi_Cmnd *done_list;
13578
13579#ifdef DEBUG_SYM53C8XX
13580     printk("sym53c8xx : interrupt received\n");
13581#endif
13582
13583     if (DEBUG_FLAGS & DEBUG_TINY) printk ("[");
13584
13585     NCR_LOCK_NCB(np, flags);
13586     ncr_exception(np);
13587     done_list     = np->done_list;
13588     np->done_list = 0;
13589     NCR_UNLOCK_NCB(np, flags);
13590
13591     if (DEBUG_FLAGS & DEBUG_TINY) printk ("]\n");
13592
13593     if (done_list) {
13594          NCR_LOCK_SCSI_DONE(np, flags);
13595          ncr_flush_done_cmds(done_list);
13596          NCR_UNLOCK_SCSI_DONE(np, flags);
13597     }
13598}
13599
13600/*
13601**   Linux entry point of the timer handler
13602*/
13603
13604static void sym53c8xx_timeout(unsigned long npref)
13605{
13606     ncb_p np = (ncb_p) npref;
13607     unsigned long flags;
13608     Scsi_Cmnd *done_list;
13609
13610     NCR_LOCK_NCB(np, flags);
13611     ncr_timeout((ncb_p) np);
13612     done_list     = np->done_list;
13613     np->done_list = 0;
13614     NCR_UNLOCK_NCB(np, flags);
13615
13616     if (done_list) {
13617          NCR_LOCK_SCSI_DONE(np, flags);
13618          ncr_flush_done_cmds(done_list);
13619          NCR_UNLOCK_SCSI_DONE(np, flags);
13620     }
13621}
13622
13623/*
13624**   Linux entry point of reset() function
13625*/
13626
13627#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
13628int sym53c8xx_reset(Scsi_Cmnd *cmd, unsigned int reset_flags)
13629#else
13630int sym53c8xx_reset(Scsi_Cmnd *cmd)
13631#endif
13632{
13633	ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
13634	int sts;
13635	unsigned long flags;
13636	Scsi_Cmnd *done_list;
13637
13638#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
13639	printk("sym53c8xx_reset: pid=%lu reset_flags=%x serial_number=%ld serial_number_at_timeout=%ld\n",
13640		cmd->pid, reset_flags, cmd->serial_number, cmd->serial_number_at_timeout);
13641#else
13642	printk("sym53c8xx_reset: command pid %lu\n", cmd->pid);
13643#endif
13644
13645	NCR_LOCK_NCB(np, flags);
13646
13647	/*
13648	 * We have to just ignore reset requests in some situations.
13649	 */
13650#if defined SCSI_RESET_NOT_RUNNING
13651	if (cmd->serial_number != cmd->serial_number_at_timeout) {
13652		sts = SCSI_RESET_NOT_RUNNING;
13653		goto out;
13654	}
13655#endif
13656	/*
13657	 * If the mid-level driver told us reset is synchronous, it seems
13658	 * that we must call the done() callback for the involved command,
13659	 * even if this command was not queued to the low-level driver,
13660	 * before returning SCSI_RESET_SUCCESS.
13661	 */
13662
13663#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
13664	sts = ncr_reset_bus(np, cmd,
13665	(reset_flags & (SCSI_RESET_SYNCHRONOUS | SCSI_RESET_ASYNCHRONOUS)) == SCSI_RESET_SYNCHRONOUS);
13666#else
13667	sts = ncr_reset_bus(np, cmd, 0);
13668#endif
13669
13670	/*
13671	 * Since we always reset the controller, when we return success,
13672	 * we add this information to the return code.
13673	 */
13674#if defined SCSI_RESET_HOST_RESET
13675	if (sts == SCSI_RESET_SUCCESS)
13676		sts |= SCSI_RESET_HOST_RESET;
13677#endif
13678
13679out:
13680	done_list     = np->done_list;
13681	np->done_list = 0;
13682	NCR_UNLOCK_NCB(np, flags);
13683
13684	ncr_flush_done_cmds(done_list);
13685
13686	return sts;
13687}
13688
13689/*
13690**   Linux entry point of abort() function
13691*/
13692
13693int sym53c8xx_abort(Scsi_Cmnd *cmd)
13694{
13695	ncb_p np = ((struct host_data *) cmd->host->hostdata)->ncb;
13696	int sts;
13697	unsigned long flags;
13698	Scsi_Cmnd *done_list;
13699
13700#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
13701	printk("sym53c8xx_abort: pid=%lu serial_number=%ld serial_number_at_timeout=%ld\n",
13702		cmd->pid, cmd->serial_number, cmd->serial_number_at_timeout);
13703#else
13704	printk("sym53c8xx_abort: command pid %lu\n", cmd->pid);
13705#endif
13706
13707	NCR_LOCK_NCB(np, flags);
13708
13709#if defined SCSI_RESET_SYNCHRONOUS && defined SCSI_RESET_ASYNCHRONOUS
13710	/*
13711	 * We have to just ignore abort requests in some situations.
13712	 */
13713	if (cmd->serial_number != cmd->serial_number_at_timeout) {
13714		sts = SCSI_ABORT_NOT_RUNNING;
13715		goto out;
13716	}
13717#endif
13718
13719	sts = ncr_abort_command(np, cmd);
13720out:
13721	done_list     = np->done_list;
13722	np->done_list = 0;
13723	NCR_UNLOCK_NCB(np, flags);
13724
13725	ncr_flush_done_cmds(done_list);
13726
13727	return sts;
13728}
13729
13730
13731#ifdef MODULE
13732int sym53c8xx_release(struct Scsi_Host *host)
13733{
13734#ifdef DEBUG_SYM53C8XX
13735printk("sym53c8xx : release\n");
13736#endif
13737     ncr_detach(((struct host_data *) host->hostdata)->ncb);
13738
13739     return 1;
13740}
13741#endif
13742
13743
13744/*
13745**	Scsi command waiting list management.
13746**
13747**	It may happen that we cannot insert a scsi command into the start queue,
13748**	in the following circumstances.
13749** 		Too few preallocated ccb(s),
13750**		maxtags < cmd_per_lun of the Linux host control block,
13751**		etc...
13752**	Such scsi commands are inserted into a waiting list.
13753**	When a scsi command complete, we try to requeue the commands of the
13754**	waiting list.
13755*/
13756
13757#define next_wcmd host_scribble
13758
13759static void insert_into_waiting_list(ncb_p np, Scsi_Cmnd *cmd)
13760{
13761	Scsi_Cmnd *wcmd;
13762
13763#ifdef DEBUG_WAITING_LIST
13764	printk("%s: cmd %lx inserted into waiting list\n", ncr_name(np), (u_long) cmd);
13765#endif
13766	cmd->next_wcmd = 0;
13767	if (!(wcmd = np->waiting_list)) np->waiting_list = cmd;
13768	else {
13769		while ((wcmd->next_wcmd) != 0)
13770			wcmd = (Scsi_Cmnd *) wcmd->next_wcmd;
13771		wcmd->next_wcmd = (char *) cmd;
13772	}
13773}
13774
13775static Scsi_Cmnd *retrieve_from_waiting_list(int to_remove, ncb_p np, Scsi_Cmnd *cmd)
13776{
13777	Scsi_Cmnd **pcmd = &np->waiting_list;
13778
13779	while (*pcmd) {
13780		if (cmd == *pcmd) {
13781			if (to_remove) {
13782				*pcmd = (Scsi_Cmnd *) cmd->next_wcmd;
13783				cmd->next_wcmd = 0;
13784			}
13785#ifdef DEBUG_WAITING_LIST
13786	printk("%s: cmd %lx retrieved from waiting list\n", ncr_name(np), (u_long) cmd);
13787#endif
13788			return cmd;
13789		}
13790		pcmd = (Scsi_Cmnd **) &(*pcmd)->next_wcmd;
13791	}
13792	return 0;
13793}
13794
13795static void process_waiting_list(ncb_p np, int sts)
13796{
13797	Scsi_Cmnd *waiting_list, *wcmd;
13798
13799	waiting_list = np->waiting_list;
13800	np->waiting_list = 0;
13801
13802#ifdef DEBUG_WAITING_LIST
13803	if (waiting_list) printk("%s: waiting_list=%lx processing sts=%d\n", ncr_name(np), (u_long) waiting_list, sts);
13804#endif
13805	while ((wcmd = waiting_list) != 0) {
13806		waiting_list = (Scsi_Cmnd *) wcmd->next_wcmd;
13807		wcmd->next_wcmd = 0;
13808		if (sts == DID_OK) {
13809#ifdef DEBUG_WAITING_LIST
13810	printk("%s: cmd %lx trying to requeue\n", ncr_name(np), (u_long) wcmd);
13811#endif
13812			sts = ncr_queue_command(np, wcmd);
13813		}
13814		if (sts != DID_OK) {
13815#ifdef DEBUG_WAITING_LIST
13816	printk("%s: cmd %lx done forced sts=%d\n", ncr_name(np), (u_long) wcmd, sts);
13817#endif
13818			SetScsiResult(wcmd, sts, 0);
13819			ncr_queue_done_cmd(np, wcmd);
13820		}
13821	}
13822}
13823
13824#undef next_wcmd
13825
13826#ifdef SCSI_NCR_PROC_INFO_SUPPORT
13827
13828/*=========================================================================
13829**	Proc file system stuff
13830**
13831**	A read operation returns adapter information.
13832**	A write operation is a control command.
13833**	The string is parsed in the driver code and the command is passed
13834**	to the ncr_usercmd() function.
13835**=========================================================================
13836*/
13837
13838#ifdef SCSI_NCR_USER_COMMAND_SUPPORT
13839
13840#define is_digit(c)	((c) >= '0' && (c) <= '9')
13841#define digit_to_bin(c)	((c) - '0')
13842#define is_space(c)	((c) == ' ' || (c) == '\t')
13843
13844static int skip_spaces(char *ptr, int len)
13845{
13846	int cnt, c;
13847
13848	for (cnt = len; cnt > 0 && (c = *ptr++) && is_space(c); cnt--);
13849
13850	return (len - cnt);
13851}
13852
13853static int get_int_arg(char *ptr, int len, u_long *pv)
13854{
13855	int	cnt, c;
13856	u_long	v;
13857
13858	for (v = 0, cnt = len; cnt > 0 && (c = *ptr++) && is_digit(c); cnt--) {
13859		v = (v * 10) + digit_to_bin(c);
13860	}
13861
13862	if (pv)
13863		*pv = v;
13864
13865	return (len - cnt);
13866}
13867
13868static int is_keyword(char *ptr, int len, char *verb)
13869{
13870	int verb_len = strlen(verb);
13871
13872	if (len >= strlen(verb) && !memcmp(verb, ptr, verb_len))
13873		return verb_len;
13874	else
13875		return 0;
13876
13877}
13878
13879#define SKIP_SPACES(min_spaces)						\
13880	if ((arg_len = skip_spaces(ptr, len)) < (min_spaces))		\
13881		return -EINVAL;						\
13882	ptr += arg_len; len -= arg_len;
13883
13884#define GET_INT_ARG(v)							\
13885	if (!(arg_len = get_int_arg(ptr, len, &(v))))			\
13886		return -EINVAL;						\
13887	ptr += arg_len; len -= arg_len;
13888
13889
13890/*
13891**	Parse a control command
13892*/
13893
13894static int ncr_user_command(ncb_p np, char *buffer, int length)
13895{
13896	char *ptr	= buffer;
13897	int len		= length;
13898	struct usrcmd	 *uc = &np->user;
13899	int		arg_len;
13900	u_long 		target;
13901
13902	bzero(uc, sizeof(*uc));
13903
13904	if (len > 0 && ptr[len-1] == '\n')
13905		--len;
13906
13907	if	((arg_len = is_keyword(ptr, len, "setsync")) != 0)
13908		uc->cmd = UC_SETSYNC;
13909	else if	((arg_len = is_keyword(ptr, len, "settags")) != 0)
13910		uc->cmd = UC_SETTAGS;
13911	else if	((arg_len = is_keyword(ptr, len, "setorder")) != 0)
13912		uc->cmd = UC_SETORDER;
13913	else if	((arg_len = is_keyword(ptr, len, "setverbose")) != 0)
13914		uc->cmd = UC_SETVERBOSE;
13915	else if	((arg_len = is_keyword(ptr, len, "setwide")) != 0)
13916		uc->cmd = UC_SETWIDE;
13917	else if	((arg_len = is_keyword(ptr, len, "setdebug")) != 0)
13918		uc->cmd = UC_SETDEBUG;
13919	else if	((arg_len = is_keyword(ptr, len, "setflag")) != 0)
13920		uc->cmd = UC_SETFLAG;
13921	else if	((arg_len = is_keyword(ptr, len, "resetdev")) != 0)
13922		uc->cmd = UC_RESETDEV;
13923	else if	((arg_len = is_keyword(ptr, len, "cleardev")) != 0)
13924		uc->cmd = UC_CLEARDEV;
13925	else
13926		arg_len = 0;
13927
13928#ifdef DEBUG_PROC_INFO
13929printk("ncr_user_command: arg_len=%d, cmd=%ld\n", arg_len, uc->cmd);
13930#endif
13931
13932	if (!arg_len)
13933		return -EINVAL;
13934	ptr += arg_len; len -= arg_len;
13935
13936	switch(uc->cmd) {
13937	case UC_SETSYNC:
13938	case UC_SETTAGS:
13939	case UC_SETWIDE:
13940	case UC_SETFLAG:
13941	case UC_RESETDEV:
13942	case UC_CLEARDEV:
13943		SKIP_SPACES(1);
13944		if ((arg_len = is_keyword(ptr, len, "all")) != 0) {
13945			ptr += arg_len; len -= arg_len;
13946			uc->target = ~0;
13947		} else {
13948			GET_INT_ARG(target);
13949			uc->target = (1<<target);
13950#ifdef DEBUG_PROC_INFO
13951printk("ncr_user_command: target=%ld\n", target);
13952#endif
13953		}
13954		break;
13955	}
13956
13957	switch(uc->cmd) {
13958	case UC_SETVERBOSE:
13959	case UC_SETSYNC:
13960	case UC_SETTAGS:
13961	case UC_SETWIDE:
13962		SKIP_SPACES(1);
13963		GET_INT_ARG(uc->data);
13964#ifdef DEBUG_PROC_INFO
13965printk("ncr_user_command: data=%ld\n", uc->data);
13966#endif
13967		break;
13968	case UC_SETORDER:
13969		SKIP_SPACES(1);
13970		if	((arg_len = is_keyword(ptr, len, "simple")))
13971			uc->data = M_SIMPLE_TAG;
13972		else if	((arg_len = is_keyword(ptr, len, "ordered")))
13973			uc->data = M_ORDERED_TAG;
13974		else if	((arg_len = is_keyword(ptr, len, "default")))
13975			uc->data = 0;
13976		else
13977			return -EINVAL;
13978		break;
13979	case UC_SETDEBUG:
13980		while (len > 0) {
13981			SKIP_SPACES(1);
13982			if	((arg_len = is_keyword(ptr, len, "alloc")))
13983				uc->data |= DEBUG_ALLOC;
13984			else if	((arg_len = is_keyword(ptr, len, "phase")))
13985				uc->data |= DEBUG_PHASE;
13986			else if	((arg_len = is_keyword(ptr, len, "queue")))
13987				uc->data |= DEBUG_QUEUE;
13988			else if	((arg_len = is_keyword(ptr, len, "result")))
13989				uc->data |= DEBUG_RESULT;
13990			else if	((arg_len = is_keyword(ptr, len, "pointer")))
13991				uc->data |= DEBUG_POINTER;
13992			else if	((arg_len = is_keyword(ptr, len, "script")))
13993				uc->data |= DEBUG_SCRIPT;
13994			else if	((arg_len = is_keyword(ptr, len, "tiny")))
13995				uc->data |= DEBUG_TINY;
13996			else if	((arg_len = is_keyword(ptr, len, "timing")))
13997				uc->data |= DEBUG_TIMING;
13998			else if	((arg_len = is_keyword(ptr, len, "nego")))
13999				uc->data |= DEBUG_NEGO;
14000			else if	((arg_len = is_keyword(ptr, len, "tags")))
14001				uc->data |= DEBUG_TAGS;
14002			else
14003				return -EINVAL;
14004			ptr += arg_len; len -= arg_len;
14005		}
14006#ifdef DEBUG_PROC_INFO
14007printk("ncr_user_command: data=%ld\n", uc->data);
14008#endif
14009		break;
14010	case UC_SETFLAG:
14011		while (len > 0) {
14012			SKIP_SPACES(1);
14013			if	((arg_len = is_keyword(ptr, len, "trace")))
14014				uc->data |= UF_TRACE;
14015			else if	((arg_len = is_keyword(ptr, len, "no_disc")))
14016				uc->data |= UF_NODISC;
14017			else
14018				return -EINVAL;
14019			ptr += arg_len; len -= arg_len;
14020		}
14021		break;
14022	default:
14023		break;
14024	}
14025
14026	if (len)
14027		return -EINVAL;
14028	else {
14029		unsigned long flags;
14030
14031		NCR_LOCK_NCB(np, flags);
14032		ncr_usercmd (np);
14033		NCR_UNLOCK_NCB(np, flags);
14034	}
14035	return length;
14036}
14037
14038#endif	/* SCSI_NCR_USER_COMMAND_SUPPORT */
14039
14040#ifdef SCSI_NCR_USER_INFO_SUPPORT
14041
14042struct info_str
14043{
14044	char *buffer;
14045	int length;
14046	int offset;
14047	int pos;
14048};
14049
14050static void copy_mem_info(struct info_str *info, char *data, int len)
14051{
14052	if (info->pos + len > info->length)
14053		len = info->length - info->pos;
14054
14055	if (info->pos + len < info->offset) {
14056		info->pos += len;
14057		return;
14058	}
14059	if (info->pos < info->offset) {
14060		data += (info->offset - info->pos);
14061		len  -= (info->offset - info->pos);
14062	}
14063
14064	if (len > 0) {
14065		memcpy(info->buffer + info->pos, data, len);
14066		info->pos += len;
14067	}
14068}
14069
14070static int copy_info(struct info_str *info, char *fmt, ...)
14071{
14072	va_list args;
14073	char buf[81];
14074	int len;
14075
14076	va_start(args, fmt);
14077	len = vsprintf(buf, fmt, args);
14078	va_end(args);
14079
14080	copy_mem_info(info, buf, len);
14081	return len;
14082}
14083
14084/*
14085**	Copy formatted information into the input buffer.
14086*/
14087
14088static int ncr_host_info(ncb_p np, char *ptr, off_t offset, int len)
14089{
14090	struct info_str info;
14091
14092	info.buffer	= ptr;
14093	info.length	= len;
14094	info.offset	= offset;
14095	info.pos	= 0;
14096
14097	copy_info(&info, "General information:\n");
14098	copy_info(&info, "  Chip " NAME53C "%s, device id 0x%x, "
14099			 "revision id 0x%x\n",
14100			 np->chip_name, np->device_id,	np->revision_id);
14101	copy_info(&info, "  On PCI bus %d, device %d, function %d, "
14102#ifdef __sparc__
14103		"IRQ %s\n",
14104#else
14105		"IRQ %d\n",
14106#endif
14107		np->bus, (np->device_fn & 0xf8) >> 3, np->device_fn & 7,
14108#ifdef __sparc__
14109		__irq_itoa(np->irq));
14110#else
14111		(int) np->irq);
14112#endif
14113	copy_info(&info, "  Synchronous period factor %d, "
14114			 "max commands per lun %d\n",
14115			 (int) np->minsync, MAX_TAGS);
14116
14117	if (driver_setup.debug || driver_setup.verbose > 1) {
14118		copy_info(&info, "  Debug flags 0x%x, verbosity level %d\n",
14119			  driver_setup.debug, driver_setup.verbose);
14120	}
14121
14122	return info.pos > info.offset? info.pos - info.offset : 0;
14123}
14124
14125#endif /* SCSI_NCR_USER_INFO_SUPPORT */
14126
14127/*
14128**	Entry point of the scsi proc fs of the driver.
14129**	- func = 0 means read  (returns adapter infos)
14130**	- func = 1 means write (parse user control command)
14131*/
14132
14133static int sym53c8xx_proc_info(char *buffer, char **start, off_t offset,
14134			int length, int hostno, int func)
14135{
14136	struct Scsi_Host *host;
14137	struct host_data *host_data;
14138	ncb_p ncb = 0;
14139	int retv;
14140
14141#ifdef DEBUG_PROC_INFO
14142printk("sym53c8xx_proc_info: hostno=%d, func=%d\n", hostno, func);
14143#endif
14144
14145	for (host = first_host; host; host = host->next) {
14146		if (host->hostt != first_host->hostt)
14147			continue;
14148		if (host->host_no == hostno) {
14149			host_data = (struct host_data *) host->hostdata;
14150			ncb = host_data->ncb;
14151			break;
14152		}
14153	}
14154
14155	if (!ncb)
14156		return -EINVAL;
14157
14158	if (func) {
14159#ifdef	SCSI_NCR_USER_COMMAND_SUPPORT
14160		retv = ncr_user_command(ncb, buffer, length);
14161#else
14162		retv = -EINVAL;
14163#endif
14164	}
14165	else {
14166		if (start)
14167			*start = buffer;
14168#ifdef SCSI_NCR_USER_INFO_SUPPORT
14169		retv = ncr_host_info(ncb, buffer, offset, length);
14170#else
14171		retv = -EINVAL;
14172#endif
14173	}
14174
14175	return retv;
14176}
14177
14178
14179/*=========================================================================
14180**	End of proc file system stuff
14181**=========================================================================
14182*/
14183#endif
14184
14185
14186#ifdef SCSI_NCR_NVRAM_SUPPORT
14187
14188/*
14189 *  24C16 EEPROM reading.
14190 *
14191 *  GPOI0 - data in/data out
14192 *  GPIO1 - clock
14193 *  Symbios NVRAM wiring now also used by Tekram.
14194 */
14195
14196#define SET_BIT 0
14197#define CLR_BIT 1
14198#define SET_CLK 2
14199#define CLR_CLK 3
14200
14201/*
14202 *  Set/clear data/clock bit in GPIO0
14203 */
14204static void __init
14205S24C16_set_bit(ncr_slot *np, u_char write_bit, u_char *gpreg, int bit_mode)
14206{
14207	UDELAY (5);
14208	switch (bit_mode){
14209	case SET_BIT:
14210		*gpreg |= write_bit;
14211		break;
14212	case CLR_BIT:
14213		*gpreg &= 0xfe;
14214		break;
14215	case SET_CLK:
14216		*gpreg |= 0x02;
14217		break;
14218	case CLR_CLK:
14219		*gpreg &= 0xfd;
14220		break;
14221
14222	}
14223	OUTB (nc_gpreg, *gpreg);
14224	UDELAY (5);
14225}
14226
14227/*
14228 *  Send START condition to NVRAM to wake it up.
14229 */
14230static void __init S24C16_start(ncr_slot *np, u_char *gpreg)
14231{
14232	S24C16_set_bit(np, 1, gpreg, SET_BIT);
14233	S24C16_set_bit(np, 0, gpreg, SET_CLK);
14234	S24C16_set_bit(np, 0, gpreg, CLR_BIT);
14235	S24C16_set_bit(np, 0, gpreg, CLR_CLK);
14236}
14237
14238/*
14239 *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZzzzz!!
14240 */
14241static void __init S24C16_stop(ncr_slot *np, u_char *gpreg)
14242{
14243	S24C16_set_bit(np, 0, gpreg, SET_CLK);
14244	S24C16_set_bit(np, 1, gpreg, SET_BIT);
14245}
14246
14247/*
14248 *  Read or write a bit to the NVRAM,
14249 *  read if GPIO0 input else write if GPIO0 output
14250 */
14251static void __init
14252S24C16_do_bit(ncr_slot *np, u_char *read_bit, u_char write_bit, u_char *gpreg)
14253{
14254	S24C16_set_bit(np, write_bit, gpreg, SET_BIT);
14255	S24C16_set_bit(np, 0, gpreg, SET_CLK);
14256	if (read_bit)
14257		*read_bit = INB (nc_gpreg);
14258	S24C16_set_bit(np, 0, gpreg, CLR_CLK);
14259	S24C16_set_bit(np, 0, gpreg, CLR_BIT);
14260}
14261
14262/*
14263 *  Output an ACK to the NVRAM after reading,
14264 *  change GPIO0 to output and when done back to an input
14265 */
14266static void __init
14267S24C16_write_ack(ncr_slot *np, u_char write_bit, u_char *gpreg, u_char *gpcntl)
14268{
14269	OUTB (nc_gpcntl, *gpcntl & 0xfe);
14270	S24C16_do_bit(np, 0, write_bit, gpreg);
14271	OUTB (nc_gpcntl, *gpcntl);
14272}
14273
14274/*
14275 *  Input an ACK from NVRAM after writing,
14276 *  change GPIO0 to input and when done back to an output
14277 */
14278static void __init
14279S24C16_read_ack(ncr_slot *np, u_char *read_bit, u_char *gpreg, u_char *gpcntl)
14280{
14281	OUTB (nc_gpcntl, *gpcntl | 0x01);
14282	S24C16_do_bit(np, read_bit, 1, gpreg);
14283	OUTB (nc_gpcntl, *gpcntl);
14284}
14285
14286/*
14287 *  WRITE a byte to the NVRAM and then get an ACK to see it was accepted OK,
14288 *  GPIO0 must already be set as an output
14289 */
14290static void __init
14291S24C16_write_byte(ncr_slot *np, u_char *ack_data, u_char write_data,
14292		  u_char *gpreg, u_char *gpcntl)
14293{
14294	int x;
14295
14296	for (x = 0; x < 8; x++)
14297		S24C16_do_bit(np, 0, (write_data >> (7 - x)) & 0x01, gpreg);
14298
14299	S24C16_read_ack(np, ack_data, gpreg, gpcntl);
14300}
14301
14302/*
14303 *  READ a byte from the NVRAM and then send an ACK to say we have got it,
14304 *  GPIO0 must already be set as an input
14305 */
14306static void __init
14307S24C16_read_byte(ncr_slot *np, u_char *read_data, u_char ack_data,
14308	         u_char *gpreg, u_char *gpcntl)
14309{
14310	int x;
14311	u_char read_bit;
14312
14313	*read_data = 0;
14314	for (x = 0; x < 8; x++) {
14315		S24C16_do_bit(np, &read_bit, 1, gpreg);
14316		*read_data |= ((read_bit & 0x01) << (7 - x));
14317	}
14318
14319	S24C16_write_ack(np, ack_data, gpreg, gpcntl);
14320}
14321
14322/*
14323 *  Read 'len' bytes starting at 'offset'.
14324 */
14325static int __init
14326sym_read_S24C16_nvram (ncr_slot *np, int offset, u_char *data, int len)
14327{
14328	u_char	gpcntl, gpreg;
14329	u_char	old_gpcntl, old_gpreg;
14330	u_char	ack_data;
14331	int	retv = 1;
14332	int	x;
14333
14334	/* save current state of GPCNTL and GPREG */
14335	old_gpreg	= INB (nc_gpreg);
14336	old_gpcntl	= INB (nc_gpcntl);
14337	gpcntl		= old_gpcntl & 0x1c;
14338
14339	/* set up GPREG & GPCNTL to set GPIO0 and GPIO1 in to known state */
14340	OUTB (nc_gpreg,  old_gpreg);
14341	OUTB (nc_gpcntl, gpcntl);
14342
14343	/* this is to set NVRAM into a known state with GPIO0/1 both low */
14344	gpreg = old_gpreg;
14345	S24C16_set_bit(np, 0, &gpreg, CLR_CLK);
14346	S24C16_set_bit(np, 0, &gpreg, CLR_BIT);
14347
14348	/* now set NVRAM inactive with GPIO0/1 both high */
14349	S24C16_stop(np, &gpreg);
14350
14351	/* activate NVRAM */
14352	S24C16_start(np, &gpreg);
14353
14354	/* write device code and random address MSB */
14355	S24C16_write_byte(np, &ack_data,
14356		0xa0 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
14357	if (ack_data & 0x01)
14358		goto out;
14359
14360	/* write random address LSB */
14361	S24C16_write_byte(np, &ack_data,
14362		offset & 0xff, &gpreg, &gpcntl);
14363	if (ack_data & 0x01)
14364		goto out;
14365
14366	/* regenerate START state to set up for reading */
14367	S24C16_start(np, &gpreg);
14368
14369	/* rewrite device code and address MSB with read bit set (lsb = 0x01) */
14370	S24C16_write_byte(np, &ack_data,
14371		0xa1 | ((offset >> 7) & 0x0e), &gpreg, &gpcntl);
14372	if (ack_data & 0x01)
14373		goto out;
14374
14375	/* now set up GPIO0 for inputting data */
14376	gpcntl |= 0x01;
14377	OUTB (nc_gpcntl, gpcntl);
14378
14379	/* input all requested data - only part of total NVRAM */
14380	for (x = 0; x < len; x++)
14381		S24C16_read_byte(np, &data[x], (x == (len-1)), &gpreg, &gpcntl);
14382
14383	/* finally put NVRAM back in inactive mode */
14384	gpcntl &= 0xfe;
14385	OUTB (nc_gpcntl, gpcntl);
14386	S24C16_stop(np, &gpreg);
14387	retv = 0;
14388out:
14389	/* return GPIO0/1 to original states after having accessed NVRAM */
14390	OUTB (nc_gpcntl, old_gpcntl);
14391	OUTB (nc_gpreg,  old_gpreg);
14392
14393	return retv;
14394}
14395
14396#undef SET_BIT
14397#undef CLR_BIT
14398#undef SET_CLK
14399#undef CLR_CLK
14400
14401/*
14402 *  Try reading Symbios NVRAM.
14403 *  Return 0 if OK.
14404 */
14405static int __init sym_read_Symbios_nvram (ncr_slot *np, Symbios_nvram *nvram)
14406{
14407	static u_char Symbios_trailer[6] = {0xfe, 0xfe, 0, 0, 0, 0};
14408	u_char *data = (u_char *) nvram;
14409	int len  = sizeof(*nvram);
14410	u_short	csum;
14411	int x;
14412
14413	/* probe the 24c16 and read the SYMBIOS 24c16 area */
14414	if (sym_read_S24C16_nvram (np, SYMBIOS_NVRAM_ADDRESS, data, len))
14415		return 1;
14416
14417	/* check valid NVRAM signature, verify byte count and checksum */
14418	if (nvram->type != 0 ||
14419	    memcmp(nvram->trailer, Symbios_trailer, 6) ||
14420	    nvram->byte_count != len - 12)
14421		return 1;
14422
14423	/* verify checksum */
14424	for (x = 6, csum = 0; x < len - 6; x++)
14425		csum += data[x];
14426	if (csum != nvram->checksum)
14427		return 1;
14428
14429	return 0;
14430}
14431
14432/*
14433 *  93C46 EEPROM reading.
14434 *
14435 *  GPOI0 - data in
14436 *  GPIO1 - data out
14437 *  GPIO2 - clock
14438 *  GPIO4 - chip select
14439 *
14440 *  Used by Tekram.
14441 */
14442
14443/*
14444 *  Pulse clock bit in GPIO0
14445 */
14446static void __init T93C46_Clk(ncr_slot *np, u_char *gpreg)
14447{
14448	OUTB (nc_gpreg, *gpreg | 0x04);
14449	UDELAY (2);
14450	OUTB (nc_gpreg, *gpreg);
14451}
14452
14453/*
14454 *  Read bit from NVRAM
14455 */
14456static void __init T93C46_Read_Bit(ncr_slot *np, u_char *read_bit, u_char *gpreg)
14457{
14458	UDELAY (2);
14459	T93C46_Clk(np, gpreg);
14460	*read_bit = INB (nc_gpreg);
14461}
14462
14463/*
14464 *  Write bit to GPIO0
14465 */
14466static void __init T93C46_Write_Bit(ncr_slot *np, u_char write_bit, u_char *gpreg)
14467{
14468	if (write_bit & 0x01)
14469		*gpreg |= 0x02;
14470	else
14471		*gpreg &= 0xfd;
14472
14473	*gpreg |= 0x10;
14474
14475	OUTB (nc_gpreg, *gpreg);
14476	UDELAY (2);
14477
14478	T93C46_Clk(np, gpreg);
14479}
14480
14481/*
14482 *  Send STOP condition to NVRAM - puts NVRAM to sleep... ZZZzzz!!
14483 */
14484static void __init T93C46_Stop(ncr_slot *np, u_char *gpreg)
14485{
14486	*gpreg &= 0xef;
14487	OUTB (nc_gpreg, *gpreg);
14488	UDELAY (2);
14489
14490	T93C46_Clk(np, gpreg);
14491}
14492
14493/*
14494 *  Send read command and address to NVRAM
14495 */
14496static void __init
14497T93C46_Send_Command(ncr_slot *np, u_short write_data,
14498		    u_char *read_bit, u_char *gpreg)
14499{
14500	int x;
14501
14502	/* send 9 bits, start bit (1), command (2), address (6)  */
14503	for (x = 0; x < 9; x++)
14504		T93C46_Write_Bit(np, (u_char) (write_data >> (8 - x)), gpreg);
14505
14506	*read_bit = INB (nc_gpreg);
14507}
14508
14509/*
14510 *  READ 2 bytes from the NVRAM
14511 */
14512static void __init
14513T93C46_Read_Word(ncr_slot *np, u_short *nvram_data, u_char *gpreg)
14514{
14515	int x;
14516	u_char read_bit;
14517
14518	*nvram_data = 0;
14519	for (x = 0; x < 16; x++) {
14520		T93C46_Read_Bit(np, &read_bit, gpreg);
14521
14522		if (read_bit & 0x01)
14523			*nvram_data |=  (0x01 << (15 - x));
14524		else
14525			*nvram_data &= ~(0x01 << (15 - x));
14526	}
14527}
14528
14529/*
14530 *  Read Tekram NvRAM data.
14531 */
14532static int __init
14533T93C46_Read_Data(ncr_slot *np, u_short *data,int len,u_char *gpreg)
14534{
14535	u_char	read_bit;
14536	int	x;
14537
14538	for (x = 0; x < len; x++)  {
14539
14540		/* output read command and address */
14541		T93C46_Send_Command(np, 0x180 | x, &read_bit, gpreg);
14542		if (read_bit & 0x01)
14543			return 1; /* Bad */
14544		T93C46_Read_Word(np, &data[x], gpreg);
14545		T93C46_Stop(np, gpreg);
14546	}
14547
14548	return 0;
14549}
14550
14551/*
14552 *  Try reading 93C46 Tekram NVRAM.
14553 */
14554static int __init
14555sym_read_T93C46_nvram (ncr_slot *np, Tekram_nvram *nvram)
14556{
14557	u_char gpcntl, gpreg;
14558	u_char old_gpcntl, old_gpreg;
14559	int retv = 1;
14560
14561	/* save current state of GPCNTL and GPREG */
14562	old_gpreg	= INB (nc_gpreg);
14563	old_gpcntl	= INB (nc_gpcntl);
14564
14565	/* set up GPREG & GPCNTL to set GPIO0/1/2/4 in to known state, 0 in,
14566	   1/2/4 out */
14567	gpreg = old_gpreg & 0xe9;
14568	OUTB (nc_gpreg, gpreg);
14569	gpcntl = (old_gpcntl & 0xe9) | 0x09;
14570	OUTB (nc_gpcntl, gpcntl);
14571
14572	/* input all of NVRAM, 64 words */
14573	retv = T93C46_Read_Data(np, (u_short *) nvram,
14574				sizeof(*nvram) / sizeof(short), &gpreg);
14575
14576	/* return GPIO0/1/2/4 to original states after having accessed NVRAM */
14577	OUTB (nc_gpcntl, old_gpcntl);
14578	OUTB (nc_gpreg,  old_gpreg);
14579
14580	return retv;
14581}
14582
14583/*
14584 *  Try reading Tekram NVRAM.
14585 *  Return 0 if OK.
14586 */
14587static int __init
14588sym_read_Tekram_nvram (ncr_slot *np, u_short device_id, Tekram_nvram *nvram)
14589{
14590	u_char *data = (u_char *) nvram;
14591	int len = sizeof(*nvram);
14592	u_short	csum;
14593	int x;
14594
14595	switch (device_id) {
14596	case PCI_DEVICE_ID_NCR_53C885:
14597	case PCI_DEVICE_ID_NCR_53C895:
14598	case PCI_DEVICE_ID_NCR_53C896:
14599		x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
14600					  data, len);
14601		break;
14602	case PCI_DEVICE_ID_NCR_53C875:
14603		x = sym_read_S24C16_nvram(np, TEKRAM_24C16_NVRAM_ADDRESS,
14604					  data, len);
14605		if (!x)
14606			break;
14607	default:
14608		x = sym_read_T93C46_nvram(np, nvram);
14609		break;
14610	}
14611	if (x)
14612		return 1;
14613
14614	/* verify checksum */
14615	for (x = 0, csum = 0; x < len - 1; x += 2)
14616		csum += data[x] + (data[x+1] << 8);
14617	if (csum != 0x1234)
14618		return 1;
14619
14620	return 0;
14621}
14622
14623#endif	/* SCSI_NCR_NVRAM_SUPPORT */
14624
14625/*
14626**	Module stuff
14627*/
14628
14629MODULE_LICENSE("GPL");
14630
14631#if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0)
14632static
14633#endif
14634#if LINUX_VERSION_CODE >= LinuxVersionCode(2,4,0) || defined(MODULE)
14635Scsi_Host_Template driver_template = SYM53C8XX;
14636#include "scsi_module.c"
14637#endif
14638