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