1/*
2 * PERM_OPTIONS are driver options which will be enabled for all NCR boards
3 * in the system at driver initialization time.
4 *
5 * Don't THINK about touching these in PERM_OPTIONS :
6 *   OPTION_IO_MAPPED
7 * 	Memory mapped IO does not work under i86 Linux.
8 *
9 *   OPTION_DEBUG_TEST1
10 *	Test 1 does bus mastering and interrupt tests, which will help weed
11 *	out brain damaged main boards.
12 *
13 * These are development kernel changes.  Code for them included in this
14 * driver release may or may not work.  If you turn them on, you should be
15 * running the latest copy of the development sources from
16 *
17 *	ftp://tsx-11.mit.edu/pub/linux/ALPHA/scsi/53c7,8xx
18 *
19 * and be subscribed to the ncr53c810@colorado.edu mailing list.  To
20 * subscribe, send mail to majordomo@colorado.edu with
21 *
22 * 	subscribe ncr53c810
23 *
24 * in the text.
25 *
26 *
27 *   OPTION_NO_ASYNC
28 *	Don't negotiate for asynchronous transfers on the first command
29 *	when OPTION_ALWAYS_SYNCHRONOUS is set.  Useful for dain bramaged
30 *	devices which do something bad rather than sending a MESSAGE
31 *	REJECT back to us like they should if they can't cope.
32 *
33 *   OPTION_SYNCHRONOUS
34 *	Enable support for synchronous transfers.  Target negotiated
35 *	synchronous transfers will be responded to.  To initiate
36 *	a synchronous transfer request,  call
37 *
38 *	    request_synchronous (hostno, target)
39 *
40 *	from within KGDB.
41 *
42 *   OPTION_ALWAYS_SYNCHRONOUS
43 *	Negotiate for synchronous transfers with every target after
44 *	driver initialization or a SCSI bus reset.  This is a bit dangerous,
45 *	since there are some dain bramaged SCSI devices which will accept
46 *	SDTR messages but keep talking asynchronously.
47 *
48 *   OPTION_DISCONNECT
49 *	Enable support for disconnect/reconnect.  To change the
50 *	default setting on a given host adapter, call
51 *
52 *	    request_disconnect (hostno, allow)
53 *
54 *	where allow is non-zero to allow, 0 to disallow.
55 *
56 *  If you really want to run 10MHz FAST SCSI-II transfers, you should
57 *  know that the NCR driver currently ignores parity information.  Most
58 *  systems do 5MHz SCSI fine.  I've seen a lot that have problems faster
59 *  than 8MHz.  To play it safe, we only request 5MHz transfers.
60 *
61 *  If you'd rather get 10MHz transfers, edit sdtr_message and change
62 *  the fourth byte from 50 to 25.
63 */
64
65#include <linux/config.h>
66
67#ifdef CONFIG_SCSI_NCR53C7xx_sync
68#ifdef CONFIG_SCSI_NCR53C7xx_DISCONNECT
69#define PERM_OPTIONS (OPTION_IO_MAPPED|OPTION_DEBUG_TEST1|OPTION_DISCONNECT|\
70	OPTION_SYNCHRONOUS|OPTION_ALWAYS_SYNCHRONOUS)
71#else
72#define PERM_OPTIONS (OPTION_IO_MAPPED|OPTION_DEBUG_TEST1|\
73	OPTION_SYNCHRONOUS|OPTION_ALWAYS_SYNCHRONOUS)
74#endif
75#else
76#ifdef CONFIG_SCSI_NCR53C7xx_DISCONNECT
77#define PERM_OPTIONS (OPTION_IO_MAPPED|OPTION_DEBUG_TEST1|OPTION_DISCONNECT|\
78	OPTION_SYNCHRONOUS)
79#else
80#define PERM_OPTIONS (OPTION_IO_MAPPED|OPTION_DEBUG_TEST1|OPTION_SYNCHRONOUS)
81#endif
82#endif
83
84/*
85 * Sponsored by
86 *	iX Multiuser Multitasking Magazine
87 *	Hannover, Germany
88 *	hm@ix.de
89 *
90 * Copyright 1993, 1994, 1995 Drew Eckhardt
91 *      Visionary Computing
92 *      (Unix and Linux consulting and custom programming)
93 *      drew@PoohSticks.ORG
94 *	+1 (303) 786-7975
95 *
96 * TolerANT and SCSI SCRIPTS are registered trademarks of NCR Corporation.
97 *
98 * For more information, please consult
99 *
100 * NCR53C810
101 * SCSI I/O Processor
102 * Programmer's Guide
103 *
104 * NCR 53C810
105 * PCI-SCSI I/O Processor
106 * Data Manual
107 *
108 * NCR 53C810/53C820
109 * PCI-SCSI I/O Processor Design In Guide
110 *
111 * For literature on Symbios Logic Inc. formerly NCR, SCSI,
112 * and Communication products please call (800) 334-5454 or
113 * (719) 536-3300.
114 *
115 * PCI BIOS Specification Revision
116 * PCI Local Bus Specification
117 * PCI System Design Guide
118 *
119 * PCI Special Interest Group
120 * M/S HF3-15A
121 * 5200 N.E. Elam Young Parkway
122 * Hillsboro, Oregon 97124-6497
123 * +1 (503) 696-2000
124 * +1 (800) 433-5177
125 */
126
127/*
128 * Design issues :
129 * The cumulative latency needed to propagate a read/write request
130 * through the file system, buffer cache, driver stacks, SCSI host, and
131 * SCSI device is ultimately the limiting factor in throughput once we
132 * have a sufficiently fast host adapter.
133 *
134 * So, to maximize performance we want to keep the ratio of latency to data
135 * transfer time to a minimum by
136 * 1.  Minimizing the total number of commands sent (typical command latency
137 *	including drive and bus mastering host overhead is as high as 4.5ms)
138 *	to transfer a given amount of data.
139 *
140 *      This is accomplished by placing no arbitrary limit on the number
141 *	of scatter/gather buffers supported, since we can transfer 1K
142 *	per scatter/gather buffer without Eric's cluster patches,
143 *	4K with.
144 *
145 * 2.  Minimizing the number of fatal interrupts serviced, since
146 * 	fatal interrupts halt the SCSI I/O processor.  Basically,
147 *	this means offloading the practical maximum amount of processing
148 *	to the SCSI chip.
149 *
150 *	On the NCR53c810/820/720,  this is accomplished by using
151 *		interrupt-on-the-fly signals when commands complete,
152 *		and only handling fatal errors and SDTR / WDTR 	messages
153 *		in the host code.
154 *
155 *	On the NCR53c710, interrupts are generated as on the NCR53c8x0,
156 *		only the lack of an interrupt-on-the-fly facility complicates
157 *		things.   Also, SCSI ID registers and commands are
158 *		bit fielded rather than binary encoded.
159 *
160 * 	On the NCR53c700 and NCR53c700-66, operations that are done via
161 *		indirect, table mode on the more advanced chips must be
162 *	        replaced by calls through a jump table which
163 *		acts as a surrogate for the DSA.  Unfortunately, this
164 * 		will mean that we must service an interrupt for each
165 *		disconnect/reconnect.
166 *
167 * 3.  Eliminating latency by pipelining operations at the different levels.
168 *
169 *	This driver allows a configurable number of commands to be enqueued
170 *	for each target/lun combination (experimentally, I have discovered
171 *	that two seems to work best) and will ultimately allow for
172 *	SCSI-II tagged queuing.
173 *
174 *
175 * Architecture :
176 * This driver is built around a Linux queue of commands waiting to
177 * be executed, and a shared Linux/NCR array of commands to start.  Commands
178 * are transferred to the array  by the run_process_issue_queue() function
179 * which is called whenever a command completes.
180 *
181 * As commands are completed, the interrupt routine is triggered,
182 * looks for commands in the linked list of completed commands with
183 * valid status, removes these commands from a list of running commands,
184 * calls the done routine, and flags their target/luns as not busy.
185 *
186 * Due to limitations in the intelligence of the NCR chips, certain
187 * concessions are made.  In many cases, it is easier to dynamically
188 * generate/fix-up code rather than calculate on the NCR at run time.
189 * So, code is generated or fixed up for
190 *
191 * - Handling data transfers, using a variable number of MOVE instructions
192 *	interspersed with CALL MSG_IN, WHEN MSGIN instructions.
193 *
194 * 	The DATAIN and DATAOUT routines	are separate, so that an incorrect
195 *	direction can be trapped, and space isn't wasted.
196 *
197 *	It may turn out that we're better off using some sort
198 *	of table indirect instruction in a loop with a variable
199 *	sized table on the NCR53c710 and newer chips.
200 *
201 * - Checking for reselection (NCR53c710 and better)
202 *
203 * - Handling the details of SCSI context switches (NCR53c710 and better),
204 *	such as reprogramming appropriate synchronous parameters,
205 *	removing the dsa structure from the NCR's queue of outstanding
206 *	commands, etc.
207 *
208 */
209
210/*
211 * Accommodate differences between stock 1.2.x and 1.3.x asm-i386/types.h
212 * so lusers can drop in 53c7,8xx.* and get something which compiles
213 * without warnings.
214 */
215
216#include <linux/version.h>
217
218#include <linux/module.h>
219
220#include <asm/dma.h>
221#include <asm/io.h>
222#include <asm/system.h>
223#include <linux/delay.h>
224#include <linux/signal.h>
225#include <linux/sched.h>
226#include <linux/errno.h>
227#include <linux/pci.h>
228#include <linux/proc_fs.h>
229#include <linux/string.h>
230#include <linux/slab.h>
231#include <linux/vmalloc.h>
232#include <linux/mm.h>
233#include <linux/ioport.h>
234#include <linux/time.h>
235#include <linux/blk.h>
236#include <linux/init.h>
237#include <linux/spinlock.h>
238
239#include "scsi.h"
240#include "hosts.h"
241#include "53c7,8xx.h"
242#include "constants.h"
243#include "sd.h"
244#include <linux/stat.h>
245#include <linux/stddef.h>
246
247static int check_address (unsigned long addr, int size);
248static void dump_events (struct Scsi_Host *host, int count);
249static Scsi_Cmnd * return_outstanding_commands (struct Scsi_Host *host,
250    int free, int issue);
251static void hard_reset (struct Scsi_Host *host);
252static void ncr_scsi_reset (struct Scsi_Host *host);
253static void print_lots (struct Scsi_Host *host);
254static void set_synchronous (struct Scsi_Host *host, int target, int sxfer,
255    int scntl3, int now_connected);
256static int datapath_residual (struct Scsi_Host *host);
257static const char * sbcl_to_phase (int sbcl);
258static void print_progress (Scsi_Cmnd *cmd);
259static void print_queues (struct Scsi_Host *host);
260static void process_issue_queue (unsigned long flags);
261static int shutdown (struct Scsi_Host *host);
262static void abnormal_finished (struct NCR53c7x0_cmd *cmd, int result);
263static int disable (struct Scsi_Host *host);
264static int NCR53c8xx_run_tests (struct Scsi_Host *host);
265static int NCR53c8xx_script_len;
266static int NCR53c8xx_dsa_len;
267static void NCR53c7x0_intr(int irq, void *dev_id, struct pt_regs * regs);
268static void do_NCR53c7x0_intr(int irq, void *dev_id, struct pt_regs * regs);
269static int ncr_halt (struct Scsi_Host *host);
270static void intr_phase_mismatch (struct Scsi_Host *host, struct NCR53c7x0_cmd
271    *cmd);
272static void intr_dma (struct Scsi_Host *host, struct NCR53c7x0_cmd *cmd);
273static void print_dsa (struct Scsi_Host *host, u32 *dsa,
274    const char *prefix);
275static int print_insn (struct Scsi_Host *host, const u32 *insn,
276    const char *prefix, int kernel);
277
278static void NCR53c8xx_dsa_fixup (struct NCR53c7x0_cmd *cmd);
279static void NCR53c8x0_init_fixup (struct Scsi_Host *host);
280static int NCR53c8x0_dstat_sir_intr (struct Scsi_Host *host, struct
281    NCR53c7x0_cmd *cmd);
282static void NCR53c8x0_soft_reset (struct Scsi_Host *host);
283
284/* INSMOD variables */
285static long long perm_options = PERM_OPTIONS;
286/* 14 = .5s; 15 is max; decreasing divides by two. */
287static int selection_timeout = 14;
288/* Size of event list (per host adapter) */
289static int track_events = 0;
290
291static struct Scsi_Host *first_host = NULL;	/* Head of list of NCR boards */
292static Scsi_Host_Template *the_template = NULL;
293
294/*
295 * KNOWN BUGS :
296 * - There is some sort of conflict when the PPP driver is compiled with
297 * 	support for 16 channels?
298 *
299 * - On systems which predate the 1.3.x initialization order change,
300 *      the NCR driver will cause Cannot get free page messages to appear.
301 *      These are harmless, but I don't know of an easy way to avoid them.
302 *
303 * - With OPTION_DISCONNECT, on two systems under unknown circumstances,
304 *	we get a PHASE MISMATCH with DSA set to zero (suggests that we
305 *	are occurring somewhere in the reselection code) where
306 *	DSP=some value DCMD|DBC=same value.
307 *
308 *	Closer inspection suggests that we may be trying to execute
309 *	some portion of the DSA?
310 * scsi0 : handling residual transfer (+ 0 bytes from DMA FIFO)
311 * scsi0 : handling residual transfer (+ 0 bytes from DMA FIFO)
312 * scsi0 : no current command : unexpected phase MSGIN.
313 *         DSP=0x1c46cc, DCMD|DBC=0x1c46ac, DSA=0x0
314 *         DSPS=0x0, TEMP=0x1c3e70, DMODE=0x80
315 * scsi0 : DSP->
316 * 001c46cc : 0x001c46cc 0x00000000
317 * 001c46d4 : 0x001c5ea0 0x000011f8
318 *
319 *	Changed the print code in the phase_mismatch handler so
320 *	that we call print_lots to try to diagnose this.
321 *
322 */
323
324/*
325 * Possible future direction of architecture for max performance :
326 *
327 * We're using a single start array for the NCR chip.  This is
328 * sub-optimal, because we cannot add a command which would conflict with
329 * an executing command to this start queue, and therefore must insert the
330 * next command for a given I/T/L combination after the first has completed;
331 * incurring our interrupt latency between SCSI commands.
332 *
333 * To allow further pipelining of the NCR and host CPU operation, we want
334 * to set things up so that immediately on termination of a command destined
335 * for a given LUN, we get that LUN busy again.
336 *
337 * To do this, we need to add a 32 bit pointer to which is jumped to
338 * on completion of a command.  If no new command is available, this
339 * would point to the usual DSA issue queue select routine.
340 *
341 * If one were, it would point to a per-NCR53c7x0_cmd select routine
342 * which starts execution immediately, inserting the command at the head
343 * of the start queue if the NCR chip is selected or reselected.
344 *
345 * We would change so that we keep a list of outstanding commands
346 * for each unit, rather than a single running_list.  We'd insert
347 * a new command into the right running list; if the NCR didn't
348 * have something running for that yet, we'd put it in the
349 * start queue as well.  Some magic needs to happen to handle the
350 * race condition between the first command terminating before the
351 * new one is written.
352 *
353 * Potential for profiling :
354 * Call do_gettimeofday(struct timeval *tv) to get 800ns resolution.
355 */
356
357
358/*
359 * TODO :
360 * 1.  To support WIDE transfers, not much needs to happen.  We
361 *	should do CHMOVE instructions instead of MOVEs when
362 *	we have scatter/gather segments of uneven length.  When
363 * 	we do this, we need to handle the case where we disconnect
364 *	between segments.
365 *
366 * 2.  Currently, when Icky things happen we do a FATAL().  Instead,
367 *     we want to do an integrity check on the parts of the NCR hostdata
368 *     structure which were initialized at boot time; FATAL() if that
369 *     fails, and otherwise try to recover.  Keep track of how many
370 *     times this has happened within a single SCSI command; if it
371 *     gets excessive, then FATAL().
372 *
373 * 3.  Parity checking is currently disabled, and a few things should
374 *     happen here now that we support synchronous SCSI transfers :
375 *     1.  On soft-reset, we should set the EPC (Enable Parity Checking)
376 *	   and AAP (Assert SATN/ on parity error) bits in SCNTL0.
377 *
378 *     2.  We should enable the parity interrupt in the SIEN0 register.
379 *
380 *     3.  intr_phase_mismatch() needs to believe that message out is
381 *	   always an "acceptable" phase to have a mismatch in.  If
382 *	   the old phase was MSG_IN, we should send a MESSAGE PARITY
383 *	   error.  If the old phase was something else, we should send
384 *	   a INITIATOR_DETECTED_ERROR message.  Note that this could
385 *	   cause a RESTORE POINTERS message; so we should handle that
386 *	   correctly first.  Instead, we should probably do an
387 *	   initiator_abort.
388 *
389 * 4.  MPEE bit of CTEST4 should be set so we get interrupted if
390 *     we detect an error.
391 *
392 *
393 * 5.  The initial code has been tested on the NCR53c810.  I don't
394 *     have access to NCR53c700, 700-66 (Forex boards), NCR53c710
395 *     (NCR Pentium systems), NCR53c720, NCR53c820, or NCR53c825 boards to
396 *     finish development on those platforms.
397 *
398 *     NCR53c820/825/720 - need to add wide transfer support, including WDTR
399 *     		negotiation, programming of wide transfer capabilities
400 *		on reselection and table indirect selection.
401 *
402 *     NCR53c710 - need to add fatal interrupt or GEN code for
403 *		command completion signaling.   Need to modify all
404 *		SDID, SCID, etc. registers, and table indirect select code
405 *		since these use bit fielded (ie 1<<target) instead of
406 *		binary encoded target ids.  Need to accommodate
407 *		different register mappings, probably scan through
408 *		the SCRIPT code and change the non SFBR register operand
409 *		of all MOVE instructions.
410 *
411 *     NCR53c700/700-66 - need to add code to refix addresses on
412 *		every nexus change, eliminate all table indirect code,
413 *		very messy.
414 *
415 * 6.  The NCR53c7x0 series is very popular on other platforms that
416 *     could be running Linux - ie, some high performance AMIGA SCSI
417 *     boards use it.
418 *
419 *     So, I should include #ifdef'd code so that it is
420 *     compatible with these systems.
421 *
422 *     Specifically, the little Endian assumptions I made in my
423 *     bit fields need to change, and if the NCR doesn't see memory
424 *     the right way, we need to provide options to reverse words
425 *     when the scripts are relocated.
426 *
427 * 7.  Use ioremap() to access memory mapped boards.
428 */
429
430/*
431 * Allow for simultaneous existence of multiple SCSI scripts so we
432 * can have a single driver binary for all of the family.
433 *
434 * - one for NCR53c700 and NCR53c700-66 chips	(not yet supported)
435 * - one for rest (only the NCR53c810, 815, 820, and 825 are currently
436 *	supported)
437 *
438 * So that we only need two SCSI scripts, we need to modify things so
439 * that we fixup register accesses in READ/WRITE instructions, and
440 * we'll also have to accommodate the bit vs. binary encoding of IDs
441 * with the 7xx chips.
442 */
443
444/*
445 * Use pci_chips_ids to translate in both directions between PCI device ID
446 * and chip numbers.
447 */
448
449static struct {
450    unsigned short pci_device_id;
451    int chip;
452/*
453 * The revision field of the PCI_CLASS_REVISION register is compared
454 * against each of these fields if the field is not -1.  If it
455 * is less than min_revision or larger than max_revision, a warning
456 * message is printed.
457 */
458    int max_revision;
459    int min_revision;
460} pci_chip_ids[] = {
461    {PCI_DEVICE_ID_NCR_53C810, 810, 2, 1},
462    {PCI_DEVICE_ID_NCR_53C815, 815, 3, 2},
463    {PCI_DEVICE_ID_NCR_53C820, 820, -1, -1},
464    {PCI_DEVICE_ID_NCR_53C825, 825, -1, -1}
465};
466
467#define NPCI_CHIP_IDS (sizeof (pci_chip_ids) / sizeof(pci_chip_ids[0]))
468
469#define ROUNDUP(adr,type)	\
470  ((void *) (((long) (adr) + sizeof(type) - 1) & ~(sizeof(type) - 1)))
471
472/*
473 * Forced detection and autoprobe code for various hardware.  Currently,
474 * entry points for these are not included in init/main.c because if the
475 * PCI BIOS code isn't working right, you're not going to be able to use
476 * the hardware anyways; this way we force users to solve their
477 * problems rather than forcing detection and blaming us when it
478 * does not work.
479 */
480
481static struct override {
482    int chip;	/* 700, 70066, 710, 720, 810, 820 */
483    int board;	/* Any special board level gunk */
484    unsigned pci:1;
485    union {
486	struct {
487	    int base;	/* Memory address - indicates memory mapped regs */
488	    int io_port;/* I/O port address - indicates I/O mapped regs */
489    	    int irq;	/* IRQ line */
490    	    int dma;	/* DMA channel 		- often none */
491	} normal;
492	struct {
493	    int bus;
494	    int device;
495	    int function;
496	} pci;
497    } data;
498    long long options;
499} overrides [4] = {{0,},};
500static int commandline_current = 0;
501static int no_overrides = 0;
502
503#define OVERRIDE_LIMIT commandline_current
504
505/*
506 * Function: issue_to_cmd
507 *
508 * Purpose: convert jump instruction in issue array to NCR53c7x0_cmd
509 *	structure pointer.
510 *
511 * Inputs; issue - pointer to start of NOP or JUMP instruction
512 *	in issue array.
513 *
514 * Returns: pointer to command on success; 0 if opcode is NOP.
515 */
516
517static inline struct NCR53c7x0_cmd *
518issue_to_cmd (struct Scsi_Host *host, struct NCR53c7x0_hostdata *hostdata,
519    u32 *issue)
520{
521    return (issue[0] != hostdata->NOP_insn) ?
522    /*
523     * If the IF TRUE bit is set, it's a JUMP instruction.  The
524     * operand is a bus pointer to the dsa_begin routine for this DSA.  The
525     * dsa field of the NCR53c7x0_cmd structure starts with the
526     * DSA code template.  By converting to a virtual address,
527     * subtracting the code template size, and offset of the
528     * dsa field, we end up with a pointer to the start of the
529     * structure (alternatively, we could use the
530     * dsa_cmnd field, an anachronism from when we weren't
531     * sure what the relationship between the NCR structures
532     * and host structures were going to be.
533     */
534	(struct NCR53c7x0_cmd *) ((char *) bus_to_virt (le32_to_cpu(issue[1])) -
535	    (hostdata->E_dsa_code_begin - hostdata->E_dsa_code_template) -
536	    offsetof(struct NCR53c7x0_cmd, dsa))
537    /* If the IF TRUE bit is not set, it's a NOP */
538	: NULL;
539}
540
541
542/*
543 * Function : static internal_setup(int board, int chip, char *str, int *ints)
544 *
545 * Purpose : LILO command line initialization of the overrides array,
546 *
547 * Inputs : board - currently, unsupported.  chip - 700, 70066, 710, 720
548 * 	810, 815, 820, 825, although currently only the NCR53c810 is
549 *	supported.
550 *
551 */
552
553static void
554internal_setup(int board, int chip, char *str, int *ints) {
555    unsigned char pci;		/* Specifies a PCI override, with bus, device,
556				   function */
557
558    pci = (str && !strcmp (str, "pci")) ? 1 : 0;
559
560/*
561 * Override syntaxes are as follows :
562 * ncr53c700,ncr53c700-66,ncr53c710,ncr53c720=mem,io,irq,dma
563 * ncr53c810,ncr53c820,ncr53c825=mem,io,irq or pci,bus,device,function
564 */
565
566    if (commandline_current < OVERRIDE_LIMIT) {
567	overrides[commandline_current].pci = pci ? 1 : 0;
568	if (!pci) {
569	    overrides[commandline_current].data.normal.base = ints[1];
570	    overrides[commandline_current].data.normal.io_port = ints[2];
571	    overrides[commandline_current].data.normal.irq = ints[3];
572    	    overrides[commandline_current].data.normal.dma = (ints[0] >= 4) ?
573    	    	ints[4] : DMA_NONE;
574    	    overrides[commandline_current].options = (ints[0] >= 5) ?
575    	    	ints[5] : 0;
576	} else {
577	    overrides[commandline_current].data.pci.bus = ints[1];
578	    overrides[commandline_current].data.pci.device = ints[2];
579	    overrides[commandline_current].data.pci.function = ints[3];
580    	    overrides[commandline_current].options = (ints[0] >= 4) ?
581    	    	ints[4] : 0;
582	}
583	overrides[commandline_current].board = board;
584	overrides[commandline_current].chip = chip;
585	++commandline_current;
586    	++no_overrides;
587    } else {
588	printk ("53c7,7x0.c:internal_setup() : too many overrides\n");
589    }
590}
591
592
593#define setup_wrapper(x) 				\
594void ncr53c##x##_setup (char *str, int *ints) {		\
595    internal_setup (BOARD_GENERIC, x, str, ints);	\
596}
597
598setup_wrapper(700)
599setup_wrapper(70066)
600setup_wrapper(710)
601setup_wrapper(720)
602setup_wrapper(810)
603setup_wrapper(815)
604setup_wrapper(820)
605setup_wrapper(825)
606
607
608/* Template for "preferred" synchronous transfer parameters. */
609
610static const unsigned char sdtr_message[] = {
611#ifdef CONFIG_SCSI_NCR53C7xx_FAST
612    EXTENDED_MESSAGE, 3 /* length */, EXTENDED_SDTR, 25 /* *4ns */, 8 /* off */
613#else
614    EXTENDED_MESSAGE, 3 /* length */, EXTENDED_SDTR, 50 /* *4ns */, 8 /* off */
615#endif
616};
617
618/* Template to request asynchronous transfers */
619
620static const unsigned char async_message[] = {
621    EXTENDED_MESSAGE, 3 /* length */, EXTENDED_SDTR, 0, 0 /* asynchronous */
622};
623
624/* Template for "preferred" WIDE transfer parameters */
625
626static const unsigned char wdtr_message[] = {
627    EXTENDED_MESSAGE, 2 /* length */, EXTENDED_WDTR, 1 /* 2^1 bytes */
628};
629
630/*
631 * Function : struct Scsi_Host *find_host (int host)
632 *
633 * Purpose : KGDB support function which translates a host number
634 * 	to a host structure.
635 *
636 * Inputs : host - number of SCSI host
637 *
638 * Returns : NULL on failure, pointer to host structure on success.
639 */
640
641
642/*
643 * Function : static void NCR53c7x0_driver_init (struct Scsi_Host *host)
644 *
645 * Purpose : Initialize internal structures, as required on startup, or
646 *	after a SCSI bus reset.
647 *
648 * Inputs : host - pointer to this host adapter's structure
649 */
650
651static void
652NCR53c7x0_driver_init (struct Scsi_Host *host) {
653    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
654	host->hostdata;
655    int i, j;
656    u32 *curr;
657    for (i = 0; i < 16; ++i) {
658	hostdata->request_sense[i] = 0;
659    	for (j = 0; j < 8; ++j)
660	    hostdata->busy[i][j] = 0;
661	set_synchronous (host, i, /* sxfer */ 0, hostdata->saved_scntl3, 0);
662    }
663    hostdata->issue_queue = NULL;
664    hostdata->running_list = hostdata->finished_queue =
665	hostdata->curr = NULL;
666    for (i = 0, curr = (u32 *) hostdata->schedule;
667	i < host->can_queue; ++i, curr += 2) {
668	curr[0] = hostdata->NOP_insn;
669	curr[1] = le32_to_cpu(0xdeadbeef);
670    }
671    curr[0] = le32_to_cpu(((DCMD_TYPE_TCI|DCMD_TCI_OP_JUMP) << 24) | DBC_TCI_TRUE);
672    curr[1] = (u32) le32_to_cpu(virt_to_bus (hostdata->script) +
673	hostdata->E_wait_reselect);
674    hostdata->reconnect_dsa_head = 0;
675    hostdata->addr_reconnect_dsa_head = (u32)
676	le32_to_cpu(virt_to_bus((void *) &(hostdata->reconnect_dsa_head)));
677    hostdata->expecting_iid = 0;
678    hostdata->expecting_sto = 0;
679    if (hostdata->options & OPTION_ALWAYS_SYNCHRONOUS)
680	hostdata->initiate_sdtr = le32_to_cpu(0xffff);
681    else
682    	hostdata->initiate_sdtr = 0;
683    hostdata->talked_to = 0;
684    hostdata->idle = 1;
685}
686
687/*
688 * Function : static int ccf_to_clock (int ccf)
689 *
690 * Purpose :  Return the largest SCSI clock allowable for a given
691 *	clock conversion factor, allowing us to do synchronous periods
692 *	when we don't know what the SCSI clock is by taking at least
693 *	as long as the device says we can.
694 *
695 * Inputs : ccf
696 *
697 * Returns : clock on success, -1 on failure.
698 */
699
700static int
701ccf_to_clock (int ccf) {
702    switch (ccf) {
703    case 1: return 25000000; 	/* Divide by 1.0 */
704    case 2: return 37500000;	/* Divide by 1.5 */
705    case 3: return 50000000;  	/* Divide by 2.0 */
706    case 0: 			/* Divide by 3.0 */
707    case 4: return 66000000;
708    default: return -1;
709    }
710}
711
712/*
713 * Function : static int clock_to_ccf (int clock)
714 *
715 * Purpose :  Return the clock conversion factor for a given SCSI clock.
716 *
717 * Inputs : clock - SCSI clock expressed in Hz.
718 *
719 * Returns : ccf on success, -1 on failure.
720 */
721
722static int
723clock_to_ccf (int clock) {
724    if (clock < 16666666)
725	return -1;
726    if (clock < 25000000)
727	return 1; 	/* Divide by 1.0 */
728    else if (clock < 37500000)
729	return 2; 	/* Divide by 1.5 */
730    else if (clock < 50000000)
731	return 3;	/* Divide by 2.0 */
732    else if (clock < 66000000)
733	return 4;	/* Divide by 3.0 */
734    else
735	return -1;
736}
737
738/*
739 * Function : static int NCR53c7x0_init (struct Scsi_Host *host)
740 *
741 * Purpose :  initialize the internal structures for a given SCSI host
742 *
743 * Inputs : host - pointer to this host adapter's structure
744 *
745 * Preconditions : when this function is called, the chip_type
746 * 	field of the hostdata structure MUST have been set.
747 *
748 * Returns : 0 on success, -1 on failure.
749 */
750
751static int
752NCR53c7x0_init (struct Scsi_Host *host) {
753    NCR53c7x0_local_declare();
754    int i, ccf, expected_ccf;
755    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
756	host->hostdata;
757    struct Scsi_Host *search;
758    /*
759     * There are some things which we need to know about in order to provide
760     * a semblance of support.  Print 'em if they aren't what we expect,
761     * otherwise don't add to the noise.
762     *
763     * -1 means we don't know what to expect.
764     */
765    int expected_id = -1;
766    int expected_clock = -1;
767    int uninitialized = 0;
768    int expected_mapping = OPTION_IO_MAPPED;
769
770    NCR53c7x0_local_setup(host);
771
772    switch (hostdata->chip) {
773    case 820:
774    case 825:
775#ifdef notyet
776	host->max_id = 15;
777#endif
778	/* Fall through */
779    case 810:
780    case 815:
781    	hostdata->dstat_sir_intr = NCR53c8x0_dstat_sir_intr;
782    	hostdata->init_save_regs = NULL;
783    	hostdata->dsa_fixup = NCR53c8xx_dsa_fixup;
784    	hostdata->init_fixup = NCR53c8x0_init_fixup;
785    	hostdata->soft_reset = NCR53c8x0_soft_reset;
786	hostdata->run_tests = NCR53c8xx_run_tests;
787/* Is the SCSI clock ever anything else on these chips? */
788	expected_clock = hostdata->scsi_clock = 40000000;
789	expected_id = 7;
790    	break;
791    default:
792	printk ("scsi%d : chip type of %d is not supported yet, detaching.\n",
793	    host->host_no, hostdata->chip);
794	scsi_unregister (host);
795	return -1;
796    }
797
798    /* Assign constants accessed by NCR */
799    hostdata->NCR53c7xx_zero = 0;
800    hostdata->NCR53c7xx_msg_reject = le32_to_cpu(MESSAGE_REJECT);
801    hostdata->NCR53c7xx_msg_abort = le32_to_cpu(ABORT);
802    hostdata->NCR53c7xx_msg_nop = le32_to_cpu(NOP);
803    hostdata->NOP_insn = le32_to_cpu((DCMD_TYPE_TCI|DCMD_TCI_OP_JUMP) << 24);
804
805    if (expected_mapping == -1 ||
806	(hostdata->options & (OPTION_MEMORY_MAPPED)) !=
807	(expected_mapping & OPTION_MEMORY_MAPPED))
808	printk ("scsi%d : using %s mapped access\n", host->host_no,
809	    (hostdata->options & OPTION_MEMORY_MAPPED) ? "memory" :
810	    "io");
811
812    hostdata->dmode = (hostdata->chip == 700 || hostdata->chip == 70066) ?
813	DMODE_REG_00 : DMODE_REG_10;
814    hostdata->istat = ((hostdata->chip / 100) == 8) ?
815    	ISTAT_REG_800 : ISTAT_REG_700;
816
817/* Only the ISTAT register is readable when the NCR is running, so make
818   sure it's halted. */
819    ncr_halt(host);
820
821    host->this_id = NCR53c7x0_read8(SCID_REG) & 15;
822    if (host->this_id == 0)
823	host->this_id = 7;	/* sanitize hostid---0 doesn't make sense */
824    hostdata->this_id_mask = 1 << host->this_id;
825
826/*
827 * Note : we should never encounter a board setup for ID0.  So,
828 * 	if we see ID0, assume that it was uninitialized and set it
829 * 	to the industry standard 7.
830 */
831    if (!host->this_id) {
832	printk("scsi%d : initiator ID was %d, changing to 7\n",
833	    host->host_no, host->this_id);
834	host->this_id = 7;
835	hostdata->this_id_mask = 1 << 7;
836	uninitialized = 1;
837    };
838
839    if (expected_id == -1 || host->this_id != expected_id)
840    	printk("scsi%d : using initiator ID %d\n", host->host_no,
841    	    host->this_id);
842
843    /*
844     * Save important registers to allow a soft reset.
845     */
846
847    if ((hostdata->chip / 100) == 8) {
848    /*
849     * CTEST4 controls burst mode disable.
850     */
851	hostdata->saved_ctest4 = NCR53c7x0_read8(CTEST4_REG_800) &
852    	    CTEST4_800_SAVE;
853    } else {
854    /*
855     * CTEST7 controls cache snooping, burst mode, and support for
856     * external differential drivers.
857     */
858	hostdata->saved_ctest7 = NCR53c7x0_read8(CTEST7_REG) & CTEST7_SAVE;
859    }
860
861    /*
862     * On NCR53c700 series chips, DCNTL controls the SCSI clock divisor,
863     * on 800 series chips, it allows for a totem-pole IRQ driver.
864     */
865
866    hostdata->saved_dcntl = NCR53c7x0_read8(DCNTL_REG);
867
868    /*
869     * DCNTL_800_IRQM controls weather we are using an open drain
870     * driver (reset) or totem pole driver (set).  In all cases,
871     * it's level active.  I suppose this is an issue when we're trying to
872     * wire-or the same PCI INTx line?
873     */
874    if ((hostdata->chip / 100) == 8)
875	hostdata->saved_dcntl &= ~DCNTL_800_IRQM;
876
877    /*
878     * DMODE controls DMA burst length, and on 700 series chips,
879     * 286 mode and bus width
880     */
881    hostdata->saved_dmode = NCR53c7x0_read8(hostdata->dmode);
882
883    /*
884     * Now that burst length and enabled/disabled status is known,
885     * clue the user in on it.
886     */
887
888    if ((hostdata->chip / 100) == 8) {
889	if (hostdata->saved_ctest4 & CTEST4_800_BDIS) {
890	    printk ("scsi%d : burst mode disabled\n", host->host_no);
891	} else {
892	    switch (hostdata->saved_dmode & DMODE_BL_MASK) {
893	    case DMODE_BL_2: i = 2; break;
894	    case DMODE_BL_4: i = 4; break;
895	    case DMODE_BL_8: i = 8; break;
896	    case DMODE_BL_16: i = 16; break;
897            default: i = 0;
898	    }
899	    printk ("scsi%d : burst length %d\n", host->host_no, i);
900	}
901    }
902
903    /*
904     * On NCR53c810 and NCR53c820 chips, SCNTL3 contails the synchronous
905     * and normal clock conversion factors.
906     */
907    if (hostdata->chip / 100 == 8)  {
908	expected_ccf = clock_to_ccf (expected_clock);
909	hostdata->saved_scntl3 = NCR53c7x0_read8(SCNTL3_REG_800);
910	ccf = hostdata->saved_scntl3 & SCNTL3_800_CCF_MASK;
911	if (expected_ccf != -1 && ccf != expected_ccf && !ccf) {
912	    hostdata->saved_scntl3 = (hostdata->saved_scntl3 &
913		~SCNTL3_800_CCF_MASK) | expected_ccf;
914	    if (!uninitialized) {
915		printk ("scsi%d : reset ccf to %d from %d\n",
916		    host->host_no, expected_ccf, ccf);
917		uninitialized = 1;
918	    }
919	}
920    } else
921    	ccf = 0;
922
923    /*
924     * If we don't have a SCSI clock programmed, pick one on the upper
925     * bound of that allowed by NCR so that our transfers err on the
926     * slow side, since transfer period must be >= the agreed
927     * upon period.
928     */
929
930    if ((!hostdata->scsi_clock) && (hostdata->scsi_clock = ccf_to_clock (ccf))
931	== -1) {
932	printk ("scsi%d : clock conversion factor %d unknown.\n"
933		"         synchronous transfers disabled\n",
934		host->host_no, ccf);
935	hostdata->options &= ~OPTION_SYNCHRONOUS;
936	hostdata->scsi_clock = 0;
937    }
938
939    if (expected_clock == -1 || hostdata->scsi_clock != expected_clock)
940    	printk ("scsi%d : using %dMHz SCSI clock\n", host->host_no,
941	    hostdata->scsi_clock / 1000000);
942
943    for (i = 0; i < 16; ++i)
944	hostdata->cmd_allocated[i] = 0;
945
946    if (hostdata->init_save_regs)
947    	hostdata->init_save_regs (host);
948    if (hostdata->init_fixup)
949    	hostdata->init_fixup (host);
950
951    if (!the_template) {
952	the_template = host->hostt;
953	first_host = host;
954    }
955
956    /*
957     * Linux SCSI drivers have always been plagued with initialization
958     * problems - some didn't work with the BIOS disabled since they expected
959     * initialization from it, some didn't work when the networking code
960     * was enabled and registers got scrambled, etc.
961     *
962     * To avoid problems like this, in the future, we will do a soft
963     * reset on the SCSI chip, taking it back to a sane state.
964     */
965
966    hostdata->soft_reset (host);
967
968    hostdata->debug_count_limit = -1;
969    hostdata->intrs = -1;
970    hostdata->resets = -1;
971    memcpy ((void *) hostdata->synchronous_want, (void *) sdtr_message,
972	sizeof (hostdata->synchronous_want));
973
974    NCR53c7x0_driver_init (host);
975
976    /*
977     * Set up an interrupt handler if we aren't already sharing an IRQ
978     * with another board.
979     */
980
981    for (search = first_host; search && !(search->hostt == the_template &&
982	search->irq == host->irq && search != host); search=search->next);
983
984    if (!search) {
985#ifdef __powerpc__
986	if (request_irq(host->irq, do_NCR53c7x0_intr, SA_SHIRQ, "53c7,8xx", NULL))
987#else
988	if (request_irq(host->irq, do_NCR53c7x0_intr, SA_INTERRUPT, "53c7,8xx", NULL))
989#endif
990	  {
991
992
993	    printk("scsi%d : IRQ%d not free, detaching\n"
994	           "         You have either a configuration problem, or a\n"
995                   "         broken BIOS.  You may wish to manually assign\n"
996	           "         an interrupt to the NCR board rather than using\n"
997                   "         an automatic setting.\n",
998		host->host_no, host->irq);
999	    scsi_unregister (host);
1000	    return -1;
1001	}
1002    } else {
1003	printk("scsi%d : using interrupt handler previously installed for scsi%d\n",
1004	    host->host_no, search->host_no);
1005    }
1006
1007
1008    if ((hostdata->run_tests && hostdata->run_tests(host) == -1) ||
1009        (hostdata->options & OPTION_DEBUG_TESTS_ONLY)) {
1010	scsi_unregister (host);
1011    	return -1;
1012    } else {
1013	if (host->io_port)  {
1014	    host->n_io_port = 128;
1015	    request_region (host->io_port, host->n_io_port, "ncr53c7,8xx");
1016	}
1017    }
1018
1019    if (NCR53c7x0_read8 (SBCL_REG) & SBCL_BSY) {
1020	printk ("scsi%d : bus wedge, doing SCSI reset\n", host->host_no);
1021	hard_reset (host);
1022    }
1023    return 0;
1024}
1025
1026/*
1027 * Function : static int normal_init(Scsi_Host_Template *tpnt, int board,
1028 *	int chip, u32 base, int io_port, int irq, int dma, int pcivalid,
1029 *	unsigned char pci_bus, unsigned char pci_device_fn,
1030 *      struct pci_dev *pci_dev, long long options);
1031 *
1032 * Purpose : initializes a NCR53c7,8x0 based on base addresses,
1033 *	IRQ, and DMA channel.
1034 *
1035 *	Useful where a new NCR chip is backwards compatible with
1036 *	a supported chip, but the DEVICE ID has changed so it
1037 *	doesn't show up when the autoprobe does a pcibios_find_device.
1038 *
1039 * Inputs : tpnt - Template for this SCSI adapter, board - board level
1040 *	product, chip - 810, 820, or 825, bus - PCI bus, device_fn -
1041 *	device and function encoding as used by PCI BIOS calls.
1042 *
1043 * Returns : 0 on success, -1 on failure.
1044 *
1045 */
1046
1047static int  __init
1048normal_init (Scsi_Host_Template *tpnt, int board, int chip,
1049    u32 base, int io_port, int irq, int dma, int pci_valid,
1050    unsigned char pci_bus, unsigned char pci_device_fn,
1051    struct pci_dev *pci_dev, long long options)
1052{
1053    struct Scsi_Host *instance;
1054    struct NCR53c7x0_hostdata *hostdata;
1055    char chip_str[80];
1056    int script_len = 0, dsa_len = 0, size = 0, max_cmd_size = 0,
1057	schedule_size = 0, ok = 0;
1058    void *tmp;
1059
1060    options |= perm_options;
1061
1062    switch (chip) {
1063    case 825:
1064    case 820:
1065    case 815:
1066    case 810:
1067	schedule_size = (tpnt->can_queue + 1) * 8 /* JUMP instruction size */;
1068	script_len = NCR53c8xx_script_len;
1069    	dsa_len = NCR53c8xx_dsa_len;
1070    	options |= OPTION_INTFLY;
1071    	sprintf (chip_str, "NCR53c%d", chip);
1072    	break;
1073    default:
1074    	printk("scsi-ncr53c7,8xx : unsupported SCSI chip %d\n", chip);
1075    	return -1;
1076    }
1077
1078    printk("scsi-ncr53c7,8xx : %s at memory 0x%x, io 0x%x, irq %d",
1079    	chip_str, (unsigned) base, io_port, irq);
1080    if (dma == DMA_NONE)
1081    	printk("\n");
1082    else
1083    	printk(", dma %d\n", dma);
1084
1085    if ((chip / 100 == 8) && !pci_valid)
1086	printk ("scsi-ncr53c7,8xx : for better reliability and performance, please use the\n"
1087		"        PCI override instead.\n"
1088		"	 Syntax : ncr53c8{10,15,20,25}=pci,<bus>,<device>,<function>\n"
1089		"                 <bus> and <device> are usually 0.\n");
1090
1091    if (options & OPTION_DEBUG_PROBE_ONLY) {
1092    	printk ("scsi-ncr53c7,8xx : probe only enabled, aborting initialization\n");
1093    	return -1;
1094    }
1095
1096    max_cmd_size = sizeof(struct NCR53c7x0_cmd) + dsa_len +
1097    	/* Size of dynamic part of command structure : */
1098	2 * /* Worst case : we don't know if we need DATA IN or DATA out */
1099		( 2 * /* Current instructions per scatter/gather segment */
1100        	  tpnt->sg_tablesize +
1101                  3 /* Current startup / termination required per phase */
1102		) *
1103	8 /* Each instruction is eight bytes */;
1104
1105    /* Allocate fixed part of hostdata, dynamic part to hold appropriate
1106       SCSI SCRIPT(tm) plus a single, maximum-sized NCR53c7x0_cmd structure.
1107
1108       We need a NCR53c7x0_cmd structure for scan_scsis() when we are
1109       not loaded as a module, and when we're loaded as a module, we
1110       can't use a non-dynamically allocated structure because modules
1111       are vmalloc()'d, which can allow structures to cross page
1112       boundaries and breaks our physical/virtual address assumptions
1113       for DMA.
1114
1115       So, we stick it past the end of our hostdata structure.
1116
1117       ASSUMPTION :
1118       	 Regardless of how many simultaneous SCSI commands we allow,
1119	 the probe code only executes a _single_ instruction at a time,
1120	 so we only need one here, and don't need to allocate NCR53c7x0_cmd
1121	 structures for each target until we are no longer in scan_scsis
1122	 and kmalloc() has become functional (memory_init() happens
1123	 after all device driver initialization).
1124    */
1125
1126    size = sizeof(struct NCR53c7x0_hostdata) + script_len +
1127    /* Note that alignment will be guaranteed, since we put the command
1128       allocated at probe time after the fixed-up SCSI script, which
1129       consists of 32 bit words, aligned on a 32 bit boundary.  But
1130       on a 64bit machine we need 8 byte alignment for hostdata->free, so
1131       we add in another 4 bytes to take care of potential misalignment
1132       */
1133	(sizeof(void *) - sizeof(u32)) + max_cmd_size + schedule_size;
1134
1135    instance = scsi_register (tpnt, size);
1136    if (!instance)
1137	return -1;
1138
1139
1140    hostdata = (struct NCR53c7x0_hostdata *)
1141    	instance->hostdata;
1142    hostdata->size = size;
1143    hostdata->script_count = script_len / sizeof(u32);
1144    hostdata = (struct NCR53c7x0_hostdata *) instance->hostdata;
1145    hostdata->board = board;
1146    hostdata->chip = chip;
1147    if ((hostdata->pci_valid = pci_valid)) {
1148	hostdata->pci_bus = pci_bus;
1149	hostdata->pci_device_fn = pci_device_fn;
1150    }
1151
1152    /*
1153     * Being memory mapped is more desirable, since
1154     *
1155     * - Memory accesses may be faster.
1156     *
1157     * - The destination and source address spaces are the same for
1158     *	 all instructions, meaning we don't have to twiddle dmode or
1159     *	 any other registers.
1160     *
1161     * So, we try for memory mapped, and if we don't get it,
1162     * we go for port mapped, and that failing we tell the user
1163     * it can't work.
1164     */
1165
1166    if (base) {
1167	instance->base = (unsigned long) base;
1168	/* Check for forced I/O mapping */
1169    	if (!(options & OPTION_IO_MAPPED)) {
1170	    options |= OPTION_MEMORY_MAPPED;
1171	    ok = 1;
1172	}
1173    } else {
1174	options &= ~OPTION_MEMORY_MAPPED;
1175    }
1176
1177    if (io_port) {
1178	instance->io_port = io_port;
1179	options |= OPTION_IO_MAPPED;
1180	ok = 1;
1181    } else {
1182	options &= ~OPTION_IO_MAPPED;
1183    }
1184
1185    if (!ok) {
1186	printk ("scsi%d : not initializing, no I/O or memory mapping known \n",
1187	    instance->host_no);
1188	scsi_unregister (instance);
1189	return -1;
1190    }
1191    instance->irq = irq;
1192    instance->dma_channel = dma;
1193    scsi_set_pci_device(instance, pci_dev);
1194
1195    hostdata->options = options;
1196    hostdata->dsa_len = dsa_len;
1197    hostdata->max_cmd_size = max_cmd_size;
1198    hostdata->num_cmds = 1;
1199    /* Initialize single command */
1200    tmp = (hostdata->script + hostdata->script_count);
1201    hostdata->free = ROUNDUP(tmp, void *);
1202    hostdata->free->real = tmp;
1203    hostdata->free->size = max_cmd_size;
1204    hostdata->free->free = NULL;
1205    hostdata->free->next = NULL;
1206    hostdata->extra_allocate = 0;
1207
1208    /* Allocate command start code space */
1209    hostdata->schedule = (chip == 700 || chip == 70066) ?
1210	NULL : (u32 *) ((char *)hostdata->free + max_cmd_size);
1211
1212/*
1213 * For diagnostic purposes, we don't really care how fast things blaze.
1214 * For profiling, we want to access the 800ns resolution system clock,
1215 * using a 'C' call on the host processor.
1216 *
1217 * Therefore, there's no need for the NCR chip to directly manipulate
1218 * this data, and we should put it wherever is most convenient for
1219 * Linux.
1220 */
1221    if (track_events)
1222	hostdata->events = (struct NCR53c7x0_event *) (track_events ?
1223	    vmalloc (sizeof (struct NCR53c7x0_event) * track_events) : NULL);
1224    else
1225	hostdata->events = NULL;
1226
1227    if (hostdata->events) {
1228	memset ((void *) hostdata->events, 0, sizeof(struct NCR53c7x0_event) *
1229	    track_events);
1230	hostdata->event_size = track_events;
1231	hostdata->event_index = 0;
1232    } else
1233	hostdata->event_size = 0;
1234
1235    return NCR53c7x0_init(instance);
1236}
1237
1238
1239/*
1240 * Function : static int ncr_pci_init(Scsi_Host_Template *tpnt, int board,
1241 *	int chip, int bus, int device_fn, long long options)
1242 *
1243 * Purpose : initializes a NCR53c800 family based on the PCI
1244 *	bus, device, and function location of it.  Allows
1245 * 	reprogramming of latency timer and determining addresses
1246 *	and whether bus mastering, etc. are OK.
1247 *
1248 *	Useful where a new NCR chip is backwards compatible with
1249 *	a supported chip, but the DEVICE ID has changed so it
1250 *	doesn't show up when the autoprobe does a pcibios_find_device.
1251 *
1252 * Inputs : tpnt - Template for this SCSI adapter, board - board level
1253 *	product, chip - 810, 820, or 825, bus - PCI bus, device_fn -
1254 *	device and function encoding as used by PCI BIOS calls.
1255 *
1256 * Returns : 0 on success, -1 on failure.
1257 *
1258 */
1259
1260static int  __init
1261ncr_pci_init (Scsi_Host_Template *tpnt, int board, int chip,
1262    unsigned char bus, unsigned char device_fn, long long options){
1263    unsigned short command;
1264    unsigned int base, io_port;
1265    unsigned char revision;
1266    int error, expected_chip;
1267    int expected_id = -1, max_revision = -1, min_revision = -1;
1268    int i, irq;
1269    struct pci_dev *pdev = pci_find_slot(bus, device_fn);
1270
1271    printk("scsi-ncr53c7,8xx : at PCI bus %d, device %d, function %d\n",
1272	bus, (int) (device_fn & 0xf8) >> 3,
1273    	(int) device_fn & 7);
1274
1275    if (!pdev) {
1276	printk("scsi-ncr53c7,8xx : not initializing -- PCI device not found,\n"
1277	       "        try using memory, port, irq override instead.\n");
1278	return -1;
1279    }
1280
1281    if ((error = pci_read_config_word (pdev, PCI_COMMAND, &command)) ||
1282	(error = pci_read_config_byte (pdev, PCI_CLASS_REVISION, &revision))) {
1283	printk ("scsi-ncr53c7,8xx : error %d not initializing due to error reading configuration space\n"
1284		"	 perhaps you specified an incorrect PCI bus, device, or function.\n", error);
1285	return -1;
1286    }
1287    if (pci_enable_device(pdev))
1288	return -1;
1289    io_port = pci_resource_start(pdev, 0);
1290    base = pci_resource_start(pdev, 1);
1291    irq = pdev->irq;
1292
1293    /* If any one ever clones the NCR chips, this will have to change */
1294
1295    if (pdev->vendor != PCI_VENDOR_ID_NCR) {
1296	printk ("scsi-ncr53c7,8xx : not initializing, 0x%04x is not NCR vendor ID\n",
1297	    (int) pdev->vendor);
1298	return -1;
1299    }
1300
1301#ifdef __powerpc__
1302    if ( ! (command & PCI_COMMAND_MASTER)) {
1303      printk("SCSI: PCI Master Bit has not been set. Setting...\n");
1304      command |= PCI_COMMAND_MASTER|PCI_COMMAND_IO;
1305      pci_write_config_word(pdev, PCI_COMMAND, command);
1306
1307      if (io_port >= 0x10000000 && is_prep ) {
1308	      /* Mapping on PowerPC can't handle this! */
1309	      unsigned long new_io_port;
1310	      new_io_port = (io_port & 0x00FFFFFF) | 0x01000000;
1311	      printk("SCSI: I/O moved from %08X to %08x\n", io_port, new_io_port);
1312	      io_port = new_io_port;
1313	      pci_write_config_dword(pdev, PCI_BASE_ADDRESS_0, io_port);
1314	      pdev->base_address[0] = io_port;
1315      }
1316    }
1317#endif
1318
1319    /*
1320     * Bit 0 is the address space indicator and must be one for I/O
1321     * space mappings, bit 1 is reserved, discard them after checking
1322     * that they have the correct value of 1.
1323     */
1324
1325    if (command & PCI_COMMAND_IO) {
1326	if (!(pdev->resource[0].flags & IORESOURCE_IO)) {
1327	    printk ("scsi-ncr53c7,8xx : disabling I/O mapping since base "
1328		    "address 0\n        contains a non-IO mapping\n");
1329	    io_port = 0;
1330	}
1331    } else {
1332    	io_port = 0;
1333    }
1334
1335    if (command & PCI_COMMAND_MEMORY) {
1336	if (!(pdev->resource[1].flags & IORESOURCE_MEM)) {
1337	    printk("scsi-ncr53c7,8xx : disabling memory mapping since base "
1338		   "address 1\n        contains a non-memory mapping\n");
1339	    base = 0;
1340	}
1341    } else {
1342	base = 0;
1343    }
1344
1345    if (!io_port && !base) {
1346	printk ("scsi-ncr53c7,8xx : not initializing, both I/O and memory mappings disabled\n");
1347	return -1;
1348    }
1349
1350    if (!(command & PCI_COMMAND_MASTER)) {
1351	printk ("scsi-ncr53c7,8xx : not initializing, BUS MASTERING was disabled\n");
1352	return -1;
1353    }
1354
1355    for (i = 0; i < NPCI_CHIP_IDS; ++i) {
1356	if (pdev->device == pci_chip_ids[i].pci_device_id) {
1357	    max_revision = pci_chip_ids[i].max_revision;
1358	    min_revision = pci_chip_ids[i].min_revision;
1359	    expected_chip = pci_chip_ids[i].chip;
1360	}
1361	if (chip == pci_chip_ids[i].chip)
1362	    expected_id = pci_chip_ids[i].pci_device_id;
1363    }
1364
1365    if (chip && pdev->device != expected_id)
1366	printk ("scsi-ncr53c7,8xx : warning : device id of 0x%04x doesn't\n"
1367                "                   match expected 0x%04x\n",
1368	    (unsigned int) pdev->device, (unsigned int) expected_id );
1369
1370    if (max_revision != -1 && revision > max_revision)
1371	printk ("scsi-ncr53c7,8xx : warning : revision of %d is greater than %d.\n",
1372	    (int) revision, max_revision);
1373    else if (min_revision != -1 && revision < min_revision)
1374	printk ("scsi-ncr53c7,8xx : warning : revision of %d is less than %d.\n",
1375	    (int) revision, min_revision);
1376
1377    if (io_port && check_region (io_port, 128)) {
1378	printk ("scsi-ncr53c7,8xx : IO region 0x%x to 0x%x is in use\n",
1379	    (unsigned) io_port, (unsigned) io_port + 127);
1380	return -1;
1381    }
1382
1383    return normal_init (tpnt, board, chip, (int) base, io_port,
1384	(int) irq, DMA_NONE, 1, bus, device_fn, pdev, options);
1385}
1386
1387
1388/*
1389 * Function : int NCR53c7xx_detect(Scsi_Host_Template *tpnt)
1390 *
1391 * Purpose : detects and initializes NCR53c7,8x0 SCSI chips
1392 *	that were autoprobed, overridden on the LILO command line,
1393 *	or specified at compile time.
1394 *
1395 * Inputs : tpnt - template for this SCSI adapter
1396 *
1397 * Returns : number of host adapters detected
1398 *
1399 */
1400
1401int __init
1402NCR53c7xx_detect(Scsi_Host_Template *tpnt){
1403    int i;
1404    int current_override;
1405    int count;			/* Number of boards detected */
1406    unsigned char pci_bus, pci_device_fn;
1407    static short pci_index=0;	/* Device index to PCI BIOS calls */
1408
1409    tpnt->proc_name = "ncr53c7xx";
1410
1411    for (current_override = count = 0; current_override < OVERRIDE_LIMIT;
1412	 ++current_override) {
1413	 if (overrides[current_override].pci ?
1414	    !ncr_pci_init (tpnt, overrides[current_override].board,
1415		overrides[current_override].chip,
1416		(unsigned char) overrides[current_override].data.pci.bus,
1417		(((overrides[current_override].data.pci.device
1418		<< 3) & 0xf8)|(overrides[current_override].data.pci.function &
1419		7)), overrides[current_override].options):
1420	    !normal_init (tpnt, overrides[current_override].board,
1421		overrides[current_override].chip,
1422		overrides[current_override].data.normal.base,
1423		overrides[current_override].data.normal.io_port,
1424		overrides[current_override].data.normal.irq,
1425		overrides[current_override].data.normal.dma,
1426		0 /* PCI data invalid */, 0 /* PCI bus place holder */,
1427		0 /* PCI device_function place holder */,
1428                NULL /* PCI pci_dev place holder */,
1429    	    	overrides[current_override].options)) {
1430    	    ++count;
1431	}
1432    }
1433
1434    if (pci_present()) {
1435	for (i = 0; i < NPCI_CHIP_IDS; ++i)
1436	    for (pci_index = 0;
1437		!pcibios_find_device (PCI_VENDOR_ID_NCR,
1438		    pci_chip_ids[i].pci_device_id, pci_index, &pci_bus,
1439		    &pci_device_fn);
1440    		++pci_index)
1441		if (!ncr_pci_init (tpnt, BOARD_GENERIC, pci_chip_ids[i].chip,
1442		    pci_bus, pci_device_fn, /* no options */ 0))
1443		    ++count;
1444    }
1445    return count;
1446}
1447
1448/* NCR53c810 and NCR53c820 script handling code */
1449
1450#include "53c8xx_d.h"
1451#ifdef A_int_debug_sync
1452#define DEBUG_SYNC_INTR A_int_debug_sync
1453#endif
1454static int NCR53c8xx_script_len = sizeof (SCRIPT);
1455static int NCR53c8xx_dsa_len = A_dsa_end + Ent_dsa_zero - Ent_dsa_code_template;
1456
1457/*
1458 * Function : static void NCR53c8x0_init_fixup (struct Scsi_Host *host)
1459 *
1460 * Purpose :  copy and fixup the SCSI SCRIPTS(tm) code for this device.
1461 *
1462 * Inputs : host - pointer to this host adapter's structure
1463 *
1464 */
1465
1466static void
1467NCR53c8x0_init_fixup (struct Scsi_Host *host) {
1468    NCR53c7x0_local_declare();
1469    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
1470	host->hostdata;
1471    unsigned char tmp;
1472    int i, ncr_to_memory, memory_to_ncr;
1473    u32 base;
1474#ifdef __powerpc__
1475    unsigned long *script_ptr;
1476#endif
1477    NCR53c7x0_local_setup(host);
1478
1479
1480    /*  Copy code into buffer that was allocated at detection time.  */
1481    memcpy ((void *) hostdata->script, (void *) SCRIPT,
1482	sizeof(SCRIPT));
1483    /* Fixup labels */
1484    for (i = 0; i < PATCHES; ++i)
1485	hostdata->script[LABELPATCHES[i]] +=
1486    	    virt_to_bus(hostdata->script);
1487    /* Fixup addresses of constants that used to be EXTERNAL */
1488
1489    patch_abs_32 (hostdata->script, 0, NCR53c7xx_msg_abort,
1490    	virt_to_bus(&(hostdata->NCR53c7xx_msg_abort)));
1491    patch_abs_32 (hostdata->script, 0, NCR53c7xx_msg_reject,
1492    	virt_to_bus(&(hostdata->NCR53c7xx_msg_reject)));
1493    patch_abs_32 (hostdata->script, 0, NCR53c7xx_zero,
1494    	virt_to_bus(&(hostdata->NCR53c7xx_zero)));
1495    patch_abs_32 (hostdata->script, 0, NCR53c7xx_sink,
1496    	virt_to_bus(&(hostdata->NCR53c7xx_sink)));
1497    patch_abs_32 (hostdata->script, 0, NOP_insn,
1498	virt_to_bus(&(hostdata->NOP_insn)));
1499    patch_abs_32 (hostdata->script, 0, schedule,
1500	virt_to_bus((void *) hostdata->schedule));
1501
1502    /* Fixup references to external variables: */
1503    for (i = 0; i < EXTERNAL_PATCHES_LEN; ++i)
1504       hostdata->script[EXTERNAL_PATCHES[i].offset] +=
1505         virt_to_bus(EXTERNAL_PATCHES[i].address);
1506
1507    /*
1508     * Fixup absolutes set at boot-time.
1509     *
1510     * All non-code absolute variables suffixed with "dsa_" and "int_"
1511     * are constants, and need no fixup provided the assembler has done
1512     * it for us (I don't know what the "real" NCR assembler does in
1513     * this case, my assembler does the right magic).
1514     */
1515
1516    patch_abs_rwri_data (hostdata->script, 0, dsa_save_data_pointer,
1517    	Ent_dsa_code_save_data_pointer - Ent_dsa_zero);
1518    patch_abs_rwri_data (hostdata->script, 0, dsa_restore_pointers,
1519    	Ent_dsa_code_restore_pointers - Ent_dsa_zero);
1520    patch_abs_rwri_data (hostdata->script, 0, dsa_check_reselect,
1521    	Ent_dsa_code_check_reselect - Ent_dsa_zero);
1522
1523    /*
1524     * Just for the hell of it, preserve the settings of
1525     * Burst Length and Enable Read Line bits from the DMODE
1526     * register.  Make sure SCRIPTS start automagically.
1527     */
1528
1529    tmp = NCR53c7x0_read8(DMODE_REG_10);
1530    tmp &= (DMODE_800_ERL | DMODE_BL_MASK);
1531
1532    if (!(hostdata->options & OPTION_MEMORY_MAPPED)) {
1533    	base = (u32) host->io_port;
1534    	memory_to_ncr = tmp|DMODE_800_DIOM;
1535    	ncr_to_memory = tmp|DMODE_800_SIOM;
1536    } else {
1537    	base = virt_to_bus((void *)host->base);
1538	memory_to_ncr = ncr_to_memory = tmp;
1539    }
1540
1541    patch_abs_32 (hostdata->script, 0, addr_scratch, base + SCRATCHA_REG_800);
1542    patch_abs_32 (hostdata->script, 0, addr_temp, base + TEMP_REG);
1543
1544    /*
1545     * I needed some variables in the script to be accessible to
1546     * both the NCR chip and the host processor. For these variables,
1547     * I made the arbitrary decision to store them directly in the
1548     * hostdata structure rather than in the RELATIVE area of the
1549     * SCRIPTS.
1550     */
1551
1552
1553    patch_abs_rwri_data (hostdata->script, 0, dmode_memory_to_memory, tmp);
1554    patch_abs_rwri_data (hostdata->script, 0, dmode_memory_to_ncr, memory_to_ncr);
1555    patch_abs_rwri_data (hostdata->script, 0, dmode_ncr_to_memory, ncr_to_memory);
1556
1557    patch_abs_32 (hostdata->script, 0, msg_buf,
1558	virt_to_bus((void *)&(hostdata->msg_buf)));
1559    patch_abs_32 (hostdata->script, 0, reconnect_dsa_head,
1560    	virt_to_bus((void *)&(hostdata->reconnect_dsa_head)));
1561    patch_abs_32 (hostdata->script, 0, addr_reconnect_dsa_head,
1562	virt_to_bus((void *)&(hostdata->addr_reconnect_dsa_head)));
1563    patch_abs_32 (hostdata->script, 0, reselected_identify,
1564    	virt_to_bus((void *)&(hostdata->reselected_identify)));
1565/* reselected_tag is currently unused */
1566
1567    patch_abs_32 (hostdata->script, 0, test_dest,
1568	virt_to_bus((void*)&hostdata->test_dest));
1569    patch_abs_32 (hostdata->script, 0, test_src,
1570	virt_to_bus(&hostdata->test_source));
1571
1572    patch_abs_rwri_data (hostdata->script, 0, dsa_check_reselect,
1573	(unsigned char)(Ent_dsa_code_check_reselect - Ent_dsa_zero));
1574
1575/* These are for event logging; the ncr_event enum contains the
1576   actual interrupt numbers. */
1577#ifdef A_int_EVENT_SELECT
1578   patch_abs_32 (hostdata->script, 0, int_EVENT_SELECT, (u32) EVENT_SELECT);
1579#endif
1580#ifdef A_int_EVENT_DISCONNECT
1581   patch_abs_32 (hostdata->script, 0, int_EVENT_DISCONNECT, (u32) EVENT_DISCONNECT);
1582#endif
1583#ifdef A_int_EVENT_RESELECT
1584   patch_abs_32 (hostdata->script, 0, int_EVENT_RESELECT, (u32) EVENT_RESELECT);
1585#endif
1586#ifdef A_int_EVENT_COMPLETE
1587   patch_abs_32 (hostdata->script, 0, int_EVENT_COMPLETE, (u32) EVENT_COMPLETE);
1588#endif
1589#ifdef A_int_EVENT_IDLE
1590   patch_abs_32 (hostdata->script, 0, int_EVENT_IDLE, (u32) EVENT_IDLE);
1591#endif
1592#ifdef A_int_EVENT_SELECT_FAILED
1593   patch_abs_32 (hostdata->script, 0, int_EVENT_SELECT_FAILED,
1594	(u32) EVENT_SELECT_FAILED);
1595#endif
1596#ifdef A_int_EVENT_BEFORE_SELECT
1597   patch_abs_32 (hostdata->script, 0, int_EVENT_BEFORE_SELECT,
1598	(u32) EVENT_BEFORE_SELECT);
1599#endif
1600#ifdef A_int_EVENT_RESELECT_FAILED
1601   patch_abs_32 (hostdata->script, 0, int_EVENT_RESELECT_FAILED,
1602	(u32) EVENT_RESELECT_FAILED);
1603#endif
1604
1605    /*
1606     * Make sure the NCR and Linux code agree on the location of
1607     * certain fields.
1608     */
1609
1610    hostdata->E_accept_message = Ent_accept_message;
1611    hostdata->E_command_complete = Ent_command_complete;
1612    hostdata->E_cmdout_cmdout = Ent_cmdout_cmdout;
1613    hostdata->E_data_transfer = Ent_data_transfer;
1614    hostdata->E_debug_break = Ent_debug_break;
1615    hostdata->E_dsa_code_template = Ent_dsa_code_template;
1616    hostdata->E_dsa_code_template_end = Ent_dsa_code_template_end;
1617    hostdata->E_end_data_transfer = Ent_end_data_transfer;
1618    hostdata->E_initiator_abort = Ent_initiator_abort;
1619    hostdata->E_msg_in = Ent_msg_in;
1620    hostdata->E_other_transfer = Ent_other_transfer;
1621    hostdata->E_other_in = Ent_other_in;
1622    hostdata->E_other_out = Ent_other_out;
1623    hostdata->E_reject_message = Ent_reject_message;
1624    hostdata->E_respond_message = Ent_respond_message;
1625    hostdata->E_select = Ent_select;
1626    hostdata->E_select_msgout = Ent_select_msgout;
1627    hostdata->E_target_abort = Ent_target_abort;
1628#ifdef Ent_test_0
1629    hostdata->E_test_0 = Ent_test_0;
1630#endif
1631    hostdata->E_test_1 = Ent_test_1;
1632    hostdata->E_test_2 = Ent_test_2;
1633#ifdef Ent_test_3
1634    hostdata->E_test_3 = Ent_test_3;
1635#endif
1636    hostdata->E_wait_reselect = Ent_wait_reselect;
1637    hostdata->E_dsa_code_begin = Ent_dsa_code_begin;
1638
1639    hostdata->dsa_cmdout = A_dsa_cmdout;
1640    hostdata->dsa_cmnd = A_dsa_cmnd;
1641    hostdata->dsa_datain = A_dsa_datain;
1642    hostdata->dsa_dataout = A_dsa_dataout;
1643    hostdata->dsa_end = A_dsa_end;
1644    hostdata->dsa_msgin = A_dsa_msgin;
1645    hostdata->dsa_msgout = A_dsa_msgout;
1646    hostdata->dsa_msgout_other = A_dsa_msgout_other;
1647    hostdata->dsa_next = A_dsa_next;
1648    hostdata->dsa_select = A_dsa_select;
1649    hostdata->dsa_start = Ent_dsa_code_template - Ent_dsa_zero;
1650    hostdata->dsa_status = A_dsa_status;
1651    hostdata->dsa_jump_dest = Ent_dsa_code_fix_jump - Ent_dsa_zero +
1652	8 /* destination operand */;
1653
1654    /* sanity check */
1655    if (A_dsa_fields_start != Ent_dsa_code_template_end -
1656    	Ent_dsa_zero)
1657    	printk("scsi%d : NCR dsa_fields start is %d not %d\n",
1658    	    host->host_no, A_dsa_fields_start, Ent_dsa_code_template_end -
1659    	    Ent_dsa_zero);
1660#ifdef __powerpc__
1661/* The PowerPC is Big Endian - adjust script appropriately */
1662    script_ptr = hostdata->script;
1663    for (i = 0;  i < sizeof(SCRIPT);  i += sizeof(long))
1664    {
1665        *script_ptr++ = le32_to_cpu(*script_ptr);
1666    }
1667#endif
1668
1669    printk("scsi%d : NCR code relocated to 0x%lx (virt 0x%p)\n", host->host_no,
1670	virt_to_bus(hostdata->script), hostdata->script);
1671}
1672
1673/*
1674 * Function : static int NCR53c8xx_run_tests (struct Scsi_Host *host)
1675 *
1676 * Purpose : run various verification tests on the NCR chip,
1677 *	including interrupt generation, and proper bus mastering
1678 * 	operation.
1679 *
1680 * Inputs : host - a properly initialized Scsi_Host structure
1681 *
1682 * Preconditions : the NCR chip must be in a halted state.
1683 *
1684 * Returns : 0 if all tests were successful, -1 on error.
1685 *
1686 */
1687
1688static int
1689NCR53c8xx_run_tests (struct Scsi_Host *host) {
1690    NCR53c7x0_local_declare();
1691    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
1692	host->hostdata;
1693    unsigned long timeout;
1694    u32 start;
1695    int failed, i;
1696    unsigned long flags;
1697    NCR53c7x0_local_setup(host);
1698
1699    /* The NCR chip _must_ be idle to run the test scripts */
1700
1701    save_flags(flags);
1702    cli();
1703    if (!hostdata->idle) {
1704	printk ("scsi%d : chip not idle, aborting tests\n", host->host_no);
1705	restore_flags(flags);
1706	return -1;
1707    }
1708
1709    /*
1710     * Check for functional interrupts, this could work as an
1711     * autoprobe routine.
1712     */
1713
1714    if ((hostdata->options & OPTION_DEBUG_TEST1) &&
1715	    hostdata->state != STATE_DISABLED) {
1716	hostdata->idle = 0;
1717	hostdata->test_running = 1;
1718	hostdata->test_completed = -1;
1719	hostdata->test_dest = 0;
1720	hostdata->test_source = 0xdeadbeef;
1721	start = virt_to_bus (hostdata->script) + hostdata->E_test_1;
1722    	hostdata->state = STATE_RUNNING;
1723	printk ("scsi%d : test 1", host->host_no);
1724	NCR53c7x0_write32 (DSP_REG, start);
1725	printk (" started\n");
1726	restore_flags(flags);
1727
1728	/*
1729	 * This is currently a .5 second timeout, since (in theory) no slow
1730	 * board will take that long.  In practice, we've seen one
1731	 * pentium which occasionally fails with this, but works with
1732	 * 10 times as much?
1733	 */
1734
1735	timeout = jiffies + 5 * HZ / 10;
1736	while ((hostdata->test_completed == -1) && time_before(jiffies, timeout)) {
1737		barrier();
1738		cpu_relax();
1739	}
1740
1741	failed = 1;
1742	if (hostdata->test_completed == -1)
1743	    printk ("scsi%d : driver test 1 timed out%s\n",host->host_no ,
1744		(hostdata->test_dest == 0xdeadbeef) ?
1745		    " due to lost interrupt.\n"
1746		    "         Please verify that the correct IRQ is being used for your board,\n"
1747		    "	      and that the motherboard IRQ jumpering matches the PCI setup on\n"
1748		    "         PCI systems.\n"
1749		    "         If you are using a NCR53c810 board in a PCI system, you should\n"
1750		    "         also verify that the board is jumpered to use PCI INTA, since\n"
1751		    "         most PCI motherboards lack support for INTB, INTC, and INTD.\n"
1752		    : "");
1753      else if (hostdata->test_completed != 1)
1754	    printk ("scsi%d : test 1 bad interrupt value (%d)\n",
1755		host->host_no, hostdata->test_completed);
1756	else
1757	    failed = (hostdata->test_dest != 0xdeadbeef);
1758
1759	if (hostdata->test_dest != 0xdeadbeef) {
1760	    printk ("scsi%d : driver test 1 read 0x%x instead of 0xdeadbeef indicating a\n"
1761                    "         probable cache invalidation problem.  Please configure caching\n"
1762		    "         as write-through or disabled\n",
1763		host->host_no, hostdata->test_dest);
1764	}
1765
1766	if (failed) {
1767	    printk ("scsi%d : DSP = 0x%p (script at 0x%p, start at 0x%x)\n",
1768		host->host_no, bus_to_virt(NCR53c7x0_read32(DSP_REG)),
1769		hostdata->script, start);
1770	    printk ("scsi%d : DSPS = 0x%x\n", host->host_no,
1771		NCR53c7x0_read32(DSPS_REG));
1772	    return -1;
1773	}
1774    	hostdata->test_running = 0;
1775    }
1776
1777    if ((hostdata->options & OPTION_DEBUG_TEST2) &&
1778	hostdata->state != STATE_DISABLED) {
1779	u32 dsa[48];
1780    	unsigned char identify = IDENTIFY(0, 0);
1781	unsigned char cmd[6];
1782	unsigned char data[36];
1783    	unsigned char status = 0xff;
1784    	unsigned char msg = 0xff;
1785
1786    	cmd[0] = INQUIRY;
1787    	cmd[1] = cmd[2] = cmd[3] = cmd[5] = 0;
1788    	cmd[4] = sizeof(data);
1789
1790/* Need to adjust for endian-ness */
1791    	dsa[2] = le32_to_cpu(1);
1792    	dsa[3] = le32_to_cpu(virt_to_bus(&identify));
1793    	dsa[4] = le32_to_cpu(6);
1794    	dsa[5] = le32_to_cpu(virt_to_bus(&cmd));
1795    	dsa[6] = le32_to_cpu(sizeof(data));
1796    	dsa[7] = le32_to_cpu(virt_to_bus(&data));
1797    	dsa[8] = le32_to_cpu(1);
1798    	dsa[9] = le32_to_cpu(virt_to_bus(&status));
1799    	dsa[10] = le32_to_cpu(1);
1800    	dsa[11] = le32_to_cpu(virt_to_bus(&msg));
1801
1802	for (i = 0; i < 3; ++i) {
1803	    cli();
1804	    if (!hostdata->idle) {
1805		printk ("scsi%d : chip not idle, aborting tests\n", host->host_no);
1806		restore_flags(flags);
1807		return -1;
1808	    }
1809
1810	    /*	     SCNTL3         SDID	*/
1811	    dsa[0] = le32_to_cpu((0x33 << 24) | (i << 16))  ;
1812	    hostdata->idle = 0;
1813	    hostdata->test_running = 2;
1814	    hostdata->test_completed = -1;
1815	    start = virt_to_bus(hostdata->script) + hostdata->E_test_2;
1816	    hostdata->state = STATE_RUNNING;
1817	    NCR53c7x0_write32 (DSA_REG, virt_to_bus(dsa));
1818	    NCR53c7x0_write32 (DSP_REG, start);
1819	    restore_flags(flags);
1820
1821	    timeout = jiffies + 5 * HZ;	/* arbitrary */
1822	    while ((hostdata->test_completed == -1) && time_before(jiffies, timeout)) {
1823	    	barrier();
1824		cpu_relax();
1825	    }
1826	    NCR53c7x0_write32 (DSA_REG, 0);
1827
1828	    if (hostdata->test_completed == 2) {
1829		data[35] = 0;
1830		printk ("scsi%d : test 2 INQUIRY to target %d, lun 0 : %s\n",
1831		    host->host_no, i, data + 8);
1832		printk ("scsi%d : status ", host->host_no);
1833		print_status (status);
1834		printk ("\nscsi%d : message ", host->host_no);
1835		print_msg (&msg);
1836		printk ("\n");
1837	    } else if (hostdata->test_completed == 3) {
1838		printk("scsi%d : test 2 no connection with target %d\n",
1839		    host->host_no, i);
1840		if (!hostdata->idle) {
1841		    printk("scsi%d : not idle\n", host->host_no);
1842		    restore_flags(flags);
1843		    return -1;
1844		}
1845	    } else if (hostdata->test_completed == -1) {
1846		printk ("scsi%d : test 2 timed out\n", host->host_no);
1847		restore_flags(flags);
1848		return -1;
1849	    }
1850	    hostdata->test_running = 0;
1851	}
1852    }
1853
1854    restore_flags(flags);
1855    return 0;
1856}
1857
1858/*
1859 * Function : static void NCR53c8xx_dsa_fixup (struct NCR53c7x0_cmd *cmd)
1860 *
1861 * Purpose : copy the NCR53c8xx dsa structure into cmd's dsa buffer,
1862 * 	performing all necessary relocation.
1863 *
1864 * Inputs : cmd, a NCR53c7x0_cmd structure with a dsa area large
1865 *	enough to hold the NCR53c8xx dsa.
1866 */
1867
1868static void
1869NCR53c8xx_dsa_fixup (struct NCR53c7x0_cmd *cmd) {
1870    Scsi_Cmnd *c = cmd->cmd;
1871    struct Scsi_Host *host = c->host;
1872    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
1873    	host->hostdata;
1874    int i;
1875#ifdef __powerpc__
1876    int len;
1877    unsigned long *dsa_ptr;
1878#endif
1879
1880    memcpy (cmd->dsa, hostdata->script + (hostdata->E_dsa_code_template / 4),
1881    	hostdata->E_dsa_code_template_end - hostdata->E_dsa_code_template);
1882#ifdef __powerpc__
1883    /* Note: the script has already been 'endianized' */
1884    dsa_ptr = cmd->dsa;
1885    len = hostdata->E_dsa_code_template_end - hostdata->E_dsa_code_template;
1886    for (i = 0;  i < len;  i += sizeof(long))
1887    {
1888       *dsa_ptr++ = le32_to_cpu(*dsa_ptr);
1889    }
1890#endif
1891
1892    /*
1893     * Note : within the NCR 'C' code, dsa points to the _start_
1894     * of the DSA structure, and _not_ the offset of dsa_zero within
1895     * that structure used to facilitate shorter signed offsets
1896     * for the 8 bit ALU.
1897     *
1898     * The implications of this are that
1899     *
1900     * - 32 bit A_dsa_* absolute values require an additional
1901     * 	 dsa_zero added to their value to be correct, since they are
1902     *   relative to dsa_zero which is in essentially a separate
1903     *   space from the code symbols.
1904     *
1905     * - All other symbols require no special treatment.
1906     */
1907
1908    patch_abs_tci_data (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1909    	dsa_temp_lun, c->lun);
1910    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1911	dsa_temp_addr_next, virt_to_bus(&cmd->dsa_next_addr));
1912    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1913    	dsa_temp_next, virt_to_bus(cmd->dsa) + Ent_dsa_zero -
1914	Ent_dsa_code_template + A_dsa_next);
1915    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1916    	dsa_temp_sync, virt_to_bus((void *)hostdata->sync[c->target].script));
1917    patch_abs_tci_data (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1918    	dsa_temp_target, c->target);
1919    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1920    	dsa_temp_addr_saved_pointer, virt_to_bus(&cmd->saved_data_pointer));
1921    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1922    	dsa_temp_addr_saved_residual, virt_to_bus(&cmd->saved_residual));
1923    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1924    	dsa_temp_addr_residual, virt_to_bus(&cmd->residual));
1925
1926    patch_abs_32 (cmd->dsa, Ent_dsa_code_template / sizeof(u32),
1927	dsa_temp_addr_dsa_value, virt_to_bus(&cmd->dsa_addr));
1928#ifdef __powerpc__
1929    dsa_ptr = cmd->dsa;
1930    len = hostdata->E_dsa_code_template_end - hostdata->E_dsa_code_template;
1931    for (i = 0;  i < len;  i += sizeof(long))
1932    {
1933       *dsa_ptr++ = le32_to_cpu(*dsa_ptr);
1934    }
1935#endif
1936
1937}
1938
1939/*
1940 * Function : run_process_issue_queue (void)
1941 *
1942 * Purpose : insure that the coroutine is running and will process our
1943 * 	request.  process_issue_queue_running is checked/set here (in an
1944 *	inline function) rather than in process_issue_queue itself to reduce
1945 * 	the chances of stack overflow.
1946 *
1947 */
1948
1949static volatile int process_issue_queue_running = 0;
1950
1951static __inline__ void
1952run_process_issue_queue(void) {
1953    unsigned long flags;
1954    save_flags (flags);
1955    cli();
1956    if (!process_issue_queue_running) {
1957	process_issue_queue_running = 1;
1958        process_issue_queue(flags);
1959	/*
1960         * process_issue_queue_running is cleared in process_issue_queue
1961	 * once it can't do more work, and process_issue_queue exits with
1962	 * interrupts disabled.
1963	 */
1964    }
1965    restore_flags (flags);
1966}
1967
1968/*
1969 * Function : static void abnormal_finished (struct NCR53c7x0_cmd *cmd, int
1970 *	result)
1971 *
1972 * Purpose : mark SCSI command as finished, OR'ing the host portion
1973 *	of the result word into the result field of the corresponding
1974 *	Scsi_Cmnd structure, and removing it from the internal queues.
1975 *
1976 * Inputs : cmd - command, result - entire result field
1977 *
1978 * Preconditions : the 	NCR chip should be in a halted state when
1979 *	abnormal_finished is run, since it modifies structures which
1980 *	the NCR expects to have exclusive access to.
1981 */
1982
1983static void
1984abnormal_finished (struct NCR53c7x0_cmd *cmd, int result) {
1985    Scsi_Cmnd *c = cmd->cmd;
1986    struct Scsi_Host *host = c->host;
1987    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
1988    	host->hostdata;
1989    unsigned long flags;
1990    int left, found;
1991    volatile struct NCR53c7x0_cmd * linux_search;
1992    volatile struct NCR53c7x0_cmd * volatile *linux_prev;
1993    volatile u32 *ncr_prev, *curr, ncr_search;
1994
1995
1996    save_flags(flags);
1997    cli();
1998    found = 0;
1999    /*
2000     * Traverse the NCR issue array until we find a match or run out
2001     * of instructions.  Instructions in the NCR issue array are
2002     * either JUMP or NOP instructions, which are 2 words in length.
2003     */
2004
2005
2006    for (found = 0, left = host->can_queue, curr = hostdata->schedule;
2007	left > 0; --left, curr += 2)
2008    {
2009	if (issue_to_cmd (host, hostdata, (u32 *) curr) == cmd)
2010	{
2011	    curr[0] = hostdata->NOP_insn;
2012	    curr[1] = le32_to_cpu(0xdeadbeef);
2013	    ++found;
2014	    break;
2015	}
2016    }
2017
2018    /*
2019     * Traverse the NCR reconnect list of DSA structures until we find
2020     * a pointer to this dsa or have found too many command structures.
2021     * We let prev point at the next field of the previous element or
2022     * head of the list, so we don't do anything different for removing
2023     * the head element.
2024     */
2025
2026    for (left = host->can_queue,
2027	    ncr_search = le32_to_cpu(hostdata->reconnect_dsa_head),
2028	    ncr_prev = &hostdata->reconnect_dsa_head;
2029	left >= 0 && ncr_search &&
2030	    ((char*)bus_to_virt(ncr_search) + hostdata->dsa_start)
2031		!= (char *) cmd->dsa;
2032	ncr_prev = (u32*) ((char*)bus_to_virt(ncr_search) +
2033	    hostdata->dsa_next), ncr_search = le32_to_cpu(*ncr_prev), --left);
2034
2035    if (left < 0) {
2036	printk("scsi%d: loop detected in ncr reconnect list\n",
2037	    host->host_no);
2038    } else if (ncr_search) {
2039	if (found)
2040	    printk("scsi%d: scsi %ld in ncr issue array and reconnect lists\n",
2041		host->host_no, c->pid);
2042	else {
2043	    volatile u32 * next = (u32 *)
2044	    	((char *)bus_to_virt(ncr_search) + hostdata->dsa_next);
2045	    *ncr_prev = *next;
2046/* If we're at the tail end of the issue queue, update that pointer too. */
2047	    found = 1;
2048	}
2049    }
2050
2051    /*
2052     * Traverse the host running list until we find this command or discover
2053     * we have too many elements, pointing linux_prev at the next field of the
2054     * linux_previous element or head of the list, search at this element.
2055     */
2056
2057    for (left = host->can_queue, linux_search = hostdata->running_list,
2058	    linux_prev = &hostdata->running_list;
2059	left >= 0 && linux_search && linux_search != cmd;
2060	linux_prev = &(linux_search->next),
2061	    linux_search = linux_search->next, --left);
2062
2063    if (left < 0)
2064	printk ("scsi%d: loop detected in host running list for scsi pid %ld\n",
2065	    host->host_no, c->pid);
2066    else if (linux_search) {
2067	*linux_prev = linux_search->next;
2068	--hostdata->busy[c->target][c->lun];
2069    }
2070
2071    /* Return the NCR command structure to the free list */
2072    cmd->next = hostdata->free;
2073    hostdata->free = cmd;
2074    c->host_scribble = NULL;
2075
2076    /* And return */
2077    c->result = result;
2078    c->scsi_done(c);
2079
2080    restore_flags(flags);
2081    run_process_issue_queue();
2082}
2083
2084/*
2085 * Function : static void intr_break (struct Scsi_Host *host,
2086 * 	struct NCR53c7x0_cmd *cmd)
2087 *
2088 * Purpose :  Handler for breakpoint interrupts from a SCSI script
2089 *
2090 * Inputs : host - pointer to this host adapter's structure,
2091 * 	cmd - pointer to the command (if any) dsa was pointing
2092 * 	to.
2093 *
2094 */
2095
2096static void
2097intr_break (struct Scsi_Host *host, struct
2098    NCR53c7x0_cmd *cmd) {
2099    NCR53c7x0_local_declare();
2100    struct NCR53c7x0_break *bp;
2101    u32 *dsp;
2102    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2103	host->hostdata;
2104    unsigned long flags;
2105    NCR53c7x0_local_setup(host);
2106
2107    /*
2108     * Find the break point corresponding to this address, and
2109     * dump the appropriate debugging information to standard
2110     * output.
2111     */
2112    save_flags(flags);
2113    cli();
2114    dsp = (u32 *) bus_to_virt(NCR53c7x0_read32(DSP_REG));
2115    for (bp = hostdata->breakpoints; bp && bp->address != dsp;
2116    	bp = bp->next);
2117    if (!bp)
2118    	panic("scsi%d : break point interrupt from %p with no breakpoint!",
2119    	    host->host_no, dsp);
2120
2121    /*
2122     * Configure the NCR chip for manual start mode, so that we can
2123     * point the DSP register at the instruction that follows the
2124     * INT int_debug_break instruction.
2125     */
2126
2127    NCR53c7x0_write8 (hostdata->dmode,
2128	NCR53c7x0_read8(hostdata->dmode)|DMODE_MAN);
2129
2130    /*
2131     * And update the DSP register, using the size of the old
2132     * instruction in bytes.
2133     */
2134
2135    restore_flags(flags);
2136}
2137/*
2138 * Function : static void print_synchronous (const char *prefix,
2139 *	const unsigned char *msg)
2140 *
2141 * Purpose : print a pretty, user and machine parsable representation
2142 *	of a SDTR message, including the "real" parameters, data
2143 *	clock so we can tell transfer rate at a glance.
2144 *
2145 * Inputs ; prefix - text to prepend, msg - SDTR message (5 bytes)
2146 */
2147
2148static void
2149print_synchronous (const char *prefix, const unsigned char *msg) {
2150    if (msg[4]) {
2151	int Hz = 1000000000 / (msg[3] * 4);
2152	int integer = Hz / 1000000;
2153	int fraction = (Hz - (integer * 1000000)) / 10000;
2154	printk ("%speriod %dns offset %d %d.%02dMHz %s SCSI%s\n",
2155	    prefix, (int) msg[3] * 4, (int) msg[4], integer, fraction,
2156	    (((msg[3] * 4) < 200) ? "FAST" : "synchronous"),
2157	    (((msg[3] * 4) < 200) ? "-II" : ""));
2158    } else
2159	printk ("%sasynchronous SCSI\n", prefix);
2160}
2161
2162/*
2163 * Function : static void set_synchronous (struct Scsi_Host *host,
2164 *	 	int target, int sxfer, int scntl3, int now_connected)
2165 *
2166 * Purpose : reprogram transfers between the selected SCSI initiator and
2167 *	target with the given register values; in the indirect
2168 *	select operand, reselection script, and chip registers.
2169 *
2170 * Inputs : host - NCR53c7,8xx SCSI host, target - number SCSI target id,
2171 *	sxfer and scntl3 - NCR registers. now_connected - if non-zero,
2172 *	we should reprogram the registers now too.
2173 */
2174
2175static void
2176set_synchronous (struct Scsi_Host *host, int target, int sxfer, int scntl3,
2177    int now_connected) {
2178    NCR53c7x0_local_declare();
2179    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2180	host->hostdata;
2181    u32 *script;
2182    NCR53c7x0_local_setup(host);
2183
2184    /* These are eight bit registers */
2185    sxfer &= 0xff;
2186    scntl3 &= 0xff;
2187
2188    hostdata->sync[target].sxfer_sanity = sxfer;
2189    hostdata->sync[target].scntl3_sanity = scntl3;
2190
2191/*
2192 * HARD CODED : synchronous script is EIGHT words long.  This
2193 * must agree with 53c7.8xx.h
2194 */
2195
2196    if ((hostdata->chip != 700) && (hostdata->chip != 70066)) {
2197	hostdata->sync[target].select_indirect = (scntl3 << 24) |
2198	    (target << 16) | (sxfer << 8);
2199
2200	script = (u32 *) hostdata->sync[target].script;
2201
2202	if ((hostdata->chip / 100) == 8) {
2203	    script[0] = ((DCMD_TYPE_RWRI | DCMD_RWRI_OPC_MODIFY |
2204		DCMD_RWRI_OP_MOVE) << 24) |
2205		(SCNTL3_REG_800 << 16) | (scntl3 << 8);
2206	    script[1] = 0;
2207	    script += 2;
2208	}
2209
2210	script[0] = ((DCMD_TYPE_RWRI | DCMD_RWRI_OPC_MODIFY |
2211	    DCMD_RWRI_OP_MOVE) << 24) |
2212		(SXFER_REG << 16) | (sxfer << 8);
2213	script[1] = 0;
2214	script += 2;
2215
2216#ifdef DEBUG_SYNC_INTR
2217	if (hostdata->options & OPTION_DEBUG_DISCONNECT) {
2218	    script[0] = ((DCMD_TYPE_TCI|DCMD_TCI_OP_INT) << 24) | DBC_TCI_TRUE;
2219	    script[1] = DEBUG_SYNC_INTR;
2220	    script += 2;
2221	}
2222#endif
2223
2224	script[0] = ((DCMD_TYPE_TCI|DCMD_TCI_OP_RETURN) << 24) | DBC_TCI_TRUE;
2225	script[1] = 0;
2226	script += 2;
2227    }
2228
2229    if (hostdata->options & OPTION_DEBUG_SYNCHRONOUS)
2230	printk ("scsi%d : target %d sync parameters are sxfer=0x%x, scntl3=0x%x\n",
2231	host->host_no, target, sxfer, scntl3);
2232
2233    if (now_connected) {
2234	if ((hostdata->chip / 100) == 8)
2235	    NCR53c7x0_write8(SCNTL3_REG_800, scntl3);
2236	NCR53c7x0_write8(SXFER_REG, sxfer);
2237    }
2238}
2239
2240
2241/*
2242 * Function : static int asynchronous (struct Scsi_Host *host, int target)
2243 *
2244 * Purpose : reprogram between the selected SCSI Host adapter and target
2245 *      (assumed to be currently connected) for asynchronous transfers.
2246 *
2247 * Inputs : host - SCSI host structure, target - numeric target ID.
2248 *
2249 * Preconditions : the NCR chip should be in one of the halted states
2250 */
2251
2252static void
2253asynchronous (struct Scsi_Host *host, int target) {
2254    NCR53c7x0_local_declare();
2255    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2256	host->hostdata;
2257    NCR53c7x0_local_setup(host);
2258    set_synchronous (host, target, /* no offset */ 0, hostdata->saved_scntl3,
2259	1);
2260    printk ("scsi%d : setting target %d to asynchronous SCSI\n",
2261	host->host_no, target);
2262}
2263
2264
2265/* Table for NCR53c8xx synchronous values */
2266static const struct {
2267    int div;		/* Total clock divisor * 10 */
2268    unsigned char scf;	/* */
2269    unsigned char tp;	/* 4 + tp = xferp divisor */
2270} syncs[] = {
2271/*	div	scf	tp	div	scf	tp	div	scf	tp */
2272    {	40,	1,	0}, {	50,	1,	1}, {	60,	1,	2},
2273    {	70,	1,	3}, {	75,	2,	1}, {	80,	1,	4},
2274    {	90,	1,	5}, {	100,	1,	6}, {	105,	2,	3},
2275    {	110,	1,	7}, {	120,	2,	4}, {	135,	2,	5},
2276    {	140,	3,	3}, {	150,	2,	6}, {	160,	3,	4},
2277    {	165,	2,	7}, {	180,	3,	5}, {	200,	3,	6},
2278    {	210,	4,	3}, {	220,	3,	7}, {	240,	4,	4},
2279    {	270,	4,	5}, {	300,	4,	6}, {	330,	4,	7}
2280};
2281
2282/*
2283 * Function : static void synchronous (struct Scsi_Host *host, int target,
2284 *	char *msg)
2285 *
2286 * Purpose : reprogram transfers between the selected SCSI initiator and
2287 *	target for synchronous SCSI transfers such that the synchronous
2288 *	offset is less than that requested and period at least as long
2289 *	as that requested.  Also modify *msg such that it contains
2290 *	an appropriate response.
2291 *
2292 * Inputs : host - NCR53c7,8xx SCSI host, target - number SCSI target id,
2293 *	msg - synchronous transfer request.
2294 */
2295
2296
2297static void
2298synchronous (struct Scsi_Host *host, int target, char *msg) {
2299    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2300	host->hostdata;
2301    int desire, divisor, i, limit;
2302    unsigned char scntl3, sxfer;
2303/* The diagnostic message fits on one line, even with max. width integers */
2304    char buf[80];
2305
2306/* Desired transfer clock in Hz */
2307    desire = 1000000000L / (msg[3] * 4);
2308/* Scale the available SCSI clock by 10 so we get tenths */
2309    divisor = (hostdata->scsi_clock * 10) / desire;
2310
2311/* NCR chips can handle at most an offset of 8 */
2312    if (msg[4] > 8)
2313	msg[4] = 8;
2314
2315    if (hostdata->options & OPTION_DEBUG_SDTR)
2316    	printk("scsi%d : optimal synchronous divisor of %d.%01d\n",
2317	    host->host_no, divisor / 10, divisor % 10);
2318
2319    limit = (sizeof(syncs) / sizeof(syncs[0]) -1);
2320    for (i = 0; (i < limit) && (divisor > syncs[i].div); ++i);
2321
2322    if (hostdata->options & OPTION_DEBUG_SDTR)
2323    	printk("scsi%d : selected synchronous divisor of %d.%01d\n",
2324	    host->host_no, syncs[i].div / 10, syncs[i].div % 10);
2325
2326    msg[3] = ((1000000000L / hostdata->scsi_clock) * syncs[i].div / 10 / 4);
2327
2328    if (hostdata->options & OPTION_DEBUG_SDTR)
2329    	printk("scsi%d : selected synchronous period of %dns\n", host->host_no,
2330	    msg[3] * 4);
2331
2332    scntl3 = (hostdata->chip / 100 == 8) ? ((hostdata->saved_scntl3 &
2333	~SCNTL3_800_SCF_MASK) | (syncs[i].scf << SCNTL3_800_SCF_SHIFT)) : 0;
2334    sxfer = (msg[4] << SXFER_MO_SHIFT) | ((syncs[i].tp) << SXFER_TP_SHIFT);
2335    if (hostdata->options & OPTION_DEBUG_SDTR)
2336    	printk ("scsi%d : sxfer=0x%x scntl3=0x%x\n",
2337	    host->host_no, (int) sxfer, (int) scntl3);
2338    set_synchronous (host, target, sxfer, scntl3, 1);
2339    sprintf (buf, "scsi%d : setting target %d to ", host->host_no, target);
2340    print_synchronous (buf, msg);
2341}
2342
2343/*
2344 * Function : static int NCR53c8x0_dstat_sir_intr (struct Scsi_Host *host,
2345 * 	struct NCR53c7x0_cmd *cmd)
2346 *
2347 * Purpose :  Handler for INT generated instructions for the
2348 * 	NCR53c810/820 SCSI SCRIPT
2349 *
2350 * Inputs : host - pointer to this host adapter's structure,
2351 * 	cmd - pointer to the command (if any) dsa was pointing
2352 * 	to.
2353 *
2354 */
2355
2356static int
2357NCR53c8x0_dstat_sir_intr (struct Scsi_Host *host, struct
2358    NCR53c7x0_cmd *cmd) {
2359    NCR53c7x0_local_declare();
2360    int print;
2361    Scsi_Cmnd *c = cmd ? cmd->cmd : NULL;
2362    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2363	host->hostdata;
2364    u32 dsps,*dsp;	/* Argument of the INT instruction */
2365    NCR53c7x0_local_setup(host);
2366    dsps = NCR53c7x0_read32(DSPS_REG);
2367    dsp = (u32 *) bus_to_virt(NCR53c7x0_read32(DSP_REG));
2368
2369    if (hostdata->options & OPTION_DEBUG_INTR)
2370	printk ("scsi%d : DSPS = 0x%x\n", host->host_no, dsps);
2371
2372    switch (dsps) {
2373    case A_int_msg_1:
2374	print = 1;
2375	switch (hostdata->msg_buf[0]) {
2376	/*
2377	 * Unless we've initiated synchronous negotiation, I don't
2378	 * think that this should happen.
2379	 */
2380	case MESSAGE_REJECT:
2381	    hostdata->dsp = hostdata->script + hostdata->E_accept_message /
2382		sizeof(u32);
2383	    hostdata->dsp_changed = 1;
2384	    if (cmd && (cmd->flags & CMD_FLAG_SDTR)) {
2385		printk ("scsi%d : target %d rejected SDTR\n", host->host_no,
2386		    c->target);
2387		cmd->flags &= ~CMD_FLAG_SDTR;
2388		asynchronous (host, c->target);
2389		print = 0;
2390	    }
2391	    break;
2392	case INITIATE_RECOVERY:
2393	    printk ("scsi%d : extended contingent allegiance not supported yet, rejecting\n",
2394		host->host_no);
2395	    /* Fall through to default */
2396	    hostdata->dsp = hostdata->script + hostdata->E_reject_message /
2397		sizeof(u32);
2398	    hostdata->dsp_changed = 1;
2399	    break;
2400	default:
2401	    printk ("scsi%d : unsupported message, rejecting\n",
2402		host->host_no);
2403	    hostdata->dsp = hostdata->script + hostdata->E_reject_message /
2404		sizeof(u32);
2405	    hostdata->dsp_changed = 1;
2406	}
2407	if (print) {
2408	    printk ("scsi%d : received message", host->host_no);
2409	    if (c)
2410	    	printk (" from target %d lun %d ", c->target, c->lun);
2411	    print_msg ((unsigned char *) hostdata->msg_buf);
2412	    printk("\n");
2413	}
2414
2415	return SPECIFIC_INT_NOTHING;
2416
2417
2418    case A_int_msg_sdtr:
2419/*
2420 * At this point, hostdata->msg_buf contains
2421 * 0 EXTENDED MESSAGE
2422 * 1 length
2423 * 2 SDTR
2424 * 3 period * 4ns
2425 * 4 offset
2426 */
2427
2428	if (cmd) {
2429	    char buf[80];
2430	    sprintf (buf, "scsi%d : target %d %s ", host->host_no, c->target,
2431		(cmd->flags & CMD_FLAG_SDTR) ? "accepting" : "requesting");
2432	    print_synchronous (buf, (unsigned char *) hostdata->msg_buf);
2433
2434	/*
2435	 * Initiator initiated, won't happen unless synchronous
2436	 * 	transfers are enabled.  If we get a SDTR message in
2437	 * 	response to our SDTR, we should program our parameters
2438	 * 	such that
2439	 *		offset <= requested offset
2440	 *		period >= requested period
2441   	 */
2442	    if (cmd->flags & CMD_FLAG_SDTR) {
2443		cmd->flags &= ~CMD_FLAG_SDTR;
2444		if (hostdata->msg_buf[4])
2445		    synchronous (host, c->target, (unsigned char *)
2446		    	hostdata->msg_buf);
2447		else
2448		    asynchronous (host, c->target);
2449		hostdata->dsp = hostdata->script + hostdata->E_accept_message /
2450		    sizeof(u32);
2451		hostdata->dsp_changed = 1;
2452		return SPECIFIC_INT_NOTHING;
2453	    } else {
2454		if (hostdata->options & OPTION_SYNCHRONOUS)  {
2455		    cmd->flags |= CMD_FLAG_DID_SDTR;
2456		    synchronous (host, c->target, (unsigned char *)
2457			hostdata->msg_buf);
2458		} else {
2459		    hostdata->msg_buf[4] = 0;		/* 0 offset = async */
2460		    asynchronous (host, c->target);
2461		}
2462		patch_dsa_32 (cmd->dsa, dsa_msgout_other, 0, le32_to_cpu(5));
2463		patch_dsa_32 (cmd->dsa, dsa_msgout_other, 1, (u32)
2464		    le32_to_cpu(virt_to_bus ((void *)&hostdata->msg_buf)));
2465		hostdata->dsp = hostdata->script +
2466		    hostdata->E_respond_message / sizeof(u32);
2467		hostdata->dsp_changed = 1;
2468	    }
2469	    return SPECIFIC_INT_NOTHING;
2470	}
2471	/* Fall through to abort if we couldn't find a cmd, and
2472	   therefore a dsa structure to twiddle */
2473    case A_int_msg_wdtr:
2474	hostdata->dsp = hostdata->script + hostdata->E_reject_message /
2475	    sizeof(u32);
2476	hostdata->dsp_changed = 1;
2477	return SPECIFIC_INT_NOTHING;
2478    case A_int_err_unexpected_phase:
2479	if (hostdata->options & OPTION_DEBUG_INTR)
2480	    printk ("scsi%d : unexpected phase\n", host->host_no);
2481	return SPECIFIC_INT_ABORT;
2482    case A_int_err_selected:
2483	printk ("scsi%d : selected by target %d\n", host->host_no,
2484	    (int) NCR53c7x0_read8(SDID_REG_800) &7);
2485	hostdata->dsp = hostdata->script + hostdata->E_target_abort /
2486    	    sizeof(u32);
2487	hostdata->dsp_changed = 1;
2488	return SPECIFIC_INT_NOTHING;
2489    case A_int_err_unexpected_reselect:
2490	printk ("scsi%d : unexpected reselect by target %d lun %d\n",
2491	    host->host_no, (int) NCR53c7x0_read8(SDID_REG_800) & 7,
2492	    hostdata->reselected_identify & 7);
2493	hostdata->dsp = hostdata->script + hostdata->E_initiator_abort /
2494    	    sizeof(u32);
2495	hostdata->dsp_changed = 1;
2496	return SPECIFIC_INT_NOTHING;
2497/*
2498 * Since contingent allegiance conditions are cleared by the next
2499 * command issued to a target, we must issue a REQUEST SENSE
2500 * command after receiving a CHECK CONDITION status, before
2501 * another command is issued.
2502 *
2503 * Since this NCR53c7x0_cmd will be freed after use, we don't
2504 * care if we step on the various fields, so modify a few things.
2505 */
2506    case A_int_err_check_condition:
2507	    printk ("scsi%d : CHECK CONDITION\n", host->host_no);
2508	if (!c) {
2509	    printk("scsi%d : CHECK CONDITION with no SCSI command\n",
2510		host->host_no);
2511	    return SPECIFIC_INT_PANIC;
2512	}
2513
2514
2515    	patch_dsa_32 (cmd->dsa, dsa_msgout, 0, le32_to_cpu(1));
2516
2517    	/*
2518    	 * Modify the table indirect for COMMAND OUT phase, since
2519    	 * Request Sense is a six byte command.
2520    	 */
2521
2522    	patch_dsa_32 (cmd->dsa, dsa_cmdout, 0, le32_to_cpu(6));
2523
2524	c->cmnd[0] = REQUEST_SENSE;
2525	c->cmnd[1] &= 0xe0;	/* Zero all but LUN */
2526	c->cmnd[2] = 0;
2527	c->cmnd[3] = 0;
2528	c->cmnd[4] = sizeof(c->sense_buffer);
2529	c->cmnd[5] = 0;
2530
2531	/*
2532	 * Disable dataout phase, and program datain to transfer to the
2533	 * sense buffer, and add a jump to other_transfer after the
2534    	 * command so overflow/underrun conditions are detected.
2535	 */
2536
2537    	patch_dsa_32 (cmd->dsa, dsa_dataout, 0,
2538	    le32_to_cpu(virt_to_bus(hostdata->script) + hostdata->E_other_transfer));
2539    	patch_dsa_32 (cmd->dsa, dsa_datain, 0,
2540	    le32_to_cpu(virt_to_bus(cmd->data_transfer_start)));
2541    	cmd->data_transfer_start[0] = le32_to_cpu((((DCMD_TYPE_BMI | DCMD_BMI_OP_MOVE_I |
2542    	    DCMD_BMI_IO)) << 24) | sizeof(c->sense_buffer));
2543    	cmd->data_transfer_start[1] = (u32) le32_to_cpu(virt_to_bus(c->sense_buffer));
2544
2545	cmd->data_transfer_start[2] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_JUMP)
2546    	    << 24) | DBC_TCI_TRUE);
2547	cmd->data_transfer_start[3] = (u32) le32_to_cpu(virt_to_bus(hostdata->script) +
2548	    hostdata->E_other_transfer);
2549
2550    	/*
2551    	 * Currently, this command is flagged as completed, ie
2552    	 * it has valid status and message data.  Reflag it as
2553    	 * incomplete.  Q - need to do something so that original
2554	 * status, etc are used.
2555    	 */
2556
2557	cmd->cmd->result = le32_to_cpu(0xffff);
2558
2559	/*
2560	 * Restart command as a REQUEST SENSE.
2561	 */
2562	hostdata->dsp = (u32 *) hostdata->script + hostdata->E_select /
2563	    sizeof(u32);
2564	hostdata->dsp_changed = 1;
2565	return SPECIFIC_INT_NOTHING;
2566    case A_int_debug_break:
2567	return SPECIFIC_INT_BREAK;
2568    case A_int_norm_aborted:
2569	hostdata->dsp = (u32 *) hostdata->schedule;
2570	hostdata->dsp_changed = 1;
2571	if (cmd)
2572	    abnormal_finished (cmd, DID_ERROR << 16);
2573	return SPECIFIC_INT_NOTHING;
2574    case A_int_test_1:
2575    case A_int_test_2:
2576	hostdata->idle = 1;
2577	hostdata->test_completed = (dsps - A_int_test_1) / 0x00010000 + 1;
2578	if (hostdata->options & OPTION_DEBUG_INTR)
2579	    printk("scsi%d : test%d complete\n", host->host_no,
2580		hostdata->test_completed);
2581	return SPECIFIC_INT_NOTHING;
2582#ifdef A_int_debug_reselected_ok
2583    case A_int_debug_reselected_ok:
2584	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2585    	    	OPTION_DEBUG_DISCONNECT)) {
2586	    /*
2587	     * Note - this dsa is not based on location relative to
2588	     * the command structure, but to location relative to the
2589	     * DSA register
2590	     */
2591	    u32 *dsa;
2592	    dsa = (u32 *) bus_to_virt (NCR53c7x0_read32(DSA_REG));
2593
2594	    printk("scsi%d : reselected_ok (DSA = 0x%x (virt 0x%p)\n",
2595		host->host_no, NCR53c7x0_read32(DSA_REG), dsa);
2596	    printk("scsi%d : resume address is 0x%x (virt 0x%p)\n",
2597		    host->host_no, cmd->saved_data_pointer,
2598		    bus_to_virt(le32_to_cpu(cmd->saved_data_pointer)));
2599	    print_insn (host, hostdata->script + Ent_reselected_ok /
2600    	    	    sizeof(u32), "", 1);
2601    	    printk ("scsi%d : sxfer=0x%x, scntl3=0x%x\n",
2602		host->host_no, NCR53c7x0_read8(SXFER_REG),
2603		NCR53c7x0_read8(SCNTL3_REG_800));
2604	    if (c) {
2605		print_insn (host, (u32 *)
2606		    hostdata->sync[c->target].script, "", 1);
2607		print_insn (host, (u32 *)
2608		    hostdata->sync[c->target].script + 2, "", 1);
2609	    }
2610	}
2611    	return SPECIFIC_INT_RESTART;
2612#endif
2613#ifdef A_int_debug_reselect_check
2614    case A_int_debug_reselect_check:
2615	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2616	    u32 *dsa;
2617	    /*
2618	     * Note - this dsa is not based on location relative to
2619	     * the command structure, but to location relative to the
2620	     * DSA register
2621	     */
2622	    dsa = bus_to_virt (NCR53c7x0_read32(DSA_REG));
2623	    printk("scsi%d : reselected_check_next (DSA = 0x%lx (virt 0x%p))\n",
2624		host->host_no, virt_to_bus(dsa), dsa);
2625	    if (dsa) {
2626		printk("scsi%d : resume address is 0x%x (virt 0x%p)\n",
2627		    host->host_no, cmd->saved_data_pointer,
2628		    bus_to_virt (le32_to_cpu(cmd->saved_data_pointer)));
2629	    }
2630	    print_insn (host, hostdata->script + Ent_reselected_ok /
2631    	    	    sizeof(u32), "", 1);
2632	}
2633    	return SPECIFIC_INT_RESTART;
2634#endif
2635#ifdef A_int_debug_dsa_schedule
2636    case A_int_debug_dsa_schedule:
2637	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2638	    u32 *dsa;
2639	    /*
2640	     * Note - this dsa is not based on location relative to
2641	     * the command structure, but to location relative to the
2642	     * DSA register
2643	     */
2644	    dsa = (u32 *) bus_to_virt (NCR53c7x0_read32(DSA_REG));
2645	    printk("scsi%d : dsa_schedule (old DSA = 0x%lx (virt 0x%p))\n",
2646		host->host_no, virt_to_bus(dsa), dsa);
2647	    if (dsa)
2648		printk("scsi%d : resume address is 0x%x (virt 0x%p)\n"
2649		       "         (temp was 0x%x (virt 0x%p))\n",
2650		    host->host_no, cmd->saved_data_pointer,
2651		    bus_to_virt (le32_to_cpu(cmd->saved_data_pointer)),
2652		    NCR53c7x0_read32 (TEMP_REG),
2653		    bus_to_virt (NCR53c7x0_read32(TEMP_REG)));
2654	}
2655    	return SPECIFIC_INT_RESTART;
2656#endif
2657#ifdef A_int_debug_scheduled
2658    case A_int_debug_scheduled:
2659	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2660	    printk("scsi%d : new I/O 0x%x (virt 0x%p) scheduled\n",
2661		host->host_no, NCR53c7x0_read32(DSA_REG),
2662	    	bus_to_virt(NCR53c7x0_read32(DSA_REG)));
2663	}
2664	return SPECIFIC_INT_RESTART;
2665#endif
2666#ifdef A_int_debug_idle
2667    case A_int_debug_idle:
2668	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2669	    printk("scsi%d : idle\n", host->host_no);
2670	}
2671	return SPECIFIC_INT_RESTART;
2672#endif
2673#ifdef A_int_debug_cmd
2674    case A_int_debug_cmd:
2675	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2676	    printk("scsi%d : command sent\n");
2677	}
2678    	return SPECIFIC_INT_RESTART;
2679#endif
2680#ifdef A_int_debug_dsa_loaded
2681    case A_int_debug_dsa_loaded:
2682	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2683	    printk("scsi%d : DSA loaded with 0x%x (virt 0x%p)\n", host->host_no,
2684		NCR53c7x0_read32(DSA_REG),
2685		bus_to_virt(NCR53c7x0_read32(DSA_REG)));
2686	}
2687	return SPECIFIC_INT_RESTART;
2688#endif
2689#ifdef A_int_debug_reselected
2690    case A_int_debug_reselected:
2691	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2692	    OPTION_DEBUG_DISCONNECT)) {
2693	    printk("scsi%d : reselected by target %d lun %d\n",
2694		host->host_no, (int) NCR53c7x0_read8(SDID_REG_800) & ~0x80,
2695		(int) hostdata->reselected_identify & 7);
2696	    print_queues(host);
2697	}
2698    	return SPECIFIC_INT_RESTART;
2699#endif
2700#ifdef A_int_debug_disconnect_msg
2701    case A_int_debug_disconnect_msg:
2702	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR)) {
2703	    if (c)
2704		printk("scsi%d : target %d lun %d disconnecting\n",
2705		    host->host_no, c->target, c->lun);
2706	    else
2707		printk("scsi%d : unknown target disconnecting\n",
2708		    host->host_no);
2709	}
2710	return SPECIFIC_INT_RESTART;
2711#endif
2712#ifdef A_int_debug_disconnected
2713    case A_int_debug_disconnected:
2714	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2715		OPTION_DEBUG_DISCONNECT)) {
2716	    printk ("scsi%d : disconnected, new queues are\n",
2717		host->host_no);
2718	    print_queues(host);
2719	    if (c) {
2720		print_insn (host, (u32 *)
2721		    hostdata->sync[c->target].script, "", 1);
2722		print_insn (host, (u32 *)
2723		    hostdata->sync[c->target].script + 2, "", 1);
2724	    }
2725	}
2726	return SPECIFIC_INT_RESTART;
2727#endif
2728#ifdef A_int_debug_panic
2729    case A_int_debug_panic:
2730	printk("scsi%d : int_debug_panic received\n", host->host_no);
2731	print_lots (host);
2732	return SPECIFIC_INT_PANIC;
2733#endif
2734#ifdef A_int_debug_saved
2735    case A_int_debug_saved:
2736    	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2737    	    OPTION_DEBUG_DISCONNECT)) {
2738    	    printk ("scsi%d : saved data pointer 0x%x (virt 0x%p)\n",
2739    	    	host->host_no, cmd->saved_data_pointer,
2740		bus_to_virt (le32_to_cpu(cmd->saved_data_pointer)));
2741    	    print_progress (c);
2742    	}
2743    	return SPECIFIC_INT_RESTART;
2744#endif
2745#ifdef A_int_debug_restored
2746    case A_int_debug_restored:
2747    	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2748    	    OPTION_DEBUG_DISCONNECT)) {
2749    	    if (cmd) {
2750		int size;
2751    	    	printk ("scsi%d : restored data pointer 0x%x (virt 0x%p)\n",
2752    	    	    host->host_no, cmd->saved_data_pointer, bus_to_virt (
2753		    le32_to_cpu(cmd->saved_data_pointer)));
2754		size = print_insn (host, (u32 *)
2755		    bus_to_virt(le32_to_cpu(cmd->saved_data_pointer)), "", 1);
2756		size = print_insn (host, (u32 *)
2757		    bus_to_virt(le32_to_cpu(cmd->saved_data_pointer)) + size, "", 1);
2758    	    	print_progress (c);
2759	    }
2760    	}
2761    	return SPECIFIC_INT_RESTART;
2762#endif
2763#ifdef A_int_debug_sync
2764    case A_int_debug_sync:
2765    	if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2766    	    OPTION_DEBUG_DISCONNECT|OPTION_DEBUG_SDTR)) {
2767	    unsigned char sxfer = NCR53c7x0_read8 (SXFER_REG),
2768		scntl3 = NCR53c7x0_read8 (SCNTL3_REG_800);
2769	    if (c) {
2770		if (sxfer != hostdata->sync[c->target].sxfer_sanity ||
2771		    scntl3 != hostdata->sync[c->target].scntl3_sanity) {
2772		   	printk ("scsi%d :  sync sanity check failed sxfer=0x%x, scntl3=0x%x",
2773			    host->host_no, sxfer, scntl3);
2774			NCR53c7x0_write8 (SXFER_REG, sxfer);
2775			NCR53c7x0_write8 (SCNTL3_REG_800, scntl3);
2776		    }
2777	    } else
2778    	    	printk ("scsi%d : unknown command sxfer=0x%x, scntl3=0x%x\n",
2779		    host->host_no, (int) sxfer, (int) scntl3);
2780	}
2781    	return SPECIFIC_INT_RESTART;
2782#endif
2783#ifdef A_int_debug_datain
2784	case A_int_debug_datain:
2785	    if (hostdata->options & (OPTION_DEBUG_SCRIPT|OPTION_DEBUG_INTR|
2786		OPTION_DEBUG_DISCONNECT|OPTION_DEBUG_SDTR)) {
2787		int size;
2788		printk ("scsi%d : In do_datain (%s) sxfer=0x%x, scntl3=0x%x\n"
2789			"         datapath residual=%d\n",
2790		    host->host_no, sbcl_to_phase (NCR53c7x0_read8 (SBCL_REG)),
2791		    (int) NCR53c7x0_read8(SXFER_REG),
2792		    (int) NCR53c7x0_read8(SCNTL3_REG_800),
2793		    datapath_residual (host)) ;
2794		print_insn (host, dsp, "", 1);
2795		size = print_insn (host, (u32 *) bus_to_virt(le32_to_cpu(dsp[1])), "", 1);
2796		print_insn (host, (u32 *) bus_to_virt(le32_to_cpu(dsp[1])) + size, "", 1);
2797	   }
2798	return SPECIFIC_INT_RESTART;
2799#endif
2800#ifdef A_int_debug_check_dsa
2801	case A_int_debug_check_dsa:
2802	    if (NCR53c7x0_read8 (SCNTL1_REG) & SCNTL1_CON) {
2803		int sdid = NCR53c7x0_read8 (SDID_REG_800) & 15;
2804		char *where = dsp - NCR53c7x0_insn_size(NCR53c7x0_read8
2805			(DCMD_REG)) == hostdata->script +
2806		    	Ent_select_check_dsa / sizeof(u32) ?
2807		    "selection" : "reselection";
2808		if (c && sdid != c->target) {
2809		    printk ("scsi%d : SDID target %d != DSA target %d at %s\n",
2810			host->host_no, sdid, c->target, where);
2811		    print_lots(host);
2812		    dump_events (host, 20);
2813		    return SPECIFIC_INT_PANIC;
2814		}
2815	    }
2816	    return SPECIFIC_INT_RESTART;
2817#endif
2818    default:
2819	if ((dsps & 0xff000000) == 0x03000000) {
2820	     printk ("scsi%d : misc debug interrupt 0x%x\n",
2821		host->host_no, dsps);
2822	    return SPECIFIC_INT_RESTART;
2823	} else if ((dsps & 0xff000000) == 0x05000000) {
2824	    if (hostdata->events) {
2825		struct NCR53c7x0_event *event;
2826		++hostdata->event_index;
2827		if (hostdata->event_index >= hostdata->event_size)
2828		    hostdata->event_index = 0;
2829		event = (struct NCR53c7x0_event *) hostdata->events +
2830		    hostdata->event_index;
2831		event->event = (enum ncr_event) dsps;
2832		event->dsa = bus_to_virt(NCR53c7x0_read32(DSA_REG));
2833		if (NCR53c7x0_read8 (SCNTL1_REG) & SCNTL1_CON)
2834			event->target = NCR53c7x0_read8(SSID_REG_800);
2835		else
2836			event->target = 255;
2837
2838		if (event->event == EVENT_RESELECT)
2839		    event->lun = hostdata->reselected_identify & 0xf;
2840		else if (c)
2841		    event->lun = c->lun;
2842		else
2843		    event->lun = 255;
2844		do_gettimeofday(&(event->time));
2845		if (c) {
2846		    event->pid = c->pid;
2847		    memcpy ((void *) event->cmnd, (void *) c->cmnd,
2848			sizeof (event->cmnd));
2849		} else {
2850		    event->pid = -1;
2851		}
2852	    }
2853	    return SPECIFIC_INT_RESTART;
2854	}
2855
2856	printk ("scsi%d : unknown user interrupt 0x%x\n",
2857	    host->host_no, (unsigned) dsps);
2858	return SPECIFIC_INT_PANIC;
2859    }
2860}
2861
2862
2863#include "53c8xx_u.h"
2864
2865
2866
2867#ifdef NCR_DEBUG
2868/*
2869 * Debugging without a debugger is no fun. So, I've provided
2870 * a debugging interface in the NCR53c7x0 driver.  To avoid
2871 * kernel cruft, there's just enough here to act as an interface
2872 * to a user level debugger (aka, GDB).
2873 *
2874 *
2875 * The following restrictions apply to debugger commands :
2876 * 1.  The command must be terminated by a newline.
2877 * 2.  Command length must be less than 80 bytes including the
2878 * 	newline.
2879 * 3.  The entire command must be written with one system call.
2880 */
2881
2882static const char debugger_help =
2883"bc <addr> 			- clear breakpoint\n"
2884"bl				- list breakpoints\n"
2885"bs <addr>			- set breakpoint\n"
2886"g				- start\n"
2887"h				- halt\n"
2888"?				- this message\n"
2889"i				- info\n"
2890"mp <addr> <size> 		- print memory\n"
2891"ms <addr> <size> <value>	- store memory\n"
2892"rp <num> <size>		- print register\n"
2893"rs <num> <size> <value> 	- store register\n"
2894"s                              - single step\n"
2895"tb				- begin trace \n"
2896"te				- end trace\n";
2897
2898/*
2899 * Whenever we change a break point, we should probably
2900 * set the NCR up so that it is in a single step mode.
2901 */
2902
2903static int debugger_fn_bc (struct Scsi_Host *host, struct debugger_token *token,
2904    u32 args[]) {
2905    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2906	instance->hostdata;
2907    struct NCR53c7x0_break *bp, **prev;
2908    unsigned long flags;
2909    save_flags(flags);
2910    cli();
2911    for (bp = (struct NCR53c7x0_break *) instance->breakpoints,
2912	    prev = (struct NCR53c7x0_break **) &instance->breakpoints;
2913	    bp; prev = (struct NCR53c7x0_break **) &(bp->next),
2914	    bp = (struct NCR53c7x0_break *) bp->next);
2915
2916    if (!bp) {
2917	restore_flags(flags);
2918	return -EIO;
2919    }
2920
2921
2922    memcpy ((void *) bp->addr, (void *) bp->old, sizeof(bp->old));
2923    if (prev)
2924	*prev = bp->next;
2925
2926    restore_flags(flags);
2927    return 0;
2928}
2929
2930
2931static int
2932debugger_fn_bl (struct Scsi_Host *host, struct debugger_token *token,
2933    u32 args[]) {
2934    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2935	host->hostdata;
2936    struct NCR53c7x0_break *bp;
2937    char buf[80];
2938    size_t len;
2939    unsigned long flags;
2940
2941    sprintf (buf, "scsi%d : bp : warning : processor not halted\b",
2942	host->host_no);
2943    debugger_kernel_write (host, buf, strlen(buf));
2944
2945    save_flags(flags);
2946    cli();
2947    for (bp = (struct NCR53c7x0_break *) host->breakpoints;
2948	    bp; bp = (struct NCR53c7x0_break *) bp->next) {
2949	    sprintf (buf, "scsi%d : bp : success : at %08x, replaces %08x %08x",
2950		bp->addr, bp->old[0], bp->old[1]);
2951	    len = strlen(buf);
2952	    if ((bp->old[0] & (DCMD_TYPE_MASK << 24)) ==
2953		(DCMD_TYPE_MMI << 24)) {
2954		sprintf(buf + len, "%08x\n", * (u32 *) bp->addr);
2955	    } else {
2956		sprintf(buf + len, "\n");
2957	    }
2958	    len = strlen(buf);
2959	    debugger_kernel_write (host, buf, len);
2960    }
2961    restore_flags(flags);
2962    return 0;
2963}
2964
2965static int
2966debugger_fn_bs (struct Scsi_Host *host, struct debugger_token *token,
2967    u32 args[]) {
2968    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
2969	host->hostdata;
2970    struct NCR53c7x0_break *bp;
2971    char buf[80];
2972    size_t len;
2973    unsigned long flags;
2974    save_flags(flags);
2975    cli();
2976
2977    if (hostdata->state != STATE_HALTED) {
2978	sprintf (buf, "scsi%d : bs : failure : NCR not halted\n", host->host_no);
2979	debugger_kernel_write (host, buf, strlen(buf));
2980	restore_flags(flags);
2981	return -1;
2982    }
2983
2984    if (!(bp = kmalloc (sizeof (struct NCR53c7x0_break)))) {
2985	printk ("scsi%d : kmalloc(%d) of breakpoint structure failed, try again\n",
2986	    host->host_no, sizeof(struct NCR53c7x0_break));
2987	restore_flags(flags);
2988	return -1;
2989    }
2990
2991    bp->address = (u32 *) args[0];
2992    memcpy ((void *) bp->old_instruction, (void *) bp->address, 8);
2993    bp->old_size = (((bp->old_instruction[0] >> 24) & DCMD_TYPE_MASK) ==
2994	DCMD_TYPE_MMI ? 3 : 2;
2995    bp->next = hostdata->breakpoints;
2996    hostdata->breakpoints = bp->next;
2997    memcpy ((void *) bp->address, (void *) hostdata->E_debug_break, 8);
2998
2999    restore_flags(flags);
3000    return 0;
3001}
3002
3003#define TOKEN(name,nargs) {#name, nargs, debugger_fn_##name}
3004static const struct debugger_token {
3005    char *name;
3006    int numargs;
3007    int (*fn)(struct debugger_token *token, u32 args[]);
3008} debugger_tokens[] = {
3009    TOKEN(bc,1), TOKEN(bl,0), TOKEN(bs,1), TOKEN(g,0), TOKEN(halt,0),
3010    {DT_help, "?", 0} , TOKEN(h,0), TOKEN(i,0), TOKEN(mp,2),
3011    TOKEN(ms,3), TOKEN(rp,2), TOKEN(rs,2), TOKEN(s,0), TOKEN(tb,0), TOKEN(te,0)
3012};
3013
3014#define NDT sizeof(debugger_tokens / sizeof(struct debugger_token))
3015
3016static struct Scsi_Host * inode_to_host (struct inode *inode) {
3017    int dev;
3018    struct Scsi_Host *tmp;
3019    for (dev = MINOR(inode->rdev), host = first_host;
3020	(host->hostt == the_template); --dev, host = host->next)
3021	if (!dev) return host;
3022    return NULL;
3023}
3024
3025
3026static int
3027debugger_user_write (struct inode *inode,struct file *filp,
3028    char *buf,int count) {
3029    struct Scsi_Host *host;			/* This SCSI host */
3030    struct NCR53c7x0_hostadata *hostdata;
3031    char input_buf[80], 			/* Kernel space copy of buf */
3032	*ptr;					/* Pointer to argument list */
3033    u32 args[3];				/* Arguments */
3034    int i, j, error, len;
3035
3036    if (!(host = inode_to_host(inode)))
3037	return -ENXIO;
3038
3039    hostdata = (struct NCR53c7x0_hostdata *) host->hostdata;
3040
3041    if (error = verify_area(VERIFY_READ,buf,count))
3042	return error;
3043
3044    if (count > 80)
3045	return -EIO;
3046
3047    memcpy_from_fs(input_buf, buf, count);
3048
3049    if (input_buf[count - 1] != '\n')
3050	return -EIO;
3051
3052    input_buf[count - 1]=0;
3053
3054    for (i = 0; i < NDT; ++i) {
3055	len = strlen (debugger_tokens[i].name);
3056	if (!strncmp(input_buf, debugger_tokens[i].name, len))
3057	    break;
3058    };
3059
3060    if (i == NDT)
3061	return -EIO;
3062
3063    for (ptr = input_buf + len, j = 0; j < debugger_tokens[i].nargs && *ptr;) {
3064	if (*ptr == ' ' || *ptr == '\t') {
3065	    ++ptr;
3066	} else if (isdigit(*ptr)) {
3067	    args[j++] = simple_strtoul (ptr, &ptr, 0);
3068	} else {
3069	    return -EIO;
3070	}
3071    }
3072
3073    if (j != debugger_tokens[i].nargs)
3074	return -EIO;
3075
3076    return count;
3077}
3078
3079static int
3080debugger_user_read (struct inode *inode,struct file *filp,
3081    char *buf,int count) {
3082    struct Scsi_Host *instance;
3083
3084}
3085
3086static int
3087debugger_kernel_write (struct Scsi_Host *host, char *buf, size_t
3088    buflen) {
3089    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
3090	host->hostdata;
3091    int copy, left;
3092    unsigned long flags;
3093    save_flags(flags);
3094    cli();
3095    while (buflen) {
3096	left = (hostdata->debug_buf + hostdata->debug_size - 1) -
3097	    hostdata->debug_write;
3098	copy = (buflen <= left) ? buflen : left;
3099	memcpy (hostdata->debug_write, buf, copy);
3100	buf += copy;
3101	buflen -= copy;
3102	hostdata->debug_count += copy;
3103	if ((hostdata->debug_write += copy) ==
3104	    (hostdata->debug_buf + hostdata->debug_size))
3105	    hosdata->debug_write = hostdata->debug_buf;
3106    }
3107    restore_flags(flags);
3108}
3109
3110#endif /* def NCRDEBUG */
3111
3112/*
3113 * Function : static void NCR538xx_soft_reset (struct Scsi_Host *host)
3114 *
3115 * Purpose :  perform a soft reset of the NCR53c8xx chip
3116 *
3117 * Inputs : host - pointer to this host adapter's structure
3118 *
3119 * Preconditions : NCR53c7x0_init must have been called for this
3120 *      host.
3121 *
3122 */
3123
3124static void
3125NCR53c8x0_soft_reset (struct Scsi_Host *host) {
3126    NCR53c7x0_local_declare();
3127    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
3128	host->hostdata;
3129    NCR53c7x0_local_setup(host);
3130
3131
3132    /*
3133     * Do a soft reset of the chip so that everything is
3134     * reinitialized to the power-on state.
3135     *
3136     * Basically follow the procedure outlined in the NCR53c700
3137     * data manual under Chapter Six, How to Use, Steps Necessary to
3138     * Start SCRIPTS, with the exception of actually starting the
3139     * script and setting up the synchronous transfer gunk.
3140     */
3141
3142    NCR53c7x0_write8(ISTAT_REG_800, ISTAT_10_SRST);
3143    NCR53c7x0_write8(ISTAT_REG_800, 0);
3144    NCR53c7x0_write8(hostdata->dmode, hostdata->saved_dmode & ~DMODE_MAN);
3145
3146
3147
3148#ifdef notyet
3149    NCR53c7x0_write8(SCID_REG, (host->this_id & 7)|SCID_800_RRE|SCID_800_SRE);
3150#else
3151    NCR53c7x0_write8(SCID_REG, (host->this_id & 7)|SCID_800_RRE);
3152#endif
3153    NCR53c7x0_write8(RESPID_REG_800, hostdata->this_id_mask);
3154
3155    /*
3156     * Use a maximum (1.6) second handshake to handshake timeout,
3157     * and SCSI recommended .5s selection timeout.
3158     */
3159
3160    /*
3161     * The new gcc won't recognize preprocessing directives
3162     * within macro args.
3163     */
3164/* Disable HTH interrupt */
3165    NCR53c7x0_write8(STIME0_REG_800,
3166    	((selection_timeout << STIME0_800_SEL_SHIFT) & STIME0_800_SEL_MASK));
3167
3168
3169    /*
3170     * Enable active negation for happy synchronous transfers.
3171     */
3172
3173    NCR53c7x0_write8(STEST3_REG_800, STEST3_800_TE);
3174
3175    /*
3176     * Enable all interrupts, except parity which we only want when
3177     * the user requests it.
3178     */
3179
3180    NCR53c7x0_write8(DIEN_REG, DIEN_800_MDPE | DIEN_800_BF |
3181		DIEN_ABRT | DIEN_SSI | DIEN_SIR | DIEN_800_IID);
3182
3183
3184    NCR53c7x0_write8(SIEN0_REG_800, ((hostdata->options & OPTION_PARITY) ?
3185	    SIEN_PAR : 0) | SIEN_RST | SIEN_UDC | SIEN_SGE | SIEN_MA);
3186    NCR53c7x0_write8(SIEN1_REG_800, SIEN1_800_STO | SIEN1_800_HTH);
3187
3188    /*
3189     * Use saved clock frequency divisor and scripts loaded in 16 bit
3190     * mode flags from the saved dcntl.
3191     */
3192
3193    NCR53c7x0_write8(DCNTL_REG, hostdata->saved_dcntl);
3194    NCR53c7x0_write8(CTEST4_REG_800, hostdata->saved_ctest4);
3195
3196    /* Enable active negation */
3197    NCR53c7x0_write8(STEST3_REG_800, STEST3_800_TE);
3198}
3199
3200/*
3201 * Function static struct NCR53c7x0_cmd *allocate_cmd (Scsi_Cmnd *cmd)
3202 *
3203 * Purpose : Return the first free NCR53c7x0_cmd structure (which are
3204 * 	reused in a LIFO manner to minimize cache thrashing).
3205 *
3206 * Side effects : If we haven't yet scheduled allocation of NCR53c7x0_cmd
3207 *	structures for this device, do so.  Attempt to complete all scheduled
3208 *	allocations using kmalloc(), putting NCR53c7x0_cmd structures on
3209 *	the free list.  Teach programmers not to drink and hack.
3210 *
3211 * Inputs : cmd - SCSI command
3212 *
3213 * Returns : NCR53c7x0_cmd structure allocated on behalf of cmd;
3214 *	NULL on failure.
3215 */
3216
3217static struct NCR53c7x0_cmd *
3218allocate_cmd (Scsi_Cmnd *cmd) {
3219    struct Scsi_Host *host = cmd->host;
3220    struct NCR53c7x0_hostdata *hostdata =
3221	(struct NCR53c7x0_hostdata *) host->hostdata;
3222    void *real;			/* Real address */
3223    int size;			/* Size of *tmp */
3224    struct NCR53c7x0_cmd *tmp;
3225    unsigned long flags;
3226
3227    if (hostdata->options & OPTION_DEBUG_ALLOCATION)
3228	printk ("scsi%d : num_cmds = %d, can_queue = %d\n"
3229		"         target = %d, lun = %d, %s\n",
3230	    host->host_no, hostdata->num_cmds, host->can_queue,
3231	    cmd->target, cmd->lun, (hostdata->cmd_allocated[cmd->target] &
3232		(1 << cmd->lun)) ? "already allocated" : "not allocated");
3233
3234/*
3235 * If we have not yet reserved commands for this I_T_L nexus, and
3236 * the device exists (as indicated by permanent Scsi_Cmnd structures
3237 * being allocated under 1.3.x, or being outside of scan_scsis in
3238 * 1.2.x), do so now.
3239 */
3240    if (!(hostdata->cmd_allocated[cmd->target] & (1 << cmd->lun)) &&
3241				cmd->device && cmd->device->has_cmdblocks
3242	) {
3243	if ((hostdata->extra_allocate + hostdata->num_cmds) < host->can_queue)
3244	    hostdata->extra_allocate += host->cmd_per_lun;
3245	hostdata->cmd_allocated[cmd->target] |= (1 << cmd->lun);
3246    }
3247
3248    for (; hostdata->extra_allocate > 0 ; --hostdata->extra_allocate,
3249    	++hostdata->num_cmds) {
3250    /* historically, kmalloc has returned unaligned addresses; pad so we
3251       have enough room to ROUNDUP */
3252	size = hostdata->max_cmd_size + sizeof (void *);
3253	real = kmalloc (size, GFP_ATOMIC);
3254	if (!real) {
3255	    if (hostdata->options & OPTION_DEBUG_ALLOCATION)
3256		printk ("scsi%d : kmalloc(%d) failed\n",
3257		    host->host_no, size);
3258	    break;
3259	}
3260	tmp = ROUNDUP(real, void *);
3261	tmp->real = real;
3262	tmp->size = size;
3263	tmp->free = ((void (*)(void *, int)) kfree);
3264	save_flags (flags);
3265	cli();
3266	tmp->next = hostdata->free;
3267	hostdata->free = tmp;
3268	restore_flags (flags);
3269    }
3270    save_flags(flags);
3271    cli();
3272    tmp = (struct NCR53c7x0_cmd *) hostdata->free;
3273    if (tmp) {
3274	hostdata->free = tmp->next;
3275    }
3276    restore_flags(flags);
3277    if (!tmp)
3278	printk ("scsi%d : can't allocate command for target %d lun %d\n",
3279	    host->host_no, cmd->target, cmd->lun);
3280    return tmp;
3281}
3282
3283/*
3284 * Function static struct NCR53c7x0_cmd *create_cmd (Scsi_Cmnd *cmd)
3285 *
3286 *
3287 * Purpose : allocate a NCR53c7x0_cmd structure, initialize it based on the
3288 * 	Scsi_Cmnd structure passed in cmd, including dsa and Linux field
3289 * 	initialization, and dsa code relocation.
3290 *
3291 * Inputs : cmd - SCSI command
3292 *
3293 * Returns : NCR53c7x0_cmd structure corresponding to cmd,
3294 *	NULL on failure.
3295 */
3296
3297static struct NCR53c7x0_cmd *
3298create_cmd (Scsi_Cmnd *cmd) {
3299    NCR53c7x0_local_declare();
3300    struct Scsi_Host *host = cmd->host;
3301    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
3302        host->hostdata;
3303    struct NCR53c7x0_cmd *tmp; 	/* NCR53c7x0_cmd structure for this command */
3304    int datain,  		/* Number of instructions per phase */
3305	dataout;
3306    int data_transfer_instructions, /* Count of dynamic instructions */
3307    	i;			/* Counter */
3308    u32 *cmd_datain,		/* Address of datain/dataout code */
3309	*cmd_dataout;		/* Incremented as we assemble */
3310#ifdef notyet
3311    unsigned char *msgptr;	/* Current byte in select message */
3312    int msglen;			/* Length of whole select message */
3313#endif
3314    unsigned long flags;
3315    NCR53c7x0_local_setup(cmd->host);
3316
3317    if (!(tmp = allocate_cmd (cmd)))
3318	return NULL;
3319
3320
3321    /*
3322     * Decide whether we need to generate commands for DATA IN,
3323     * DATA OUT, neither, or both based on the SCSI command
3324     */
3325
3326    switch (cmd->cmnd[0]) {
3327    /* These commands do DATA IN */
3328    case INQUIRY:
3329    case MODE_SENSE:
3330    case READ_6:
3331    case READ_10:
3332    case READ_CAPACITY:
3333    case REQUEST_SENSE:
3334	datain = 2 * (cmd->use_sg ? cmd->use_sg : 1) + 3;
3335    	dataout = 0;
3336	break;
3337    /* These commands do DATA OUT */
3338    case MODE_SELECT:
3339    case WRITE_6:
3340    case WRITE_10:
3341    	datain = 0;
3342	dataout = 2 * (cmd->use_sg ? cmd->use_sg : 1) + 3;
3343	break;
3344    /*
3345     * These commands do no data transfer, we should force an
3346     * interrupt if a data phase is attempted on them.
3347     */
3348    case START_STOP: /* also SCAN, which may do DATA OUT */
3349    case TEST_UNIT_READY:
3350    	datain = dataout = 0;
3351	break;
3352    /*
3353     * We don't know about these commands, so generate code to handle
3354     * both DATA IN and DATA OUT phases.
3355     */
3356    default:
3357	datain = dataout = 2 * (cmd->use_sg ? cmd->use_sg : 1) + 3;
3358    }
3359
3360    /*
3361     * New code : so that active pointers work correctly regardless
3362     * 	of where the saved data pointer is at, we want to immediately
3363     * 	enter the dynamic code after selection, and on a non-data
3364     * 	phase perform a CALL to the non-data phase handler, with
3365     * 	returns back to this address.
3366     *
3367     * 	If a phase mismatch is encountered in the middle of a
3368     * 	Block MOVE instruction, we want to _leave_ that instruction
3369     *	unchanged as the current case is, modify a temporary buffer,
3370     *	and point the active pointer (TEMP) at that.
3371     *
3372     * 	Furthermore, we want to implement a saved data pointer,
3373     * 	set by the SAVE_DATA_POINTERs message.
3374     *
3375     * 	So, the data transfer segments will change to
3376     *		CALL data_transfer, WHEN NOT data phase
3377     *		MOVE x, x, WHEN data phase
3378     *		( repeat )
3379     *		JUMP other_transfer
3380     */
3381
3382    data_transfer_instructions = datain + dataout;
3383
3384    /*
3385     * When we perform a request sense, we overwrite various things,
3386     * including the data transfer code.  Make sure we have enough
3387     * space to do that.
3388     */
3389
3390    if (data_transfer_instructions < 2)
3391    	data_transfer_instructions = 2;
3392
3393
3394    /*
3395     * The saved data pointer is set up so that a RESTORE POINTERS message
3396     * will start the data transfer over at the beginning.
3397     */
3398
3399    tmp->saved_data_pointer = le32_to_cpu(virt_to_bus (hostdata->script) +
3400	hostdata->E_data_transfer);
3401
3402    /*
3403     * Initialize Linux specific fields.
3404     */
3405
3406    tmp->cmd = cmd;
3407    tmp->next = NULL;
3408    tmp->flags = 0;
3409    tmp->dsa_next_addr = le32_to_cpu(virt_to_bus(tmp->dsa) + hostdata->dsa_next -
3410	hostdata->dsa_start);
3411    tmp->dsa_addr = le32_to_cpu(virt_to_bus(tmp->dsa) - hostdata->dsa_start);
3412
3413    /*
3414     * Calculate addresses of dynamic code to fill in DSA
3415     */
3416
3417    tmp->data_transfer_start = tmp->dsa + (hostdata->dsa_end -
3418    	hostdata->dsa_start) / sizeof(u32);
3419    tmp->data_transfer_end = tmp->data_transfer_start +
3420    	2 * data_transfer_instructions;
3421
3422    cmd_datain = datain ? tmp->data_transfer_start : NULL;
3423    cmd_dataout = dataout ? (datain ? cmd_datain + 2 * datain : tmp->
3424    	data_transfer_start) : NULL;
3425
3426    /*
3427     * Fill in the NCR53c7x0_cmd structure as follows
3428     * dsa, with fixed up DSA code
3429     * datain code
3430     * dataout code
3431     */
3432
3433    /* Copy template code into dsa and perform all necessary fixups */
3434    if (hostdata->dsa_fixup)
3435    	hostdata->dsa_fixup(tmp);
3436
3437    patch_dsa_32(tmp->dsa, dsa_next, 0, le32_to_cpu(0));
3438    patch_dsa_32(tmp->dsa, dsa_cmnd, 0, le32_to_cpu(virt_to_bus(cmd)));
3439
3440    if (hostdata->options & OPTION_DEBUG_SYNCHRONOUS)
3441	if (hostdata->sync[cmd->target].select_indirect !=
3442	    ((hostdata->sync[cmd->target].scntl3_sanity << 24) |
3443		(cmd->target << 16) |
3444		(hostdata->sync[cmd->target].sxfer_sanity << 8))) {
3445	    printk ("scsi%d :  sanity check failed select_indirect=0x%x\n",
3446		host->host_no, hostdata->sync[cmd->target].select_indirect);
3447	    FATAL(host);
3448
3449	}
3450
3451    patch_dsa_32(tmp->dsa, dsa_select, 0, le32_to_cpu(hostdata->sync[cmd->target].
3452    	select_indirect));
3453    /*
3454     * Right now, we'll do the WIDE and SYNCHRONOUS negotiations on
3455     * different commands; although it should be trivial to do them
3456     * both at the same time.
3457     */
3458    if (hostdata->initiate_wdtr & (1 << cmd->target)) {
3459	memcpy ((void *) (tmp->select + 1), (void *) wdtr_message,
3460	    sizeof(wdtr_message));
3461    	patch_dsa_32(tmp->dsa, dsa_msgout, 0, le32_to_cpu(1 + sizeof(wdtr_message)));
3462	save_flags(flags);
3463	cli();
3464	hostdata->initiate_wdtr &= ~(1 << cmd->target);
3465	restore_flags(flags);
3466    } else if (hostdata->initiate_sdtr & (1 << cmd->target)) {
3467	memcpy ((void *) (tmp->select + 1), (void *) sdtr_message,
3468	    sizeof(sdtr_message));
3469    	patch_dsa_32(tmp->dsa, dsa_msgout, 0, le32_to_cpu(1 + sizeof(sdtr_message)));
3470	tmp->flags |= CMD_FLAG_SDTR;
3471	save_flags(flags);
3472	cli();
3473	hostdata->initiate_sdtr &= ~(1 << cmd->target);
3474	restore_flags(flags);
3475
3476    }
3477    else if (!(hostdata->talked_to & (1 << cmd->target)) &&
3478		!(hostdata->options & OPTION_NO_ASYNC)) {
3479	memcpy ((void *) (tmp->select + 1), (void *) async_message,
3480	    sizeof(async_message));
3481    	patch_dsa_32(tmp->dsa, dsa_msgout, 0, le32_to_cpu(1 + sizeof(async_message)));
3482	tmp->flags |= CMD_FLAG_SDTR;
3483    }
3484    else
3485    	patch_dsa_32(tmp->dsa, dsa_msgout, 0, le32_to_cpu(1));
3486    hostdata->talked_to |= (1 << cmd->target);
3487    tmp->select[0] = (hostdata->options & OPTION_DISCONNECT) ?
3488	IDENTIFY (1, cmd->lun) : IDENTIFY (0, cmd->lun);
3489    patch_dsa_32(tmp->dsa, dsa_msgout, 1, le32_to_cpu(virt_to_bus(tmp->select)));
3490    patch_dsa_32(tmp->dsa, dsa_cmdout, 0, le32_to_cpu(cmd->cmd_len));
3491    patch_dsa_32(tmp->dsa, dsa_cmdout, 1, le32_to_cpu(virt_to_bus(cmd->cmnd)));
3492    patch_dsa_32(tmp->dsa, dsa_dataout, 0, le32_to_cpu(cmd_dataout ?
3493    	    virt_to_bus (cmd_dataout)
3494	: virt_to_bus (hostdata->script) + hostdata->E_other_transfer));
3495    patch_dsa_32(tmp->dsa, dsa_datain, 0, le32_to_cpu(cmd_datain ?
3496    	    virt_to_bus (cmd_datain)
3497	: virt_to_bus (hostdata->script) + hostdata->E_other_transfer));
3498    patch_dsa_32(tmp->dsa, dsa_msgin, 0, le32_to_cpu(1));
3499    patch_dsa_32(tmp->dsa, dsa_msgin, 1, le32_to_cpu(virt_to_bus(&cmd->result) + 1));
3500    patch_dsa_32(tmp->dsa, dsa_status, 0, le32_to_cpu(1));
3501    patch_dsa_32(tmp->dsa, dsa_status, 1, le32_to_cpu(virt_to_bus(&cmd->result)));
3502    patch_dsa_32(tmp->dsa, dsa_msgout_other, 0, le32_to_cpu(1));
3503    patch_dsa_32(tmp->dsa, dsa_msgout_other, 1,
3504	le32_to_cpu(virt_to_bus(&(hostdata->NCR53c7xx_msg_nop))));
3505
3506    /*
3507     * Generate code for zero or more of the DATA IN, DATA OUT phases
3508     * in the format
3509     *
3510     * CALL data_transfer, WHEN NOT phase
3511     * MOVE first buffer length, first buffer address, WHEN phase
3512     * ...
3513     * MOVE last buffer length, last buffer address, WHEN phase
3514     * JUMP other_transfer
3515     */
3516
3517/*
3518 * See if we're getting to data transfer by generating an unconditional
3519 * interrupt.
3520 */
3521
3522
3523    for (i = 0; cmd->use_sg ? (i < cmd->use_sg) : !i; cmd_datain += 4,
3524	cmd_dataout += 4, ++i) {
3525	u32 buf = cmd->use_sg ?
3526	    virt_to_bus(((struct scatterlist *)cmd->buffer)[i].address) :
3527	    virt_to_bus(cmd->request_buffer);
3528	u32 count = cmd->use_sg ?
3529	    ((struct scatterlist *)cmd->buffer)[i].length :
3530	    cmd->request_bufflen;
3531
3532	if (datain) {
3533	    /* CALL other_in, WHEN NOT DATA_IN */
3534	    cmd_datain[0] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_CALL |
3535		DCMD_TCI_IO) << 24) |
3536		DBC_TCI_WAIT_FOR_VALID | DBC_TCI_COMPARE_PHASE);
3537	    cmd_datain[1] = le32_to_cpu(virt_to_bus (hostdata->script) +
3538		hostdata->E_other_in);
3539	    /* MOVE count, buf, WHEN DATA_IN */
3540	    cmd_datain[2] = le32_to_cpu(((DCMD_TYPE_BMI | DCMD_BMI_OP_MOVE_I | DCMD_BMI_IO)
3541    	    	<< 24) | count);
3542	    cmd_datain[3] = le32_to_cpu(buf);
3543	}
3544	if (dataout) {
3545	    /* CALL other_out, WHEN NOT DATA_OUT */
3546	    cmd_dataout[0] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_CALL) << 24) |
3547		DBC_TCI_WAIT_FOR_VALID | DBC_TCI_COMPARE_PHASE);
3548	    cmd_dataout[1] = le32_to_cpu(virt_to_bus(hostdata->script) +
3549    	    	hostdata->E_other_out);
3550	    /* MOVE count, buf, WHEN DATA+OUT */
3551	    cmd_dataout[2] = le32_to_cpu(((DCMD_TYPE_BMI | DCMD_BMI_OP_MOVE_I) << 24)
3552		| count);
3553	    cmd_dataout[3] = le32_to_cpu(buf);
3554	}
3555    }
3556
3557    /*
3558     * Install JUMP instructions after the data transfer routines to return
3559     * control to the do_other_transfer routines.
3560     */
3561
3562
3563    if (datain) {
3564	cmd_datain[0] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_JUMP) << 24) |
3565    	    DBC_TCI_TRUE);
3566	cmd_datain[1] = le32_to_cpu(virt_to_bus(hostdata->script) +
3567    	    hostdata->E_other_transfer);
3568	cmd_datain += 2;
3569    }
3570    if (dataout) {
3571	cmd_dataout[0] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_JUMP) << 24) |
3572    	    DBC_TCI_TRUE);
3573	cmd_dataout[1] = le32_to_cpu(virt_to_bus(hostdata->script) +
3574    	    hostdata->E_other_transfer);
3575	cmd_dataout += 2;
3576    }
3577    return tmp;
3578}
3579
3580/*
3581 * Function : int NCR53c7xx_queue_command (Scsi_Cmnd *cmd,
3582 *      void (*done)(Scsi_Cmnd *))
3583 *
3584 * Purpose :  enqueues a SCSI command
3585 *
3586 * Inputs : cmd - SCSI command, done - function called on completion, with
3587 *      a pointer to the command descriptor.
3588 *
3589 * Returns : 0
3590 *
3591 * Side effects :
3592 *      cmd is added to the per instance driver issue_queue, with major
3593 *      twiddling done to the host specific fields of cmd.  If the
3594 *      process_issue_queue coroutine isn't running, it is restarted.
3595 *
3596 * NOTE : we use the host_scribble field of the Scsi_Cmnd structure to
3597 *	hold our own data, and pervert the ptr field of the SCp field
3598 *	to create a linked list.
3599 */
3600
3601int
3602NCR53c7xx_queue_command (Scsi_Cmnd *cmd, void (* done)(Scsi_Cmnd *)) {
3603    struct Scsi_Host *host = cmd->host;
3604    struct NCR53c7x0_hostdata *hostdata =
3605	(struct NCR53c7x0_hostdata *) host->hostdata;
3606    unsigned long flags;
3607    Scsi_Cmnd *tmp;
3608
3609    cmd->scsi_done = done;
3610    cmd->host_scribble = NULL;
3611    cmd->SCp.ptr = NULL;
3612    cmd->SCp.buffer = NULL;
3613
3614    save_flags(flags);
3615    cli();
3616    if ((hostdata->options & (OPTION_DEBUG_INIT_ONLY|OPTION_DEBUG_PROBE_ONLY))
3617	|| ((hostdata->options & OPTION_DEBUG_TARGET_LIMIT) &&
3618	    !(hostdata->debug_lun_limit[cmd->target] & (1 << cmd->lun)))
3619	|| cmd->target > host->max_id
3620	|| cmd->target == host->this_id
3621	|| hostdata->state == STATE_DISABLED) {
3622	printk("scsi%d : disabled or bad target %d lun %d\n", host->host_no,
3623	    cmd->target, cmd->lun);
3624	cmd->result = DID_BAD_TARGET << 16;
3625    } else if ((hostdata->options & OPTION_DEBUG_NCOMMANDS_LIMIT) &&
3626	(hostdata->debug_count_limit == 0)) {
3627	printk("scsi%d : maximum commands exceeded\n", host->host_no);
3628	cmd->result = DID_BAD_TARGET << 16;
3629    } else if (hostdata->options & OPTION_DEBUG_READ_ONLY) {
3630	switch (cmd->cmnd[0]) {
3631	case WRITE_6:
3632	case WRITE_10:
3633	    printk("scsi%d : WRITE attempted with NO_WRITE debugging flag set\n",
3634		host->host_no);
3635	    cmd->result = DID_BAD_TARGET << 16;
3636	}
3637    } else {
3638    	if ((hostdata->options & OPTION_DEBUG_TARGET_LIMIT) &&
3639	    hostdata->debug_count_limit != -1)
3640	    --hostdata->debug_count_limit;
3641	restore_flags (flags);
3642	cmd->result = le32_to_cpu(0xffff);	/* The NCR will overwrite message
3643				       and status with valid data */
3644	cmd->host_scribble = (unsigned char *) tmp = create_cmd (cmd);
3645    }
3646    cli();
3647    /*
3648     * REQUEST SENSE commands are inserted at the head of the queue
3649     * so that we do not clear the contingent allegiance condition
3650     * they may be looking at.
3651     */
3652
3653    if (!(hostdata->issue_queue) || (cmd->cmnd[0] == REQUEST_SENSE)) {
3654	cmd->SCp.ptr = (unsigned char *) hostdata->issue_queue;
3655	hostdata->issue_queue = cmd;
3656    } else {
3657	for (tmp = (Scsi_Cmnd *) hostdata->issue_queue; tmp->SCp.ptr;
3658		tmp = (Scsi_Cmnd *) tmp->SCp.ptr);
3659	tmp->SCp.ptr = (unsigned char *) cmd;
3660    }
3661    restore_flags (flags);
3662    run_process_issue_queue();
3663    return 0;
3664}
3665
3666/*
3667 * Function : void to_schedule_list (struct Scsi_Host *host,
3668 * 	struct NCR53c7x0_hostdata * hostdata, Scsi_Cmnd *cmd)
3669 *
3670 * Purpose : takes a SCSI command which was just removed from the
3671 *	issue queue, and deals with it by inserting it in the first
3672 *	free slot in the schedule list or by terminating it immediately.
3673 *
3674 * Inputs :
3675 *	host - SCSI host adapter; hostdata - hostdata structure for
3676 *	this adapter; cmd - a pointer to the command; should have
3677 *	the host_scribble field initialized to point to a valid
3678 *
3679 * Side effects :
3680 *      cmd is added to the per instance schedule list, with minor
3681 *      twiddling done to the host specific fields of cmd.
3682 *
3683 */
3684
3685static __inline__ void
3686to_schedule_list (struct Scsi_Host *host, struct NCR53c7x0_hostdata *hostdata,
3687    struct NCR53c7x0_cmd *cmd) {
3688    NCR53c7x0_local_declare();
3689    Scsi_Cmnd *tmp = cmd->cmd;
3690    unsigned long flags;
3691    /* dsa start is negative, so subtraction is used */
3692    volatile u32 *curr;
3693
3694    int i;
3695    NCR53c7x0_local_setup(host);
3696
3697    save_flags(flags);
3698    cli();
3699
3700    /*
3701     * Work around race condition : if an interrupt fired and we
3702     * got disabled forget about this command.
3703     */
3704
3705    if (hostdata->state == STATE_DISABLED) {
3706	printk("scsi%d : driver disabled\n", host->host_no);
3707	tmp->result = DID_BAD_TARGET << 16;
3708	cmd->next = (struct NCR53c7x0_cmd *) hostdata->free;
3709	hostdata->free = cmd;
3710	tmp->scsi_done(tmp);
3711	restore_flags (flags);
3712	return;
3713    }
3714
3715    for (i = host->can_queue, curr = hostdata->schedule;
3716	i > 0  && curr[0] != hostdata->NOP_insn;
3717	--i, curr += 2 /* JUMP instructions are two words */);
3718
3719    if (i > 0) {
3720	++hostdata->busy[tmp->target][tmp->lun];
3721	cmd->next = hostdata->running_list;
3722	hostdata->running_list = cmd;
3723
3724	/* Restore this instruction to a NOP once the command starts */
3725	cmd->dsa [(hostdata->dsa_jump_dest - hostdata->dsa_start) /
3726	    sizeof(u32)] = (u32) le32_to_cpu(virt_to_bus ((void *)curr));
3727	/* Replace the current jump operand.  */
3728	curr[1] =
3729	    le32_to_cpu(virt_to_bus ((void *) cmd->dsa) + hostdata->E_dsa_code_begin -
3730	    hostdata->E_dsa_code_template);
3731	/* Replace the NOP instruction with a JUMP */
3732	curr[0] = le32_to_cpu(((DCMD_TYPE_TCI|DCMD_TCI_OP_JUMP) << 24) |
3733	    DBC_TCI_TRUE);
3734    }  else {
3735	printk ("scsi%d: no free slot\n", host->host_no);
3736	disable(host);
3737	tmp->result = DID_ERROR << 16;
3738	cmd->next = (struct NCR53c7x0_cmd *) hostdata->free;
3739	hostdata->free = cmd;
3740	tmp->scsi_done(tmp);
3741	restore_flags (flags);
3742	return;
3743    }
3744
3745    /*
3746     * If the NCR chip is in an idle state, start it running the scheduler
3747     * immediately.  Otherwise, signal the chip to jump to schedule as
3748     * soon as it is idle.
3749     */
3750    if (hostdata->idle) {
3751	hostdata->idle = 0;
3752	hostdata->state = STATE_RUNNING;
3753	NCR53c7x0_write32 (DSP_REG,  virt_to_bus ((void *)hostdata->schedule));
3754    } else {
3755	NCR53c7x0_write8(hostdata->istat, ISTAT_10_SIGP);
3756    }
3757
3758    restore_flags(flags);
3759}
3760
3761/*
3762 * Function : busyp (struct Scsi_Host *host, struct NCR53c7x0_hostdata
3763 *	*hostdata, Scsi_Cmnd *cmd)
3764 *
3765 * Purpose : decide if we can pass the given SCSI command on to the
3766 *	device in question or not.
3767 *
3768 * Returns : non-zero when we're busy, 0 when we aren't.
3769 */
3770
3771static __inline__ int
3772busyp (struct Scsi_Host *host, struct NCR53c7x0_hostdata *hostdata,
3773    Scsi_Cmnd *cmd) {
3774    return hostdata->busy[cmd->target][cmd->lun];
3775}
3776
3777/*
3778 * Function : process_issue_queue (void)
3779 *
3780 * Purpose : transfer commands from the issue queue to NCR start queue
3781 *	of each NCR53c7/8xx in the system, avoiding kernel stack
3782 *	overflows when the scsi_done() function is invoked recursively.
3783 *
3784 * NOTE : process_issue_queue exits with interrupts *disabled*, so the
3785 *	caller must reenable them if it desires.
3786 *
3787 * NOTE : process_issue_queue should be called from both
3788 *	NCR53c7x0_queue_command() and from the interrupt handler
3789 *	after command completion in case NCR53c7x0_queue_command()
3790 * 	isn't invoked again but we've freed up resources that are
3791 *	needed.
3792 */
3793
3794static void
3795process_issue_queue (unsigned long flags) {
3796    Scsi_Cmnd *tmp, *prev;
3797    struct Scsi_Host *host;
3798    struct NCR53c7x0_hostdata *hostdata;
3799    int done;
3800
3801    /*
3802     * We run (with interrupts disabled) until we're sure that none of
3803     * the host adapters have anything that can be done, at which point
3804     * we set process_issue_queue_running to 0 and exit.
3805     *
3806     * Interrupts are enabled before doing various other internal
3807     * instructions, after we've decided that we need to run through
3808     * the loop again.
3809     *
3810     */
3811
3812    do {
3813	cli(); /* Freeze request queues */
3814	done = 1;
3815	for (host = first_host; host && host->hostt == the_template;
3816	    host = host->next) {
3817	    hostdata = (struct NCR53c7x0_hostdata *) host->hostdata;
3818	    cli();
3819	    if (hostdata->issue_queue) {
3820	    	if (hostdata->state == STATE_DISABLED) {
3821		    tmp = (Scsi_Cmnd *) hostdata->issue_queue;
3822		    hostdata->issue_queue = (Scsi_Cmnd *) tmp->SCp.ptr;
3823		    tmp->result = DID_BAD_TARGET << 16;
3824		    if (tmp->host_scribble) {
3825			((struct NCR53c7x0_cmd *)tmp->host_scribble)->next =
3826			    hostdata->free;
3827			hostdata->free =
3828			    (struct NCR53c7x0_cmd *)tmp->host_scribble;
3829			tmp->host_scribble = NULL;
3830		    }
3831		    tmp->scsi_done (tmp);
3832		    done = 0;
3833		} else
3834		    for (tmp = (Scsi_Cmnd *) hostdata->issue_queue,
3835			prev = NULL; tmp; prev = tmp, tmp = (Scsi_Cmnd *)
3836			tmp->SCp.ptr)
3837			if (!tmp->host_scribble ||
3838			    !busyp (host, hostdata, tmp)) {
3839				if (prev)
3840				    prev->SCp.ptr = tmp->SCp.ptr;
3841				else
3842				    hostdata->issue_queue = (Scsi_Cmnd *)
3843					tmp->SCp.ptr;
3844			    tmp->SCp.ptr = NULL;
3845			    if (tmp->host_scribble) {
3846				if (hostdata->options & OPTION_DEBUG_QUEUES)
3847				    printk ("scsi%d : moving command for target %d lun %d to start list\n",
3848					host->host_no, tmp->target, tmp->lun);
3849
3850
3851			    	to_schedule_list (host, hostdata,
3852				    (struct NCR53c7x0_cmd *)
3853				    tmp->host_scribble);
3854			    } else {
3855			    	tmp->result = le32_to_cpu(tmp->result);
3856				if (((tmp->result & 0xff) == 0xff) ||
3857			    	    ((tmp->result & 0xff00) == 0xff00)) {
3858				    printk ("scsi%d : danger Will Robinson!\n",
3859					host->host_no);
3860				    tmp->result = DID_ERROR << 16;
3861				    disable (host);
3862				}
3863				tmp->scsi_done(tmp);
3864			    }
3865			    done = 0;
3866			} /* if target/lun is not busy */
3867	    } /* if hostdata->issue_queue */
3868	    if (!done)
3869		restore_flags (flags);
3870    	} /* for host */
3871    } while (!done);
3872    process_issue_queue_running = 0;
3873}
3874
3875/*
3876 * Function : static void intr_scsi (struct Scsi_Host *host,
3877 * 	struct NCR53c7x0_cmd *cmd)
3878 *
3879 * Purpose : handle all SCSI interrupts, indicated by the setting
3880 * 	of the SIP bit in the ISTAT register.
3881 *
3882 * Inputs : host, cmd - host and NCR command causing the interrupt, cmd
3883 * 	may be NULL.
3884 */
3885
3886static void
3887intr_scsi (struct Scsi_Host *host, struct NCR53c7x0_cmd *cmd) {
3888    NCR53c7x0_local_declare();
3889    struct NCR53c7x0_hostdata *hostdata =
3890    	(struct NCR53c7x0_hostdata *) host->hostdata;
3891    unsigned char sstat0_sist0, sist1, 		/* Registers */
3892	    fatal; 				/* Did a fatal interrupt
3893						   occur ? */
3894
3895    int is_8xx_chip;
3896    NCR53c7x0_local_setup(host);
3897
3898    fatal = 0;
3899
3900    is_8xx_chip = ((unsigned) (hostdata->chip - 800)) < 100;
3901    if (is_8xx_chip) {
3902    	sstat0_sist0 = NCR53c7x0_read8(SIST0_REG_800);
3903	udelay(1);
3904    	sist1 = NCR53c7x0_read8(SIST1_REG_800);
3905    } else {
3906    	sstat0_sist0 = NCR53c7x0_read8(SSTAT0_REG);
3907    	sist1 = 0;
3908    }
3909
3910    if (hostdata->options & OPTION_DEBUG_INTR)
3911	printk ("scsi%d : SIST0 0x%0x, SIST1 0x%0x\n", host->host_no,
3912	    sstat0_sist0, sist1);
3913
3914    /* 250ms selection timeout */
3915    if ((is_8xx_chip && (sist1 & SIST1_800_STO)) ||
3916        (!is_8xx_chip && (sstat0_sist0 & SSTAT0_700_STO))) {
3917	fatal = 1;
3918	if (hostdata->options & OPTION_DEBUG_INTR) {
3919	    printk ("scsi%d : Selection Timeout\n", host->host_no);
3920    	    if (cmd) {
3921    	    	printk("scsi%d : target %d, lun %d, command ",
3922    	    	    host->host_no, cmd->cmd->target, cmd->cmd->lun);
3923    	    	print_command (cmd->cmd->cmnd);
3924		printk("scsi%d : dsp = 0x%x (virt 0x%p)\n", host->host_no,
3925		    NCR53c7x0_read32(DSP_REG),
3926		    bus_to_virt(NCR53c7x0_read32(DSP_REG)));
3927    	    } else {
3928    	    	printk("scsi%d : no command\n", host->host_no);
3929    	    }
3930    	}
3931
3932	if (1) {
3933	    hostdata->idle = 1;
3934	    hostdata->expecting_sto = 0;
3935
3936	    if (hostdata->test_running) {
3937		hostdata->test_running = 0;
3938		hostdata->test_completed = 3;
3939	    } else if (cmd) {
3940		abnormal_finished(cmd, DID_BAD_TARGET << 16);
3941	    }
3942	}
3943    }
3944
3945    if (sstat0_sist0 & SSTAT0_UDC) {
3946	fatal = 1;
3947	if (cmd) {
3948	    printk("scsi%d : target %d lun %d unexpected disconnect\n",
3949		host->host_no, cmd->cmd->target, cmd->cmd->lun);
3950	    print_lots (host);
3951	    abnormal_finished(cmd, DID_ERROR << 16);
3952	} else
3953	     printk("scsi%d : unexpected disconnect (no command)\n",
3954		host->host_no);
3955
3956	hostdata->dsp = (u32 *) hostdata->schedule;
3957	hostdata->dsp_changed = 1;
3958    }
3959
3960    /* SCSI PARITY error */
3961    if (sstat0_sist0 & SSTAT0_PAR) {
3962	fatal = 1;
3963	if (cmd && cmd->cmd) {
3964	    printk("scsi%d : target %d lun %d parity error.\n",
3965		host->host_no, cmd->cmd->target, cmd->cmd->lun);
3966	    abnormal_finished (cmd, DID_PARITY << 16);
3967	} else
3968	    printk("scsi%d : parity error\n", host->host_no);
3969	/* Should send message out, parity error */
3970
3971	hostdata->dsp = hostdata->script + hostdata->E_initiator_abort /
3972    	    sizeof(u32);
3973	hostdata->dsp_changed = 1;
3974    /* SCSI GROSS error */
3975    }
3976
3977    if (sstat0_sist0 & SSTAT0_SGE) {
3978	fatal = 1;
3979	printk("scsi%d : gross error\n", host->host_no);
3980	/* Reset SCSI offset */
3981	if ((hostdata->chip / 100) == 8) {
3982	    NCR53c7x0_write8 (STEST2_REG_800, STEST2_800_ROF);
3983	}
3984
3985	/*
3986         * A SCSI gross error may occur when we have
3987	 *
3988	 * - A synchronous offset which causes the SCSI FIFO to be overwritten.
3989	 *
3990	 * - A REQ which causes the maximum synchronous offset programmed in
3991	 * 	the SXFER register to be exceeded.
3992	 *
3993	 * - A phase change with an outstanding synchronous offset.
3994	 *
3995	 * - Residual data in the synchronous data FIFO, with a transfer
3996	 *	other than a synchronous receive is started.$#
3997	 */
3998
3999
4000	hostdata->dsp = hostdata->script + hostdata->E_initiator_abort /
4001    	    sizeof(u32);
4002	hostdata->dsp_changed = 1;
4003    /* Phase mismatch */
4004    }
4005
4006    if (sstat0_sist0 & SSTAT0_MA) {
4007	fatal = 1;
4008	if (hostdata->options & OPTION_DEBUG_INTR)
4009	    printk ("scsi%d : SSTAT0_MA\n", host->host_no);
4010	intr_phase_mismatch (host, cmd);
4011    }
4012
4013
4014/*
4015 * If a fatal SCSI interrupt occurs, we must insure that the DMA and
4016 * SCSI FIFOs were flushed.
4017 */
4018
4019    if (fatal) {
4020	if (!hostdata->dstat_valid) {
4021	    hostdata->dstat = NCR53c7x0_read8(DSTAT_REG);
4022	    hostdata->dstat_valid = 1;
4023	}
4024
4025	if (!(hostdata->dstat & DSTAT_DFE)) {
4026	    printk ("scsi%d : DMA FIFO not empty\n", host->host_no);
4027    	    if (NCR53c7x0_read8 (CTEST2_REG_800) & CTEST2_800_DDIR) {
4028		printk ("scsi%d: Flushing DMA FIFO\n",
4029			host->host_no);
4030    	    	NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_FLF);
4031    	    	while (!((hostdata->dstat = NCR53c7x0_read8(DSTAT_REG)) &
4032    	    	    DSTAT_DFE));
4033    	    } else {
4034    	    	NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_CLF);
4035    	    	while (NCR53c7x0_read8 (CTEST3_REG_800) & CTEST3_800_CLF);
4036    	    }
4037	    hostdata->dstat |= DSTAT_DFE;
4038    	}
4039    }
4040}
4041
4042/*
4043 * Function : do_NCR53c7x0_intr()
4044 *
4045 * Purpose : A quick wrapper function added to grab the io_request_lock
4046 *      spin lock prior to entering the real interrupt handler.  Needed
4047 *      for 2.1.95 and above.
4048 */
4049static void
4050do_NCR53c7x0_intr(int irq, void *dev_id, struct pt_regs * regs) {
4051    unsigned long flags;
4052
4053    spin_lock_irqsave(&io_request_lock, flags);
4054    NCR53c7x0_intr(irq, dev_id, regs);
4055    spin_unlock_irqrestore(&io_request_lock, flags);
4056}
4057
4058/*
4059 * Function : static void NCR53c7x0_intr (int irq, void *dev_id, struct pt_regs * regs)
4060 *
4061 * Purpose : handle NCR53c7x0 interrupts for all NCR devices sharing
4062 *	the same IRQ line.
4063 *
4064 * Inputs : Since we're using the SA_INTERRUPT interrupt handler
4065 *	semantics, irq indicates the interrupt which invoked
4066 *	this handler.
4067 */
4068
4069static void
4070NCR53c7x0_intr (int irq, void *dev_id, struct pt_regs * regs) {
4071    NCR53c7x0_local_declare();
4072    struct Scsi_Host *host;			/* Host we are looking at */
4073    unsigned char istat; 			/* Values of interrupt regs */
4074    struct NCR53c7x0_hostdata *hostdata;	/* host->hostdata */
4075    struct NCR53c7x0_cmd *cmd,			/* command which halted */
4076	**cmd_prev_ptr;
4077    u32 *dsa;					/* DSA */
4078    int done = 1;				/* Indicates when handler
4079						   should terminate */
4080    int interrupted = 0;			/* This HA generated
4081						   an interrupt */
4082    int have_intfly;				/* Don't print warning
4083						   messages when we stack
4084						   INTFLYs */
4085    unsigned long flags;
4086
4087#ifdef NCR_DEBUG
4088    char buf[80];				/* Debugging sprintf buffer */
4089    size_t buflen;				/* Length of same */
4090#endif
4091    do {
4092	done = 1;
4093	for (host = first_host; host; host = host->next)
4094	    if (host->hostt == the_template && host->irq == irq) {
4095    	    NCR53c7x0_local_setup(host);
4096
4097	    hostdata = (struct NCR53c7x0_hostdata *) host->hostdata;
4098	    hostdata->dsp_changed = 0;
4099	    interrupted = 0;
4100	    have_intfly = 0;
4101
4102	    do {
4103		int is_8xx_chip;
4104
4105		hostdata->dstat_valid = 0;
4106		interrupted = 0;
4107		/*
4108		 * Only read istat once, since reading it again will unstack
4109		 * interrupts?
4110		 */
4111		istat = NCR53c7x0_read8(hostdata->istat);
4112
4113		/*
4114		 * INTFLY interrupts are used by the NCR53c720, NCR53c810,
4115		 * and NCR53c820 to signify completion of a command.  Since
4116		 * the SCSI processor continues running, we can't just look
4117		 * at the contents of the DSA register and continue running.
4118		 */
4119		is_8xx_chip = ((unsigned) (hostdata->chip - 800)) < 100;
4120		if ((hostdata->options & OPTION_INTFLY) &&
4121		    (is_8xx_chip && (istat & ISTAT_800_INTF))) {
4122		    char search_found = 0;	/* Got at least one ? */
4123		    done = 0;
4124		    interrupted = 1;
4125
4126		    /*
4127		     * Clear the INTF bit by writing a one.
4128		     * This reset operation is self-clearing.
4129		     */
4130		    NCR53c7x0_write8(hostdata->istat, istat|ISTAT_800_INTF);
4131
4132		    if (hostdata->options & OPTION_DEBUG_INTR)
4133			printk ("scsi%d : INTFLY\n", host->host_no);
4134
4135		    /*
4136		     * Traverse our list of running commands, and look
4137		     * for those with valid (non-0xff ff) status and message
4138		     * bytes encoded in the result which signify command
4139		     * completion.
4140		     */
4141
4142
4143		    save_flags(flags);
4144		    cli();
4145restart:
4146		    for (cmd_prev_ptr = (struct NCR53c7x0_cmd **)
4147			 &(hostdata->running_list), cmd =
4148			 (struct NCR53c7x0_cmd *) hostdata->running_list; cmd ;
4149			 cmd_prev_ptr = (struct NCR53c7x0_cmd **) &(cmd->next),
4150    	    	    	 cmd = (struct NCR53c7x0_cmd *) cmd->next) {
4151			Scsi_Cmnd *tmp;
4152
4153			if (!cmd) {
4154			    printk("scsi%d : very weird.\n", host->host_no);
4155			    break;
4156			}
4157
4158			if (!(tmp = cmd->cmd)) {
4159			    printk("scsi%d : weird.  NCR53c7x0_cmd has no Scsi_Cmnd\n",
4160				host->host_no);
4161				continue;
4162			}
4163
4164#ifdef __powerpc__
4165			if (tmp->result == le32_to_cpu(0xffff))
4166			    continue;
4167			tmp->result = le32_to_cpu(tmp->result);
4168#else
4169			if (((tmp->result & 0xff) == 0xff) ||
4170			    ((tmp->result & 0xff00) == 0xff00))
4171			    continue;
4172#endif
4173
4174			search_found = 1;
4175
4176			/* Important - remove from list _before_ done is called */
4177			if (cmd_prev_ptr)
4178			    *cmd_prev_ptr = (struct NCR53c7x0_cmd *) cmd->next;
4179
4180			--hostdata->busy[tmp->target][tmp->lun];
4181    	    	    	cmd->next = hostdata->free;
4182    	    	    	hostdata->free = cmd;
4183
4184    	    	    	tmp->host_scribble = NULL;
4185
4186			if (hostdata->options & OPTION_DEBUG_INTR) {
4187			    printk ("scsi%d : command complete : pid %lu, id %d,lun %d result 0x%x ",
4188				host->host_no, tmp->pid, tmp->target, tmp->lun, tmp->result);
4189			    print_command (tmp->cmnd);
4190			}
4191
4192			tmp->scsi_done(tmp);
4193			goto restart;
4194
4195		    }
4196		    restore_flags(flags);
4197
4198    /*
4199     * I think that we're stacking INTFLY interrupts; taking care of
4200     * all the finished commands on the first one, and then getting
4201     * worried when we see the next one.  The magic with have_intfly
4202     * should tell if this is the case..
4203     */
4204
4205		    if (!search_found && !have_intfly)  {
4206			printk ("scsi%d : WARNING : INTFLY with no completed commands.\n",
4207			    host->host_no);
4208		    } else if (!have_intfly)  {
4209			have_intfly = 1;
4210    		    	run_process_issue_queue();
4211		    }
4212		}
4213
4214		if (istat & (ISTAT_SIP|ISTAT_DIP)) {
4215		    done = 0;
4216		    interrupted = 1;
4217    	    	    hostdata->state = STATE_HALTED;
4218
4219		    if (NCR53c7x0_read8 ((hostdata->chip / 100) == 8 ?
4220			SSTAT1_REG : SSTAT2_REG) & SSTAT2_FF_MASK)
4221			printk ("scsi%d : SCSI FIFO not empty\n",
4222			    host->host_no);
4223
4224		    /*
4225		     * NCR53c700 and NCR53c700-66 change the current SCSI
4226		     * process, hostdata->curr, in the Linux driver so
4227		     * cmd = hostdata->curr.
4228		     *
4229		     * With other chips, we must look through the commands
4230		     * executing and find the command structure which
4231		     * corresponds to the DSA register.
4232		     */
4233
4234		    if (hostdata->options & OPTION_700) {
4235			cmd = (struct NCR53c7x0_cmd *) hostdata->curr;
4236		    } else {
4237			dsa = bus_to_virt(NCR53c7x0_read32(DSA_REG));
4238			for (cmd = (struct NCR53c7x0_cmd *)
4239			    hostdata->running_list; cmd &&
4240    	    	    	    (dsa + (hostdata->dsa_start / sizeof(u32))) !=
4241    	    	    	    	cmd->dsa;
4242			    cmd = (struct NCR53c7x0_cmd *)(cmd->next));
4243		    }
4244		    if (hostdata->options & OPTION_DEBUG_INTR) {
4245			if (cmd) {
4246			    printk("scsi%d : interrupt for pid %lu, id %d, lun %d ",
4247				host->host_no, cmd->cmd->pid, (int) cmd->cmd->target,
4248				(int) cmd->cmd->lun);
4249			    print_command (cmd->cmd->cmnd);
4250			} else {
4251			    printk("scsi%d : no active command\n", host->host_no);
4252			}
4253		    }
4254		    if (istat & ISTAT_SIP) {
4255			if (hostdata->options & OPTION_DEBUG_INTR)
4256			    printk ("scsi%d : ISTAT_SIP\n", host->host_no);
4257			intr_scsi (host, cmd);
4258		    }
4259
4260		    if (istat & ISTAT_DIP) {
4261			if (hostdata->options & OPTION_DEBUG_INTR)
4262			    printk ("scsi%d : ISTAT_DIP\n", host->host_no);
4263			intr_dma (host, cmd);
4264		    }
4265
4266		    if (!hostdata->dstat_valid) {
4267			hostdata->dstat = NCR53c7x0_read8(DSTAT_REG);
4268			hostdata->dstat_valid = 1;
4269		    }
4270
4271		    if (!(hostdata->dstat & DSTAT_DFE)) {
4272			printk ("scsi%d : DMA FIFO not empty\n", host->host_no);
4273			if (NCR53c7x0_read8 (CTEST2_REG_800) & CTEST2_800_DDIR) {
4274			    printk ("scsi%d: Flushing DMA FIFO\n",
4275				host->host_no);
4276			    NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_FLF);
4277			    while (!((hostdata->dstat = NCR53c7x0_read8(DSTAT_REG)) &
4278				DSTAT_DFE));
4279			} else
4280			{
4281			    NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_CLF);
4282			    while (NCR53c7x0_read8 (CTEST3_REG_800) & CTEST3_800_CLF);
4283			}
4284			hostdata->dstat |= DSTAT_DFE;
4285		    }
4286		}
4287	    } while (interrupted);
4288
4289
4290
4291	    if (hostdata->intrs != -1)
4292		hostdata->intrs++;
4293
4294	    if (!hostdata->idle && hostdata->state == STATE_HALTED) {
4295		if (!hostdata->dsp_changed) {
4296		    hostdata->dsp = (u32 *)
4297			bus_to_virt(NCR53c7x0_read32(DSP_REG));
4298		}
4299
4300
4301		hostdata->state = STATE_RUNNING;
4302		NCR53c7x0_write32 (DSP_REG, virt_to_bus(hostdata->dsp));
4303	    }
4304	}
4305    } while (!done);
4306}
4307
4308
4309/*
4310 * Function : static int abort_connected (struct Scsi_Host *host)
4311 *
4312 * Purpose : Assuming that the NCR SCSI processor is currently
4313 * 	halted, break the currently established nexus.  Clean
4314 *	up of the NCR53c7x0_cmd and Scsi_Cmnd structures should
4315 *	be done on receipt of the abort interrupt.
4316 *
4317 * Inputs : host - SCSI host
4318 *
4319 */
4320
4321static int
4322abort_connected (struct Scsi_Host *host) {
4323#ifdef NEW_ABORT
4324    NCR53c7x0_local_declare();
4325#endif
4326    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
4327	host->hostdata;
4328    static int counter = 5;
4329#ifdef NEW_ABORT
4330    int sstat, phase, offset;
4331    u32 *script;
4332    NCR53c7x0_local_setup(host);
4333#endif
4334
4335    if (--counter <= 0) {
4336	disable(host);
4337	return 0;
4338    }
4339
4340    printk ("scsi%d : DANGER : abort_connected() called \n",
4341	host->host_no);
4342
4343#ifdef NEW_ABORT
4344
4345/*
4346 * New strategy : Rather than using a generic abort routine,
4347 * we'll specifically try to source or sink the appropriate
4348 * amount of data for the phase we're currently in (taking into
4349 * account the current synchronous offset)
4350 */
4351
4352    sstat = (NCR53c8x0_read8 ((chip / 100) == 8 ? SSTAT1_REG : SSTAT2_REG);
4353    offset = OFFSET (sstat & SSTAT2_FF_MASK) >> SSTAT2_FF_SHIFT;
4354    phase = sstat & SSTAT2_PHASE_MASK;
4355
4356/*
4357 * SET ATN
4358 * MOVE source_or_sink, WHEN CURRENT PHASE
4359 * < repeat for each outstanding byte >
4360 * JUMP send_abort_message
4361 */
4362
4363    script = hostdata->abort_script = kmalloc (
4364	8  /* instruction size */ * (
4365	    1 /* set ATN */ +
4366	    (!offset ? 1 : offset) /* One transfer per outstanding byte */ +
4367	    1 /* send abort message */),
4368	GFP_ATOMIC);
4369
4370
4371#else /* def NEW_ABORT */
4372    hostdata->dsp = hostdata->script + hostdata->E_initiator_abort /
4373	    sizeof(u32);
4374#endif /* def NEW_ABORT */
4375    hostdata->dsp_changed = 1;
4376
4377    return 0;
4378}
4379
4380/*
4381 * Function : static int datapath_residual (Scsi_Host *host)
4382 *
4383 * Purpose : return residual data count of what's in the chip.
4384 *
4385 * Inputs : host - SCSI host
4386 */
4387
4388static int
4389datapath_residual (struct Scsi_Host *host) {
4390    NCR53c7x0_local_declare();
4391    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
4392    	host->hostdata;
4393    int count, synchronous, sstat;
4394    NCR53c7x0_local_setup(host);
4395    /* COMPAT : the 700 and 700-66 need to use DFIFO_00_BO_MASK */
4396    count = ((NCR53c7x0_read8 (DFIFO_REG) & DFIFO_10_BO_MASK) -
4397	(NCR53c7x0_read32 (DBC_REG) & DFIFO_10_BO_MASK)) & DFIFO_10_BO_MASK;
4398    synchronous = NCR53c7x0_read8 (SXFER_REG) & SXFER_MO_MASK;
4399    /* COMPAT : DDIR is elsewhere on non-'8xx chips. */
4400    if (NCR53c7x0_read8 (CTEST2_REG_800) & CTEST2_800_DDIR) {
4401    /* Receive */
4402	if (synchronous)
4403	    count += (NCR53c7x0_read8 ((hostdata->chip / 100) == 8 ?
4404		SSTAT1_REG : SSTAT2_REG) & SSTAT2_FF_MASK) >> SSTAT2_FF_SHIFT;
4405	else
4406	    if (NCR53c7x0_read8 ((hostdata->chip / 100) == 8 ?
4407		SSTAT0_REG : SSTAT1_REG) & SSTAT1_ILF)
4408		++count;
4409    } else {
4410    /* Send */
4411	sstat = ((hostdata->chip / 100) == 8) ?  NCR53c7x0_read8 (SSTAT0_REG) :
4412	    NCR53c7x0_read8 (SSTAT1_REG);
4413	if (sstat & SSTAT1_OLF)
4414	    ++count;
4415	if (synchronous && (sstat & SSTAT1_ORF))
4416	    ++count;
4417    }
4418    return count;
4419}
4420
4421/*
4422 * Function : static const char * sbcl_to_phase (int sbcl)_
4423 *
4424 * Purpose : Convert SBCL register to user-parsable phase representation
4425 *
4426 * Inputs : sbcl - value of sbcl register
4427 */
4428
4429
4430static const char *
4431sbcl_to_phase (int sbcl) {
4432    switch (sbcl & SBCL_PHASE_MASK) {
4433    case SBCL_PHASE_DATAIN:
4434	return "DATAIN";
4435    case SBCL_PHASE_DATAOUT:
4436	return "DATAOUT";
4437    case SBCL_PHASE_MSGIN:
4438	return "MSGIN";
4439    case SBCL_PHASE_MSGOUT:
4440	return "MSGOUT";
4441    case SBCL_PHASE_CMDOUT:
4442	return "CMDOUT";
4443    case SBCL_PHASE_STATIN:
4444	return "STATUSIN";
4445    default:
4446	return "unknown";
4447    }
4448}
4449
4450/*
4451 * Function : static const char * sstat2_to_phase (int sstat)_
4452 *
4453 * Purpose : Convert SSTAT2 register to user-parsable phase representation
4454 *
4455 * Inputs : sstat - value of sstat register
4456 */
4457
4458
4459static const char *
4460sstat2_to_phase (int sstat) {
4461    switch (sstat & SSTAT2_PHASE_MASK) {
4462    case SSTAT2_PHASE_DATAIN:
4463	return "DATAIN";
4464    case SSTAT2_PHASE_DATAOUT:
4465	return "DATAOUT";
4466    case SSTAT2_PHASE_MSGIN:
4467	return "MSGIN";
4468    case SSTAT2_PHASE_MSGOUT:
4469	return "MSGOUT";
4470    case SSTAT2_PHASE_CMDOUT:
4471	return "CMDOUT";
4472    case SSTAT2_PHASE_STATIN:
4473	return "STATUSIN";
4474    default:
4475	return "unknown";
4476    }
4477}
4478
4479/*
4480 * Function : static void intr_phase_mismatch (struct Scsi_Host *host,
4481 *	struct NCR53c7x0_cmd *cmd)
4482 *
4483 * Purpose : Handle phase mismatch interrupts
4484 *
4485 * Inputs : host, cmd - host and NCR command causing the interrupt, cmd
4486 * 	may be NULL.
4487 *
4488 * Side effects : The abort_connected() routine is called or the NCR chip
4489 *	is restarted, jumping to the command_complete entry point, or
4490 *	patching the address and transfer count of the current instruction
4491 *	and calling the msg_in entry point as appropriate.
4492 */
4493
4494static void
4495intr_phase_mismatch (struct Scsi_Host *host, struct NCR53c7x0_cmd *cmd) {
4496    NCR53c7x0_local_declare();
4497    u32 dbc_dcmd, *dsp, *dsp_next;
4498    unsigned char dcmd, sbcl;
4499    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
4500    	host->hostdata;
4501    int residual;
4502    enum {ACTION_ABORT, ACTION_ABORT_PRINT, ACTION_CONTINUE} action =
4503	ACTION_ABORT_PRINT;
4504    const char *where = NULL;
4505    NCR53c7x0_local_setup(host);
4506
4507    /*
4508     * Corrective action is based on where in the SCSI SCRIPT(tm) the error
4509     * occurred, as well as which SCSI phase we are currently in.
4510     */
4511    dsp_next = bus_to_virt(NCR53c7x0_read32(DSP_REG));
4512
4513    /*
4514     * Fetch the current instruction, and remove the operands for easier
4515     * interpretation.
4516     */
4517    dbc_dcmd = NCR53c7x0_read32(DBC_REG);
4518    dcmd = (dbc_dcmd & 0xff000000) >> 24;
4519    /*
4520     * Like other processors, the NCR adjusts the instruction pointer before
4521     * instruction decode.  Set the DSP address back to what it should
4522     * be for this instruction based on its size (2 or 3 32 bit words).
4523     */
4524    dsp = dsp_next - NCR53c7x0_insn_size(dcmd);
4525
4526
4527    /*
4528     * Read new SCSI phase from the SBCL lines.  Since all of our code uses
4529     * a WHEN conditional instead of an IF conditional, we don't need to
4530     * wait for a new REQ.
4531     */
4532    sbcl = NCR53c7x0_read8(SBCL_REG) & SBCL_PHASE_MASK;
4533
4534    if (!cmd) {
4535	action = ACTION_ABORT_PRINT;
4536	where = "no current command";
4537    /*
4538     * The way my SCSI SCRIPTS(tm) are architected, recoverable phase
4539     * mismatches should only occur where we're doing a multi-byte
4540     * BMI instruction.  Specifically, this means
4541     *
4542     *  - select messages (a SCSI-I target may ignore additional messages
4543     * 		after the IDENTIFY; any target may reject a SDTR or WDTR)
4544     *
4545     *  - command out (targets may send a message to signal an error
4546     * 		condition, or go into STATUSIN after they've decided
4547     *		they don't like the command.
4548     *
4549     *	- reply_message (targets may reject a multi-byte message in the
4550     *		middle)
4551     *
4552     * 	- data transfer routines (command completion with buffer space
4553     *		left, disconnect message, or error message)
4554     */
4555    } else if (((dsp >= cmd->data_transfer_start &&
4556	dsp < cmd->data_transfer_end)) || dsp == (cmd->residual + 2)) {
4557	if ((dcmd & (DCMD_TYPE_MASK|DCMD_BMI_OP_MASK|DCMD_BMI_INDIRECT|
4558		DCMD_BMI_MSG|DCMD_BMI_CD)) == (DCMD_TYPE_BMI|
4559		DCMD_BMI_OP_MOVE_I)) {
4560	    residual = datapath_residual (host);
4561	    if (hostdata->options & OPTION_DEBUG_DISCONNECT)
4562	    	printk ("scsi%d : handling residual transfer (+ %d bytes from DMA FIFO)\n",
4563		    host->host_no, residual);
4564
4565	    /*
4566	     * The first instruction is a CALL to the alternate handler for
4567	     * this data transfer phase, so we can do calls to
4568	     * munge_msg_restart as we would if control were passed
4569	     * from normal dynamic code.
4570	     */
4571	    if (dsp != cmd->residual + 2) {
4572		cmd->residual[0] = le32_to_cpu(((DCMD_TYPE_TCI | DCMD_TCI_OP_CALL |
4573			((dcmd & DCMD_BMI_IO) ? DCMD_TCI_IO : 0)) << 24) |
4574		    DBC_TCI_WAIT_FOR_VALID | DBC_TCI_COMPARE_PHASE);
4575		cmd->residual[1] = le32_to_cpu(virt_to_bus(hostdata->script)
4576		    + ((dcmd & DCMD_BMI_IO)
4577		       ? hostdata->E_other_in : hostdata->E_other_out));
4578	    }
4579
4580	    /*
4581	     * The second instruction is the a data transfer block
4582	     * move instruction, reflecting the pointer and count at the
4583	     * time of the phase mismatch.
4584	     */
4585	    cmd->residual[2] = le32_to_cpu(dbc_dcmd + residual);
4586	    cmd->residual[3] = le32_to_cpu(NCR53c7x0_read32(DNAD_REG) - residual);
4587
4588	    /*
4589	     * The third and final instruction is a jump to the instruction
4590	     * which follows the instruction which had to be 'split'
4591	     */
4592	    if (dsp != cmd->residual + 2) {
4593		cmd->residual[4] = le32_to_cpu(((DCMD_TYPE_TCI|DCMD_TCI_OP_JUMP)
4594		    << 24) | DBC_TCI_TRUE);
4595		cmd->residual[5] = le32_to_cpu(virt_to_bus(dsp_next));
4596	    }
4597
4598	    /*
4599	     * For the sake of simplicity, transfer control to the
4600	     * conditional CALL at the start of the residual buffer.
4601	     */
4602	    hostdata->dsp = cmd->residual;
4603	    hostdata->dsp_changed = 1;
4604	    action = ACTION_CONTINUE;
4605	} else {
4606	    where = "non-BMI dynamic DSA code";
4607	    action = ACTION_ABORT_PRINT;
4608	}
4609    } else if (dsp == (hostdata->script + hostdata->E_select_msgout / 4)) {
4610	/* Release ATN */
4611	NCR53c7x0_write8 (SOCL_REG, 0);
4612	switch (sbcl) {
4613    /*
4614     * Some devices (SQ555 come to mind) grab the IDENTIFY message
4615     * sent on selection, and decide to go into COMMAND OUT phase
4616     * rather than accepting the rest of the messages or rejecting
4617     * them.  Handle these devices gracefully.
4618     */
4619	case SBCL_PHASE_CMDOUT:
4620	    hostdata->dsp = dsp + 2 /* two _words_ */;
4621	    hostdata->dsp_changed = 1;
4622	    printk ("scsi%d : target %d ignored SDTR and went into COMMAND OUT\n",
4623		host->host_no, cmd->cmd->target);
4624	    cmd->flags &= ~CMD_FLAG_SDTR;
4625	    action = ACTION_CONTINUE;
4626	    break;
4627	case SBCL_PHASE_MSGIN:
4628	    hostdata->dsp = hostdata->script + hostdata->E_msg_in /
4629		sizeof(u32);
4630	    hostdata->dsp_changed = 1;
4631	    action = ACTION_CONTINUE;
4632	    break;
4633	default:
4634	    where="select message out";
4635	    action = ACTION_ABORT_PRINT;
4636	}
4637    /*
4638     * Some SCSI devices will interpret a command as they read the bytes
4639     * off the SCSI bus, and may decide that the command is Bogus before
4640     * they've read the entire command off the bus.
4641     */
4642    } else if (dsp == hostdata->script + hostdata->E_cmdout_cmdout / sizeof
4643	(u32)) {
4644	hostdata->dsp = hostdata->script + hostdata->E_data_transfer /
4645	    sizeof (u32);
4646	hostdata->dsp_changed = 1;
4647	action = ACTION_CONTINUE;
4648#ifdef notyet
4649    } else if (dsp == hostdata->script + hostdata->E_reply_message) {
4650	switch (sbcl) {
4651    /* Any other phase mismatches abort the currently executing command.  */
4652#endif
4653    } else {
4654	where = "unknown location";
4655	action = ACTION_ABORT_PRINT;
4656    }
4657
4658    /* Flush DMA FIFO */
4659    if (!hostdata->dstat_valid) {
4660	hostdata->dstat = NCR53c7x0_read8(DSTAT_REG);
4661	hostdata->dstat_valid = 1;
4662    }
4663    if (!(hostdata->dstat & DSTAT_DFE)) {
4664	if (NCR53c7x0_read8 (CTEST2_REG_800) & CTEST2_800_DDIR) {
4665	    printk ("scsi%d: Flushing DMA FIFO\n",
4666		    host->host_no);
4667	    NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_FLF);
4668	    while (!((hostdata->dstat = NCR53c7x0_read8(DSTAT_REG)) &
4669		DSTAT_DFE));
4670	} else {
4671	    NCR53c7x0_write8 (CTEST3_REG_800, CTEST3_800_CLF);
4672	    while (NCR53c7x0_read8 (CTEST3_REG_800) & CTEST3_800_CLF);
4673	}
4674	hostdata->dstat |= DSTAT_DFE;
4675    }
4676
4677    switch (action) {
4678    case ACTION_ABORT_PRINT:
4679	printk("scsi%d : %s : unexpected phase %s.\n",
4680	     host->host_no, where ? where : "unknown location",
4681	     sbcl_to_phase(sbcl));
4682	print_lots (host);
4683    /* Fall through to ACTION_ABORT */
4684    case ACTION_ABORT:
4685	abort_connected (host);
4686	break;
4687    case ACTION_CONTINUE:
4688	break;
4689    }
4690
4691
4692}
4693
4694/*
4695 * Function : static void intr_bf (struct Scsi_Host *host,
4696 * 	struct NCR53c7x0_cmd *cmd)
4697 *
4698 * Purpose : handle BUS FAULT interrupts
4699 *
4700 * Inputs : host, cmd - host and NCR command causing the interrupt, cmd
4701 * 	may be NULL.
4702 */
4703
4704static void
4705intr_bf (struct Scsi_Host *host, struct NCR53c7x0_cmd *cmd) {
4706    NCR53c7x0_local_declare();
4707    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
4708	    host->hostdata;
4709    u32 *dsp,
4710	*next_dsp,		/* Current dsp */
4711    	*dsa,
4712	dbc_dcmd;		/* DCMD (high eight bits) + DBC */
4713    unsigned short pci_status;
4714    int tmp;
4715    unsigned long flags;
4716    char *reason = NULL;
4717    /* Default behavior is for a silent error, with a retry until we've
4718       exhausted retries. */
4719    enum {MAYBE, ALWAYS, NEVER} retry = MAYBE;
4720    int report = 0;
4721    NCR53c7x0_local_setup(host);
4722
4723    dbc_dcmd = NCR53c7x0_read32 (DBC_REG);
4724    next_dsp = bus_to_virt (NCR53c7x0_read32(DSP_REG));
4725    dsp = next_dsp - NCR53c7x0_insn_size ((dbc_dcmd >> 24) & 0xff);
4726    dsa = bus_to_virt (NCR53c7x0_read32(DSA_REG));
4727
4728    /*
4729     * Bus faults can be caused by either a Bad Address or
4730     * Target Abort. We should check the Received Target Abort
4731     * bit of the PCI status register and Master Abort Bit.
4732     *
4733     * 	- Master Abort bit indicates that no device claimed
4734     *		the address with DEVSEL within five clocks
4735     *
4736     *	- Target Abort bit indicates that a target claimed it,
4737     *		but changed its mind once it saw the byte enables.
4738     *
4739     */
4740
4741    if ((hostdata->chip / 100) == 8) {
4742	save_flags (flags);
4743	cli();
4744	tmp = pcibios_read_config_word (hostdata->pci_bus,
4745	    hostdata->pci_device_fn, PCI_STATUS, &pci_status);
4746	restore_flags (flags);
4747	if (tmp == PCIBIOS_SUCCESSFUL) {
4748	    if (pci_status & PCI_STATUS_REC_TARGET_ABORT) {
4749		reason = "PCI target abort";
4750		pci_status &= ~PCI_STATUS_REC_TARGET_ABORT;
4751	    } else if (pci_status & PCI_STATUS_REC_MASTER_ABORT) {
4752		reason = "No device asserted PCI DEVSEL within five bus clocks";
4753		pci_status &= ~PCI_STATUS_REC_MASTER_ABORT;
4754	    } else if (pci_status & PCI_STATUS_PARITY) {
4755		report = 1;
4756		pci_status &= ~PCI_STATUS_PARITY;
4757	    }
4758	} else {
4759	    printk ("scsi%d : couldn't read status register : error %d\n",
4760		host->host_no, tmp);
4761	    retry = NEVER;
4762	}
4763    }
4764
4765#ifndef notyet
4766    report = 1;
4767#endif
4768    if (report && reason) {
4769	printk(KERN_ALERT "scsi%d : BUS FAULT reason = %s\n",
4770	     host->host_no, reason ? reason : "unknown");
4771	print_lots (host);
4772    }
4773
4774#ifndef notyet
4775    retry = NEVER;
4776#endif
4777
4778    /*
4779     * TODO : we should attempt to recover from any spurious bus
4780     * faults.  After X retries, we should figure that things are
4781     * sufficiently wedged, and call NCR53c7xx_reset.
4782     *
4783     * This code should only get executed once we've decided that we
4784     * cannot retry.
4785     */
4786
4787    if (retry == NEVER) {
4788    	printk(KERN_ALERT "          mail drew@PoohSticks.ORG\n");
4789    	FATAL (host);
4790    }
4791}
4792
4793/*
4794 * Function : static void intr_dma (struct Scsi_Host *host,
4795 * 	struct NCR53c7x0_cmd *cmd)
4796 *
4797 * Purpose : handle all DMA interrupts, indicated by the setting
4798 * 	of the DIP bit in the ISTAT register.
4799 *
4800 * Inputs : host, cmd - host and NCR command causing the interrupt, cmd
4801 * 	may be NULL.
4802 */
4803
4804static void
4805intr_dma (struct Scsi_Host *host, struct NCR53c7x0_cmd *cmd) {
4806    NCR53c7x0_local_declare();
4807    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
4808	host->hostdata;
4809    unsigned char dstat;	/* DSTAT */
4810    u32 *dsp,
4811	*next_dsp,		/* Current dsp */
4812    	*dsa,
4813	dbc_dcmd;		/* DCMD (high eight bits) + DBC */
4814    int tmp;
4815    unsigned long flags;
4816    NCR53c7x0_local_setup(host);
4817
4818    if (!hostdata->dstat_valid) {
4819	hostdata->dstat = NCR53c7x0_read8(DSTAT_REG);
4820	hostdata->dstat_valid = 1;
4821    }
4822
4823    dstat = hostdata->dstat;
4824
4825    if (hostdata->options & OPTION_DEBUG_INTR)
4826	printk("scsi%d : DSTAT=0x%x\n", host->host_no, (int) dstat);
4827
4828    dbc_dcmd = NCR53c7x0_read32 (DBC_REG);
4829    next_dsp = bus_to_virt(NCR53c7x0_read32(DSP_REG));
4830    dsp = next_dsp - NCR53c7x0_insn_size ((dbc_dcmd >> 24) & 0xff);
4831    dsa = bus_to_virt(NCR53c7x0_read32(DSA_REG));
4832
4833    /*
4834     * DSTAT_ABRT is the aborted interrupt.  This is set whenever the
4835     * SCSI chip is aborted.
4836     *
4837     * With NCR53c700 and NCR53c700-66 style chips, we should only
4838     * get this when the chip is currently running the accept
4839     * reselect/select code and we have set the abort bit in the
4840     * ISTAT register.
4841     *
4842     */
4843
4844    if (dstat & DSTAT_ABRT) {
4845	{
4846	    printk(KERN_ALERT "scsi%d : unexpected abort interrupt at\n"
4847		   "         ", host->host_no);
4848	    print_insn (host, dsp, KERN_ALERT "s ", 1);
4849	    FATAL (host);
4850	}
4851    }
4852
4853    /*
4854     * DSTAT_SSI is the single step interrupt.  Should be generated
4855     * whenever we have single stepped or are tracing.
4856     */
4857
4858    if (dstat & DSTAT_SSI) {
4859	if (hostdata->options & OPTION_DEBUG_TRACE) {
4860	} else if (hostdata->options & OPTION_DEBUG_SINGLE) {
4861	    print_insn (host, dsp, "s ", 0);
4862	    save_flags(flags);
4863	    cli();
4864
4865	    NCR53c7x0_write8 (DCNTL_REG, (NCR53c7x0_read8(DCNTL_REG) &
4866    	    	~DCNTL_SSM) | DCNTL_STD);
4867	    restore_flags(flags);
4868	} else {
4869	    printk(KERN_ALERT "scsi%d : unexpected single step interrupt at\n"
4870		   "         ", host->host_no);
4871	    print_insn (host, dsp, KERN_ALERT "", 1);
4872	    printk(KERN_ALERT "         mail drew@PoohSticks.ORG\n");
4873    	    FATAL (host);
4874    	}
4875    }
4876
4877
4878    if (dstat & DSTAT_OPC) {
4879    /*
4880     * Ascertain if this IID interrupts occurred before or after a STO
4881     * interrupt.  Since the interrupt handling code now leaves
4882     * DSP unmodified until _after_ all stacked interrupts have been
4883     * processed, reading the DSP returns the original DSP register.
4884     * This means that if dsp lies between the select code, and
4885     * message out following the selection code (where the IID interrupt
4886     * would have to have occurred by due to the implicit wait for REQ),
4887     * we have an IID interrupt resulting from a STO condition and
4888     * can ignore it.
4889     */
4890
4891	if (((dsp >= (hostdata->script + hostdata->E_select / sizeof(u32))) &&
4892	    (dsp <= (hostdata->script + hostdata->E_select_msgout /
4893    	    sizeof(u32) + 8))) || (hostdata->test_running == 2)) {
4894	    if (hostdata->options & OPTION_DEBUG_INTR)
4895		printk ("scsi%d : ignoring DSTAT_IID for SSTAT_STO\n",
4896		    host->host_no);
4897	    if (hostdata->expecting_iid) {
4898		hostdata->expecting_iid = 0;
4899		hostdata->idle = 1;
4900		if (hostdata->test_running == 2) {
4901		    hostdata->test_running = 0;
4902		    hostdata->test_completed = 3;
4903		} else if (cmd)
4904			abnormal_finished (cmd, DID_BAD_TARGET << 16);
4905	    } else {
4906		hostdata->expecting_sto = 1;
4907	    }
4908    /*
4909     * We can't guarantee we'll be able to execute the WAIT DISCONNECT
4910     * instruction within the 3.4us of bus free and arbitration delay
4911     * that a target can RESELECT in and assert REQ after we've dropped
4912     * ACK.  If this happens, we'll get an illegal instruction interrupt.
4913     * Doing away with the WAIT DISCONNECT instructions broke everything,
4914     * so instead I'll settle for moving one WAIT DISCONNECT a few
4915     * instructions closer to the CLEAR ACK before it to minimize the
4916     * chances of this happening, and handle it if it occurs anyway.
4917     *
4918     * Simply continue with what we were doing, and control should
4919     * be transferred to the schedule routine which will ultimately
4920     * pass control onto the reselection or selection (not yet)
4921     * code.
4922     */
4923	} else if (dbc_dcmd == 0x48000000 && (NCR53c7x0_read8 (SBCL_REG) &
4924	    SBCL_REQ)) {
4925	    if (!(hostdata->options & OPTION_NO_PRINT_RACE))
4926	    {
4927		printk("scsi%d: REQ before WAIT DISCONNECT IID\n",
4928		    host->host_no);
4929		hostdata->options |= OPTION_NO_PRINT_RACE;
4930	    }
4931	} else {
4932	    printk(KERN_ALERT "scsi%d : illegal instruction\n", host->host_no);
4933	    print_lots (host);
4934	    printk(KERN_ALERT "         mail drew@PoohSticks.ORG with ALL\n"
4935		              "         boot messages and diagnostic output\n");
4936    	    FATAL (host);
4937	}
4938    }
4939
4940    /*
4941     * DSTAT_BF are bus fault errors
4942     */
4943
4944    if (dstat & DSTAT_800_BF) {
4945	intr_bf (host, cmd);
4946    }
4947
4948
4949    /*
4950     * DSTAT_SIR interrupts are generated by the execution of
4951     * the INT instruction.  Since the exact values available
4952     * are determined entirely by the SCSI script running,
4953     * and are local to a particular script, a unique handler
4954     * is called for each script.
4955     */
4956
4957    if (dstat & DSTAT_SIR) {
4958	if (hostdata->options & OPTION_DEBUG_INTR)
4959	    printk ("scsi%d : DSTAT_SIR\n", host->host_no);
4960	switch ((tmp = hostdata->dstat_sir_intr (host, cmd))) {
4961	case SPECIFIC_INT_NOTHING:
4962	case SPECIFIC_INT_RESTART:
4963	    break;
4964	case SPECIFIC_INT_ABORT:
4965	    abort_connected(host);
4966	    break;
4967	case SPECIFIC_INT_PANIC:
4968	    printk(KERN_ALERT "scsi%d : failure at ", host->host_no);
4969	    print_insn (host, dsp, KERN_ALERT "", 1);
4970	    printk(KERN_ALERT "          dstat_sir_intr() returned SPECIFIC_INT_PANIC\n");
4971    	    FATAL (host);
4972	    break;
4973	case SPECIFIC_INT_BREAK:
4974	    intr_break (host, cmd);
4975	    break;
4976	default:
4977	    printk(KERN_ALERT "scsi%d : failure at ", host->host_no);
4978	    print_insn (host, dsp, KERN_ALERT "", 1);
4979	    printk(KERN_ALERT"          dstat_sir_intr() returned unknown value %d\n",
4980		tmp);
4981    	    FATAL (host);
4982	}
4983    }
4984
4985    if ((hostdata->chip / 100) == 8 && (dstat & DSTAT_800_MDPE)) {
4986	printk(KERN_ALERT "scsi%d : Master Data Parity Error\n",
4987	    host->host_no);
4988	FATAL (host);
4989    }
4990}
4991
4992/*
4993 * Function : static int print_insn (struct Scsi_Host *host,
4994 * 	u32 *insn, int kernel)
4995 *
4996 * Purpose : print numeric representation of the instruction pointed
4997 * 	to by insn to the debugging or kernel message buffer
4998 *	as appropriate.
4999 *
5000 * 	If desired, a user level program can interpret this
5001 * 	information.
5002 *
5003 * Inputs : host, insn - host, pointer to instruction, prefix -
5004 *	string to prepend, kernel - use printk instead of debugging buffer.
5005 *
5006 * Returns : size, in u32s, of instruction printed.
5007 */
5008
5009
5010static int
5011print_insn (struct Scsi_Host *host, const u32 *insn,
5012    const char *prefix, int kernel) {
5013    char buf[160], 		/* Temporary buffer and pointer.  ICKY
5014				   arbitrary length.  */
5015
5016
5017	*tmp;
5018    unsigned char dcmd;		/* dcmd register for *insn */
5019    int size;
5020
5021
5022    if (virt_to_phys((void *)insn) < PAGE_SIZE ||
5023	virt_to_phys((void *)(insn + 8)) > virt_to_phys(high_memory) ||
5024	((((dcmd = (insn[0] >> 24) & 0xff) & DCMD_TYPE_MMI) == DCMD_TYPE_MMI) &&
5025	virt_to_phys((void *)(insn + 12)) > virt_to_phys(high_memory))) {
5026	size = 0;
5027	sprintf (buf, "%s%p: address out of range\n",
5028	    prefix, insn);
5029    } else {
5030	sprintf(buf, "%s0x%lx (virt 0x%p) : 0x%08x 0x%08x (virt 0x%p)",
5031	    (prefix ? prefix : ""), virt_to_bus((void *) insn), insn,
5032	    insn[0], insn[1], bus_to_virt (le32_to_cpu(insn[1])));
5033	tmp = buf + strlen(buf);
5034	if ((dcmd & DCMD_TYPE_MASK) == DCMD_TYPE_MMI)  {
5035	    sprintf (tmp, " 0x%08x (virt 0x%p)\n", insn[2],
5036		bus_to_virt(le32_to_cpu(insn[2])));
5037	    size = 3;
5038	} else {
5039	    sprintf (tmp, "\n");
5040	    size = 2;
5041	}
5042    }
5043
5044    if (kernel)
5045	printk ("%s", buf);
5046#ifdef NCR_DEBUG
5047    else {
5048	size_t len = strlen(buf);
5049	debugger_kernel_write(host, buf, len);
5050    }
5051#endif
5052    return size;
5053}
5054
5055/*
5056 * Function : static const char *ncr_state (int state)
5057 *
5058 * Purpose : convert state (probably from hostdata->state) to a string
5059 *
5060 * Inputs : state
5061 *
5062 * Returns : char * representation of state, "unknown" on error.
5063 */
5064
5065
5066/*
5067 * Function : int NCR53c7xx_abort (Scsi_Cmnd *cmd)
5068 *
5069 * Purpose : Abort an errant SCSI command, doing all necessary
5070 *	cleanup of the issue_queue, running_list, shared Linux/NCR
5071 *	dsa issue and reconnect queues.
5072 *
5073 * Inputs : cmd - command to abort, code - entire result field
5074 *
5075 * Returns : 0 on success, -1 on failure.
5076 */
5077
5078int
5079NCR53c7xx_abort (Scsi_Cmnd *cmd) {
5080    NCR53c7x0_local_declare();
5081    struct Scsi_Host *host = cmd->host;
5082    struct NCR53c7x0_hostdata *hostdata = host ? (struct NCR53c7x0_hostdata *)
5083	host->hostdata : NULL;
5084    unsigned long flags;
5085    unsigned long result;
5086    struct NCR53c7x0_cmd *curr, **prev;
5087    Scsi_Cmnd *me, **last;
5088
5089
5090    if (!host) {
5091	printk ("Bogus SCSI command pid %ld; no host structure\n",
5092	    cmd->pid);
5093	return SCSI_ABORT_ERROR;
5094    } else if (!hostdata) {
5095	printk ("Bogus SCSI host %d; no hostdata\n", host->host_no);
5096	return SCSI_ABORT_ERROR;
5097    }
5098    NCR53c7x0_local_setup(host);
5099
5100/*
5101 * CHECK : I don't think that reading ISTAT will unstack any interrupts,
5102 *	since we need to write the INTF bit to clear it, and SCSI/DMA
5103 * 	interrupts don't clear until we read SSTAT/SIST and DSTAT registers.
5104 *
5105 *	See that this is the case.
5106 *
5107 * I suspect that several of our failures may be coming from a new fatal
5108 * interrupt (possibly due to a phase mismatch) happening after we've left
5109 * the interrupt handler, but before the PIC has had the interrupt condition
5110 * cleared.
5111 */
5112
5113    if (NCR53c7x0_read8(hostdata->istat) &
5114	(ISTAT_DIP|ISTAT_SIP|
5115	    (hostdata->chip / 100 == 8 ? ISTAT_800_INTF : 0))) {
5116	printk ("scsi%d : dropped interrupt for command %ld\n", host->host_no,
5117	    cmd->pid);
5118	NCR53c7x0_intr (host->irq, NULL, NULL);
5119	return SCSI_ABORT_BUSY;
5120    }
5121
5122    save_flags(flags);
5123    cli();
5124
5125
5126/*
5127 * The command could be hiding in the issue_queue.  This would be very
5128 * nice, as commands can't be moved from the high level driver's issue queue
5129 * into the shared queue until an interrupt routine is serviced, and this
5130 * moving is atomic.
5131 *
5132 * If this is the case, we don't have to worry about anything - we simply
5133 * pull the command out of the old queue, and call it aborted.
5134 */
5135
5136    for (me = (Scsi_Cmnd *) hostdata->issue_queue,
5137         last = (Scsi_Cmnd **) &(hostdata->issue_queue);
5138	 me && me != cmd;  last = (Scsi_Cmnd **)&(me->SCp.ptr),
5139	 me = (Scsi_Cmnd *)me->SCp.ptr);
5140
5141    if (me) {
5142	*last = (Scsi_Cmnd *) me->SCp.ptr;
5143	if (me->host_scribble) {
5144	    ((struct NCR53c7x0_cmd *)me->host_scribble)->next = hostdata->free;
5145	    hostdata->free = (struct NCR53c7x0_cmd *) me->host_scribble;
5146	    me->host_scribble = NULL;
5147	}
5148	cmd->result = DID_ABORT << 16;
5149	cmd->scsi_done(cmd);
5150	printk ("scsi%d : found command %ld in Linux issue queue\n",
5151	    host->host_no, me->pid);
5152	restore_flags(flags);
5153    	run_process_issue_queue();
5154	return SCSI_ABORT_SUCCESS;
5155    }
5156
5157/*
5158 * That failing, the command could be in our list of already executing
5159 * commands.  If this is the case, drastic measures are called for.
5160 */
5161
5162    for (curr = (struct NCR53c7x0_cmd *) hostdata->running_list,
5163    	 prev = (struct NCR53c7x0_cmd **) &(hostdata->running_list);
5164	 curr && curr->cmd != cmd; prev = (struct NCR53c7x0_cmd **)
5165         &(curr->next), curr = (struct NCR53c7x0_cmd *) curr->next);
5166
5167    if (curr) {
5168	result = le32_to_cpu(cmd->result);
5169	if ((result & 0xff) != 0xff && (result & 0xff00) != 0xff00) {
5170	    if (prev)
5171		*prev = (struct NCR53c7x0_cmd *) curr->next;
5172	    curr->next = (struct NCR53c7x0_cmd *) hostdata->free;
5173	    cmd->host_scribble = NULL;
5174	    hostdata->free = curr;
5175	    cmd->scsi_done(cmd);
5176	printk ("scsi%d : found finished command %ld in running list\n",
5177	    host->host_no, cmd->pid);
5178	    restore_flags(flags);
5179	    return SCSI_ABORT_NOT_RUNNING;
5180	} else {
5181	    printk ("scsi%d : DANGER : command running, can not abort.\n",
5182		cmd->host->host_no);
5183	    restore_flags(flags);
5184	    return SCSI_ABORT_BUSY;
5185	}
5186    }
5187
5188/*
5189 * And if we couldn't find it in any of our queues, it must have been
5190 * a dropped interrupt.
5191 */
5192
5193    curr = (struct NCR53c7x0_cmd *) cmd->host_scribble;
5194    if (curr) {
5195	curr->next = hostdata->free;
5196	hostdata->free = curr;
5197	cmd->host_scribble = NULL;
5198    }
5199
5200    result = le32_to_cpu(cmd->result);
5201    if (((result & 0xff00) == 0xff00) ||
5202	((result & 0xff) == 0xff)) {
5203	printk ("scsi%d : did this command ever run?\n", host->host_no);
5204	cmd->result = DID_ABORT << 16;
5205    } else {
5206	printk ("scsi%d : probably lost INTFLY, normal completion\n",
5207	    host->host_no);
5208        --hostdata->busy[cmd->target][cmd->lun];
5209    }
5210    restore_flags(flags);
5211    cmd->scsi_done(cmd);
5212
5213/*
5214 * We need to run process_issue_queue since termination of this command
5215 * may allow another queued command to execute first?
5216 */
5217    return SCSI_ABORT_NOT_RUNNING;
5218}
5219
5220/*
5221 * Function : int NCR53c7xx_reset (Scsi_Cmnd *cmd)
5222 *
5223 * Purpose : perform a hard reset of the SCSI bus and NCR
5224 * 	chip.
5225 *
5226 * Inputs : cmd - command which caused the SCSI RESET
5227 *
5228 * Returns : 0 on success.
5229 */
5230
5231int
5232NCR53c7xx_reset (Scsi_Cmnd *cmd, unsigned int reset_flags) {
5233    NCR53c7x0_local_declare();
5234    unsigned long flags;
5235    int found = 0;
5236    struct NCR53c7x0_cmd * c;
5237    Scsi_Cmnd *tmp;
5238    /*
5239     * When we call scsi_done(), it's going to wake up anything sleeping on the
5240     * resources which were in use by the aborted commands, and we'll start to
5241     * get new commands.
5242     *
5243     * We can't let this happen until after we've re-initialized the driver
5244     * structures, and can't reinitialize those structures until after we've
5245     * dealt with their contents.
5246     *
5247     * So, we need to find all of the commands which were running, stick
5248     * them on a linked list of completed commands (we'll use the host_scribble
5249     * pointer), do our reinitialization, and then call the done function for
5250     * each command.
5251     */
5252    Scsi_Cmnd *nuke_list = NULL;
5253    struct Scsi_Host *host = cmd->host;
5254    struct NCR53c7x0_hostdata *hostdata =
5255    	(struct NCR53c7x0_hostdata *) host->hostdata;
5256
5257    NCR53c7x0_local_setup(host);
5258    save_flags(flags);
5259    cli();
5260    ncr_halt (host);
5261    print_lots (host);
5262    dump_events (host, 30);
5263    ncr_scsi_reset (host);
5264    for (tmp = nuke_list = return_outstanding_commands (host, 1 /* free */,
5265	0 /* issue */ ); tmp; tmp = (Scsi_Cmnd *) tmp->SCp.buffer)
5266	if (tmp == cmd) {
5267	    found = 1;
5268	    break;
5269	}
5270
5271    /*
5272     * If we didn't find the command which caused this reset in our running
5273     * list, then we've lost it.  See that it terminates normally anyway.
5274     */
5275    if (!found) {
5276    	c = (struct NCR53c7x0_cmd *) cmd->host_scribble;
5277    	if (c) {
5278	    cmd->host_scribble = NULL;
5279    	    c->next = hostdata->free;
5280    	    hostdata->free = c;
5281    	} else
5282	    printk ("scsi%d: lost command %ld\n", host->host_no, cmd->pid);
5283	cmd->SCp.buffer = (struct scatterlist *) nuke_list;
5284	nuke_list = cmd;
5285    }
5286
5287    NCR53c7x0_driver_init (host);
5288    hostdata->soft_reset (host);
5289    if (hostdata->resets == 0)
5290	disable(host);
5291    else if (hostdata->resets != -1)
5292	--hostdata->resets;
5293    restore_flags(flags);
5294    for (; nuke_list; nuke_list = tmp) {
5295	tmp = (Scsi_Cmnd *) nuke_list->SCp.buffer;
5296    	nuke_list->result = DID_RESET << 16;
5297	nuke_list->scsi_done (nuke_list);
5298    }
5299    restore_flags(flags);
5300    return SCSI_RESET_SUCCESS;
5301}
5302
5303/*
5304 * The NCR SDMS bios follows Annex A of the SCSI-CAM draft, and
5305 * therefore shares the scsicam_bios_param function.
5306 */
5307
5308/*
5309 * Function : int insn_to_offset (Scsi_Cmnd *cmd, u32 *insn)
5310 *
5311 * Purpose : convert instructions stored at NCR pointer into data
5312 *	pointer offset.
5313 *
5314 * Inputs : cmd - SCSI command; insn - pointer to instruction.  Either current
5315 *	DSP, or saved data pointer.
5316 *
5317 * Returns : offset on success, -1 on failure.
5318 */
5319
5320
5321static int
5322insn_to_offset (Scsi_Cmnd *cmd, u32 *insn) {
5323    struct NCR53c7x0_hostdata *hostdata =
5324	(struct NCR53c7x0_hostdata *) cmd->host->hostdata;
5325    struct NCR53c7x0_cmd *ncmd =
5326	(struct NCR53c7x0_cmd *) cmd->host_scribble;
5327    int offset = 0, buffers;
5328    struct scatterlist *segment;
5329    char *ptr;
5330    int found = 0;
5331
5332/*
5333 * With the current code implementation, if the insn is inside dynamically
5334 * generated code, the data pointer will be the instruction preceding
5335 * the next transfer segment.
5336 */
5337
5338    if (!check_address ((unsigned long) ncmd, sizeof (struct NCR53c7x0_cmd)) &&
5339	((insn >= ncmd->data_transfer_start &&
5340    	    insn < ncmd->data_transfer_end) ||
5341    	(insn >= ncmd->residual &&
5342    	    insn < (ncmd->residual +
5343    	    	sizeof(ncmd->residual))))) {
5344	    ptr = bus_to_virt(le32_to_cpu(insn[3]));
5345
5346	    if ((buffers = cmd->use_sg)) {
5347    	    	for (offset = 0,
5348		     	segment = (struct scatterlist *) cmd->buffer;
5349    	    	     buffers && !((found = ((ptr >= segment->address) &&
5350    	    	    	    (ptr < (segment->address + segment->length)))));
5351    	    	     --buffers, offset += segment->length, ++segment)
5352		    ;
5353    	    	    offset += ptr - segment->address;
5354    	    } else {
5355		found = 1;
5356    	    	offset = ptr - (char *) (cmd->request_buffer);
5357    	    }
5358    } else if ((insn >= hostdata->script +
5359		hostdata->E_data_transfer / sizeof(u32)) &&
5360	       (insn <= hostdata->script +
5361		hostdata->E_end_data_transfer / sizeof(u32))) {
5362    	found = 1;
5363	offset = 0;
5364    }
5365    return found ? offset : -1;
5366}
5367
5368
5369
5370/*
5371 * Function : void print_progress (Scsi_Cmnd *cmd)
5372 *
5373 * Purpose : print the current location of the saved data pointer
5374 *
5375 * Inputs : cmd - command we are interested in
5376 *
5377 */
5378
5379static void
5380print_progress (Scsi_Cmnd *cmd) {
5381    NCR53c7x0_local_declare();
5382    struct NCR53c7x0_cmd *ncmd =
5383	(struct NCR53c7x0_cmd *) cmd->host_scribble;
5384    int offset, i;
5385    char *where;
5386    u32 *ptr;
5387    NCR53c7x0_local_setup (cmd->host);
5388    for (i = 0; i < 2; ++i) {
5389	if (check_address ((unsigned long) ncmd,
5390	    sizeof (struct NCR53c7x0_cmd)) == -1)
5391	    continue;
5392	if (!i) {
5393	    where = "saved";
5394	    ptr = bus_to_virt(le32_to_cpu(ncmd->saved_data_pointer));
5395	} else {
5396	    where = "active";
5397	    ptr = bus_to_virt (NCR53c7x0_read32 (DSP_REG) -
5398		NCR53c7x0_insn_size (NCR53c7x0_read8 (DCMD_REG)) *
5399		sizeof(u32));
5400	}
5401	offset = insn_to_offset (cmd, ptr);
5402
5403	if (offset != -1)
5404	    printk ("scsi%d : %s data pointer at offset %d\n",
5405		cmd->host->host_no, where, offset);
5406	else {
5407	    int size;
5408	    printk ("scsi%d : can't determine %s data pointer offset\n",
5409		cmd->host->host_no, where);
5410	    if (ncmd) {
5411		size = print_insn (cmd->host,
5412		    bus_to_virt(le32_to_cpu(ncmd->saved_data_pointer)), "", 1);
5413		print_insn (cmd->host,
5414		    bus_to_virt(le32_to_cpu(ncmd->saved_data_pointer)) + size * sizeof(u32),
5415		    "", 1);
5416	    }
5417	}
5418    }
5419}
5420
5421
5422static void
5423print_dsa (struct Scsi_Host *host, u32 *dsa, const char *prefix) {
5424    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5425	host->hostdata;
5426    int i, len;
5427    char *ptr;
5428    Scsi_Cmnd *cmd;
5429
5430    if (check_address ((unsigned long) dsa, hostdata->dsa_end -
5431	hostdata->dsa_start) == -1) {
5432	printk("scsi%d : bad dsa virt 0x%p\n", host->host_no, dsa);
5433	return;
5434    }
5435    printk("%sscsi%d : dsa at phys 0x%lx (virt 0x%p)\n"
5436	    "        + %d : dsa_msgout length = %u, data = 0x%x (virt 0x%p)\n" ,
5437    	    prefix ? prefix : "",
5438    	    host->host_no,  virt_to_bus (dsa), dsa, hostdata->dsa_msgout,
5439    	    le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32)]),
5440	    le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32) + 1]),
5441	    bus_to_virt (le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32) + 1])));
5442
5443    /*
5444     * Only print messages if they're sane in length so we don't
5445     * blow the kernel printk buffer on something which won't buy us
5446     * anything.
5447     */
5448
5449    if (le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32)]) <
5450	    sizeof (hostdata->free->select))
5451	for (i = le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32)]),
5452	    ptr = bus_to_virt (le32_to_cpu(dsa[hostdata->dsa_msgout / sizeof(u32) + 1]));
5453	    i > 0 && !check_address ((unsigned long) ptr, 1);
5454	    ptr += len, i -= len) {
5455	    printk("               ");
5456	    len = print_msg (ptr);
5457	    printk("\n");
5458	    if (!len)
5459		break;
5460	}
5461
5462    printk("        + %d : select_indirect = 0x%x\n",
5463	hostdata->dsa_select, le32_to_cpu(dsa[hostdata->dsa_select / sizeof(u32)]));
5464    cmd = (Scsi_Cmnd *) bus_to_virt(le32_to_cpu(dsa[hostdata->dsa_cmnd / sizeof(u32)]));
5465    printk("        + %d : dsa_cmnd = 0x%x ", hostdata->dsa_cmnd,
5466	   (u32) virt_to_bus(cmd));
5467    if (cmd) {
5468	printk("               result = 0x%x, target = %d, lun = %d, cmd = ",
5469	    cmd->result, cmd->target, cmd->lun);
5470	print_command(cmd->cmnd);
5471    } else
5472	printk("\n");
5473    printk("        + %d : dsa_next = 0x%x\n", hostdata->dsa_next,
5474	le32_to_cpu(dsa[hostdata->dsa_next / sizeof(u32)]));
5475    if (cmd) {
5476	printk("scsi%d target %d : sxfer_sanity = 0x%x, scntl3_sanity = 0x%x\n"
5477	       "                   script : ",
5478	    host->host_no, cmd->target,
5479	    hostdata->sync[cmd->target].sxfer_sanity,
5480	    hostdata->sync[cmd->target].scntl3_sanity);
5481	for (i = 0; i < (sizeof(hostdata->sync[cmd->target].script) / 4); ++i)
5482	    printk ("0x%x ", hostdata->sync[cmd->target].script[i]);
5483	printk ("\n");
5484    	print_progress (cmd);
5485    }
5486}
5487/*
5488 * Function : void print_queues (Scsi_Host *host)
5489 *
5490 * Purpose : print the contents of the NCR issue and reconnect queues
5491 *
5492 * Inputs : host - SCSI host we are interested in
5493 *
5494 */
5495
5496static void
5497print_queues (struct Scsi_Host *host) {
5498    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5499	host->hostdata;
5500    u32 *dsa, *next_dsa;
5501    volatile u32 *curr;
5502    int left;
5503    Scsi_Cmnd *cmd, *next_cmd;
5504    unsigned long flags;
5505
5506    printk ("scsi%d : issue queue\n", host->host_no);
5507
5508    for (left = host->can_queue, cmd = (Scsi_Cmnd *) hostdata->issue_queue;
5509	    left >= 0 && cmd;
5510	    cmd = next_cmd) {
5511	next_cmd = (Scsi_Cmnd *) cmd->SCp.ptr;
5512	save_flags(flags);
5513	cli();
5514	if (cmd->host_scribble) {
5515	    if (check_address ((unsigned long) (cmd->host_scribble),
5516		sizeof (cmd->host_scribble)) == -1)
5517		printk ("scsi%d: scsi pid %ld bad pointer to NCR53c7x0_cmd\n",
5518		    host->host_no, cmd->pid);
5519	    /* print_dsa does sanity check on address, no need to check */
5520	    else
5521	    	print_dsa (host, bus_to_virt(le32_to_cpu(((struct NCR53c7x0_cmd *) cmd->host_scribble)-> dsa)), "");
5522	} else
5523	    printk ("scsi%d : scsi pid %ld for target %d lun %d has no NCR53c7x0_cmd\n",
5524		host->host_no, cmd->pid, cmd->target, cmd->lun);
5525	restore_flags(flags);
5526    }
5527
5528    if (left <= 0) {
5529	printk ("scsi%d : loop detected in issue queue\n",
5530	    host->host_no);
5531    }
5532
5533    /*
5534     * Traverse the NCR reconnect and start DSA structures, printing out
5535     * each element until we hit the end or detect a loop.  Currently,
5536     * the reconnect structure is a linked list; and the start structure
5537     * is an array.  Eventually, the reconnect structure will become a
5538     * list as well, since this simplifies the code.
5539     */
5540
5541    printk ("scsi%d : schedule dsa array :\n", host->host_no);
5542    for (left = host->can_queue, curr = hostdata->schedule;
5543	    left > 0; curr += 2, --left)
5544	if (curr[0] != hostdata->NOP_insn)
5545	    print_dsa (host, bus_to_virt (le32_to_cpu(curr[1]) -
5546		(hostdata->E_dsa_code_begin -
5547		hostdata->E_dsa_code_template)), "");
5548    printk ("scsi%d : end schedule dsa array\n", host->host_no);
5549
5550    printk ("scsi%d : reconnect_dsa_head :\n", host->host_no);
5551
5552    for (left = host->can_queue,
5553	dsa = bus_to_virt (le32_to_cpu(hostdata->reconnect_dsa_head));
5554	left >= 0 && dsa;
5555	dsa = next_dsa) {
5556	save_flags (flags);
5557	cli();
5558	if (check_address ((unsigned long) dsa, sizeof(dsa)) == -1) {
5559	    printk ("scsi%d: bad DSA pointer 0x%p", host->host_no,
5560		dsa);
5561	    next_dsa = NULL;
5562	}
5563	else
5564	{
5565	    next_dsa = bus_to_virt(le32_to_cpu(dsa[hostdata->dsa_next / sizeof(u32)]));
5566	    print_dsa (host, dsa, "");
5567	}
5568	restore_flags(flags);
5569    }
5570    printk ("scsi%d : end reconnect_dsa_head\n", host->host_no);
5571    if (left < 0)
5572	printk("scsi%d: possible loop in ncr reconnect list\n",
5573	    host->host_no);
5574}
5575
5576static void
5577print_lots (struct Scsi_Host *host) {
5578    NCR53c7x0_local_declare();
5579    struct NCR53c7x0_hostdata *hostdata =
5580	(struct NCR53c7x0_hostdata *) host->hostdata;
5581    u32 *dsp_next, *dsp, *dsa, dbc_dcmd;
5582    unsigned char dcmd, sbcl;
5583    int i, size;
5584    NCR53c7x0_local_setup(host);
5585
5586    if ((dsp_next = bus_to_virt(NCR53c7x0_read32 (DSP_REG)))) {
5587    	dbc_dcmd = NCR53c7x0_read32(DBC_REG);
5588    	dcmd = (dbc_dcmd & 0xff000000) >> 24;
5589    	dsp = dsp_next - NCR53c7x0_insn_size(dcmd);
5590	dsa = bus_to_virt(NCR53c7x0_read32(DSA_REG));
5591	sbcl = NCR53c7x0_read8 (SBCL_REG);
5592
5593
5594    	printk ("scsi%d : DCMD|DBC=0x%x, DNAD=0x%x (virt 0x%p)\n"
5595		"         DSA=0x%lx (virt 0x%p)\n"
5596	        "         DSPS=0x%x, TEMP=0x%x (virt 0x%p), DMODE=0x%x\n"
5597		"         SXFER=0x%x, SCNTL3=0x%x\n"
5598		"         %s%s%sphase=%s, %d bytes in SCSI FIFO\n"
5599		"         STEST0=0x%x\n",
5600	    host->host_no, dbc_dcmd, NCR53c7x0_read32(DNAD_REG),
5601		bus_to_virt(NCR53c7x0_read32(DNAD_REG)),
5602	    virt_to_bus(dsa), dsa,
5603	    NCR53c7x0_read32(DSPS_REG), NCR53c7x0_read32(TEMP_REG),
5604	    bus_to_virt (NCR53c7x0_read32(TEMP_REG)),
5605	    (int) NCR53c7x0_read8(hostdata->dmode),
5606	    (int) NCR53c7x0_read8(SXFER_REG),
5607	    (int) NCR53c7x0_read8(SCNTL3_REG_800),
5608	    (sbcl & SBCL_BSY) ? "BSY " : "",
5609	    (sbcl & SBCL_SEL) ? "SEL " : "",
5610	    (sbcl & SBCL_REQ) ? "REQ " : "",
5611	    sstat2_to_phase(NCR53c7x0_read8 (((hostdata->chip / 100) == 8) ?
5612	    	SSTAT1_REG : SSTAT2_REG)),
5613	    (NCR53c7x0_read8 ((hostdata->chip / 100) == 8 ?
5614		SSTAT1_REG : SSTAT2_REG) & SSTAT2_FF_MASK) >> SSTAT2_FF_SHIFT,
5615	    NCR53c7x0_read8 (STEST0_REG_800));
5616	printk ("scsi%d : DSP 0x%lx (virt 0x%p) ->\n", host->host_no,
5617	    virt_to_bus(dsp), dsp);
5618    	for (i = 6; i > 0; --i, dsp += size)
5619	    size = print_insn (host, dsp, "", 1);
5620	if (NCR53c7x0_read8 (SCNTL1_REG) & SCNTL1_CON)  {
5621	    printk ("scsi%d : connected (SDID=0x%x, SSID=0x%x)\n",
5622		host->host_no, NCR53c7x0_read8 (SDID_REG_800),
5623		NCR53c7x0_read8 (SSID_REG_800));
5624	    print_dsa (host, dsa, "");
5625	}
5626
5627	print_queues (host);
5628    }
5629}
5630
5631/*
5632 * Function : static int shutdown (struct Scsi_Host *host)
5633 *
5634 * Purpose : does a clean (we hope) shutdown of the NCR SCSI
5635 *	chip.  Use prior to dumping core, unloading the NCR driver,
5636 *
5637 * Returns : 0 on success
5638 */
5639static int
5640shutdown (struct Scsi_Host *host) {
5641    NCR53c7x0_local_declare();
5642    unsigned long flags;
5643    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5644	host->hostdata;
5645    NCR53c7x0_local_setup(host);
5646    save_flags (flags);
5647    cli();
5648/* Get in a state where we can reset the SCSI bus */
5649    ncr_halt (host);
5650    ncr_scsi_reset (host);
5651    hostdata->soft_reset(host);
5652
5653    disable (host);
5654    restore_flags (flags);
5655    return 0;
5656}
5657
5658/*
5659 * Function : void ncr_scsi_reset (struct Scsi_Host *host)
5660 *
5661 * Purpose : reset the SCSI bus.
5662 */
5663
5664static void
5665ncr_scsi_reset (struct Scsi_Host *host) {
5666    NCR53c7x0_local_declare();
5667    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5668	host->hostdata;
5669    unsigned long flags;
5670    int sien = 0;
5671    NCR53c7x0_local_setup(host);
5672    save_flags (flags);
5673    cli();
5674    if ((hostdata->chip / 100) == 8) {
5675	sien = NCR53c7x0_read8(SIEN0_REG_800);
5676	NCR53c7x0_write8(SIEN0_REG_800, sien & ~SIEN_RST);
5677    }
5678    NCR53c7x0_write8(SCNTL1_REG, SCNTL1_RST);
5679    udelay(25);	/* Minimum amount of time to assert RST */
5680    NCR53c7x0_write8(SCNTL1_REG, 0);
5681    if ((hostdata->chip / 100) == 8) {
5682	NCR53c7x0_write8(SIEN0_REG_800, sien);
5683    }
5684    restore_flags (flags);
5685}
5686
5687/*
5688 * Function : void hard_reset (struct Scsi_Host *host)
5689 *
5690 */
5691
5692static void
5693hard_reset (struct Scsi_Host *host) {
5694    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5695	host->hostdata;
5696    unsigned long flags;
5697    save_flags (flags);
5698    cli();
5699    ncr_scsi_reset(host);
5700    NCR53c7x0_driver_init (host);
5701    if (hostdata->soft_reset)
5702	hostdata->soft_reset (host);
5703    restore_flags(flags);
5704}
5705
5706
5707/*
5708 * Function : Scsi_Cmnd *return_outstanding_commands (struct Scsi_Host *host,
5709 *	int free, int issue)
5710 *
5711 * Purpose : return a linked list (using the SCp.buffer field as next,
5712 *	so we don't perturb hostdata.  We don't use a field of the
5713 *	NCR53c7x0_cmd structure since we may not have allocated one
5714 *	for the command causing the reset.) of Scsi_Cmnd structures that
5715 *  	had propagated below the Linux issue queue level.  If free is set,
5716 *	free the NCR53c7x0_cmd structures which are associated with
5717 *	the Scsi_Cmnd structures, and clean up any internal
5718 *	NCR lists that the commands were on.  If issue is set,
5719 *	also return commands in the issue queue.
5720 *
5721 * Returns : linked list of commands
5722 *
5723 * NOTE : the caller should insure that the NCR chip is halted
5724 *	if the free flag is set.
5725 */
5726
5727static Scsi_Cmnd *
5728return_outstanding_commands (struct Scsi_Host *host, int free, int issue) {
5729    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5730	host->hostdata;
5731    struct NCR53c7x0_cmd *c;
5732    int i;
5733    u32 *curr;
5734    Scsi_Cmnd *list = NULL, *tmp;
5735    for (c = (struct NCR53c7x0_cmd *) hostdata->running_list; c;
5736    	c = (struct NCR53c7x0_cmd *) c->next)  {
5737	if (c->cmd->SCp.buffer) {
5738	    printk ("scsi%d : loop detected in running list!\n", host->host_no);
5739	    break;
5740	} else {
5741	    printk ("Duh? Bad things happening in the NCR driver\n");
5742	    break;
5743	}
5744
5745	c->cmd->SCp.buffer = (struct scatterlist *) list;
5746	list = c->cmd;
5747	if (free) {
5748    	    c->next = hostdata->free;
5749    	    hostdata->free = c;
5750	}
5751    }
5752
5753    if (free) {
5754	for (i = 0, curr = (u32 *) hostdata->schedule;
5755	    i < host->can_queue; ++i, curr += 2) {
5756	    curr[0] = hostdata->NOP_insn;
5757	    curr[1] = le32_to_cpu(0xdeadbeef);
5758	}
5759	hostdata->curr = NULL;
5760    }
5761
5762    if (issue) {
5763	for (tmp = (Scsi_Cmnd *) hostdata->issue_queue; tmp; tmp = tmp->next) {
5764	    if (tmp->SCp.buffer) {
5765		printk ("scsi%d : loop detected in issue queue!\n",
5766			host->host_no);
5767		break;
5768	    }
5769	    tmp->SCp.buffer = (struct scatterlist *) list;
5770	    list = tmp;
5771	}
5772	if (free)
5773	    hostdata->issue_queue = NULL;
5774
5775    }
5776    return list;
5777}
5778
5779/*
5780 * Function : static int disable (struct Scsi_Host *host)
5781 *
5782 * Purpose : disables the given NCR host, causing all commands
5783 * 	to return a driver error.  Call this so we can unload the
5784 * 	module during development and try again.  Eventually,
5785 * 	we should be able to find clean workarounds for these
5786 * 	problems.
5787 *
5788 * Inputs : host - hostadapter to twiddle
5789 *
5790 * Returns : 0 on success.
5791 */
5792
5793static int
5794disable (struct Scsi_Host *host) {
5795    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5796	host->hostdata;
5797    unsigned long flags;
5798    Scsi_Cmnd *nuke_list, *tmp;
5799    save_flags(flags);
5800    cli();
5801    if (hostdata->state != STATE_HALTED)
5802	ncr_halt (host);
5803    nuke_list = return_outstanding_commands (host, 1 /* free */, 1 /* issue */);
5804    hard_reset (host);
5805    hostdata->state = STATE_DISABLED;
5806    restore_flags(flags);
5807    printk ("scsi%d : nuking commands\n", host->host_no);
5808    for (; nuke_list; nuke_list = tmp) {
5809	    tmp = (Scsi_Cmnd *) nuke_list->SCp.buffer;
5810	    nuke_list->result = DID_ERROR << 16;
5811	    nuke_list->scsi_done(nuke_list);
5812    }
5813    printk ("scsi%d : done. \n", host->host_no);
5814    printk (KERN_ALERT "scsi%d : disabled.  Unload and reload\n",
5815    	host->host_no);
5816    return 0;
5817}
5818
5819/*
5820 * Function : static int ncr_halt (struct Scsi_Host *host)
5821 *
5822 * Purpose : halts the SCSI SCRIPTS(tm) processor on the NCR chip
5823 *
5824 * Inputs : host - SCSI chip to halt
5825 *
5826 * Returns : 0 on success
5827 */
5828
5829static int
5830ncr_halt (struct Scsi_Host *host) {
5831    NCR53c7x0_local_declare();
5832    unsigned long flags;
5833    unsigned char istat, tmp;
5834    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5835	host->hostdata;
5836    int stage;
5837    NCR53c7x0_local_setup(host);
5838
5839    save_flags(flags);
5840    cli();
5841    /* Stage 0 : eat all interrupts
5842       Stage 1 : set ABORT
5843       Stage 2 : eat all but abort interrupts
5844       Stage 3 : eat all interrupts
5845     */
5846    for (stage = 0;;) {
5847	if (stage == 1) {
5848	    NCR53c7x0_write8(hostdata->istat, ISTAT_ABRT);
5849	    ++stage;
5850	}
5851	istat = NCR53c7x0_read8 (hostdata->istat);
5852	if (istat & ISTAT_SIP) {
5853	    if ((hostdata->chip / 100) == 8) {
5854		tmp = NCR53c7x0_read8(SIST0_REG_800);
5855		udelay(1);
5856		tmp = NCR53c7x0_read8(SIST1_REG_800);
5857	    } else {
5858		tmp = NCR53c7x0_read8(SSTAT0_REG);
5859	    }
5860	} else if (istat & ISTAT_DIP) {
5861	    tmp = NCR53c7x0_read8(DSTAT_REG);
5862	    if (stage == 2) {
5863		if (tmp & DSTAT_ABRT) {
5864		    NCR53c7x0_write8(hostdata->istat, 0);
5865		    ++stage;
5866		} else {
5867		    printk(KERN_ALERT "scsi%d : could not halt NCR chip\n",
5868			host->host_no);
5869		    disable (host);
5870	    	}
5871    	    }
5872	}
5873	if (!(istat & (ISTAT_SIP|ISTAT_DIP))) {
5874	    if (stage == 0)
5875	    	++stage;
5876	    else if (stage == 3)
5877		break;
5878	}
5879    }
5880    hostdata->state = STATE_HALTED;
5881    restore_flags(flags);
5882    return 0;
5883}
5884
5885/*
5886 * Function: event_name (int event)
5887 *
5888 * Purpose: map event enum into user-readable strings.
5889 */
5890
5891static const char *
5892event_name (int event) {
5893    switch (event) {
5894    case EVENT_NONE:		return "none";
5895    case EVENT_ISSUE_QUEUE:	return "to issue queue";
5896    case EVENT_START_QUEUE:	return "to start queue";
5897    case EVENT_SELECT:		return "selected";
5898    case EVENT_DISCONNECT:	return "disconnected";
5899    case EVENT_RESELECT:	return "reselected";
5900    case EVENT_COMPLETE:	return "completed";
5901    case EVENT_IDLE:		return "idle";
5902    case EVENT_SELECT_FAILED:	return "select failed";
5903    case EVENT_BEFORE_SELECT:	return "before select";
5904    case EVENT_RESELECT_FAILED:	return "reselect failed";
5905    default:			return "unknown";
5906    }
5907}
5908
5909/*
5910 * Function : void dump_events (struct Scsi_Host *host, count)
5911 *
5912 * Purpose : print last count events which have occurred.
5913 */
5914static void
5915dump_events (struct Scsi_Host *host, int count) {
5916    struct NCR53c7x0_hostdata *hostdata = (struct NCR53c7x0_hostdata *)
5917	host->hostdata;
5918    struct NCR53c7x0_event event;
5919    int i;
5920    unsigned long flags;
5921    if (hostdata->events) {
5922	if (count > hostdata->event_size)
5923	    count = hostdata->event_size;
5924	for (i = hostdata->event_index; count > 0;
5925	    i = (i ? i - 1 : hostdata->event_size -1), --count) {
5926	    save_flags(flags);
5927/*
5928 * By copying the event we're currently examining with interrupts
5929 * disabled, we can do multiple printk(), etc. operations and
5930 * still be guaranteed that they're happening on the same
5931 * event structure.
5932 */
5933	    cli();
5934	    memcpy ((void *) &event, (void *) &(hostdata->events[i]),
5935		sizeof(event));
5936
5937	    restore_flags(flags);
5938	    printk ("scsi%d : %s event %d at %ld secs %ld usecs target %d lun %d\n",
5939		host->host_no, event_name (event.event), count,
5940		(long) event.time.tv_sec, (long) event.time.tv_usec,
5941		event.target, event.lun);
5942	    if (event.dsa)
5943		printk ("         event for dsa 0x%lx (virt 0x%p)\n",
5944		    virt_to_bus(event.dsa), event.dsa);
5945	    if (event.pid != -1) {
5946		printk ("         event for pid %ld ", event.pid);
5947		print_command (event.cmnd);
5948	    }
5949	}
5950    }
5951}
5952
5953/*
5954 * Function: check_address
5955 *
5956 * Purpose: Check to see if a possibly corrupt pointer will fault the
5957 *	kernel.
5958 *
5959 * Inputs: addr - address; size - size of area
5960 *
5961 * Returns: 0 if area is OK, -1 on error.
5962 *
5963 * NOTES: should be implemented in terms of vverify on kernels
5964 *	that have it.
5965 */
5966
5967static int
5968check_address (unsigned long addr, int size) {
5969    return (virt_to_phys((void *)addr) < PAGE_SIZE || virt_to_phys((void *)(addr + size)) > virt_to_phys(high_memory) ?  -1 : 0);
5970}
5971
5972#ifdef MODULE
5973int
5974NCR53c7x0_release(struct Scsi_Host *host) {
5975    struct NCR53c7x0_hostdata *hostdata =
5976	(struct NCR53c7x0_hostdata *) host->hostdata;
5977    struct NCR53c7x0_cmd *cmd, *tmp;
5978    shutdown (host);
5979    if (host->irq != IRQ_NONE)
5980	{
5981	    int irq_count;
5982	    struct Scsi_Host *tmp;
5983	    for (irq_count = 0, tmp = first_host; tmp; tmp = tmp->next)
5984		if (tmp->hostt == the_template && tmp->irq == host->irq)
5985		    ++irq_count;
5986	    if (irq_count == 1)
5987		free_irq(host->irq, NULL);
5988	}
5989    if (host->dma_channel != DMA_NONE)
5990	free_dma(host->dma_channel);
5991    if (host->io_port)
5992	release_region(host->io_port, host->n_io_port);
5993
5994    for (cmd = (struct NCR53c7x0_cmd *) hostdata->free; cmd; cmd = tmp,
5995	--hostdata->num_cmds) {
5996	tmp = (struct NCR53c7x0_cmd *) cmd->next;
5997    /*
5998     * If we're going to loop, try to stop it to get a more accurate
5999     * count of the leaked commands.
6000     */
6001	cmd->next = NULL;
6002	if (cmd->free)
6003	    cmd->free ((void *) cmd->real, cmd->size);
6004    }
6005    if (hostdata->num_cmds)
6006	printk ("scsi%d : leaked %d NCR53c7x0_cmd structures\n",
6007	    host->host_no, hostdata->num_cmds);
6008    if (hostdata->events)
6009	vfree ((void *)hostdata->events);
6010    return 1;
6011}
6012#endif /* def MODULE */
6013MODULE_LICENSE("GPL");
6014
6015static Scsi_Host_Template driver_template = NCR53c7xx;
6016#include "scsi_module.c"
6017