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