Merge branch 'for-linus' of git://git.kernel.org/pub/scm/linux/kernel/git/jmorris...
[pandora-kernel.git] / drivers / scsi / NCR53C9x.c
1 /* NCR53C9x.c:  Generic SCSI driver code for NCR53C9x chips.
2  *
3  * Originally esp.c : EnhancedScsiProcessor Sun SCSI driver code.
4  *
5  * Copyright (C) 1995, 1998 David S. Miller (davem@caip.rutgers.edu)
6  *
7  * Most DMA dependencies put in driver specific files by 
8  * Jesper Skov (jskov@cygnus.co.uk)
9  *
10  * Set up to use esp_read/esp_write (preprocessor macros in NCR53c9x.h) by
11  * Tymm Twillman (tymm@coe.missouri.edu)
12  */
13
14 /* TODO:
15  *
16  * 1) Maybe disable parity checking in config register one for SCSI1
17  *    targets.  (Gilmore says parity error on the SBus can lock up
18  *    old sun4c's)
19  * 2) Add support for DMA2 pipelining.
20  * 3) Add tagged queueing.
21  * 4) Maybe change use of "esp" to something more "NCR"'ish.
22  */
23
24 #include <linux/module.h>
25
26 #include <linux/kernel.h>
27 #include <linux/delay.h>
28 #include <linux/types.h>
29 #include <linux/string.h>
30 #include <linux/slab.h>
31 #include <linux/blkdev.h>
32 #include <linux/interrupt.h>
33 #include <linux/proc_fs.h>
34 #include <linux/stat.h>
35 #include <linux/init.h>
36
37 #include "scsi.h"
38 #include <scsi/scsi_host.h>
39 #include "NCR53C9x.h"
40
41 #include <asm/system.h>
42 #include <asm/ptrace.h>
43 #include <asm/pgtable.h>
44 #include <asm/io.h>
45 #include <asm/irq.h>
46
47 /* Command phase enumeration. */
48 enum {
49         not_issued    = 0x00,  /* Still in the issue_SC queue.          */
50
51         /* Various forms of selecting a target. */
52 #define in_slct_mask    0x10
53         in_slct_norm  = 0x10,  /* ESP is arbitrating, normal selection  */
54         in_slct_stop  = 0x11,  /* ESP will select, then stop with IRQ   */
55         in_slct_msg   = 0x12,  /* select, then send a message           */
56         in_slct_tag   = 0x13,  /* select and send tagged queue msg      */
57         in_slct_sneg  = 0x14,  /* select and acquire sync capabilities  */
58
59         /* Any post selection activity. */
60 #define in_phases_mask  0x20
61         in_datain     = 0x20,  /* Data is transferring from the bus     */
62         in_dataout    = 0x21,  /* Data is transferring to the bus       */
63         in_data_done  = 0x22,  /* Last DMA data operation done (maybe)  */
64         in_msgin      = 0x23,  /* Eating message from target            */
65         in_msgincont  = 0x24,  /* Eating more msg bytes from target     */
66         in_msgindone  = 0x25,  /* Decide what to do with what we got    */
67         in_msgout     = 0x26,  /* Sending message to target             */
68         in_msgoutdone = 0x27,  /* Done sending msg out                  */
69         in_cmdbegin   = 0x28,  /* Sending cmd after abnormal selection  */
70         in_cmdend     = 0x29,  /* Done sending slow cmd                 */
71         in_status     = 0x2a,  /* Was in status phase, finishing cmd    */
72         in_freeing    = 0x2b,  /* freeing the bus for cmd cmplt or disc */
73         in_the_dark   = 0x2c,  /* Don't know what bus phase we are in   */
74
75         /* Special states, ie. not normal bus transitions... */
76 #define in_spec_mask    0x80
77         in_abortone   = 0x80,  /* Aborting one command currently        */
78         in_abortall   = 0x81,  /* Blowing away all commands we have     */
79         in_resetdev   = 0x82,  /* SCSI target reset in progress         */
80         in_resetbus   = 0x83,  /* SCSI bus reset in progress            */
81         in_tgterror   = 0x84,  /* Target did something stupid           */
82 };
83
84 enum {
85         /* Zero has special meaning, see skipahead[12]. */
86 /*0*/   do_never,
87
88 /*1*/   do_phase_determine,
89 /*2*/   do_reset_bus,
90 /*3*/   do_reset_complete,
91 /*4*/   do_work_bus,
92 /*5*/   do_intr_end
93 };
94
95 /* The master ring of all esp hosts we are managing in this driver. */
96 static struct NCR_ESP *espchain;
97 int nesps = 0, esps_in_use = 0, esps_running = 0;
98
99 irqreturn_t esp_intr(int irq, void *dev_id);
100
101 /* Debugging routines */
102 static struct esp_cmdstrings {
103         unchar cmdchar;
104         char *text;
105 } esp_cmd_strings[] = {
106         /* Miscellaneous */
107         { ESP_CMD_NULL, "ESP_NOP", },
108         { ESP_CMD_FLUSH, "FIFO_FLUSH", },
109         { ESP_CMD_RC, "RSTESP", },
110         { ESP_CMD_RS, "RSTSCSI", },
111         /* Disconnected State Group */
112         { ESP_CMD_RSEL, "RESLCTSEQ", },
113         { ESP_CMD_SEL, "SLCTNATN", },
114         { ESP_CMD_SELA, "SLCTATN", },
115         { ESP_CMD_SELAS, "SLCTATNSTOP", },
116         { ESP_CMD_ESEL, "ENSLCTRESEL", },
117         { ESP_CMD_DSEL, "DISSELRESEL", },
118         { ESP_CMD_SA3, "SLCTATN3", },
119         { ESP_CMD_RSEL3, "RESLCTSEQ", },
120         /* Target State Group */
121         { ESP_CMD_SMSG, "SNDMSG", },
122         { ESP_CMD_SSTAT, "SNDSTATUS", },
123         { ESP_CMD_SDATA, "SNDDATA", },
124         { ESP_CMD_DSEQ, "DISCSEQ", },
125         { ESP_CMD_TSEQ, "TERMSEQ", },
126         { ESP_CMD_TCCSEQ, "TRGTCMDCOMPSEQ", },
127         { ESP_CMD_DCNCT, "DISC", },
128         { ESP_CMD_RMSG, "RCVMSG", },
129         { ESP_CMD_RCMD, "RCVCMD", },
130         { ESP_CMD_RDATA, "RCVDATA", },
131         { ESP_CMD_RCSEQ, "RCVCMDSEQ", },
132         /* Initiator State Group */
133         { ESP_CMD_TI, "TRANSINFO", },
134         { ESP_CMD_ICCSEQ, "INICMDSEQCOMP", },
135         { ESP_CMD_MOK, "MSGACCEPTED", },
136         { ESP_CMD_TPAD, "TPAD", },
137         { ESP_CMD_SATN, "SATN", },
138         { ESP_CMD_RATN, "RATN", },
139 };
140 #define NUM_ESP_COMMANDS  ((sizeof(esp_cmd_strings)) / (sizeof(struct esp_cmdstrings)))
141
142 /* Print textual representation of an ESP command */
143 static inline void esp_print_cmd(unchar espcmd)
144 {
145         unchar dma_bit = espcmd & ESP_CMD_DMA;
146         int i;
147
148         espcmd &= ~dma_bit;
149         for(i=0; i<NUM_ESP_COMMANDS; i++)
150                 if(esp_cmd_strings[i].cmdchar == espcmd)
151                         break;
152         if(i==NUM_ESP_COMMANDS)
153                 printk("ESP_Unknown");
154         else
155                 printk("%s%s", esp_cmd_strings[i].text,
156                        ((dma_bit) ? "+DMA" : ""));
157 }
158
159 /* Print the status register's value */
160 static inline void esp_print_statreg(unchar statreg)
161 {
162         unchar phase;
163
164         printk("STATUS<");
165         phase = statreg & ESP_STAT_PMASK;
166         printk("%s,", (phase == ESP_DOP ? "DATA-OUT" :
167                        (phase == ESP_DIP ? "DATA-IN" :
168                         (phase == ESP_CMDP ? "COMMAND" :
169                          (phase == ESP_STATP ? "STATUS" :
170                           (phase == ESP_MOP ? "MSG-OUT" :
171                            (phase == ESP_MIP ? "MSG_IN" :
172                             "unknown")))))));
173         if(statreg & ESP_STAT_TDONE)
174                 printk("TRANS_DONE,");
175         if(statreg & ESP_STAT_TCNT)
176                 printk("TCOUNT_ZERO,");
177         if(statreg & ESP_STAT_PERR)
178                 printk("P_ERROR,");
179         if(statreg & ESP_STAT_SPAM)
180                 printk("SPAM,");
181         if(statreg & ESP_STAT_INTR)
182                 printk("IRQ,");
183         printk(">");
184 }
185
186 /* Print the interrupt register's value */
187 static inline void esp_print_ireg(unchar intreg)
188 {
189         printk("INTREG< ");
190         if(intreg & ESP_INTR_S)
191                 printk("SLCT_NATN ");
192         if(intreg & ESP_INTR_SATN)
193                 printk("SLCT_ATN ");
194         if(intreg & ESP_INTR_RSEL)
195                 printk("RSLCT ");
196         if(intreg & ESP_INTR_FDONE)
197                 printk("FDONE ");
198         if(intreg & ESP_INTR_BSERV)
199                 printk("BSERV ");
200         if(intreg & ESP_INTR_DC)
201                 printk("DISCNCT ");
202         if(intreg & ESP_INTR_IC)
203                 printk("ILL_CMD ");
204         if(intreg & ESP_INTR_SR)
205                 printk("SCSI_BUS_RESET ");
206         printk(">");
207 }
208
209 /* Print the sequence step registers contents */
210 static inline void esp_print_seqreg(unchar stepreg)
211 {
212         stepreg &= ESP_STEP_VBITS;
213         printk("STEP<%s>",
214                (stepreg == ESP_STEP_ASEL ? "SLCT_ARB_CMPLT" :
215                 (stepreg == ESP_STEP_SID ? "1BYTE_MSG_SENT" :
216                  (stepreg == ESP_STEP_NCMD ? "NOT_IN_CMD_PHASE" :
217                   (stepreg == ESP_STEP_PPC ? "CMD_BYTES_LOST" :
218                    (stepreg == ESP_STEP_FINI4 ? "CMD_SENT_OK" :
219                     "UNKNOWN"))))));
220 }
221
222 static char *phase_string(int phase)
223 {
224         switch(phase) {
225         case not_issued:
226                 return "UNISSUED";
227         case in_slct_norm:
228                 return "SLCTNORM";
229         case in_slct_stop:
230                 return "SLCTSTOP";
231         case in_slct_msg:
232                 return "SLCTMSG";
233         case in_slct_tag:
234                 return "SLCTTAG";
235         case in_slct_sneg:
236                 return "SLCTSNEG";
237         case in_datain:
238                 return "DATAIN";
239         case in_dataout:
240                 return "DATAOUT";
241         case in_data_done:
242                 return "DATADONE";
243         case in_msgin:
244                 return "MSGIN";
245         case in_msgincont:
246                 return "MSGINCONT";
247         case in_msgindone:
248                 return "MSGINDONE";
249         case in_msgout:
250                 return "MSGOUT";
251         case in_msgoutdone:
252                 return "MSGOUTDONE";
253         case in_cmdbegin:
254                 return "CMDBEGIN";
255         case in_cmdend:
256                 return "CMDEND";
257         case in_status:
258                 return "STATUS";
259         case in_freeing:
260                 return "FREEING";
261         case in_the_dark:
262                 return "CLUELESS";
263         case in_abortone:
264                 return "ABORTONE";
265         case in_abortall:
266                 return "ABORTALL";
267         case in_resetdev:
268                 return "RESETDEV";
269         case in_resetbus:
270                 return "RESETBUS";
271         case in_tgterror:
272                 return "TGTERROR";
273         default:
274                 return "UNKNOWN";
275         };
276 }
277
278 #ifdef DEBUG_STATE_MACHINE
279 static inline void esp_advance_phase(Scsi_Cmnd *s, int newphase)
280 {
281         ESPLOG(("<%s>", phase_string(newphase)));
282         s->SCp.sent_command = s->SCp.phase;
283         s->SCp.phase = newphase;
284 }
285 #else
286 #define esp_advance_phase(__s, __newphase) \
287         (__s)->SCp.sent_command = (__s)->SCp.phase; \
288         (__s)->SCp.phase = (__newphase);
289 #endif
290
291 #ifdef DEBUG_ESP_CMDS
292 static inline void esp_cmd(struct NCR_ESP *esp, struct ESP_regs *eregs,
293                            unchar cmd)
294 {
295         esp->espcmdlog[esp->espcmdent] = cmd;
296         esp->espcmdent = (esp->espcmdent + 1) & 31;
297         esp_write(eregs->esp_cmnd, cmd);
298 }
299 #else
300 #define esp_cmd(__esp, __eregs, __cmd)  esp_write((__eregs)->esp_cmnd, (__cmd))
301 #endif
302
303 /* How we use the various Linux SCSI data structures for operation.
304  *
305  * struct scsi_cmnd:
306  *
307  *   We keep track of the syncronous capabilities of a target
308  *   in the device member, using sync_min_period and
309  *   sync_max_offset.  These are the values we directly write
310  *   into the ESP registers while running a command.  If offset
311  *   is zero the ESP will use asynchronous transfers.
312  *   If the borken flag is set we assume we shouldn't even bother
313  *   trying to negotiate for synchronous transfer as this target
314  *   is really stupid.  If we notice the target is dropping the
315  *   bus, and we have been allowing it to disconnect, we clear
316  *   the disconnect flag.
317  */
318
319 /* Manipulation of the ESP command queues.  Thanks to the aha152x driver
320  * and its author, Juergen E. Fischer, for the methods used here.
321  * Note that these are per-ESP queues, not global queues like
322  * the aha152x driver uses.
323  */
324 static inline void append_SC(Scsi_Cmnd **SC, Scsi_Cmnd *new_SC)
325 {
326         Scsi_Cmnd *end;
327
328         new_SC->host_scribble = (unsigned char *) NULL;
329         if(!*SC)
330                 *SC = new_SC;
331         else {
332                 for(end=*SC;end->host_scribble;end=(Scsi_Cmnd *)end->host_scribble)
333                         ;
334                 end->host_scribble = (unsigned char *) new_SC;
335         }
336 }
337
338 static inline void prepend_SC(Scsi_Cmnd **SC, Scsi_Cmnd *new_SC)
339 {
340         new_SC->host_scribble = (unsigned char *) *SC;
341         *SC = new_SC;
342 }
343
344 static inline Scsi_Cmnd *remove_first_SC(Scsi_Cmnd **SC)
345 {
346         Scsi_Cmnd *ptr;
347
348         ptr = *SC;
349         if(ptr)
350                 *SC = (Scsi_Cmnd *) (*SC)->host_scribble;
351         return ptr;
352 }
353
354 static inline Scsi_Cmnd *remove_SC(Scsi_Cmnd **SC, int target, int lun)
355 {
356         Scsi_Cmnd *ptr, *prev;
357
358         for(ptr = *SC, prev = NULL;
359             ptr && ((ptr->device->id != target) || (ptr->device->lun != lun));
360             prev = ptr, ptr = (Scsi_Cmnd *) ptr->host_scribble)
361                 ;
362         if(ptr) {
363                 if(prev)
364                         prev->host_scribble=ptr->host_scribble;
365                 else
366                         *SC=(Scsi_Cmnd *)ptr->host_scribble;
367         }
368         return ptr;
369 }
370
371 /* Resetting various pieces of the ESP scsi driver chipset */
372
373 /* Reset the ESP chip, _not_ the SCSI bus. */
374 static void esp_reset_esp(struct NCR_ESP *esp, struct ESP_regs *eregs)
375 {
376         int family_code, version, i;
377         volatile int trash;
378
379         /* Now reset the ESP chip */
380         esp_cmd(esp, eregs, ESP_CMD_RC);
381         esp_cmd(esp, eregs, ESP_CMD_NULL | ESP_CMD_DMA);
382         if(esp->erev == fast)
383                 esp_write(eregs->esp_cfg2, ESP_CONFIG2_FENAB);
384         esp_cmd(esp, eregs, ESP_CMD_NULL | ESP_CMD_DMA);
385
386         /* This is the only point at which it is reliable to read
387          * the ID-code for a fast ESP chip variant.
388          */
389         esp->max_period = ((35 * esp->ccycle) / 1000);
390         if(esp->erev == fast) {
391                 char *erev2string[] = {
392                         "Emulex FAS236",
393                         "Emulex FPESP100A",
394                         "fast",
395                         "QLogic FAS366",
396                         "Emulex FAS216",
397                         "Symbios Logic 53CF9x-2",
398                         "unknown!"
399                 };
400                         
401                 version = esp_read(eregs->esp_uid);
402                 family_code = (version & 0xf8) >> 3;
403                 if(family_code == 0x02) {
404                         if ((version & 7) == 2)
405                                 esp->erev = fas216;     
406                         else
407                                 esp->erev = fas236;
408                 } else if(family_code == 0x0a)
409                         esp->erev = fas366; /* Version is usually '5'. */
410                 else if(family_code == 0x00) {
411                         if ((version & 7) == 2)
412                                 esp->erev = fas100a; /* NCR53C9X */
413                         else
414                                 esp->erev = espunknown;
415                 } else if(family_code == 0x14) {
416                         if ((version & 7) == 2)
417                                 esp->erev = fsc;
418                         else
419                                 esp->erev = espunknown;
420                 } else if(family_code == 0x00) {
421                         if ((version & 7) == 2)
422                                 esp->erev = fas100a; /* NCR53C9X */
423                         else
424                                 esp->erev = espunknown;
425                 } else
426                         esp->erev = espunknown;
427                 ESPLOG(("esp%d: FAST chip is %s (family=%d, version=%d)\n",
428                         esp->esp_id, erev2string[esp->erev - fas236],
429                         family_code, (version & 7)));
430
431                 esp->min_period = ((4 * esp->ccycle) / 1000);
432         } else {
433                 esp->min_period = ((5 * esp->ccycle) / 1000);
434         }
435
436         /* Reload the configuration registers */
437         esp_write(eregs->esp_cfact, esp->cfact);
438         esp->prev_stp = 0;
439         esp_write(eregs->esp_stp, 0);
440         esp->prev_soff = 0;
441         esp_write(eregs->esp_soff, 0);
442         esp_write(eregs->esp_timeo, esp->neg_defp);
443         esp->max_period = (esp->max_period + 3)>>2;
444         esp->min_period = (esp->min_period + 3)>>2;
445
446         esp_write(eregs->esp_cfg1, esp->config1);
447         switch(esp->erev) {
448         case esp100:
449                 /* nothing to do */
450                 break;
451         case esp100a:
452                 esp_write(eregs->esp_cfg2, esp->config2);
453                 break;
454         case esp236:
455                 /* Slow 236 */
456                 esp_write(eregs->esp_cfg2, esp->config2);
457                 esp->prev_cfg3 = esp->config3[0];
458                 esp_write(eregs->esp_cfg3, esp->prev_cfg3);
459                 break;
460         case fas366:
461                 panic("esp: FAS366 support not present, please notify "
462                       "jongk@cs.utwente.nl");
463                 break;
464         case fas216:
465         case fas236:
466         case fsc:
467                 /* Fast ESP variants */
468                 esp_write(eregs->esp_cfg2, esp->config2);
469                 for(i=0; i<8; i++)
470                         esp->config3[i] |= ESP_CONFIG3_FCLK;
471                 esp->prev_cfg3 = esp->config3[0];
472                 esp_write(eregs->esp_cfg3, esp->prev_cfg3);
473                 if(esp->diff)
474                         esp->radelay = 0;
475                 else
476                         esp->radelay = 16;
477                 /* Different timeout constant for these chips */
478                 esp->neg_defp =
479                         FSC_NEG_DEFP(esp->cfreq,
480                                      (esp->cfact == ESP_CCF_F0 ?
481                                       ESP_CCF_F7 + 1 : esp->cfact));
482                 esp_write(eregs->esp_timeo, esp->neg_defp);
483                 /* Enable Active Negotiation if possible */
484                 if((esp->erev == fsc) && !esp->diff)
485                         esp_write(eregs->esp_cfg4, ESP_CONFIG4_EAN);
486                 break;
487         case fas100a:
488                 /* Fast 100a */
489                 esp_write(eregs->esp_cfg2, esp->config2);
490                 for(i=0; i<8; i++)
491                         esp->config3[i] |= ESP_CONFIG3_FCLOCK;
492                 esp->prev_cfg3 = esp->config3[0];
493                 esp_write(eregs->esp_cfg3, esp->prev_cfg3);
494                 esp->radelay = 32;
495                 break;
496         default:
497                 panic("esp: what could it be... I wonder...");
498                 break;
499         };
500
501         /* Eat any bitrot in the chip */
502         trash = esp_read(eregs->esp_intrpt);
503         udelay(100);
504 }
505
506 /* This places the ESP into a known state at boot time. */
507 void esp_bootup_reset(struct NCR_ESP *esp, struct ESP_regs *eregs)
508 {
509         volatile unchar trash;
510
511         /* Reset the DMA */
512         if(esp->dma_reset)
513                 esp->dma_reset(esp);
514
515         /* Reset the ESP */
516         esp_reset_esp(esp, eregs);
517
518         /* Reset the SCSI bus, but tell ESP not to generate an irq */
519         esp_write(eregs->esp_cfg1, (esp_read(eregs->esp_cfg1) | ESP_CONFIG1_SRRDISAB));
520         esp_cmd(esp, eregs, ESP_CMD_RS);
521         udelay(400);
522         esp_write(eregs->esp_cfg1, esp->config1);
523
524         /* Eat any bitrot in the chip and we are done... */
525         trash = esp_read(eregs->esp_intrpt);
526 }
527
528 /* Allocate structure and insert basic data such as SCSI chip frequency
529  * data and a pointer to the device
530  */
531 struct NCR_ESP* esp_allocate(struct scsi_host_template *tpnt, void *esp_dev,
532                              int hotplug)
533 {
534         struct NCR_ESP *esp, *elink;
535         struct Scsi_Host *esp_host;
536
537         if (hotplug)
538                 esp_host = scsi_host_alloc(tpnt, sizeof(struct NCR_ESP));
539         else
540                 esp_host = scsi_register(tpnt, sizeof(struct NCR_ESP));
541         if(!esp_host)
542                 panic("Cannot register ESP SCSI host");
543         esp = (struct NCR_ESP *) esp_host->hostdata;
544         if(!esp)
545                 panic("No esp in hostdata");
546         esp->ehost = esp_host;
547         esp->edev = esp_dev;
548         esp->esp_id = nesps++;
549
550         /* Set bitshift value (only used on Amiga with multiple ESPs) */
551         esp->shift = 2;
552
553         /* Put into the chain of esp chips detected */
554         if(espchain) {
555                 elink = espchain;
556                 while(elink->next) elink = elink->next;
557                 elink->next = esp;
558         } else {
559                 espchain = esp;
560         }
561         esp->next = NULL;
562
563         return esp;
564 }
565
566 void esp_deallocate(struct NCR_ESP *esp)
567 {
568         struct NCR_ESP *elink;
569
570         if(espchain == esp) {
571                 espchain = NULL;
572         } else {
573                 for(elink = espchain; elink && (elink->next != esp); elink = elink->next);
574                 if(elink) 
575                         elink->next = esp->next;
576         }
577         nesps--;
578 }
579
580 /* Complete initialization of ESP structure and device
581  * Caller must have initialized appropriate parts of the ESP structure
582  * between the call to esp_allocate and this function.
583  */
584 void esp_initialize(struct NCR_ESP *esp)
585 {
586         struct ESP_regs *eregs = esp->eregs;
587         unsigned int fmhz;
588         unchar ccf;
589         int i;
590         
591         /* Check out the clock properties of the chip. */
592
593         /* This is getting messy but it has to be done
594          * correctly or else you get weird behavior all
595          * over the place.  We are trying to basically
596          * figure out three pieces of information.
597          *
598          * a) Clock Conversion Factor
599          *
600          *    This is a representation of the input
601          *    crystal clock frequency going into the
602          *    ESP on this machine.  Any operation whose
603          *    timing is longer than 400ns depends on this
604          *    value being correct.  For example, you'll
605          *    get blips for arbitration/selection during
606          *    high load or with multiple targets if this
607          *    is not set correctly.
608          *
609          * b) Selection Time-Out
610          *
611          *    The ESP isn't very bright and will arbitrate
612          *    for the bus and try to select a target
613          *    forever if you let it.  This value tells
614          *    the ESP when it has taken too long to
615          *    negotiate and that it should interrupt
616          *    the CPU so we can see what happened.
617          *    The value is computed as follows (from
618          *    NCR/Symbios chip docs).
619          *
620          *          (Time Out Period) *  (Input Clock)
621          *    STO = ----------------------------------
622          *          (8192) * (Clock Conversion Factor)
623          *
624          *    You usually want the time out period to be
625          *    around 250ms, I think we'll set it a little
626          *    bit higher to account for fully loaded SCSI
627          *    bus's and slow devices that don't respond so
628          *    quickly to selection attempts. (yeah, I know
629          *    this is out of spec. but there is a lot of
630          *    buggy pieces of firmware out there so bite me)
631          *
632          * c) Imperical constants for synchronous offset
633          *    and transfer period register values
634          *
635          *    This entails the smallest and largest sync
636          *    period we could ever handle on this ESP.
637          */
638         
639         fmhz = esp->cfreq;
640
641         if(fmhz <= (5000000))
642                 ccf = 0;
643         else
644                 ccf = (((5000000 - 1) + (fmhz))/(5000000));
645         if(!ccf || ccf > 8) {
646                 /* If we can't find anything reasonable,
647                  * just assume 20MHZ.  This is the clock
648                  * frequency of the older sun4c's where I've
649                  * been unable to find the clock-frequency
650                  * PROM property.  All other machines provide
651                  * useful values it seems.
652                  */
653                 ccf = ESP_CCF_F4;
654                 fmhz = (20000000);
655         }
656         if(ccf==(ESP_CCF_F7+1))
657                 esp->cfact = ESP_CCF_F0;
658         else if(ccf == ESP_CCF_NEVER)
659                 esp->cfact = ESP_CCF_F2;
660         else
661                 esp->cfact = ccf;
662         esp->cfreq = fmhz;
663         esp->ccycle = ESP_MHZ_TO_CYCLE(fmhz);
664         esp->ctick = ESP_TICK(ccf, esp->ccycle);
665         esp->neg_defp = ESP_NEG_DEFP(fmhz, ccf);
666         esp->sync_defp = SYNC_DEFP_SLOW;
667
668         printk("SCSI ID %d Clk %dMHz CCF=%d TOut %d ",
669                esp->scsi_id, (esp->cfreq / 1000000),
670                ccf, (int) esp->neg_defp);
671
672         /* Fill in ehost data */
673         esp->ehost->base = (unsigned long)eregs;
674         esp->ehost->this_id = esp->scsi_id;
675         esp->ehost->irq = esp->irq;
676
677         /* SCSI id mask */
678         esp->scsi_id_mask = (1 << esp->scsi_id);
679
680         /* Probe the revision of this esp */
681         esp->config1 = (ESP_CONFIG1_PENABLE | (esp->scsi_id & 7));
682         esp->config2 = (ESP_CONFIG2_SCSI2ENAB | ESP_CONFIG2_REGPARITY);
683         esp_write(eregs->esp_cfg2, esp->config2);
684         if((esp_read(eregs->esp_cfg2) & ~(ESP_CONFIG2_MAGIC)) !=
685            (ESP_CONFIG2_SCSI2ENAB | ESP_CONFIG2_REGPARITY)) {
686                 printk("NCR53C90(esp100)\n");
687                 esp->erev = esp100;
688         } else {
689                 esp->config2 = 0;
690                 esp_write(eregs->esp_cfg2, 0);
691                 esp_write(eregs->esp_cfg3, 5);
692                 if(esp_read(eregs->esp_cfg3) != 5) {
693                         printk("NCR53C90A(esp100a)\n");
694                         esp->erev = esp100a;
695                 } else {
696                         int target;
697
698                         for(target=0; target<8; target++)
699                                 esp->config3[target] = 0;
700                         esp->prev_cfg3 = 0;
701                         esp_write(eregs->esp_cfg3, 0);
702                         if(ccf > ESP_CCF_F5) {
703                                 printk("NCR53C9XF(espfast)\n");
704                                 esp->erev = fast;
705                                 esp->sync_defp = SYNC_DEFP_FAST;
706                         } else {
707                                 printk("NCR53C9x(esp236)\n");
708                                 esp->erev = esp236;
709                         }
710                 }
711         }                               
712
713         /* Initialize the command queues */
714         esp->current_SC = NULL;
715         esp->disconnected_SC = NULL;
716         esp->issue_SC = NULL;
717
718         /* Clear the state machines. */
719         esp->targets_present = 0;
720         esp->resetting_bus = 0;
721         esp->snip = 0;
722
723         init_waitqueue_head(&esp->reset_queue);
724
725         esp->fas_premature_intr_workaround = 0;
726         for(i = 0; i < 32; i++)
727                 esp->espcmdlog[i] = 0;
728         esp->espcmdent = 0;
729         for(i = 0; i < 16; i++) {
730                 esp->cur_msgout[i] = 0;
731                 esp->cur_msgin[i] = 0;
732         }
733         esp->prevmsgout = esp->prevmsgin = 0;
734         esp->msgout_len = esp->msgin_len = 0;
735
736         /* Clear the one behind caches to hold unmatchable values. */
737         esp->prev_soff = esp->prev_stp = esp->prev_cfg3 = 0xff;
738
739         /* Reset the thing before we try anything... */
740         esp_bootup_reset(esp, eregs);
741
742         esps_in_use++;
743 }
744
745 /* The info function will return whatever useful
746  * information the developer sees fit.  If not provided, then
747  * the name field will be used instead.
748  */
749 const char *esp_info(struct Scsi_Host *host)
750 {
751         struct NCR_ESP *esp;
752
753         esp = (struct NCR_ESP *) host->hostdata;
754         switch(esp->erev) {
755         case esp100:
756                 return "ESP100 (NCR53C90)";
757         case esp100a:
758                 return "ESP100A (NCR53C90A)";
759         case esp236:
760                 return "ESP236 (NCR53C9x)";
761         case fas216:
762                 return "Emulex FAS216";
763         case fas236:
764                 return "Emulex FAS236";
765         case fas366:
766                 return "QLogic FAS366";
767         case fas100a:
768                 return "FPESP100A";
769         case fsc:
770                 return "Symbios Logic 53CF9x-2";
771         default:
772                 panic("Bogon ESP revision");
773         };
774 }
775
776 /* From Wolfgang Stanglmeier's NCR scsi driver. */
777 struct info_str
778 {
779         char *buffer;
780         int length;
781         int offset;
782         int pos;
783 };
784
785 static void copy_mem_info(struct info_str *info, char *data, int len)
786 {
787         if (info->pos + len > info->length)
788                 len = info->length - info->pos;
789
790         if (info->pos + len < info->offset) {
791                 info->pos += len;
792                 return;
793         }
794         if (info->pos < info->offset) {
795                 data += (info->offset - info->pos);
796                 len  -= (info->offset - info->pos);
797         }
798
799         if (len > 0) {
800                 memcpy(info->buffer + info->pos, data, len);
801                 info->pos += len;
802         }
803 }
804
805 static int copy_info(struct info_str *info, char *fmt, ...)
806 {
807         va_list args;
808         char buf[81];
809         int len;
810
811         va_start(args, fmt);
812         len = vsprintf(buf, fmt, args);
813         va_end(args);
814
815         copy_mem_info(info, buf, len);
816         return len;
817 }
818
819 static int esp_host_info(struct NCR_ESP *esp, char *ptr, off_t offset, int len)
820 {
821         struct scsi_device *sdev;
822         struct info_str info;
823         int i;
824
825         info.buffer     = ptr;
826         info.length     = len;
827         info.offset     = offset;
828         info.pos        = 0;
829
830         copy_info(&info, "ESP Host Adapter:\n");
831         copy_info(&info, "\tESP Model\t\t");
832         switch(esp->erev) {
833         case esp100:
834                 copy_info(&info, "ESP100 (NCR53C90)\n");
835                 break;
836         case esp100a:
837                 copy_info(&info, "ESP100A (NCR53C90A)\n");
838                 break;
839         case esp236:
840                 copy_info(&info, "ESP236 (NCR53C9x)\n");
841                 break;
842         case fas216:
843                 copy_info(&info, "Emulex FAS216\n");
844                 break;
845         case fas236:
846                 copy_info(&info, "Emulex FAS236\n");
847                 break;
848         case fas100a:
849                 copy_info(&info, "FPESP100A\n");
850                 break;
851         case fast:
852                 copy_info(&info, "Generic FAST\n");
853                 break;
854         case fas366:
855                 copy_info(&info, "QLogic FAS366\n");
856                 break;
857         case fsc:
858                 copy_info(&info, "Symbios Logic 53C9x-2\n");
859                 break;
860         case espunknown:
861         default:
862                 copy_info(&info, "Unknown!\n");
863                 break;
864         };
865         copy_info(&info, "\tLive Targets\t\t[ ");
866         for(i = 0; i < 15; i++) {
867                 if(esp->targets_present & (1 << i))
868                         copy_info(&info, "%d ", i);
869         }
870         copy_info(&info, "]\n\n");
871         
872         /* Now describe the state of each existing target. */
873         copy_info(&info, "Target #\tconfig3\t\tSync Capabilities\tDisconnect\n");
874
875         shost_for_each_device(sdev, esp->ehost) {
876                 struct esp_device *esp_dev = sdev->hostdata;
877                 uint id = sdev->id;
878
879                 if (!(esp->targets_present & (1 << id)))
880                         continue;
881
882                 copy_info(&info, "%d\t\t", id);
883                 copy_info(&info, "%08lx\t", esp->config3[id]);
884                 copy_info(&info, "[%02lx,%02lx]\t\t\t",
885                         esp_dev->sync_max_offset,
886                         esp_dev->sync_min_period);
887                 copy_info(&info, "%s\n", esp_dev->disconnect ? "yes" : "no");
888         }
889
890         return info.pos > info.offset? info.pos - info.offset : 0;
891 }
892
893 /* ESP proc filesystem code. */
894 int esp_proc_info(struct Scsi_Host *shost, char *buffer, char **start, off_t offset, int length,
895                   int inout)
896 {
897         struct NCR_ESP *esp = (struct NCR_ESP *)shost->hostdata;
898
899         if(inout)
900                 return -EINVAL; /* not yet */
901         if(start)
902                 *start = buffer;
903         return esp_host_info(esp, buffer, offset, length);
904 }
905
906 static void esp_get_dmabufs(struct NCR_ESP *esp, Scsi_Cmnd *sp)
907 {
908         if(sp->use_sg == 0) {
909                 sp->SCp.this_residual = sp->request_bufflen;
910                 sp->SCp.buffer = (struct scatterlist *) sp->request_buffer;
911                 sp->SCp.buffers_residual = 0;
912                 if (esp->dma_mmu_get_scsi_one)
913                         esp->dma_mmu_get_scsi_one(esp, sp);
914                 else
915                         sp->SCp.ptr =
916                                 (char *) virt_to_phys(sp->request_buffer);
917         } else {
918                 sp->SCp.buffer = (struct scatterlist *) sp->request_buffer;
919                 sp->SCp.buffers_residual = sp->use_sg - 1;
920                 sp->SCp.this_residual = sp->SCp.buffer->length;
921                 if (esp->dma_mmu_get_scsi_sgl)
922                         esp->dma_mmu_get_scsi_sgl(esp, sp);
923                 else
924                         sp->SCp.ptr =
925                                 (char *) virt_to_phys((page_address(sp->SCp.buffer->page) + sp->SCp.buffer->offset));
926         }
927 }
928
929 static void esp_release_dmabufs(struct NCR_ESP *esp, Scsi_Cmnd *sp)
930 {
931         if(sp->use_sg == 0) {
932                 if (esp->dma_mmu_release_scsi_one)
933                         esp->dma_mmu_release_scsi_one(esp, sp);
934         } else {
935                 if (esp->dma_mmu_release_scsi_sgl)
936                         esp->dma_mmu_release_scsi_sgl(esp, sp);
937         }
938 }
939
940 static void esp_restore_pointers(struct NCR_ESP *esp, Scsi_Cmnd *sp)
941 {
942         struct esp_pointers *ep = &esp->data_pointers[scmd_id(sp)];
943
944         sp->SCp.ptr = ep->saved_ptr;
945         sp->SCp.buffer = ep->saved_buffer;
946         sp->SCp.this_residual = ep->saved_this_residual;
947         sp->SCp.buffers_residual = ep->saved_buffers_residual;
948 }
949
950 static void esp_save_pointers(struct NCR_ESP *esp, Scsi_Cmnd *sp)
951 {
952         struct esp_pointers *ep = &esp->data_pointers[scmd_id(sp)];
953
954         ep->saved_ptr = sp->SCp.ptr;
955         ep->saved_buffer = sp->SCp.buffer;
956         ep->saved_this_residual = sp->SCp.this_residual;
957         ep->saved_buffers_residual = sp->SCp.buffers_residual;
958 }
959
960 /* Some rules:
961  *
962  *   1) Never ever panic while something is live on the bus.
963  *      If there is to be any chance of syncing the disks this
964  *      rule is to be obeyed.
965  *
966  *   2) Any target that causes a foul condition will no longer
967  *      have synchronous transfers done to it, no questions
968  *      asked.
969  *
970  *   3) Keep register accesses to a minimum.  Think about some
971  *      day when we have Xbus machines this is running on and
972  *      the ESP chip is on the other end of the machine on a
973  *      different board from the cpu where this is running.
974  */
975
976 /* Fire off a command.  We assume the bus is free and that the only
977  * case where we could see an interrupt is where we have disconnected
978  * commands active and they are trying to reselect us.
979  */
980 static inline void esp_check_cmd(struct NCR_ESP *esp, Scsi_Cmnd *sp)
981 {
982         switch(sp->cmd_len) {
983         case 6:
984         case 10:
985         case 12:
986                 esp->esp_slowcmd = 0;
987                 break;
988
989         default:
990                 esp->esp_slowcmd = 1;
991                 esp->esp_scmdleft = sp->cmd_len;
992                 esp->esp_scmdp = &sp->cmnd[0];
993                 break;
994         };
995 }
996
997 static inline void build_sync_nego_msg(struct NCR_ESP *esp, int period, int offset)
998 {
999         esp->cur_msgout[0] = EXTENDED_MESSAGE;
1000         esp->cur_msgout[1] = 3;
1001         esp->cur_msgout[2] = EXTENDED_SDTR;
1002         esp->cur_msgout[3] = period;
1003         esp->cur_msgout[4] = offset;
1004         esp->msgout_len = 5;
1005 }
1006
1007 static void esp_exec_cmd(struct NCR_ESP *esp)
1008 {
1009         struct ESP_regs *eregs = esp->eregs;
1010         struct esp_device *esp_dev;
1011         Scsi_Cmnd *SCptr;
1012         struct scsi_device *SDptr;
1013         volatile unchar *cmdp = esp->esp_command;
1014         unsigned char the_esp_command;
1015         int lun, target;
1016         int i;
1017
1018         /* Hold off if we have disconnected commands and
1019          * an IRQ is showing...
1020          */
1021         if(esp->disconnected_SC && esp->dma_irq_p(esp))
1022                 return;
1023
1024         /* Grab first member of the issue queue. */
1025         SCptr = esp->current_SC = remove_first_SC(&esp->issue_SC);
1026
1027         /* Safe to panic here because current_SC is null. */
1028         if(!SCptr)
1029                 panic("esp: esp_exec_cmd and issue queue is NULL");
1030
1031         SDptr = SCptr->device;
1032         esp_dev = SDptr->hostdata;
1033         lun = SCptr->device->lun;
1034         target = SCptr->device->id;
1035
1036         esp->snip = 0;
1037         esp->msgout_len = 0;
1038
1039         /* Send it out whole, or piece by piece?   The ESP
1040          * only knows how to automatically send out 6, 10,
1041          * and 12 byte commands.  I used to think that the
1042          * Linux SCSI code would never throw anything other
1043          * than that to us, but then again there is the
1044          * SCSI generic driver which can send us anything.
1045          */
1046         esp_check_cmd(esp, SCptr);
1047
1048         /* If arbitration/selection is successful, the ESP will leave
1049          * ATN asserted, causing the target to go into message out
1050          * phase.  The ESP will feed the target the identify and then
1051          * the target can only legally go to one of command,
1052          * datain/out, status, or message in phase, or stay in message
1053          * out phase (should we be trying to send a sync negotiation
1054          * message after the identify).  It is not allowed to drop
1055          * BSY, but some buggy targets do and we check for this
1056          * condition in the selection complete code.  Most of the time
1057          * we'll make the command bytes available to the ESP and it
1058          * will not interrupt us until it finishes command phase, we
1059          * cannot do this for command sizes the ESP does not
1060          * understand and in this case we'll get interrupted right
1061          * when the target goes into command phase.
1062          *
1063          * It is absolutely _illegal_ in the presence of SCSI-2 devices
1064          * to use the ESP select w/o ATN command.  When SCSI-2 devices are
1065          * present on the bus we _must_ always go straight to message out
1066          * phase with an identify message for the target.  Being that
1067          * selection attempts in SCSI-1 w/o ATN was an option, doing SCSI-2
1068          * selections should not confuse SCSI-1 we hope.
1069          */
1070
1071         if(esp_dev->sync) {
1072                 /* this targets sync is known */
1073 #ifdef CONFIG_SCSI_MAC_ESP
1074 do_sync_known:
1075 #endif
1076                 if(esp_dev->disconnect)
1077                         *cmdp++ = IDENTIFY(1, lun);
1078                 else
1079                         *cmdp++ = IDENTIFY(0, lun);
1080
1081                 if(esp->esp_slowcmd) {
1082                         the_esp_command = (ESP_CMD_SELAS | ESP_CMD_DMA);
1083                         esp_advance_phase(SCptr, in_slct_stop);
1084                 } else {
1085                         the_esp_command = (ESP_CMD_SELA | ESP_CMD_DMA);
1086                         esp_advance_phase(SCptr, in_slct_norm);
1087                 }
1088         } else if(!(esp->targets_present & (1<<target)) || !(esp_dev->disconnect)) {
1089                 /* After the bootup SCSI code sends both the
1090                  * TEST_UNIT_READY and INQUIRY commands we want
1091                  * to at least attempt allowing the device to
1092                  * disconnect.
1093                  */
1094                 ESPMISC(("esp: Selecting device for first time. target=%d "
1095                          "lun=%d\n", target, SCptr->device->lun));
1096                 if(!SDptr->borken && !esp_dev->disconnect)
1097                         esp_dev->disconnect = 1;
1098
1099                 *cmdp++ = IDENTIFY(0, lun);
1100                 esp->prevmsgout = NOP;
1101                 esp_advance_phase(SCptr, in_slct_norm);
1102                 the_esp_command = (ESP_CMD_SELA | ESP_CMD_DMA);
1103
1104                 /* Take no chances... */
1105                 esp_dev->sync_max_offset = 0;
1106                 esp_dev->sync_min_period = 0;
1107         } else {
1108                 int toshiba_cdrom_hwbug_wkaround = 0;
1109
1110 #ifdef CONFIG_SCSI_MAC_ESP
1111                 /* Never allow synchronous transfers (disconnect OK) on
1112                  * Macintosh. Well, maybe later when we figured out how to 
1113                  * do DMA on the machines that support it ...
1114                  */
1115                 esp_dev->disconnect = 1;
1116                 esp_dev->sync_max_offset = 0;
1117                 esp_dev->sync_min_period = 0;
1118                 esp_dev->sync = 1;
1119                 esp->snip = 0;
1120                 goto do_sync_known;
1121 #endif
1122                 /* We've talked to this guy before,
1123                  * but never negotiated.  Let's try
1124                  * sync negotiation.
1125                  */
1126                 if(!SDptr->borken) {
1127                         if((SDptr->type == TYPE_ROM) &&
1128                            (!strncmp(SDptr->vendor, "TOSHIBA", 7))) {
1129                                 /* Nice try sucker... */
1130                                 ESPMISC(("esp%d: Disabling sync for buggy "
1131                                          "Toshiba CDROM.\n", esp->esp_id));
1132                                 toshiba_cdrom_hwbug_wkaround = 1;
1133                                 build_sync_nego_msg(esp, 0, 0);
1134                         } else {
1135                                 build_sync_nego_msg(esp, esp->sync_defp, 15);
1136                         }
1137                 } else {
1138                         build_sync_nego_msg(esp, 0, 0);
1139                 }
1140                 esp_dev->sync = 1;
1141                 esp->snip = 1;
1142
1143                 /* A fix for broken SCSI1 targets, when they disconnect
1144                  * they lock up the bus and confuse ESP.  So disallow
1145                  * disconnects for SCSI1 targets for now until we
1146                  * find a better fix.
1147                  *
1148                  * Addendum: This is funny, I figured out what was going
1149                  *           on.  The blotzed SCSI1 target would disconnect,
1150                  *           one of the other SCSI2 targets or both would be
1151                  *           disconnected as well.  The SCSI1 target would
1152                  *           stay disconnected long enough that we start
1153                  *           up a command on one of the SCSI2 targets.  As
1154                  *           the ESP is arbitrating for the bus the SCSI1
1155                  *           target begins to arbitrate as well to reselect
1156                  *           the ESP.  The SCSI1 target refuses to drop it's
1157                  *           ID bit on the data bus even though the ESP is
1158                  *           at ID 7 and is the obvious winner for any
1159                  *           arbitration.  The ESP is a poor sport and refuses
1160                  *           to lose arbitration, it will continue indefinitely
1161                  *           trying to arbitrate for the bus and can only be
1162                  *           stopped via a chip reset or SCSI bus reset.
1163                  *           Therefore _no_ disconnects for SCSI1 targets
1164                  *           thank you very much. ;-)
1165                  */
1166                 if(((SDptr->scsi_level < 3) && (SDptr->type != TYPE_TAPE)) ||
1167                    toshiba_cdrom_hwbug_wkaround || SDptr->borken) {
1168                         ESPMISC((KERN_INFO "esp%d: Disabling DISCONNECT for target %d "
1169                                  "lun %d\n", esp->esp_id, SCptr->device->id, SCptr->device->lun));
1170                         esp_dev->disconnect = 0;
1171                         *cmdp++ = IDENTIFY(0, lun);
1172                 } else {
1173                         *cmdp++ = IDENTIFY(1, lun);
1174                 }
1175
1176                 /* ESP fifo is only so big...
1177                  * Make this look like a slow command.
1178                  */
1179                 esp->esp_slowcmd = 1;
1180                 esp->esp_scmdleft = SCptr->cmd_len;
1181                 esp->esp_scmdp = &SCptr->cmnd[0];
1182
1183                 the_esp_command = (ESP_CMD_SELAS | ESP_CMD_DMA);
1184                 esp_advance_phase(SCptr, in_slct_msg);
1185         }
1186
1187         if(!esp->esp_slowcmd)
1188                 for(i = 0; i < SCptr->cmd_len; i++)
1189                         *cmdp++ = SCptr->cmnd[i];
1190
1191         esp_write(eregs->esp_busid, (target & 7));
1192         if (esp->prev_soff != esp_dev->sync_max_offset ||
1193             esp->prev_stp  != esp_dev->sync_min_period ||
1194             (esp->erev > esp100a &&
1195              esp->prev_cfg3 != esp->config3[target])) {
1196                 esp->prev_soff = esp_dev->sync_max_offset;
1197                 esp_write(eregs->esp_soff, esp->prev_soff);
1198                 esp->prev_stp = esp_dev->sync_min_period;
1199                 esp_write(eregs->esp_stp, esp->prev_stp); 
1200                 if(esp->erev > esp100a) {
1201                         esp->prev_cfg3 = esp->config3[target];
1202                         esp_write(eregs->esp_cfg3, esp->prev_cfg3);
1203                 }
1204         }
1205         i = (cmdp - esp->esp_command);
1206
1207         /* Set up the DMA and ESP counters */
1208         if(esp->do_pio_cmds){
1209                 int j = 0;
1210
1211                 /* 
1212                  * XXX MSch:
1213                  *
1214                  * It seems this is required, at least to clean up
1215                  * after failed commands when using PIO mode ...
1216                  */
1217                 esp_cmd(esp, eregs, ESP_CMD_FLUSH);
1218
1219                 for(;j<i;j++)
1220                         esp_write(eregs->esp_fdata, esp->esp_command[j]);
1221                 the_esp_command &= ~ESP_CMD_DMA;
1222
1223                 /* Tell ESP to "go". */
1224                 esp_cmd(esp, eregs, the_esp_command);
1225         } else {
1226                 /* Set up the ESP counters */
1227                 esp_write(eregs->esp_tclow, i);
1228                 esp_write(eregs->esp_tcmed, 0);
1229                 esp->dma_init_write(esp, esp->esp_command_dvma, i);
1230
1231                 /* Tell ESP to "go". */
1232                 esp_cmd(esp, eregs, the_esp_command);
1233         }
1234 }
1235
1236 /* Queue a SCSI command delivered from the mid-level Linux SCSI code. */
1237 int esp_queue(Scsi_Cmnd *SCpnt, void (*done)(Scsi_Cmnd *))
1238 {
1239         struct NCR_ESP *esp;
1240
1241         /* Set up func ptr and initial driver cmd-phase. */
1242         SCpnt->scsi_done = done;
1243         SCpnt->SCp.phase = not_issued;
1244
1245         esp = (struct NCR_ESP *) SCpnt->device->host->hostdata;
1246
1247         if(esp->dma_led_on)
1248                 esp->dma_led_on(esp);
1249
1250         /* We use the scratch area. */
1251         ESPQUEUE(("esp_queue: target=%d lun=%d ", SCpnt->device->id, SCpnt->lun));
1252         ESPDISC(("N<%02x,%02x>", SCpnt->device->id, SCpnt->lun));
1253
1254         esp_get_dmabufs(esp, SCpnt);
1255         esp_save_pointers(esp, SCpnt); /* FIXME for tag queueing */
1256
1257         SCpnt->SCp.Status           = CHECK_CONDITION;
1258         SCpnt->SCp.Message          = 0xff;
1259         SCpnt->SCp.sent_command     = 0;
1260
1261         /* Place into our queue. */
1262         if(SCpnt->cmnd[0] == REQUEST_SENSE) {
1263                 ESPQUEUE(("RQSENSE\n"));
1264                 prepend_SC(&esp->issue_SC, SCpnt);
1265         } else {
1266                 ESPQUEUE(("\n"));
1267                 append_SC(&esp->issue_SC, SCpnt);
1268         }
1269
1270         /* Run it now if we can. */
1271         if(!esp->current_SC && !esp->resetting_bus)
1272                 esp_exec_cmd(esp);
1273
1274         return 0;
1275 }
1276
1277 /* Dump driver state. */
1278 static void esp_dump_cmd(Scsi_Cmnd *SCptr)
1279 {
1280         ESPLOG(("[tgt<%02x> lun<%02x> "
1281                 "pphase<%s> cphase<%s>]",
1282                 SCptr->device->id, SCptr->device->lun,
1283                 phase_string(SCptr->SCp.sent_command),
1284                 phase_string(SCptr->SCp.phase)));
1285 }
1286
1287 static void esp_dump_state(struct NCR_ESP *esp, 
1288                            struct ESP_regs *eregs)
1289 {
1290         Scsi_Cmnd *SCptr = esp->current_SC;
1291 #ifdef DEBUG_ESP_CMDS
1292         int i;
1293 #endif
1294
1295         ESPLOG(("esp%d: dumping state\n", esp->esp_id));
1296         
1297         /* Print DMA status */
1298         esp->dma_dump_state(esp);
1299
1300         ESPLOG(("esp%d: SW [sreg<%02x> sstep<%02x> ireg<%02x>]\n",
1301                 esp->esp_id, esp->sreg, esp->seqreg, esp->ireg));
1302         ESPLOG(("esp%d: HW reread [sreg<%02x> sstep<%02x> ireg<%02x>]\n",
1303                 esp->esp_id, esp_read(eregs->esp_status), esp_read(eregs->esp_sstep),
1304                 esp_read(eregs->esp_intrpt)));
1305 #ifdef DEBUG_ESP_CMDS
1306         printk("esp%d: last ESP cmds [", esp->esp_id);
1307         i = (esp->espcmdent - 1) & 31;
1308         printk("<");
1309         esp_print_cmd(esp->espcmdlog[i]);
1310         printk(">");
1311         i = (i - 1) & 31;
1312         printk("<");
1313         esp_print_cmd(esp->espcmdlog[i]);
1314         printk(">");
1315         i = (i - 1) & 31;
1316         printk("<");
1317         esp_print_cmd(esp->espcmdlog[i]);
1318         printk(">");
1319         i = (i - 1) & 31;
1320         printk("<");
1321         esp_print_cmd(esp->espcmdlog[i]);
1322         printk(">");
1323         printk("]\n");
1324 #endif /* (DEBUG_ESP_CMDS) */
1325
1326         if(SCptr) {
1327                 ESPLOG(("esp%d: current command ", esp->esp_id));
1328                 esp_dump_cmd(SCptr);
1329         }
1330         ESPLOG(("\n"));
1331         SCptr = esp->disconnected_SC;
1332         ESPLOG(("esp%d: disconnected ", esp->esp_id));
1333         while(SCptr) {
1334                 esp_dump_cmd(SCptr);
1335                 SCptr = (Scsi_Cmnd *) SCptr->host_scribble;
1336         }
1337         ESPLOG(("\n"));
1338 }
1339
1340 /* Abort a command.  The host_lock is acquired by caller. */
1341 int esp_abort(Scsi_Cmnd *SCptr)
1342 {
1343         struct NCR_ESP *esp = (struct NCR_ESP *) SCptr->device->host->hostdata;
1344         struct ESP_regs *eregs = esp->eregs;
1345         int don;
1346
1347         ESPLOG(("esp%d: Aborting command\n", esp->esp_id));
1348         esp_dump_state(esp, eregs);
1349
1350         /* Wheee, if this is the current command on the bus, the
1351          * best we can do is assert ATN and wait for msgout phase.
1352          * This should even fix a hung SCSI bus when we lose state
1353          * in the driver and timeout because the eventual phase change
1354          * will cause the ESP to (eventually) give an interrupt.
1355          */
1356         if(esp->current_SC == SCptr) {
1357                 esp->cur_msgout[0] = ABORT;
1358                 esp->msgout_len = 1;
1359                 esp->msgout_ctr = 0;
1360                 esp_cmd(esp, eregs, ESP_CMD_SATN);
1361                 return SUCCESS;
1362         }
1363
1364         /* If it is still in the issue queue then we can safely
1365          * call the completion routine and report abort success.
1366          */
1367         don = esp->dma_ports_p(esp);
1368         if(don) {
1369                 esp->dma_ints_off(esp);
1370                 synchronize_irq(esp->irq);
1371         }
1372         if(esp->issue_SC) {
1373                 Scsi_Cmnd **prev, *this;
1374                 for(prev = (&esp->issue_SC), this = esp->issue_SC;
1375                     this;
1376                     prev = (Scsi_Cmnd **) &(this->host_scribble),
1377                     this = (Scsi_Cmnd *) this->host_scribble) {
1378                         if(this == SCptr) {
1379                                 *prev = (Scsi_Cmnd *) this->host_scribble;
1380                                 this->host_scribble = NULL;
1381                                 esp_release_dmabufs(esp, this);
1382                                 this->result = DID_ABORT << 16;
1383                                 this->done(this);
1384                                 if(don)
1385                                         esp->dma_ints_on(esp);
1386                                 return SUCCESS;
1387                         }
1388                 }
1389         }
1390
1391         /* Yuck, the command to abort is disconnected, it is not
1392          * worth trying to abort it now if something else is live
1393          * on the bus at this time.  So, we let the SCSI code wait
1394          * a little bit and try again later.
1395          */
1396         if(esp->current_SC) {
1397                 if(don)
1398                         esp->dma_ints_on(esp);
1399                 return FAILED;
1400         }
1401
1402         /* It's disconnected, we have to reconnect to re-establish
1403          * the nexus and tell the device to abort.  However, we really
1404          * cannot 'reconnect' per se.  Don't try to be fancy, just
1405          * indicate failure, which causes our caller to reset the whole
1406          * bus.
1407          */
1408
1409         if(don)
1410                 esp->dma_ints_on(esp);
1411         return FAILED;
1412 }
1413
1414 /* We've sent ESP_CMD_RS to the ESP, the interrupt had just
1415  * arrived indicating the end of the SCSI bus reset.  Our job
1416  * is to clean out the command queues and begin re-execution
1417  * of SCSI commands once more.
1418  */
1419 static int esp_finish_reset(struct NCR_ESP *esp,
1420                             struct ESP_regs *eregs)
1421 {
1422         Scsi_Cmnd *sp = esp->current_SC;
1423
1424         /* Clean up currently executing command, if any. */
1425         if (sp != NULL) {
1426                 esp_release_dmabufs(esp, sp);
1427                 sp->result = (DID_RESET << 16);
1428                 sp->scsi_done(sp);
1429                 esp->current_SC = NULL;
1430         }
1431
1432         /* Clean up disconnected queue, they have been invalidated
1433          * by the bus reset.
1434          */
1435         if (esp->disconnected_SC) {
1436                 while((sp = remove_first_SC(&esp->disconnected_SC)) != NULL) {
1437                         esp_release_dmabufs(esp, sp);
1438                         sp->result = (DID_RESET << 16);
1439                         sp->scsi_done(sp);
1440                 }
1441         }
1442
1443         /* SCSI bus reset is complete. */
1444         esp->resetting_bus = 0;
1445         wake_up(&esp->reset_queue);
1446
1447         /* Ok, now it is safe to get commands going once more. */
1448         if(esp->issue_SC)
1449                 esp_exec_cmd(esp);
1450
1451         return do_intr_end;
1452 }
1453
1454 static int esp_do_resetbus(struct NCR_ESP *esp,
1455                            struct ESP_regs *eregs)
1456 {
1457         ESPLOG(("esp%d: Resetting scsi bus\n", esp->esp_id));
1458         esp->resetting_bus = 1;
1459         esp_cmd(esp, eregs, ESP_CMD_RS);
1460
1461         return do_intr_end;
1462 }
1463
1464 /* Reset ESP chip, reset hanging bus, then kill active and
1465  * disconnected commands for targets without soft reset.
1466  *
1467  * The host_lock is acquired by caller.
1468  */
1469 int esp_reset(Scsi_Cmnd *SCptr)
1470 {
1471         struct NCR_ESP *esp = (struct NCR_ESP *) SCptr->device->host->hostdata;
1472
1473         spin_lock_irq(esp->ehost->host_lock);
1474         (void) esp_do_resetbus(esp, esp->eregs);
1475         spin_unlock_irq(esp->ehost->host_lock);
1476
1477         wait_event(esp->reset_queue, (esp->resetting_bus == 0));
1478
1479         return SUCCESS;
1480 }
1481
1482 /* Internal ESP done function. */
1483 static void esp_done(struct NCR_ESP *esp, int error)
1484 {
1485         Scsi_Cmnd *done_SC;
1486
1487         if(esp->current_SC) {
1488                 done_SC = esp->current_SC;
1489                 esp->current_SC = NULL;
1490                 esp_release_dmabufs(esp, done_SC);
1491                 done_SC->result = error;
1492                 done_SC->scsi_done(done_SC);
1493
1494                 /* Bus is free, issue any commands in the queue. */
1495                 if(esp->issue_SC && !esp->current_SC)
1496                         esp_exec_cmd(esp);
1497         } else {
1498                 /* Panic is safe as current_SC is null so we may still
1499                  * be able to accept more commands to sync disk buffers.
1500                  */
1501                 ESPLOG(("panicing\n"));
1502                 panic("esp: done() called with NULL esp->current_SC");
1503         }
1504 }
1505
1506 /* Wheee, ESP interrupt engine. */  
1507
1508 /* Forward declarations. */
1509 static int esp_do_phase_determine(struct NCR_ESP *esp, 
1510                                   struct ESP_regs *eregs);
1511 static int esp_do_data_finale(struct NCR_ESP *esp, struct ESP_regs *eregs);
1512 static int esp_select_complete(struct NCR_ESP *esp, struct ESP_regs *eregs);
1513 static int esp_do_status(struct NCR_ESP *esp, struct ESP_regs *eregs);
1514 static int esp_do_msgin(struct NCR_ESP *esp, struct ESP_regs *eregs);
1515 static int esp_do_msgindone(struct NCR_ESP *esp, struct ESP_regs *eregs);
1516 static int esp_do_msgout(struct NCR_ESP *esp, struct ESP_regs *eregs);
1517 static int esp_do_cmdbegin(struct NCR_ESP *esp, struct ESP_regs *eregs);
1518
1519 #define sreg_datainp(__sreg)  (((__sreg) & ESP_STAT_PMASK) == ESP_DIP)
1520 #define sreg_dataoutp(__sreg) (((__sreg) & ESP_STAT_PMASK) == ESP_DOP)
1521
1522 /* We try to avoid some interrupts by jumping ahead and see if the ESP
1523  * has gotten far enough yet.  Hence the following.
1524  */
1525 static inline int skipahead1(struct NCR_ESP *esp, struct ESP_regs *eregs,
1526                              Scsi_Cmnd *scp, int prev_phase, int new_phase)
1527 {
1528         if(scp->SCp.sent_command != prev_phase)
1529                 return 0;
1530
1531         if(esp->dma_irq_p(esp)) {
1532                 /* Yes, we are able to save an interrupt. */
1533                 esp->sreg = (esp_read(eregs->esp_status) & ~(ESP_STAT_INTR));
1534                 esp->ireg = esp_read(eregs->esp_intrpt);
1535                 if(!(esp->ireg & ESP_INTR_SR))
1536                         return 0;
1537                 else
1538                         return do_reset_complete;
1539         }
1540         /* Ho hum, target is taking forever... */
1541         scp->SCp.sent_command = new_phase; /* so we don't recurse... */
1542         return do_intr_end;
1543 }
1544
1545 static inline int skipahead2(struct NCR_ESP *esp,
1546                              struct ESP_regs *eregs,
1547                              Scsi_Cmnd *scp, int prev_phase1, int prev_phase2,
1548                              int new_phase)
1549 {
1550         if(scp->SCp.sent_command != prev_phase1 &&
1551            scp->SCp.sent_command != prev_phase2)
1552                 return 0;
1553         if(esp->dma_irq_p(esp)) {
1554                 /* Yes, we are able to save an interrupt. */
1555                 esp->sreg = (esp_read(eregs->esp_status) & ~(ESP_STAT_INTR));
1556                 esp->ireg = esp_read(eregs->esp_intrpt);
1557                 if(!(esp->ireg & ESP_INTR_SR))
1558                         return 0;
1559                 else
1560                         return do_reset_complete;
1561         }
1562         /* Ho hum, target is taking forever... */
1563         scp->SCp.sent_command = new_phase; /* so we don't recurse... */
1564         return do_intr_end;
1565 }
1566
1567 /* Misc. esp helper macros. */
1568 #define esp_setcount(__eregs, __cnt) \
1569         esp_write((__eregs)->esp_tclow, ((__cnt) & 0xff)); \
1570         esp_write((__eregs)->esp_tcmed, (((__cnt) >> 8) & 0xff))
1571
1572 #define esp_getcount(__eregs) \
1573         ((esp_read((__eregs)->esp_tclow)&0xff) | \
1574          ((esp_read((__eregs)->esp_tcmed)&0xff) << 8))
1575
1576 #define fcount(__esp, __eregs) \
1577         (esp_read((__eregs)->esp_fflags) & ESP_FF_FBYTES)
1578
1579 #define fnzero(__esp, __eregs) \
1580         (esp_read((__eregs)->esp_fflags) & ESP_FF_ONOTZERO)
1581
1582 /* XXX speculative nops unnecessary when continuing amidst a data phase
1583  * XXX even on esp100!!!  another case of flooding the bus with I/O reg
1584  * XXX writes...
1585  */
1586 #define esp_maybe_nop(__esp, __eregs) \
1587         if((__esp)->erev == esp100) \
1588                 esp_cmd((__esp), (__eregs), ESP_CMD_NULL)
1589
1590 #define sreg_to_dataphase(__sreg) \
1591         ((((__sreg) & ESP_STAT_PMASK) == ESP_DOP) ? in_dataout : in_datain)
1592
1593 /* The ESP100 when in synchronous data phase, can mistake a long final
1594  * REQ pulse from the target as an extra byte, it places whatever is on
1595  * the data lines into the fifo.  For now, we will assume when this
1596  * happens that the target is a bit quirky and we don't want to
1597  * be talking synchronously to it anyways.  Regardless, we need to
1598  * tell the ESP to eat the extraneous byte so that we can proceed
1599  * to the next phase.
1600  */
1601 static inline int esp100_sync_hwbug(struct NCR_ESP *esp, struct ESP_regs *eregs,
1602                                     Scsi_Cmnd *sp, int fifocnt)
1603 {
1604         /* Do not touch this piece of code. */
1605         if((!(esp->erev == esp100)) ||
1606            (!(sreg_datainp((esp->sreg = esp_read(eregs->esp_status))) && !fifocnt) &&
1607             !(sreg_dataoutp(esp->sreg) && !fnzero(esp, eregs)))) {
1608                 if(sp->SCp.phase == in_dataout)
1609                         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
1610                 return 0;
1611         } else {
1612                 /* Async mode for this guy. */
1613                 build_sync_nego_msg(esp, 0, 0);
1614
1615                 /* Ack the bogus byte, but set ATN first. */
1616                 esp_cmd(esp, eregs, ESP_CMD_SATN);
1617                 esp_cmd(esp, eregs, ESP_CMD_MOK);
1618                 return 1;
1619         }
1620 }
1621
1622 /* This closes the window during a selection with a reselect pending, because
1623  * we use DMA for the selection process the FIFO should hold the correct
1624  * contents if we get reselected during this process.  So we just need to
1625  * ack the possible illegal cmd interrupt pending on the esp100.
1626  */
1627 static inline int esp100_reconnect_hwbug(struct NCR_ESP *esp,
1628                                          struct ESP_regs *eregs)
1629 {
1630         volatile unchar junk;
1631
1632         if(esp->erev != esp100)
1633                 return 0;
1634         junk = esp_read(eregs->esp_intrpt);
1635
1636         if(junk & ESP_INTR_SR)
1637                 return 1;
1638         return 0;
1639 }
1640
1641 /* This verifies the BUSID bits during a reselection so that we know which
1642  * target is talking to us.
1643  */
1644 static inline int reconnect_target(struct NCR_ESP *esp, struct ESP_regs *eregs)
1645 {
1646         int it, me = esp->scsi_id_mask, targ = 0;
1647
1648         if(2 != fcount(esp, eregs))
1649                 return -1;
1650         it = esp_read(eregs->esp_fdata);
1651         if(!(it & me))
1652                 return -1;
1653         it &= ~me;
1654         if(it & (it - 1))
1655                 return -1;
1656         while(!(it & 1))
1657                 targ++, it >>= 1;
1658         return targ;
1659 }
1660
1661 /* This verifies the identify from the target so that we know which lun is
1662  * being reconnected.
1663  */
1664 static inline int reconnect_lun(struct NCR_ESP *esp, struct ESP_regs *eregs)
1665 {
1666         int lun;
1667
1668         if((esp->sreg & ESP_STAT_PMASK) != ESP_MIP)
1669                 return -1;
1670         lun = esp_read(eregs->esp_fdata);
1671
1672         /* Yes, you read this correctly.  We report lun of zero
1673          * if we see parity error.  ESP reports parity error for
1674          * the lun byte, and this is the only way to hope to recover
1675          * because the target is connected.
1676          */
1677         if(esp->sreg & ESP_STAT_PERR)
1678                 return 0;
1679
1680         /* Check for illegal bits being set in the lun. */
1681         if((lun & 0x40) || !(lun & 0x80))
1682                 return -1;
1683
1684         return lun & 7;
1685 }
1686
1687 /* This puts the driver in a state where it can revitalize a command that
1688  * is being continued due to reselection.
1689  */
1690 static inline void esp_connect(struct NCR_ESP *esp, struct ESP_regs *eregs,
1691                                Scsi_Cmnd *sp)
1692 {
1693         struct scsi_device *dp = sp->device;
1694         struct esp_device *esp_dev = dp->hostdata;
1695
1696         if(esp->prev_soff  != esp_dev->sync_max_offset ||
1697            esp->prev_stp   != esp_dev->sync_min_period ||
1698            (esp->erev > esp100a &&
1699             esp->prev_cfg3 != esp->config3[scmd_id(sp)])) {
1700                 esp->prev_soff = esp_dev->sync_max_offset;
1701                 esp_write(eregs->esp_soff, esp->prev_soff);
1702                 esp->prev_stp = esp_dev->sync_min_period;
1703                 esp_write(eregs->esp_stp, esp->prev_stp);
1704                 if(esp->erev > esp100a) {
1705                         esp->prev_cfg3 = esp->config3[scmd_id(sp)];
1706                         esp_write(eregs->esp_cfg3, esp->prev_cfg3);
1707                 } 
1708         }
1709         esp->current_SC = sp;
1710 }
1711
1712 /* This will place the current working command back into the issue queue
1713  * if we are to receive a reselection amidst a selection attempt.
1714  */
1715 static inline void esp_reconnect(struct NCR_ESP *esp, Scsi_Cmnd *sp)
1716 {
1717         if(!esp->disconnected_SC)
1718                 ESPLOG(("esp%d: Weird, being reselected but disconnected "
1719                         "command queue is empty.\n", esp->esp_id));
1720         esp->snip = 0;
1721         esp->current_SC = NULL;
1722         sp->SCp.phase = not_issued;
1723         append_SC(&esp->issue_SC, sp);
1724 }
1725
1726 /* Begin message in phase. */
1727 static int esp_do_msgin(struct NCR_ESP *esp, struct ESP_regs *eregs)
1728 {
1729         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
1730         esp_maybe_nop(esp, eregs);
1731         esp_cmd(esp, eregs, ESP_CMD_TI);
1732         esp->msgin_len = 1;
1733         esp->msgin_ctr = 0;
1734         esp_advance_phase(esp->current_SC, in_msgindone);
1735         return do_work_bus;
1736 }
1737
1738 static inline void advance_sg(struct NCR_ESP *esp, Scsi_Cmnd *sp)
1739 {
1740         ++sp->SCp.buffer;
1741         --sp->SCp.buffers_residual;
1742         sp->SCp.this_residual = sp->SCp.buffer->length;
1743         if (esp->dma_advance_sg)
1744                 esp->dma_advance_sg (sp);
1745         else
1746                 sp->SCp.ptr = (char *) virt_to_phys((page_address(sp->SCp.buffer->page) + sp->SCp.buffer->offset));
1747
1748 }
1749
1750 /* Please note that the way I've coded these routines is that I _always_
1751  * check for a disconnect during any and all information transfer
1752  * phases.  The SCSI standard states that the target _can_ cause a BUS
1753  * FREE condition by dropping all MSG/CD/IO/BSY signals.  Also note
1754  * that during information transfer phases the target controls every
1755  * change in phase, the only thing the initiator can do is "ask" for
1756  * a message out phase by driving ATN true.  The target can, and sometimes
1757  * will, completely ignore this request so we cannot assume anything when
1758  * we try to force a message out phase to abort/reset a target.  Most of
1759  * the time the target will eventually be nice and go to message out, so
1760  * we may have to hold on to our state about what we want to tell the target
1761  * for some period of time.
1762  */
1763
1764 /* I think I have things working here correctly.  Even partial transfers
1765  * within a buffer or sub-buffer should not upset us at all no matter
1766  * how bad the target and/or ESP fucks things up.
1767  */
1768 static int esp_do_data(struct NCR_ESP *esp, struct ESP_regs *eregs)
1769 {
1770         Scsi_Cmnd *SCptr = esp->current_SC;
1771         int thisphase, hmuch;
1772
1773         ESPDATA(("esp_do_data: "));
1774         esp_maybe_nop(esp, eregs);
1775         thisphase = sreg_to_dataphase(esp->sreg);
1776         esp_advance_phase(SCptr, thisphase);
1777         ESPDATA(("newphase<%s> ", (thisphase == in_datain) ? "DATAIN" : "DATAOUT"));
1778         hmuch = esp->dma_can_transfer(esp, SCptr);
1779
1780         /*
1781          * XXX MSch: cater for PIO transfer here; PIO used if hmuch == 0
1782          */
1783         if (hmuch) {    /* DMA */
1784                 /*
1785                  * DMA
1786                  */
1787                 ESPDATA(("hmuch<%d> ", hmuch));
1788                 esp->current_transfer_size = hmuch;
1789                 esp_setcount(eregs, (esp->fas_premature_intr_workaround ?
1790                                      (hmuch + 0x40) : hmuch));
1791                 esp->dma_setup(esp, (__u32)((unsigned long)SCptr->SCp.ptr), 
1792                                hmuch, (thisphase == in_datain));
1793                 ESPDATA(("DMA|TI --> do_intr_end\n"));
1794                 esp_cmd(esp, eregs, ESP_CMD_DMA | ESP_CMD_TI);
1795                 return do_intr_end;
1796                 /*
1797                  * end DMA
1798                  */
1799         } else {
1800                 /*
1801                  * PIO
1802                  */
1803                 int oldphase, i = 0; /* or where we left off last time ?? esp->current_data ?? */
1804                 int fifocnt = 0;
1805                 unsigned char *p = phys_to_virt((unsigned long)SCptr->SCp.ptr);
1806
1807                 oldphase = esp_read(eregs->esp_status) & ESP_STAT_PMASK;
1808
1809                 /*
1810                  * polled transfer; ugly, can we make this happen in a DRQ 
1811                  * interrupt handler ??
1812                  * requires keeping track of state information in host or 
1813                  * command struct!
1814                  * Problem: I've never seen a DRQ happen on Mac, not even
1815                  * with ESP_CMD_DMA ...
1816                  */
1817
1818                 /* figure out how much needs to be transferred */
1819                 hmuch = SCptr->SCp.this_residual;
1820                 ESPDATA(("hmuch<%d> pio ", hmuch));
1821                 esp->current_transfer_size = hmuch;
1822
1823                 /* tell the ESP ... */
1824                 esp_setcount(eregs, hmuch);
1825
1826                 /* loop */
1827                 while (hmuch) {
1828                         int j, fifo_stuck = 0, newphase;
1829                         unsigned long timeout;
1830 #if 0
1831                         unsigned long flags;
1832 #endif
1833 #if 0
1834                         if ( i % 10 )
1835                                 ESPDATA(("\r"));
1836                         else
1837                                 ESPDATA(( /*"\n"*/ "\r"));
1838 #endif
1839 #if 0
1840                         local_irq_save(flags);
1841 #endif
1842                         if(thisphase == in_datain) {
1843                                 /* 'go' ... */ 
1844                                 esp_cmd(esp, eregs, ESP_CMD_TI);
1845
1846                                 /* wait for data */
1847                                 timeout = 1000000;
1848                                 while (!((esp->sreg=esp_read(eregs->esp_status)) & ESP_STAT_INTR) && --timeout)
1849                                         udelay(2);
1850                                 if (timeout == 0)
1851                                         printk("DRQ datain timeout! \n");
1852
1853                                 newphase = esp->sreg & ESP_STAT_PMASK;
1854
1855                                 /* see how much we got ... */
1856                                 fifocnt = (esp_read(eregs->esp_fflags) & ESP_FF_FBYTES);
1857
1858                                 if (!fifocnt)
1859                                         fifo_stuck++;
1860                                 else
1861                                         fifo_stuck = 0;
1862
1863                                 ESPDATA(("\rgot %d st %x ph %x", fifocnt, esp->sreg, newphase));
1864
1865                                 /* read fifo */
1866                                 for(j=0;j<fifocnt;j++)
1867                                         p[i++] = esp_read(eregs->esp_fdata);
1868
1869                                 ESPDATA(("(%d) ", i));
1870
1871                                 /* how many to go ?? */
1872                                 hmuch -= fifocnt;
1873
1874                                 /* break if status phase !! */
1875                                 if(newphase == ESP_STATP) {
1876                                         /* clear int. */
1877                                         esp->ireg = esp_read(eregs->esp_intrpt);
1878                                         break;
1879                                 }
1880                         } else {
1881 #define MAX_FIFO 8
1882                                 /* how much will fit ? */
1883                                 int this_count = MAX_FIFO - fifocnt;
1884                                 if (this_count > hmuch)
1885                                         this_count = hmuch;
1886
1887                                 /* fill fifo */
1888                                 for(j=0;j<this_count;j++)
1889                                         esp_write(eregs->esp_fdata, p[i++]);
1890
1891                                 /* how many left if this goes out ?? */
1892                                 hmuch -= this_count;
1893
1894                                 /* 'go' ... */ 
1895                                 esp_cmd(esp, eregs, ESP_CMD_TI);
1896
1897                                 /* wait for 'got it' */
1898                                 timeout = 1000000;
1899                                 while (!((esp->sreg=esp_read(eregs->esp_status)) & ESP_STAT_INTR) && --timeout)
1900                                         udelay(2);
1901                                 if (timeout == 0)
1902                                         printk("DRQ dataout timeout!  \n");
1903
1904                                 newphase = esp->sreg & ESP_STAT_PMASK;
1905
1906                                 /* need to check how much was sent ?? */
1907                                 fifocnt = (esp_read(eregs->esp_fflags) & ESP_FF_FBYTES);
1908
1909                                 ESPDATA(("\rsent %d st %x ph %x", this_count - fifocnt, esp->sreg, newphase));
1910
1911                                 ESPDATA(("(%d) ", i));
1912
1913                                 /* break if status phase !! */
1914                                 if(newphase == ESP_STATP) {
1915                                         /* clear int. */
1916                                         esp->ireg = esp_read(eregs->esp_intrpt);
1917                                         break;
1918                                 }
1919
1920                         }
1921
1922                         /* clear int. */
1923                         esp->ireg = esp_read(eregs->esp_intrpt);
1924
1925                         ESPDATA(("ir %x ... ", esp->ireg));
1926
1927                         if (hmuch == 0)
1928                                 ESPDATA(("done! \n"));
1929
1930 #if 0
1931                         local_irq_restore(flags);
1932 #endif
1933
1934                         /* check new bus phase */
1935                         if (newphase != oldphase && i < esp->current_transfer_size) {
1936                                 /* something happened; disconnect ?? */
1937                                 ESPDATA(("phase change, dropped out with %d done ... ", i));
1938                                 break;
1939                         }
1940
1941                         /* check int. status */
1942                         if (esp->ireg & ESP_INTR_DC) {
1943                                 /* disconnect */
1944                                 ESPDATA(("disconnect; %d transferred ... ", i));
1945                                 break;
1946                         } else if (esp->ireg & ESP_INTR_FDONE) {
1947                                 /* function done */
1948                                 ESPDATA(("function done; %d transferred ... ", i));
1949                                 break;
1950                         }
1951
1952                         /* XXX fixme: bail out on stall */
1953                         if (fifo_stuck > 10) {
1954                                 /* we're stuck */
1955                                 ESPDATA(("fifo stall; %d transferred ... ", i));
1956                                 break;
1957                         }
1958                 }
1959
1960                 ESPDATA(("\n"));
1961                 /* check successful completion ?? */
1962
1963                 if (thisphase == in_dataout)
1964                         hmuch += fifocnt; /* stuck?? adjust data pointer ...*/
1965
1966                 /* tell do_data_finale how much was transferred */
1967                 esp->current_transfer_size -= hmuch;
1968
1969                 /* still not completely sure on this one ... */         
1970                 return /*do_intr_end*/ do_work_bus /*do_phase_determine*/ ;
1971
1972                 /*
1973                  * end PIO
1974                  */
1975         }
1976         return do_intr_end;
1977 }
1978
1979 /* See how successful the data transfer was. */
1980 static int esp_do_data_finale(struct NCR_ESP *esp,
1981                               struct ESP_regs *eregs)
1982 {
1983         Scsi_Cmnd *SCptr = esp->current_SC;
1984         struct esp_device *esp_dev = SCptr->device->hostdata;
1985         int bogus_data = 0, bytes_sent = 0, fifocnt, ecount = 0;
1986
1987         if(esp->dma_led_off)
1988                 esp->dma_led_off(esp);
1989
1990         ESPDATA(("esp_do_data_finale: "));
1991
1992         if(SCptr->SCp.phase == in_datain) {
1993                 if(esp->sreg & ESP_STAT_PERR) {
1994                         /* Yuck, parity error.  The ESP asserts ATN
1995                          * so that we can go to message out phase
1996                          * immediately and inform the target that
1997                          * something bad happened.
1998                          */
1999                         ESPLOG(("esp%d: data bad parity detected.\n",
2000                                 esp->esp_id));
2001                         esp->cur_msgout[0] = INITIATOR_ERROR;
2002                         esp->msgout_len = 1;
2003                 }
2004                 if(esp->dma_drain)
2005                         esp->dma_drain(esp);
2006         }
2007         if(esp->dma_invalidate)
2008                 esp->dma_invalidate(esp);
2009
2010         /* This could happen for the above parity error case. */
2011         if(!(esp->ireg == ESP_INTR_BSERV)) {
2012                 /* Please go to msgout phase, please please please... */
2013                 ESPLOG(("esp%d: !BSERV after data, probably to msgout\n",
2014                         esp->esp_id));
2015                 return esp_do_phase_determine(esp, eregs);
2016         }       
2017
2018         /* Check for partial transfers and other horrible events. */
2019         fifocnt = (esp_read(eregs->esp_fflags) & ESP_FF_FBYTES);
2020         ecount = esp_getcount(eregs);
2021         if(esp->fas_premature_intr_workaround)
2022                 ecount -= 0x40;
2023         bytes_sent = esp->current_transfer_size;
2024
2025         ESPDATA(("trans_sz=%d, ", bytes_sent));
2026         if(!(esp->sreg & ESP_STAT_TCNT))
2027                 bytes_sent -= ecount;
2028         if(SCptr->SCp.phase == in_dataout)
2029                 bytes_sent -= fifocnt;
2030
2031         ESPDATA(("bytes_sent=%d (ecount=%d, fifocnt=%d), ", bytes_sent,
2032                  ecount, fifocnt));
2033
2034         /* If we were in synchronous mode, check for peculiarities. */
2035         if(esp_dev->sync_max_offset)
2036                 bogus_data = esp100_sync_hwbug(esp, eregs, SCptr, fifocnt);
2037         else
2038                 esp_cmd(esp, eregs, ESP_CMD_FLUSH);
2039
2040         /* Until we are sure of what has happened, we are certainly
2041          * in the dark.
2042          */
2043         esp_advance_phase(SCptr, in_the_dark);
2044
2045         /* Check for premature interrupt condition. Can happen on FAS2x6
2046          * chips. QLogic recommends a workaround by overprogramming the
2047          * transfer counters, but this makes doing scatter-gather impossible.
2048          * Until there is a way to disable scatter-gather for a single target,
2049          * and not only for the entire host adapter as it is now, the workaround
2050          * is way to expensive performance wise.
2051          * Instead, it turns out that when this happens the target has disconnected
2052          * already but it doesn't show in the interrupt register. Compensate for
2053          * that here to try and avoid a SCSI bus reset.
2054          */
2055         if(!esp->fas_premature_intr_workaround && (fifocnt == 1) &&
2056            sreg_dataoutp(esp->sreg)) {
2057                 ESPLOG(("esp%d: Premature interrupt, enabling workaround\n",
2058                         esp->esp_id));
2059 #if 0
2060                 /* Disable scatter-gather operations, they are not possible
2061                  * when using this workaround.
2062                  */
2063                 esp->ehost->sg_tablesize = 0;
2064                 esp->ehost->use_clustering = ENABLE_CLUSTERING;
2065                 esp->fas_premature_intr_workaround = 1;
2066                 bytes_sent = 0;
2067                 if(SCptr->use_sg) {
2068                         ESPLOG(("esp%d: Aborting scatter-gather operation\n",
2069                                 esp->esp_id));
2070                         esp->cur_msgout[0] = ABORT;
2071                         esp->msgout_len = 1;
2072                         esp->msgout_ctr = 0;
2073                         esp_cmd(esp, eregs, ESP_CMD_SATN);
2074                         esp_setcount(eregs, 0xffff);
2075                         esp_cmd(esp, eregs, ESP_CMD_NULL);
2076                         esp_cmd(esp, eregs, ESP_CMD_TPAD | ESP_CMD_DMA);
2077                         return do_intr_end;
2078                 }
2079 #else
2080                 /* Just set the disconnected bit. That's what appears to
2081                  * happen anyway. The state machine will pick it up when
2082                  * we return.
2083                  */
2084                 esp->ireg |= ESP_INTR_DC;
2085 #endif
2086         }
2087
2088         if(bytes_sent < 0) {
2089                 /* I've seen this happen due to lost state in this
2090                  * driver.  No idea why it happened, but allowing
2091                  * this value to be negative caused things to
2092                  * lock up.  This allows greater chance of recovery.
2093                  * In fact every time I've seen this, it has been
2094                  * a driver bug without question.
2095                  */
2096                 ESPLOG(("esp%d: yieee, bytes_sent < 0!\n", esp->esp_id));
2097                 ESPLOG(("esp%d: csz=%d fifocount=%d ecount=%d\n",
2098                         esp->esp_id,
2099                         esp->current_transfer_size, fifocnt, ecount));
2100                 ESPLOG(("esp%d: use_sg=%d ptr=%p this_residual=%d\n",
2101                         esp->esp_id,
2102                         SCptr->use_sg, SCptr->SCp.ptr, SCptr->SCp.this_residual));
2103                 ESPLOG(("esp%d: Forcing async for target %d\n", esp->esp_id, 
2104                         SCptr->device->id));
2105                 SCptr->device->borken = 1;
2106                 esp_dev->sync = 0;
2107                 bytes_sent = 0;
2108         }
2109
2110         /* Update the state of our transfer. */
2111         SCptr->SCp.ptr += bytes_sent;
2112         SCptr->SCp.this_residual -= bytes_sent;
2113         if(SCptr->SCp.this_residual < 0) {
2114                 /* shit */
2115                 ESPLOG(("esp%d: Data transfer overrun.\n", esp->esp_id));
2116                 SCptr->SCp.this_residual = 0;
2117         }
2118
2119         /* Maybe continue. */
2120         if(!bogus_data) {
2121                 ESPDATA(("!bogus_data, "));
2122                 /* NO MATTER WHAT, we advance the scatterlist,
2123                  * if the target should decide to disconnect
2124                  * in between scatter chunks (which is common)
2125                  * we could die horribly!  I used to have the sg
2126                  * advance occur only if we are going back into
2127                  * (or are staying in) a data phase, you can
2128                  * imagine the hell I went through trying to
2129                  * figure this out.
2130                  */
2131                 if(!SCptr->SCp.this_residual && SCptr->SCp.buffers_residual)
2132                         advance_sg(esp, SCptr);
2133 #ifdef DEBUG_ESP_DATA
2134                 if(sreg_datainp(esp->sreg) || sreg_dataoutp(esp->sreg)) {
2135                         ESPDATA(("to more data\n"));
2136                 } else {
2137                         ESPDATA(("to new phase\n"));
2138                 }
2139 #endif
2140                 return esp_do_phase_determine(esp, eregs);
2141         }
2142         /* Bogus data, just wait for next interrupt. */
2143         ESPLOG(("esp%d: bogus_data during end of data phase\n",
2144                 esp->esp_id));
2145         return do_intr_end;
2146 }
2147
2148 /* We received a non-good status return at the end of
2149  * running a SCSI command.  This is used to decide if
2150  * we should clear our synchronous transfer state for
2151  * such a device when that happens.
2152  *
2153  * The idea is that when spinning up a disk or rewinding
2154  * a tape, we don't want to go into a loop re-negotiating
2155  * synchronous capabilities over and over.
2156  */
2157 static int esp_should_clear_sync(Scsi_Cmnd *sp)
2158 {
2159         unchar cmd = sp->cmnd[0];
2160
2161         /* These cases are for spinning up a disk and
2162          * waiting for that spinup to complete.
2163          */
2164         if(cmd == START_STOP)
2165                 return 0;
2166
2167         if(cmd == TEST_UNIT_READY)
2168                 return 0;
2169
2170         /* One more special case for SCSI tape drives,
2171          * this is what is used to probe the device for
2172          * completion of a rewind or tape load operation.
2173          */
2174         if(sp->device->type == TYPE_TAPE && cmd == MODE_SENSE)
2175                 return 0;
2176
2177         return 1;
2178 }
2179
2180 /* Either a command is completing or a target is dropping off the bus
2181  * to continue the command in the background so we can do other work.
2182  */
2183 static int esp_do_freebus(struct NCR_ESP *esp, struct ESP_regs *eregs)
2184 {
2185         Scsi_Cmnd *SCptr = esp->current_SC;
2186         int rval;
2187
2188         rval = skipahead2(esp, eregs, SCptr, in_status, in_msgindone, in_freeing);
2189         if(rval)
2190                 return rval;
2191
2192         if(esp->ireg != ESP_INTR_DC) {
2193                 ESPLOG(("esp%d: Target will not disconnect\n", esp->esp_id));
2194                 return do_reset_bus; /* target will not drop BSY... */
2195         }
2196         esp->msgout_len = 0;
2197         esp->prevmsgout = NOP;
2198         if(esp->prevmsgin == COMMAND_COMPLETE) {
2199                 struct esp_device *esp_dev = SCptr->device->hostdata;
2200                 /* Normal end of nexus. */
2201                 if(esp->disconnected_SC)
2202                         esp_cmd(esp, eregs, ESP_CMD_ESEL);
2203
2204                 if(SCptr->SCp.Status != GOOD &&
2205                    SCptr->SCp.Status != CONDITION_GOOD &&
2206                    ((1<<scmd_id(SCptr)) & esp->targets_present) &&
2207                    esp_dev->sync && esp_dev->sync_max_offset) {
2208                         /* SCSI standard says that the synchronous capabilities
2209                          * should be renegotiated at this point.  Most likely
2210                          * we are about to request sense from this target
2211                          * in which case we want to avoid using sync
2212                          * transfers until we are sure of the current target
2213                          * state.
2214                          */
2215                         ESPMISC(("esp: Status <%d> for target %d lun %d\n",
2216                                  SCptr->SCp.Status, SCptr->device->id, SCptr->device->lun));
2217
2218                         /* But don't do this when spinning up a disk at
2219                          * boot time while we poll for completion as it
2220                          * fills up the console with messages.  Also, tapes
2221                          * can report not ready many times right after
2222                          * loading up a tape.
2223                          */
2224                         if(esp_should_clear_sync(SCptr) != 0)
2225                                 esp_dev->sync = 0;
2226                 }
2227                 ESPDISC(("F<%02x,%02x>", SCptr->device->id, SCptr->device->lun));
2228                 esp_done(esp, ((SCptr->SCp.Status & 0xff) |
2229                                ((SCptr->SCp.Message & 0xff)<<8) |
2230                                (DID_OK << 16)));
2231         } else if(esp->prevmsgin == DISCONNECT) {
2232                 /* Normal disconnect. */
2233                 esp_cmd(esp, eregs, ESP_CMD_ESEL);
2234                 ESPDISC(("D<%02x,%02x>", SCptr->device->id, SCptr->device->lun));
2235                 append_SC(&esp->disconnected_SC, SCptr);
2236                 esp->current_SC = NULL;
2237                 if(esp->issue_SC)
2238                         esp_exec_cmd(esp);
2239         } else {
2240                 /* Driver bug, we do not expect a disconnect here
2241                  * and should not have advanced the state engine
2242                  * to in_freeing.
2243                  */
2244                 ESPLOG(("esp%d: last msg not disc and not cmd cmplt.\n",
2245                         esp->esp_id));
2246                 return do_reset_bus;
2247         }
2248         return do_intr_end;
2249 }
2250
2251 /* When a reselect occurs, and we cannot find the command to
2252  * reconnect to in our queues, we do this.
2253  */
2254 static int esp_bad_reconnect(struct NCR_ESP *esp)
2255 {
2256         Scsi_Cmnd *sp;
2257
2258         ESPLOG(("esp%d: Eieeee, reconnecting unknown command!\n",
2259                 esp->esp_id));
2260         ESPLOG(("QUEUE DUMP\n"));
2261         sp = esp->issue_SC;
2262         ESPLOG(("esp%d: issue_SC[", esp->esp_id));
2263         while(sp) {
2264                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2265                 sp = (Scsi_Cmnd *) sp->host_scribble;
2266         }
2267         ESPLOG(("]\n"));
2268         sp = esp->current_SC;
2269         ESPLOG(("esp%d: current_SC[", esp->esp_id));
2270         while(sp) {
2271                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2272                 sp = (Scsi_Cmnd *) sp->host_scribble;
2273         }
2274         ESPLOG(("]\n"));
2275         sp = esp->disconnected_SC;
2276         ESPLOG(("esp%d: disconnected_SC[", esp->esp_id));
2277         while(sp) {
2278                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2279                 sp = (Scsi_Cmnd *) sp->host_scribble;
2280         }
2281         ESPLOG(("]\n"));
2282         return do_reset_bus;
2283 }
2284
2285 /* Do the needy when a target tries to reconnect to us. */
2286 static int esp_do_reconnect(struct NCR_ESP *esp, 
2287                             struct ESP_regs *eregs)
2288 {
2289         int lun, target;
2290         Scsi_Cmnd *SCptr;
2291
2292         /* Check for all bogus conditions first. */
2293         target = reconnect_target(esp, eregs);
2294         if(target < 0) {
2295                 ESPDISC(("bad bus bits\n"));
2296                 return do_reset_bus;
2297         }
2298         lun = reconnect_lun(esp, eregs);
2299         if(lun < 0) {
2300                 ESPDISC(("target=%2x, bad identify msg\n", target));
2301                 return do_reset_bus;
2302         }
2303
2304         /* Things look ok... */
2305         ESPDISC(("R<%02x,%02x>", target, lun));
2306
2307         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
2308         if(esp100_reconnect_hwbug(esp, eregs))
2309                 return do_reset_bus;
2310         esp_cmd(esp, eregs, ESP_CMD_NULL);
2311
2312         SCptr = remove_SC(&esp->disconnected_SC, (unchar) target, (unchar) lun);
2313         if(!SCptr)
2314                 return esp_bad_reconnect(esp);
2315
2316         esp_connect(esp, eregs, SCptr);
2317         esp_cmd(esp, eregs, ESP_CMD_MOK);
2318
2319         /* Reconnect implies a restore pointers operation. */
2320         esp_restore_pointers(esp, SCptr);
2321
2322         esp->snip = 0;
2323         esp_advance_phase(SCptr, in_the_dark);
2324         return do_intr_end;
2325 }
2326
2327 /* End of NEXUS (hopefully), pick up status + message byte then leave if
2328  * all goes well.
2329  */
2330 static int esp_do_status(struct NCR_ESP *esp, struct ESP_regs *eregs)
2331 {
2332         Scsi_Cmnd *SCptr = esp->current_SC;
2333         int intr, rval;
2334
2335         rval = skipahead1(esp, eregs, SCptr, in_the_dark, in_status);
2336         if(rval)
2337                 return rval;
2338
2339         intr = esp->ireg;
2340         ESPSTAT(("esp_do_status: "));
2341         if(intr != ESP_INTR_DC) {
2342                 int message_out = 0; /* for parity problems */
2343
2344                 /* Ack the message. */
2345                 ESPSTAT(("ack msg, "));
2346                 esp_cmd(esp, eregs, ESP_CMD_MOK);
2347
2348                 if(esp->dma_poll)
2349                         esp->dma_poll(esp, (unsigned char *) esp->esp_command);
2350
2351                 ESPSTAT(("got something, "));
2352                 /* ESP chimes in with one of
2353                  *
2354                  * 1) function done interrupt:
2355                  *      both status and message in bytes
2356                  *      are available
2357                  *
2358                  * 2) bus service interrupt:
2359                  *      only status byte was acquired
2360                  *
2361                  * 3) Anything else:
2362                  *      can't happen, but we test for it
2363                  *      anyways
2364                  *
2365                  * ALSO: If bad parity was detected on either
2366                  *       the status _or_ the message byte then
2367                  *       the ESP has asserted ATN on the bus
2368                  *       and we must therefore wait for the
2369                  *       next phase change.
2370                  */
2371                 if(intr & ESP_INTR_FDONE) {
2372                         /* We got it all, hallejulia. */
2373                         ESPSTAT(("got both, "));
2374                         SCptr->SCp.Status = esp->esp_command[0];
2375                         SCptr->SCp.Message = esp->esp_command[1];
2376                         esp->prevmsgin = SCptr->SCp.Message;
2377                         esp->cur_msgin[0] = SCptr->SCp.Message;
2378                         if(esp->sreg & ESP_STAT_PERR) {
2379                                 /* There was bad parity for the
2380                                  * message byte, the status byte
2381                                  * was ok.
2382                                  */
2383                                 message_out = MSG_PARITY_ERROR;
2384                         }
2385                 } else if(intr == ESP_INTR_BSERV) {
2386                         /* Only got status byte. */
2387                         ESPLOG(("esp%d: got status only, ", esp->esp_id));
2388                         if(!(esp->sreg & ESP_STAT_PERR)) {
2389                                 SCptr->SCp.Status = esp->esp_command[0];
2390                                 SCptr->SCp.Message = 0xff;
2391                         } else {
2392                                 /* The status byte had bad parity.
2393                                  * we leave the scsi_pointer Status
2394                                  * field alone as we set it to a default
2395                                  * of CHECK_CONDITION in esp_queue.
2396                                  */
2397                                 message_out = INITIATOR_ERROR;
2398                         }
2399                 } else {
2400                         /* This shouldn't happen ever. */
2401                         ESPSTAT(("got bolixed\n"));
2402                         esp_advance_phase(SCptr, in_the_dark);
2403                         return esp_do_phase_determine(esp, eregs);
2404                 }
2405
2406                 if(!message_out) {
2407                         ESPSTAT(("status=%2x msg=%2x, ", SCptr->SCp.Status,
2408                                 SCptr->SCp.Message));
2409                         if(SCptr->SCp.Message == COMMAND_COMPLETE) {
2410                                 ESPSTAT(("and was COMMAND_COMPLETE\n"));
2411                                 esp_advance_phase(SCptr, in_freeing);
2412                                 return esp_do_freebus(esp, eregs);
2413                         } else {
2414                                 ESPLOG(("esp%d: and _not_ COMMAND_COMPLETE\n",
2415                                         esp->esp_id));
2416                                 esp->msgin_len = esp->msgin_ctr = 1;
2417                                 esp_advance_phase(SCptr, in_msgindone);
2418                                 return esp_do_msgindone(esp, eregs);
2419                         }
2420                 } else {
2421                         /* With luck we'll be able to let the target
2422                          * know that bad parity happened, it will know
2423                          * which byte caused the problems and send it
2424                          * again.  For the case where the status byte
2425                          * receives bad parity, I do not believe most
2426                          * targets recover very well.  We'll see.
2427                          */
2428                         ESPLOG(("esp%d: bad parity somewhere mout=%2x\n",
2429                                 esp->esp_id, message_out));
2430                         esp->cur_msgout[0] = message_out;
2431                         esp->msgout_len = esp->msgout_ctr = 1;
2432                         esp_advance_phase(SCptr, in_the_dark);
2433                         return esp_do_phase_determine(esp, eregs);
2434                 }
2435         } else {
2436                 /* If we disconnect now, all hell breaks loose. */
2437                 ESPLOG(("esp%d: whoops, disconnect\n", esp->esp_id));
2438                 esp_advance_phase(SCptr, in_the_dark);
2439                 return esp_do_phase_determine(esp, eregs);
2440         }
2441 }
2442
2443 static int esp_enter_status(struct NCR_ESP *esp,
2444                             struct ESP_regs *eregs)
2445 {
2446         unchar thecmd = ESP_CMD_ICCSEQ;
2447
2448         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
2449
2450         if(esp->do_pio_cmds) {
2451                 esp_advance_phase(esp->current_SC, in_status);
2452                 esp_cmd(esp, eregs, thecmd);
2453                 while(!(esp_read(esp->eregs->esp_status) & ESP_STAT_INTR));
2454                 esp->esp_command[0] = esp_read(eregs->esp_fdata);
2455                 while(!(esp_read(esp->eregs->esp_status) & ESP_STAT_INTR));
2456                 esp->esp_command[1] = esp_read(eregs->esp_fdata);
2457         } else {
2458                 esp->esp_command[0] = esp->esp_command[1] = 0xff;
2459                 esp_write(eregs->esp_tclow, 2);
2460                 esp_write(eregs->esp_tcmed, 0);
2461                 esp->dma_init_read(esp, esp->esp_command_dvma, 2);
2462                 thecmd |= ESP_CMD_DMA;
2463                 esp_cmd(esp, eregs, thecmd);
2464                 esp_advance_phase(esp->current_SC, in_status);
2465         }
2466
2467         return esp_do_status(esp, eregs);
2468 }
2469
2470 static int esp_disconnect_amidst_phases(struct NCR_ESP *esp,
2471                                         struct ESP_regs *eregs)
2472 {
2473         Scsi_Cmnd *sp = esp->current_SC;
2474         struct esp_device *esp_dev = sp->device->hostdata;
2475
2476         /* This means real problems if we see this
2477          * here.  Unless we were actually trying
2478          * to force the device to abort/reset.
2479          */
2480         ESPLOG(("esp%d: Disconnect amidst phases, ", esp->esp_id));
2481         ESPLOG(("pphase<%s> cphase<%s>, ",
2482                 phase_string(sp->SCp.phase),
2483                 phase_string(sp->SCp.sent_command)));
2484
2485         if(esp->disconnected_SC)
2486                 esp_cmd(esp, eregs, ESP_CMD_ESEL);
2487
2488         switch(esp->cur_msgout[0]) {
2489         default:
2490                 /* We didn't expect this to happen at all. */
2491                 ESPLOG(("device is bolixed\n"));
2492                 esp_advance_phase(sp, in_tgterror);
2493                 esp_done(esp, (DID_ERROR << 16));
2494                 break;
2495
2496         case BUS_DEVICE_RESET:
2497                 ESPLOG(("device reset successful\n"));
2498                 esp_dev->sync_max_offset = 0;
2499                 esp_dev->sync_min_period = 0;
2500                 esp_dev->sync = 0;
2501                 esp_advance_phase(sp, in_resetdev);
2502                 esp_done(esp, (DID_RESET << 16));
2503                 break;
2504
2505         case ABORT:
2506                 ESPLOG(("device abort successful\n"));
2507                 esp_advance_phase(sp, in_abortone);
2508                 esp_done(esp, (DID_ABORT << 16));
2509                 break;
2510
2511         };
2512         return do_intr_end;
2513 }
2514
2515 static int esp_enter_msgout(struct NCR_ESP *esp,
2516                             struct ESP_regs *eregs)
2517 {
2518         esp_advance_phase(esp->current_SC, in_msgout);
2519         return esp_do_msgout(esp, eregs);
2520 }
2521
2522 static int esp_enter_msgin(struct NCR_ESP *esp,
2523                            struct ESP_regs *eregs)
2524 {
2525         esp_advance_phase(esp->current_SC, in_msgin);
2526         return esp_do_msgin(esp, eregs);
2527 }
2528
2529 static int esp_enter_cmd(struct NCR_ESP *esp,
2530                          struct ESP_regs *eregs)
2531 {
2532         esp_advance_phase(esp->current_SC, in_cmdbegin);
2533         return esp_do_cmdbegin(esp, eregs);
2534 }
2535
2536 static int esp_enter_badphase(struct NCR_ESP *esp,
2537                               struct ESP_regs *eregs)
2538 {
2539         ESPLOG(("esp%d: Bizarre bus phase %2x.\n", esp->esp_id,
2540                 esp->sreg & ESP_STAT_PMASK));
2541         return do_reset_bus;
2542 }
2543
2544 typedef int (*espfunc_t)(struct NCR_ESP *,
2545                          struct ESP_regs *);
2546
2547 static espfunc_t phase_vector[] = {
2548         esp_do_data,            /* ESP_DOP */
2549         esp_do_data,            /* ESP_DIP */
2550         esp_enter_cmd,          /* ESP_CMDP */
2551         esp_enter_status,       /* ESP_STATP */
2552         esp_enter_badphase,     /* ESP_STAT_PMSG */
2553         esp_enter_badphase,     /* ESP_STAT_PMSG | ESP_STAT_PIO */
2554         esp_enter_msgout,       /* ESP_MOP */
2555         esp_enter_msgin,        /* ESP_MIP */
2556 };
2557
2558 /* The target has control of the bus and we have to see where it has
2559  * taken us.
2560  */
2561 static int esp_do_phase_determine(struct NCR_ESP *esp,
2562                                   struct ESP_regs *eregs)
2563 {
2564         if ((esp->ireg & ESP_INTR_DC) != 0)
2565                 return esp_disconnect_amidst_phases(esp, eregs);
2566         return phase_vector[esp->sreg & ESP_STAT_PMASK](esp, eregs);
2567 }
2568
2569 /* First interrupt after exec'ing a cmd comes here. */
2570 static int esp_select_complete(struct NCR_ESP *esp, struct ESP_regs *eregs)
2571 {
2572         Scsi_Cmnd *SCptr = esp->current_SC;
2573         struct esp_device *esp_dev = SCptr->device->hostdata;
2574         int cmd_bytes_sent, fcnt;
2575
2576         fcnt = (esp_read(eregs->esp_fflags) & ESP_FF_FBYTES);
2577         cmd_bytes_sent = esp->dma_bytes_sent(esp, fcnt);
2578         if(esp->dma_invalidate)
2579                 esp->dma_invalidate(esp);
2580
2581         /* Let's check to see if a reselect happened
2582          * while we we're trying to select.  This must
2583          * be checked first.
2584          */
2585         if(esp->ireg == (ESP_INTR_RSEL | ESP_INTR_FDONE)) {
2586                 esp_reconnect(esp, SCptr);
2587                 return esp_do_reconnect(esp, eregs);
2588         }
2589
2590         /* Looks like things worked, we should see a bus service &
2591          * a function complete interrupt at this point.  Note we
2592          * are doing a direct comparison because we don't want to
2593          * be fooled into thinking selection was successful if
2594          * ESP_INTR_DC is set, see below.
2595          */
2596         if(esp->ireg == (ESP_INTR_FDONE | ESP_INTR_BSERV)) {
2597                 /* target speaks... */
2598                 esp->targets_present |= (1<<scmd_id(SCptr));
2599
2600                 /* What if the target ignores the sdtr? */
2601                 if(esp->snip)
2602                         esp_dev->sync = 1;
2603
2604                 /* See how far, if at all, we got in getting
2605                  * the information out to the target.
2606                  */
2607                 switch(esp->seqreg) {
2608                 default:
2609
2610                 case ESP_STEP_ASEL:
2611                         /* Arbitration won, target selected, but
2612                          * we are in some phase which is not command
2613                          * phase nor is it message out phase.
2614                          *
2615                          * XXX We've confused the target, obviously.
2616                          * XXX So clear it's state, but we also end
2617                          * XXX up clearing everyone elses.  That isn't
2618                          * XXX so nice.  I'd like to just reset this
2619                          * XXX target, but if I cannot even get it's
2620                          * XXX attention and finish selection to talk
2621                          * XXX to it, there is not much more I can do.
2622                          * XXX If we have a loaded bus we're going to
2623                          * XXX spend the next second or so renegotiating
2624                          * XXX for synchronous transfers.
2625                          */
2626                         ESPLOG(("esp%d: STEP_ASEL for tgt %d\n",
2627                                 esp->esp_id, SCptr->device->id));
2628
2629                 case ESP_STEP_SID:
2630                         /* Arbitration won, target selected, went
2631                          * to message out phase, sent one message
2632                          * byte, then we stopped.  ATN is asserted
2633                          * on the SCSI bus and the target is still
2634                          * there hanging on.  This is a legal
2635                          * sequence step if we gave the ESP a select
2636                          * and stop command.
2637                          *
2638                          * XXX See above, I could set the borken flag
2639                          * XXX in the device struct and retry the
2640                          * XXX command.  But would that help for
2641                          * XXX tagged capable targets?
2642                          */
2643
2644                 case ESP_STEP_NCMD:
2645                         /* Arbitration won, target selected, maybe
2646                          * sent the one message byte in message out
2647                          * phase, but we did not go to command phase
2648                          * in the end.  Actually, we could have sent
2649                          * only some of the message bytes if we tried
2650                          * to send out the entire identify and tag
2651                          * message using ESP_CMD_SA3.
2652                          */
2653                         cmd_bytes_sent = 0;
2654                         break;
2655
2656                 case ESP_STEP_PPC:
2657                         /* No, not the powerPC pinhead.  Arbitration
2658                          * won, all message bytes sent if we went to
2659                          * message out phase, went to command phase
2660                          * but only part of the command was sent.
2661                          *
2662                          * XXX I've seen this, but usually in conjunction
2663                          * XXX with a gross error which appears to have
2664                          * XXX occurred between the time I told the
2665                          * XXX ESP to arbitrate and when I got the
2666                          * XXX interrupt.  Could I have misloaded the
2667                          * XXX command bytes into the fifo?  Actually,
2668                          * XXX I most likely missed a phase, and therefore
2669                          * XXX went into never never land and didn't even
2670                          * XXX know it.  That was the old driver though.
2671                          * XXX What is even more peculiar is that the ESP
2672                          * XXX showed the proper function complete and
2673                          * XXX bus service bits in the interrupt register.
2674                          */
2675
2676                 case ESP_STEP_FINI4:
2677                 case ESP_STEP_FINI5:
2678                 case ESP_STEP_FINI6:
2679                 case ESP_STEP_FINI7:
2680                         /* Account for the identify message */
2681                         if(SCptr->SCp.phase == in_slct_norm)
2682                                 cmd_bytes_sent -= 1;
2683                 };
2684                 esp_cmd(esp, eregs, ESP_CMD_NULL);
2685
2686                 /* Be careful, we could really get fucked during synchronous
2687                  * data transfers if we try to flush the fifo now.
2688                  */
2689                 if(!fcnt && /* Fifo is empty and... */
2690                    /* either we are not doing synchronous transfers or... */
2691                    (!esp_dev->sync_max_offset ||
2692                     /* We are not going into data in phase. */
2693                     ((esp->sreg & ESP_STAT_PMASK) != ESP_DIP)))
2694                         esp_cmd(esp, eregs, ESP_CMD_FLUSH); /* flush is safe */
2695
2696                 /* See how far we got if this is not a slow command. */
2697                 if(!esp->esp_slowcmd) {
2698                         if(cmd_bytes_sent < 0)
2699                                 cmd_bytes_sent = 0;
2700                         if(cmd_bytes_sent != SCptr->cmd_len) {
2701                                 /* Crapola, mark it as a slowcmd
2702                                  * so that we have some chance of
2703                                  * keeping the command alive with
2704                                  * good luck.
2705                                  *
2706                                  * XXX Actually, if we didn't send it all
2707                                  * XXX this means either we didn't set things
2708                                  * XXX up properly (driver bug) or the target
2709                                  * XXX or the ESP detected parity on one of
2710                                  * XXX the command bytes.  This makes much
2711                                  * XXX more sense, and therefore this code
2712                                  * XXX should be changed to send out a
2713                                  * XXX parity error message or if the status
2714                                  * XXX register shows no parity error then
2715                                  * XXX just expect the target to bring the
2716                                  * XXX bus into message in phase so that it
2717                                  * XXX can send us the parity error message.
2718                                  * XXX SCSI sucks...
2719                                  */
2720                                 esp->esp_slowcmd = 1;
2721                                 esp->esp_scmdp = &(SCptr->cmnd[cmd_bytes_sent]);
2722                                 esp->esp_scmdleft = (SCptr->cmd_len - cmd_bytes_sent);
2723                         }
2724                 }
2725
2726                 /* Now figure out where we went. */
2727                 esp_advance_phase(SCptr, in_the_dark);
2728                 return esp_do_phase_determine(esp, eregs);
2729         }
2730
2731         /* Did the target even make it? */
2732         if(esp->ireg == ESP_INTR_DC) {
2733                 /* wheee... nobody there or they didn't like
2734                  * what we told it to do, clean up.
2735                  */
2736
2737                 /* If anyone is off the bus, but working on
2738                  * a command in the background for us, tell
2739                  * the ESP to listen for them.
2740                  */
2741                 if(esp->disconnected_SC)
2742                         esp_cmd(esp, eregs, ESP_CMD_ESEL);
2743
2744                 if(((1<<SCptr->device->id) & esp->targets_present) &&
2745                    esp->seqreg && esp->cur_msgout[0] == EXTENDED_MESSAGE &&
2746                    (SCptr->SCp.phase == in_slct_msg ||
2747                     SCptr->SCp.phase == in_slct_stop)) {
2748                         /* shit */
2749                         esp->snip = 0;
2750                         ESPLOG(("esp%d: Failed synchronous negotiation for target %d "
2751                                 "lun %d\n", esp->esp_id, SCptr->device->id, SCptr->device->lun));
2752                         esp_dev->sync_max_offset = 0;
2753                         esp_dev->sync_min_period = 0;
2754                         esp_dev->sync = 1; /* so we don't negotiate again */
2755
2756                         /* Run the command again, this time though we
2757                          * won't try to negotiate for synchronous transfers.
2758                          *
2759                          * XXX I'd like to do something like send an
2760                          * XXX INITIATOR_ERROR or ABORT message to the
2761                          * XXX target to tell it, "Sorry I confused you,
2762                          * XXX please come back and I will be nicer next
2763                          * XXX time".  But that requires having the target
2764                          * XXX on the bus, and it has dropped BSY on us.
2765                          */
2766                         esp->current_SC = NULL;
2767                         esp_advance_phase(SCptr, not_issued);
2768                         prepend_SC(&esp->issue_SC, SCptr);
2769                         esp_exec_cmd(esp);
2770                         return do_intr_end;
2771                 }
2772
2773                 /* Ok, this is normal, this is what we see during boot
2774                  * or whenever when we are scanning the bus for targets.
2775                  * But first make sure that is really what is happening.
2776                  */
2777                 if(((1<<SCptr->device->id) & esp->targets_present)) {
2778                         ESPLOG(("esp%d: Warning, live target %d not responding to "
2779                                 "selection.\n", esp->esp_id, SCptr->device->id));
2780
2781                         /* This _CAN_ happen.  The SCSI standard states that
2782                          * the target is to _not_ respond to selection if
2783                          * _it_ detects bad parity on the bus for any reason.
2784                          * Therefore, we assume that if we've talked successfully
2785                          * to this target before, bad parity is the problem.
2786                          */
2787                         esp_done(esp, (DID_PARITY << 16));
2788                 } else {
2789                         /* Else, there really isn't anyone there. */
2790                         ESPMISC(("esp: selection failure, maybe nobody there?\n"));
2791                         ESPMISC(("esp: target %d lun %d\n",
2792                                  SCptr->device->id, SCptr->device->lun));
2793                         esp_done(esp, (DID_BAD_TARGET << 16));
2794                 }
2795                 return do_intr_end;
2796         }
2797
2798
2799         ESPLOG(("esp%d: Selection failure.\n", esp->esp_id));
2800         printk("esp%d: Currently -- ", esp->esp_id);
2801         esp_print_ireg(esp->ireg);
2802         printk(" ");
2803         esp_print_statreg(esp->sreg);
2804         printk(" ");
2805         esp_print_seqreg(esp->seqreg);
2806         printk("\n");
2807         printk("esp%d: New -- ", esp->esp_id);
2808         esp->sreg = esp_read(eregs->esp_status);
2809         esp->seqreg = esp_read(eregs->esp_sstep);
2810         esp->ireg = esp_read(eregs->esp_intrpt);
2811         esp_print_ireg(esp->ireg);
2812         printk(" ");
2813         esp_print_statreg(esp->sreg);
2814         printk(" ");
2815         esp_print_seqreg(esp->seqreg);
2816         printk("\n");
2817         ESPLOG(("esp%d: resetting bus\n", esp->esp_id));
2818         return do_reset_bus; /* ugh... */
2819 }
2820
2821 /* Continue reading bytes for msgin phase. */
2822 static int esp_do_msgincont(struct NCR_ESP *esp, struct ESP_regs *eregs)
2823 {
2824         if(esp->ireg & ESP_INTR_BSERV) {
2825                 /* in the right phase too? */
2826                 if((esp->sreg & ESP_STAT_PMASK) == ESP_MIP) {
2827                         /* phew... */
2828                         esp_cmd(esp, eregs, ESP_CMD_TI);
2829                         esp_advance_phase(esp->current_SC, in_msgindone);
2830                         return do_intr_end;
2831                 }
2832
2833                 /* We changed phase but ESP shows bus service,
2834                  * in this case it is most likely that we, the
2835                  * hacker who has been up for 20hrs straight
2836                  * staring at the screen, drowned in coffee
2837                  * smelling like retched cigarette ashes
2838                  * have miscoded something..... so, try to
2839                  * recover as best we can.
2840                  */
2841                 ESPLOG(("esp%d: message in mis-carriage.\n", esp->esp_id));
2842         }
2843         esp_advance_phase(esp->current_SC, in_the_dark);
2844         return do_phase_determine;
2845 }
2846
2847 static int check_singlebyte_msg(struct NCR_ESP *esp,
2848                                 struct ESP_regs *eregs)
2849 {
2850         esp->prevmsgin = esp->cur_msgin[0];
2851         if(esp->cur_msgin[0] & 0x80) {
2852                 /* wheee... */
2853                 ESPLOG(("esp%d: target sends identify amidst phases\n",
2854                         esp->esp_id));
2855                 esp_advance_phase(esp->current_SC, in_the_dark);
2856                 return 0;
2857         } else if(((esp->cur_msgin[0] & 0xf0) == 0x20) ||
2858                   (esp->cur_msgin[0] == EXTENDED_MESSAGE)) {
2859                 esp->msgin_len = 2;
2860                 esp_advance_phase(esp->current_SC, in_msgincont);
2861                 return 0;
2862         }
2863         esp_advance_phase(esp->current_SC, in_the_dark);
2864         switch(esp->cur_msgin[0]) {
2865         default:
2866                 /* We don't want to hear about it. */
2867                 ESPLOG(("esp%d: msg %02x which we don't know about\n", esp->esp_id,
2868                         esp->cur_msgin[0]));
2869                 return MESSAGE_REJECT;
2870
2871         case NOP:
2872                 ESPLOG(("esp%d: target %d sends a nop\n", esp->esp_id,
2873                         esp->current_SC->device->id));
2874                 return 0;
2875
2876         case RESTORE_POINTERS:
2877                 /* In this case we might also have to backup the
2878                  * "slow command" pointer.  It is rare to get such
2879                  * a save/restore pointer sequence so early in the
2880                  * bus transition sequences, but cover it.
2881                  */
2882                 if(esp->esp_slowcmd) {
2883                         esp->esp_scmdleft = esp->current_SC->cmd_len;
2884                         esp->esp_scmdp = &esp->current_SC->cmnd[0];
2885                 }
2886                 esp_restore_pointers(esp, esp->current_SC);
2887                 return 0;
2888
2889         case SAVE_POINTERS:
2890                 esp_save_pointers(esp, esp->current_SC);
2891                 return 0;
2892
2893         case COMMAND_COMPLETE:
2894         case DISCONNECT:
2895                 /* Freeing the bus, let it go. */
2896                 esp->current_SC->SCp.phase = in_freeing;
2897                 return 0;
2898
2899         case MESSAGE_REJECT:
2900                 ESPMISC(("msg reject, "));
2901                 if(esp->prevmsgout == EXTENDED_MESSAGE) {
2902                         struct esp_device *esp_dev = esp->current_SC->device->hostdata;
2903
2904                         /* Doesn't look like this target can
2905                          * do synchronous or WIDE transfers.
2906                          */
2907                         ESPSDTR(("got reject, was trying nego, clearing sync/WIDE\n"));
2908                         esp_dev->sync = 1;
2909                         esp_dev->wide = 1;
2910                         esp_dev->sync_min_period = 0;
2911                         esp_dev->sync_max_offset = 0;
2912                         return 0;
2913                 } else {
2914                         ESPMISC(("not sync nego, sending ABORT\n"));
2915                         return ABORT;
2916                 }
2917         };
2918 }
2919
2920 /* Target negotiates for synchronous transfers before we do, this
2921  * is legal although very strange.  What is even funnier is that
2922  * the SCSI2 standard specifically recommends against targets doing
2923  * this because so many initiators cannot cope with this occurring.
2924  */
2925 static int target_with_ants_in_pants(struct NCR_ESP *esp,
2926                                      Scsi_Cmnd *SCptr,
2927                                      struct esp_device *esp_dev)
2928 {
2929         if(esp_dev->sync || SCptr->device->borken) {
2930                 /* sorry, no can do */
2931                 ESPSDTR(("forcing to async, "));
2932                 build_sync_nego_msg(esp, 0, 0);
2933                 esp_dev->sync = 1;
2934                 esp->snip = 1;
2935                 ESPLOG(("esp%d: hoping for msgout\n", esp->esp_id));
2936                 esp_advance_phase(SCptr, in_the_dark);
2937                 return EXTENDED_MESSAGE;
2938         }
2939
2940         /* Ok, we'll check them out... */
2941         return 0;
2942 }
2943
2944 static void sync_report(struct NCR_ESP *esp)
2945 {
2946         int msg3, msg4;
2947         char *type;
2948
2949         msg3 = esp->cur_msgin[3];
2950         msg4 = esp->cur_msgin[4];
2951         if(msg4) {
2952                 int hz = 1000000000 / (msg3 * 4);
2953                 int integer = hz / 1000000;
2954                 int fraction = (hz - (integer * 1000000)) / 10000;
2955                 if((msg3 * 4) < 200) {
2956                         type = "FAST";
2957                 } else {
2958                         type = "synchronous";
2959                 }
2960
2961                 /* Do not transform this back into one big printk
2962                  * again, it triggers a bug in our sparc64-gcc272
2963                  * sibling call optimization.  -DaveM
2964                  */
2965                 ESPLOG((KERN_INFO "esp%d: target %d ",
2966                         esp->esp_id, esp->current_SC->device->id));
2967                 ESPLOG(("[period %dns offset %d %d.%02dMHz ",
2968                         (int) msg3 * 4, (int) msg4,
2969                         integer, fraction));
2970                 ESPLOG(("%s SCSI%s]\n", type,
2971                         (((msg3 * 4) < 200) ? "-II" : "")));
2972         } else {
2973                 ESPLOG((KERN_INFO "esp%d: target %d asynchronous\n",
2974                         esp->esp_id, esp->current_SC->device->id));
2975         }
2976 }
2977
2978 static int check_multibyte_msg(struct NCR_ESP *esp,
2979                                struct ESP_regs *eregs)
2980 {
2981         Scsi_Cmnd *SCptr = esp->current_SC;
2982         struct esp_device *esp_dev = SCptr->device->hostdata;
2983         unchar regval = 0;
2984         int message_out = 0;
2985
2986         ESPSDTR(("chk multibyte msg: "));
2987         if(esp->cur_msgin[2] == EXTENDED_SDTR) {
2988                 int period = esp->cur_msgin[3];
2989                 int offset = esp->cur_msgin[4];
2990
2991                 ESPSDTR(("is sync nego response, "));
2992                 if(!esp->snip) {
2993                         int rval;
2994
2995                         /* Target negotiates first! */
2996                         ESPSDTR(("target jumps the gun, "));
2997                         message_out = EXTENDED_MESSAGE; /* we must respond */
2998                         rval = target_with_ants_in_pants(esp, SCptr, esp_dev);
2999                         if(rval)
3000                                 return rval;
3001                 }
3002
3003                 ESPSDTR(("examining sdtr, "));
3004
3005                 /* Offset cannot be larger than ESP fifo size. */
3006                 if(offset > 15) {
3007                         ESPSDTR(("offset too big %2x, ", offset));
3008                         offset = 15;
3009                         ESPSDTR(("sending back new offset\n"));
3010                         build_sync_nego_msg(esp, period, offset);
3011                         return EXTENDED_MESSAGE;
3012                 }
3013
3014                 if(offset && period > esp->max_period) {
3015                         /* Yeee, async for this slow device. */
3016                         ESPSDTR(("period too long %2x, ", period));
3017                         build_sync_nego_msg(esp, 0, 0);
3018                         ESPSDTR(("hoping for msgout\n"));
3019                         esp_advance_phase(esp->current_SC, in_the_dark);
3020                         return EXTENDED_MESSAGE;
3021                 } else if (offset && period < esp->min_period) {
3022                         ESPSDTR(("period too short %2x, ", period));
3023                         period = esp->min_period;
3024                         if(esp->erev > esp236)
3025                                 regval = 4;
3026                         else
3027                                 regval = 5;
3028                 } else if(offset) {
3029                         int tmp;
3030
3031                         ESPSDTR(("period is ok, "));
3032                         tmp = esp->ccycle / 1000;
3033                         regval = (((period << 2) + tmp - 1) / tmp);
3034                         if(regval && (esp->erev > esp236)) {
3035                                 if(period >= 50)
3036                                         regval--;
3037                         }
3038                 }
3039
3040                 if(offset) {
3041                         unchar bit;
3042
3043                         esp_dev->sync_min_period = (regval & 0x1f);
3044                         esp_dev->sync_max_offset = (offset | esp->radelay);
3045                         if(esp->erev > esp236) {
3046                                 if(esp->erev == fas100a)
3047                                         bit = ESP_CONFIG3_FAST;
3048                                 else
3049                                         bit = ESP_CONFIG3_FSCSI;
3050                                 if(period < 50)
3051                                         esp->config3[SCptr->device->id] |= bit;
3052                                 else
3053                                         esp->config3[SCptr->device->id] &= ~bit;
3054                                 esp->prev_cfg3 = esp->config3[SCptr->device->id];
3055                                 esp_write(eregs->esp_cfg3, esp->prev_cfg3);
3056                         }
3057                         esp->prev_soff = esp_dev->sync_min_period;
3058                         esp_write(eregs->esp_soff, esp->prev_soff);
3059                         esp->prev_stp = esp_dev->sync_max_offset;
3060                         esp_write(eregs->esp_stp, esp->prev_stp);
3061
3062                         ESPSDTR(("soff=%2x stp=%2x cfg3=%2x\n",
3063                                 esp_dev->sync_max_offset,
3064                                 esp_dev->sync_min_period,
3065                                 esp->config3[scmd_id(SCptr)]));
3066
3067                         esp->snip = 0;
3068                 } else if(esp_dev->sync_max_offset) {
3069                         unchar bit;
3070
3071                         /* back to async mode */
3072                         ESPSDTR(("unaccaptable sync nego, forcing async\n"));
3073                         esp_dev->sync_max_offset = 0;
3074                         esp_dev->sync_min_period = 0;
3075                         esp->prev_soff = 0;
3076                         esp_write(eregs->esp_soff, 0);
3077                         esp->prev_stp = 0;
3078                         esp_write(eregs->esp_stp, 0);
3079                         if(esp->erev > esp236) {
3080                                 if(esp->erev == fas100a)
3081                                         bit = ESP_CONFIG3_FAST;
3082                                 else
3083                                         bit = ESP_CONFIG3_FSCSI;
3084                                 esp->config3[SCptr->device->id] &= ~bit;
3085                                 esp->prev_cfg3 = esp->config3[SCptr->device->id];
3086                                 esp_write(eregs->esp_cfg3, esp->prev_cfg3);
3087                         }
3088                 }
3089
3090                 sync_report(esp);
3091
3092                 ESPSDTR(("chk multibyte msg: sync is known, "));
3093                 esp_dev->sync = 1;
3094
3095                 if(message_out) {
3096                         ESPLOG(("esp%d: sending sdtr back, hoping for msgout\n",
3097                                 esp->esp_id));
3098                         build_sync_nego_msg(esp, period, offset);
3099                         esp_advance_phase(SCptr, in_the_dark);
3100                         return EXTENDED_MESSAGE;
3101                 }
3102
3103                 ESPSDTR(("returning zero\n"));
3104                 esp_advance_phase(SCptr, in_the_dark); /* ...or else! */
3105                 return 0;
3106         } else if(esp->cur_msgin[2] == EXTENDED_WDTR) {
3107                 ESPLOG(("esp%d: AIEEE wide msg received\n", esp->esp_id));
3108                 message_out = MESSAGE_REJECT;
3109         } else if(esp->cur_msgin[2] == EXTENDED_MODIFY_DATA_POINTER) {
3110                 ESPLOG(("esp%d: rejecting modify data ptr msg\n", esp->esp_id));
3111                 message_out = MESSAGE_REJECT;
3112         }
3113         esp_advance_phase(SCptr, in_the_dark);
3114         return message_out;
3115 }
3116
3117 static int esp_do_msgindone(struct NCR_ESP *esp, struct ESP_regs *eregs)
3118 {
3119         Scsi_Cmnd *SCptr = esp->current_SC;
3120         int message_out = 0, it = 0, rval;
3121
3122         rval = skipahead1(esp, eregs, SCptr, in_msgin, in_msgindone);
3123         if(rval)
3124                 return rval;
3125         if(SCptr->SCp.sent_command != in_status) {
3126                 if(!(esp->ireg & ESP_INTR_DC)) {
3127                         if(esp->msgin_len && (esp->sreg & ESP_STAT_PERR)) {
3128                                 message_out = MSG_PARITY_ERROR;
3129                                 esp_cmd(esp, eregs, ESP_CMD_FLUSH);
3130                         } else if((it = (esp_read(eregs->esp_fflags) & ESP_FF_FBYTES))!=1) {
3131                                 /* We certainly dropped the ball somewhere. */
3132                                 message_out = INITIATOR_ERROR;
3133                                 esp_cmd(esp, eregs, ESP_CMD_FLUSH);
3134                         } else if(!esp->msgin_len) {
3135                                 it = esp_read(eregs->esp_fdata);
3136                                 esp_advance_phase(SCptr, in_msgincont);
3137                         } else {
3138                                 /* it is ok and we want it */
3139                                 it = esp->cur_msgin[esp->msgin_ctr] =
3140                                         esp_read(eregs->esp_fdata);
3141                                 esp->msgin_ctr++;
3142                         }
3143                 } else {
3144                         esp_advance_phase(SCptr, in_the_dark);
3145                         return do_work_bus;
3146                 }
3147         } else {
3148                 it = esp->cur_msgin[0];
3149         }
3150         if(!message_out && esp->msgin_len) {
3151                 if(esp->msgin_ctr < esp->msgin_len) {
3152                         esp_advance_phase(SCptr, in_msgincont);
3153                 } else if(esp->msgin_len == 1) {
3154                         message_out = check_singlebyte_msg(esp, eregs);
3155                 } else if(esp->msgin_len == 2) {
3156                         if(esp->cur_msgin[0] == EXTENDED_MESSAGE) {
3157                                 if((it+2) >= 15) {
3158                                         message_out = MESSAGE_REJECT;
3159                                 } else {
3160                                         esp->msgin_len = (it + 2);
3161                                         esp_advance_phase(SCptr, in_msgincont);
3162                                 }
3163                         } else {
3164                                 message_out = MESSAGE_REJECT; /* foo on you */
3165                         }
3166                 } else {
3167                         message_out = check_multibyte_msg(esp, eregs);
3168                 }
3169         }
3170         if(message_out < 0) {
3171                 return -message_out;
3172         } else if(message_out) {
3173                 if(((message_out != 1) &&
3174                     ((message_out < 0x20) || (message_out & 0x80))))
3175                         esp->msgout_len = 1;
3176                 esp->cur_msgout[0] = message_out;
3177                 esp_cmd(esp, eregs, ESP_CMD_SATN);
3178                 esp_advance_phase(SCptr, in_the_dark);
3179                 esp->msgin_len = 0;
3180         }
3181         esp->sreg = esp_read(eregs->esp_status);
3182         esp->sreg &= ~(ESP_STAT_INTR);
3183         if((esp->sreg & (ESP_STAT_PMSG|ESP_STAT_PCD)) == (ESP_STAT_PMSG|ESP_STAT_PCD))
3184                 esp_cmd(esp, eregs, ESP_CMD_MOK);
3185         if((SCptr->SCp.sent_command == in_msgindone) &&
3186             (SCptr->SCp.phase == in_freeing))
3187                 return esp_do_freebus(esp, eregs);
3188         return do_intr_end;
3189 }
3190
3191 static int esp_do_cmdbegin(struct NCR_ESP *esp, struct ESP_regs *eregs)
3192 {
3193         unsigned char tmp;
3194         Scsi_Cmnd *SCptr = esp->current_SC;
3195
3196         esp_advance_phase(SCptr, in_cmdend);
3197         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
3198         tmp = *esp->esp_scmdp++;
3199         esp->esp_scmdleft--;
3200         esp_write(eregs->esp_fdata, tmp);
3201         esp_cmd(esp, eregs, ESP_CMD_TI);
3202         return do_intr_end;
3203 }
3204
3205 static int esp_do_cmddone(struct NCR_ESP *esp, struct ESP_regs *eregs)
3206 {
3207         esp_cmd(esp, eregs, ESP_CMD_NULL);
3208         if(esp->ireg & ESP_INTR_BSERV) {
3209                 esp_advance_phase(esp->current_SC, in_the_dark);
3210                 return esp_do_phase_determine(esp, eregs);
3211         }
3212         ESPLOG(("esp%d: in do_cmddone() but didn't get BSERV interrupt.\n",
3213                 esp->esp_id));
3214         return do_reset_bus;
3215 }
3216
3217 static int esp_do_msgout(struct NCR_ESP *esp, struct ESP_regs *eregs)
3218 {
3219         esp_cmd(esp, eregs, ESP_CMD_FLUSH);
3220         switch(esp->msgout_len) {
3221         case 1:
3222                 esp_write(eregs->esp_fdata, esp->cur_msgout[0]);
3223                 esp_cmd(esp, eregs, ESP_CMD_TI);
3224                 break;
3225
3226         case 2:
3227                 if(esp->do_pio_cmds){
3228                         esp_write(eregs->esp_fdata, esp->cur_msgout[0]);
3229                         esp_write(eregs->esp_fdata, esp->cur_msgout[1]);
3230                         esp_cmd(esp, eregs, ESP_CMD_TI);
3231                 } else {
3232                         esp->esp_command[0] = esp->cur_msgout[0];
3233                         esp->esp_command[1] = esp->cur_msgout[1];
3234                         esp->dma_setup(esp, esp->esp_command_dvma, 2, 0);
3235                         esp_setcount(eregs, 2);
3236                         esp_cmd(esp, eregs, ESP_CMD_DMA | ESP_CMD_TI);
3237                 }
3238                 break;
3239
3240         case 4:
3241                 esp->snip = 1;
3242                 if(esp->do_pio_cmds){
3243                         esp_write(eregs->esp_fdata, esp->cur_msgout[0]);
3244                         esp_write(eregs->esp_fdata, esp->cur_msgout[1]);
3245                         esp_write(eregs->esp_fdata, esp->cur_msgout[2]);
3246                         esp_write(eregs->esp_fdata, esp->cur_msgout[3]);
3247                         esp_cmd(esp, eregs, ESP_CMD_TI);
3248                 } else {
3249                         esp->esp_command[0] = esp->cur_msgout[0];
3250                         esp->esp_command[1] = esp->cur_msgout[1];
3251                         esp->esp_command[2] = esp->cur_msgout[2];
3252                         esp->esp_command[3] = esp->cur_msgout[3];
3253                         esp->dma_setup(esp, esp->esp_command_dvma, 4, 0);
3254                         esp_setcount(eregs, 4);
3255                         esp_cmd(esp, eregs, ESP_CMD_DMA | ESP_CMD_TI);
3256                 }
3257                 break;
3258
3259         case 5:
3260                 esp->snip = 1;
3261                 if(esp->do_pio_cmds){
3262                         esp_write(eregs->esp_fdata, esp->cur_msgout[0]);
3263                         esp_write(eregs->esp_fdata, esp->cur_msgout[1]);
3264                         esp_write(eregs->esp_fdata, esp->cur_msgout[2]);
3265                         esp_write(eregs->esp_fdata, esp->cur_msgout[3]);
3266                         esp_write(eregs->esp_fdata, esp->cur_msgout[4]);
3267                         esp_cmd(esp, eregs, ESP_CMD_TI);
3268                 } else {
3269                         esp->esp_command[0] = esp->cur_msgout[0];
3270                         esp->esp_command[1] = esp->cur_msgout[1];
3271                         esp->esp_command[2] = esp->cur_msgout[2];
3272                         esp->esp_command[3] = esp->cur_msgout[3];
3273                         esp->esp_command[4] = esp->cur_msgout[4];
3274                         esp->dma_setup(esp, esp->esp_command_dvma, 5, 0);
3275                         esp_setcount(eregs, 5);
3276                         esp_cmd(esp, eregs, ESP_CMD_DMA | ESP_CMD_TI);
3277                 }
3278                 break;
3279
3280         default:
3281                 /* whoops */
3282                 ESPMISC(("bogus msgout sending NOP\n"));
3283                 esp->cur_msgout[0] = NOP;
3284                 esp_write(eregs->esp_fdata, esp->cur_msgout[0]);
3285                 esp->msgout_len = 1;
3286                 esp_cmd(esp, eregs, ESP_CMD_TI);
3287                 break;
3288         }
3289         esp_advance_phase(esp->current_SC, in_msgoutdone);
3290         return do_intr_end;
3291 }
3292
3293 static int esp_do_msgoutdone(struct NCR_ESP *esp, 
3294                              struct ESP_regs *eregs)
3295 {
3296         if((esp->msgout_len > 1) && esp->dma_barrier)
3297                 esp->dma_barrier(esp);
3298
3299         if(!(esp->ireg & ESP_INTR_DC)) {
3300                 esp_cmd(esp, eregs, ESP_CMD_NULL);
3301                 switch(esp->sreg & ESP_STAT_PMASK) {
3302                 case ESP_MOP:
3303                         /* whoops, parity error */
3304                         ESPLOG(("esp%d: still in msgout, parity error assumed\n",
3305                                 esp->esp_id));
3306                         if(esp->msgout_len > 1)
3307                                 esp_cmd(esp, eregs, ESP_CMD_SATN);
3308                         esp_advance_phase(esp->current_SC, in_msgout);
3309                         return do_work_bus;
3310
3311                 case ESP_DIP:
3312                         break;
3313
3314                 default:
3315                         if(!fcount(esp, eregs) &&
3316                            !(((struct esp_device *)esp->current_SC->device->hostdata)->sync_max_offset))
3317                                 esp_cmd(esp, eregs, ESP_CMD_FLUSH);
3318                         break;
3319
3320                 };
3321         }
3322
3323         /* If we sent out a synchronous negotiation message, update
3324          * our state.
3325          */
3326         if(esp->cur_msgout[2] == EXTENDED_MESSAGE &&
3327            esp->cur_msgout[4] == EXTENDED_SDTR) {
3328                 esp->snip = 1; /* anal retentiveness... */
3329         }
3330
3331         esp->prevmsgout = esp->cur_msgout[0];
3332         esp->msgout_len = 0;
3333         esp_advance_phase(esp->current_SC, in_the_dark);
3334         return esp_do_phase_determine(esp, eregs);
3335 }
3336
3337 static int esp_bus_unexpected(struct NCR_ESP *esp, struct ESP_regs *eregs)
3338 {
3339         ESPLOG(("esp%d: command in weird state %2x\n",
3340                 esp->esp_id, esp->current_SC->SCp.phase));
3341         return do_reset_bus;
3342 }
3343
3344 static espfunc_t bus_vector[] = {
3345         esp_do_data_finale,
3346         esp_do_data_finale,
3347         esp_bus_unexpected,
3348         esp_do_msgin,
3349         esp_do_msgincont,
3350         esp_do_msgindone,
3351         esp_do_msgout,
3352         esp_do_msgoutdone,
3353         esp_do_cmdbegin,
3354         esp_do_cmddone,
3355         esp_do_status,
3356         esp_do_freebus,
3357         esp_do_phase_determine,
3358         esp_bus_unexpected,
3359         esp_bus_unexpected,
3360         esp_bus_unexpected,
3361 };
3362
3363 /* This is the second tier in our dual-level SCSI state machine. */
3364 static int esp_work_bus(struct NCR_ESP *esp, struct ESP_regs *eregs)
3365 {
3366         Scsi_Cmnd *SCptr = esp->current_SC;
3367         unsigned int phase;
3368
3369         ESPBUS(("esp_work_bus: "));
3370         if(!SCptr) {
3371                 ESPBUS(("reconnect\n"));
3372                 return esp_do_reconnect(esp, eregs);
3373         }
3374         phase = SCptr->SCp.phase;
3375         if ((phase & 0xf0) == in_phases_mask)
3376                 return bus_vector[(phase & 0x0f)](esp, eregs);
3377         else if((phase & 0xf0) == in_slct_mask)
3378                 return esp_select_complete(esp, eregs);
3379         else
3380                 return esp_bus_unexpected(esp, eregs);
3381 }
3382
3383 static espfunc_t isvc_vector[] = {
3384         NULL,
3385         esp_do_phase_determine,
3386         esp_do_resetbus,
3387         esp_finish_reset,
3388         esp_work_bus
3389 };
3390
3391 /* Main interrupt handler for an esp adapter. */
3392 void esp_handle(struct NCR_ESP *esp)
3393 {
3394         struct ESP_regs *eregs;
3395         Scsi_Cmnd *SCptr;
3396         int what_next = do_intr_end;
3397         eregs = esp->eregs;
3398         SCptr = esp->current_SC;
3399
3400         if(esp->dma_irq_entry)
3401                 esp->dma_irq_entry(esp);
3402
3403         /* Check for errors. */
3404         esp->sreg = esp_read(eregs->esp_status);
3405         esp->sreg &= (~ESP_STAT_INTR);
3406         esp->seqreg = (esp_read(eregs->esp_sstep) & ESP_STEP_VBITS);
3407         esp->ireg = esp_read(eregs->esp_intrpt);   /* Unlatch intr and stat regs */
3408         ESPIRQ(("handle_irq: [sreg<%02x> sstep<%02x> ireg<%02x>]\n",
3409                 esp->sreg, esp->seqreg, esp->ireg));
3410         if(esp->sreg & (ESP_STAT_SPAM)) {
3411                 /* Gross error, could be due to one of:
3412                  *
3413                  * - top of fifo overwritten, could be because
3414                  *   we tried to do a synchronous transfer with
3415                  *   an offset greater than ESP fifo size
3416                  *
3417                  * - top of command register overwritten
3418                  *
3419                  * - DMA setup to go in one direction, SCSI
3420                  *   bus points in the other, whoops
3421                  *
3422                  * - weird phase change during asynchronous
3423                  *   data phase while we are initiator
3424                  */
3425                 ESPLOG(("esp%d: Gross error sreg=%2x\n", esp->esp_id, esp->sreg));
3426
3427                 /* If a command is live on the bus we cannot safely
3428                  * reset the bus, so we'll just let the pieces fall
3429                  * where they may.  Here we are hoping that the
3430                  * target will be able to cleanly go away soon
3431                  * so we can safely reset things.
3432                  */
3433                 if(!SCptr) {
3434                         ESPLOG(("esp%d: No current cmd during gross error, "
3435                                 "resetting bus\n", esp->esp_id));
3436                         what_next = do_reset_bus;
3437                         goto state_machine;
3438                 }
3439         }
3440
3441         /* No current cmd is only valid at this point when there are
3442          * commands off the bus or we are trying a reset.
3443          */
3444         if(!SCptr && !esp->disconnected_SC && !(esp->ireg & ESP_INTR_SR)) {
3445                 /* Panic is safe, since current_SC is null. */
3446                 ESPLOG(("esp%d: no command in esp_handle()\n", esp->esp_id));
3447                 panic("esp_handle: current_SC == penguin within interrupt!");
3448         }
3449
3450         if(esp->ireg & (ESP_INTR_IC)) {
3451                 /* Illegal command fed to ESP.  Outside of obvious
3452                  * software bugs that could cause this, there is
3453                  * a condition with ESP100 where we can confuse the
3454                  * ESP into an erroneous illegal command interrupt
3455                  * because it does not scrape the FIFO properly
3456                  * for reselection.  See esp100_reconnect_hwbug()
3457                  * to see how we try very hard to avoid this.
3458                  */
3459                 ESPLOG(("esp%d: invalid command\n", esp->esp_id));
3460
3461                 esp_dump_state(esp, eregs);
3462
3463                 if(SCptr) {
3464                         /* Devices with very buggy firmware can drop BSY
3465                          * during a scatter list interrupt when using sync
3466                          * mode transfers.  We continue the transfer as
3467                          * expected, the target drops the bus, the ESP
3468                          * gets confused, and we get a illegal command
3469                          * interrupt because the bus is in the disconnected
3470                          * state now and ESP_CMD_TI is only allowed when
3471                          * a nexus is alive on the bus.
3472                          */
3473                         ESPLOG(("esp%d: Forcing async and disabling disconnect for "
3474                                 "target %d\n", esp->esp_id, SCptr->device->id));
3475                         SCptr->device->borken = 1; /* foo on you */
3476                 }
3477
3478                 what_next = do_reset_bus;
3479         } else if(!(esp->ireg & ~(ESP_INTR_FDONE | ESP_INTR_BSERV | ESP_INTR_DC))) {
3480                 int phase;
3481
3482                 if(SCptr) {
3483                         phase = SCptr->SCp.phase;
3484                         if(phase & in_phases_mask) {
3485                                 what_next = esp_work_bus(esp, eregs);
3486                         } else if(phase & in_slct_mask) {
3487                                 what_next = esp_select_complete(esp, eregs);
3488                         } else {
3489                                 ESPLOG(("esp%d: interrupt for no good reason...\n",
3490                                         esp->esp_id));
3491                                 what_next = do_intr_end;
3492                         }
3493                 } else {
3494                         ESPLOG(("esp%d: BSERV or FDONE or DC while SCptr==NULL\n",
3495                                 esp->esp_id));
3496                         what_next = do_reset_bus;
3497                 }
3498         } else if(esp->ireg & ESP_INTR_SR) {
3499                 ESPLOG(("esp%d: SCSI bus reset interrupt\n", esp->esp_id));
3500                 what_next = do_reset_complete;
3501         } else if(esp->ireg & (ESP_INTR_S | ESP_INTR_SATN)) {
3502                 ESPLOG(("esp%d: AIEEE we have been selected by another initiator!\n",
3503                         esp->esp_id));
3504                 what_next = do_reset_bus;
3505         } else if(esp->ireg & ESP_INTR_RSEL) {
3506                 if(!SCptr) {
3507                         /* This is ok. */
3508                         what_next = esp_do_reconnect(esp, eregs);
3509                 } else if(SCptr->SCp.phase & in_slct_mask) {
3510                         /* Only selection code knows how to clean
3511                          * up properly.
3512                          */
3513                         ESPDISC(("Reselected during selection attempt\n"));
3514                         what_next = esp_select_complete(esp, eregs);
3515                 } else {
3516                         ESPLOG(("esp%d: Reselected while bus is busy\n",
3517                                 esp->esp_id));
3518                         what_next = do_reset_bus;
3519                 }
3520         }
3521
3522         /* This is tier-one in our dual level SCSI state machine. */
3523 state_machine:
3524         while(what_next != do_intr_end) {
3525                 if (what_next >= do_phase_determine &&
3526                     what_next < do_intr_end)
3527                         what_next = isvc_vector[what_next](esp, eregs);
3528                 else {
3529                         /* state is completely lost ;-( */
3530                         ESPLOG(("esp%d: interrupt engine loses state, resetting bus\n",
3531                                 esp->esp_id));
3532                         what_next = do_reset_bus;
3533                 }
3534         }
3535         if(esp->dma_irq_exit)
3536                 esp->dma_irq_exit(esp);
3537 }
3538
3539 #ifndef CONFIG_SMP
3540 irqreturn_t esp_intr(int irq, void *dev_id)
3541 {
3542         struct NCR_ESP *esp;
3543         unsigned long flags;
3544         int again;
3545         struct Scsi_Host *dev = dev_id;
3546
3547         /* Handle all ESP interrupts showing at this IRQ level. */
3548         spin_lock_irqsave(dev->host_lock, flags);
3549 repeat:
3550         again = 0;
3551         for_each_esp(esp) {
3552 #ifndef __mips__            
3553                 if(((esp)->irq & 0xff) == irq) {
3554 #endif              
3555                         if(esp->dma_irq_p(esp)) {
3556                                 again = 1;
3557
3558                                 esp->dma_ints_off(esp);
3559
3560                                 ESPIRQ(("I%d(", esp->esp_id));
3561                                 esp_handle(esp);
3562                                 ESPIRQ((")"));
3563
3564                                 esp->dma_ints_on(esp);
3565                         }
3566 #ifndef __mips__                    
3567                 }
3568 #endif      
3569         }
3570         if(again)
3571                 goto repeat;
3572         spin_unlock_irqrestore(dev->host_lock, flags);
3573         return IRQ_HANDLED;
3574 }
3575 #else
3576 /* For SMP we only service one ESP on the list list at our IRQ level! */
3577 irqreturn_t esp_intr(int irq, void *dev_id)
3578 {
3579         struct NCR_ESP *esp;
3580         unsigned long flags;
3581         struct Scsi_Host *dev = dev_id;
3582         
3583         /* Handle all ESP interrupts showing at this IRQ level. */
3584         spin_lock_irqsave(dev->host_lock, flags);
3585         for_each_esp(esp) {
3586                 if(((esp)->irq & 0xf) == irq) {
3587                         if(esp->dma_irq_p(esp)) {
3588                                 esp->dma_ints_off(esp);
3589
3590                                 ESPIRQ(("I[%d:%d](",
3591                                         smp_processor_id(), esp->esp_id));
3592                                 esp_handle(esp);
3593                                 ESPIRQ((")"));
3594
3595                                 esp->dma_ints_on(esp);
3596                                 goto out;
3597                         }
3598                 }
3599         }
3600 out:
3601         spin_unlock_irqrestore(dev->host_lock, flags);
3602         return IRQ_HANDLED;
3603 }
3604 #endif
3605
3606 int esp_slave_alloc(struct scsi_device *SDptr)
3607 {
3608         struct esp_device *esp_dev =
3609                 kzalloc(sizeof(struct esp_device), GFP_ATOMIC);
3610
3611         if (!esp_dev)
3612                 return -ENOMEM;
3613         SDptr->hostdata = esp_dev;
3614         return 0;
3615 }
3616
3617 void esp_slave_destroy(struct scsi_device *SDptr)
3618 {
3619         struct NCR_ESP *esp = (struct NCR_ESP *) SDptr->host->hostdata;
3620
3621         esp->targets_present &= ~(1 << sdev_id(SDptr));
3622         kfree(SDptr->hostdata);
3623         SDptr->hostdata = NULL;
3624 }
3625
3626 #ifdef MODULE
3627 int init_module(void) { return 0; }
3628 void cleanup_module(void) {}
3629 void esp_release(void)
3630 {
3631         esps_in_use--;
3632         esps_running = esps_in_use;
3633 }
3634 #endif
3635
3636 EXPORT_SYMBOL(esp_abort);
3637 EXPORT_SYMBOL(esp_allocate);
3638 EXPORT_SYMBOL(esp_deallocate);
3639 EXPORT_SYMBOL(esp_initialize);
3640 EXPORT_SYMBOL(esp_intr);
3641 EXPORT_SYMBOL(esp_queue);
3642 EXPORT_SYMBOL(esp_reset);
3643 EXPORT_SYMBOL(esp_slave_alloc);
3644 EXPORT_SYMBOL(esp_slave_destroy);
3645 EXPORT_SYMBOL(esps_in_use);
3646
3647 MODULE_LICENSE("GPL");