ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / scsi / esp.c
1 /* $Id: esp.c,v 1.101 2002/01/15 06:48:55 davem Exp $
2  * esp.c:  EnhancedScsiProcessor Sun SCSI driver code.
3  *
4  * Copyright (C) 1995, 1998 David S. Miller (davem@caip.rutgers.edu)
5  */
6
7 /* TODO:
8  *
9  * 1) Maybe disable parity checking in config register one for SCSI1
10  *    targets.  (Gilmore says parity error on the SBus can lock up
11  *    old sun4c's)
12  * 2) Add support for DMA2 pipelining.
13  * 3) Add tagged queueing.
14  */
15
16 #include <linux/config.h>
17 #include <linux/kernel.h>
18 #include <linux/delay.h>
19 #include <linux/types.h>
20 #include <linux/string.h>
21 #include <linux/slab.h>
22 #include <linux/blkdev.h>
23 #include <linux/proc_fs.h>
24 #include <linux/stat.h>
25 #include <linux/init.h>
26 #include <linux/spinlock.h>
27 #include <linux/interrupt.h>
28
29 #include "scsi.h"
30 #include "hosts.h"
31 #include "esp.h"
32
33 #include <asm/sbus.h>
34 #include <asm/dma.h>
35 #include <asm/system.h>
36 #include <asm/ptrace.h>
37 #include <asm/pgtable.h>
38 #include <asm/oplib.h>
39 #include <asm/io.h>
40 #include <asm/irq.h>
41
42 #ifndef __sparc_v9__
43 #include <asm/machines.h>
44 #include <asm/idprom.h>
45 #endif
46
47 #include <linux/module.h>
48
49 #define DEBUG_ESP
50 /* #define DEBUG_ESP_HME */
51 /* #define DEBUG_ESP_DATA */
52 /* #define DEBUG_ESP_QUEUE */
53 /* #define DEBUG_ESP_DISCONNECT */
54 /* #define DEBUG_ESP_STATUS */
55 /* #define DEBUG_ESP_PHASES */
56 /* #define DEBUG_ESP_WORKBUS */
57 /* #define DEBUG_STATE_MACHINE */
58 /* #define DEBUG_ESP_CMDS */
59 /* #define DEBUG_ESP_IRQS */
60 /* #define DEBUG_SDTR */
61 /* #define DEBUG_ESP_SG */
62
63 /* Use the following to sprinkle debugging messages in a way which
64  * suits you if combinations of the above become too verbose when
65  * trying to track down a specific problem.
66  */
67 /* #define DEBUG_ESP_MISC */
68
69 #if defined(DEBUG_ESP)
70 #define ESPLOG(foo)  printk foo
71 #else
72 #define ESPLOG(foo)
73 #endif /* (DEBUG_ESP) */
74
75 #if defined(DEBUG_ESP_HME)
76 #define ESPHME(foo)  printk foo
77 #else
78 #define ESPHME(foo)
79 #endif
80
81 #if defined(DEBUG_ESP_DATA)
82 #define ESPDATA(foo)  printk foo
83 #else
84 #define ESPDATA(foo)
85 #endif
86
87 #if defined(DEBUG_ESP_QUEUE)
88 #define ESPQUEUE(foo)  printk foo
89 #else
90 #define ESPQUEUE(foo)
91 #endif
92
93 #if defined(DEBUG_ESP_DISCONNECT)
94 #define ESPDISC(foo)  printk foo
95 #else
96 #define ESPDISC(foo)
97 #endif
98
99 #if defined(DEBUG_ESP_STATUS)
100 #define ESPSTAT(foo)  printk foo
101 #else
102 #define ESPSTAT(foo)
103 #endif
104
105 #if defined(DEBUG_ESP_PHASES)
106 #define ESPPHASE(foo)  printk foo
107 #else
108 #define ESPPHASE(foo)
109 #endif
110
111 #if defined(DEBUG_ESP_WORKBUS)
112 #define ESPBUS(foo)  printk foo
113 #else
114 #define ESPBUS(foo)
115 #endif
116
117 #if defined(DEBUG_ESP_IRQS)
118 #define ESPIRQ(foo)  printk foo
119 #else
120 #define ESPIRQ(foo)
121 #endif
122
123 #if defined(DEBUG_SDTR)
124 #define ESPSDTR(foo)  printk foo
125 #else
126 #define ESPSDTR(foo)
127 #endif
128
129 #if defined(DEBUG_ESP_MISC)
130 #define ESPMISC(foo)  printk foo
131 #else
132 #define ESPMISC(foo)
133 #endif
134
135 /* Command phase enumeration. */
136 enum {
137         not_issued    = 0x00,  /* Still in the issue_SC queue.          */
138
139         /* Various forms of selecting a target. */
140 #define in_slct_mask    0x10
141         in_slct_norm  = 0x10,  /* ESP is arbitrating, normal selection  */
142         in_slct_stop  = 0x11,  /* ESP will select, then stop with IRQ   */
143         in_slct_msg   = 0x12,  /* select, then send a message           */
144         in_slct_tag   = 0x13,  /* select and send tagged queue msg      */
145         in_slct_sneg  = 0x14,  /* select and acquire sync capabilities  */
146
147         /* Any post selection activity. */
148 #define in_phases_mask  0x20
149         in_datain     = 0x20,  /* Data is transferring from the bus     */
150         in_dataout    = 0x21,  /* Data is transferring to the bus       */
151         in_data_done  = 0x22,  /* Last DMA data operation done (maybe)  */
152         in_msgin      = 0x23,  /* Eating message from target            */
153         in_msgincont  = 0x24,  /* Eating more msg bytes from target     */
154         in_msgindone  = 0x25,  /* Decide what to do with what we got    */
155         in_msgout     = 0x26,  /* Sending message to target             */
156         in_msgoutdone = 0x27,  /* Done sending msg out                  */
157         in_cmdbegin   = 0x28,  /* Sending cmd after abnormal selection  */
158         in_cmdend     = 0x29,  /* Done sending slow cmd                 */
159         in_status     = 0x2a,  /* Was in status phase, finishing cmd    */
160         in_freeing    = 0x2b,  /* freeing the bus for cmd cmplt or disc */
161         in_the_dark   = 0x2c,  /* Don't know what bus phase we are in   */
162
163         /* Special states, ie. not normal bus transitions... */
164 #define in_spec_mask    0x80
165         in_abortone   = 0x80,  /* Aborting one command currently        */
166         in_abortall   = 0x81,  /* Blowing away all commands we have     */
167         in_resetdev   = 0x82,  /* SCSI target reset in progress         */
168         in_resetbus   = 0x83,  /* SCSI bus reset in progress            */
169         in_tgterror   = 0x84,  /* Target did something stupid           */
170 };
171
172 enum {
173         /* Zero has special meaning, see skipahead[12]. */
174 /*0*/   do_never,
175
176 /*1*/   do_phase_determine,
177 /*2*/   do_reset_bus,
178 /*3*/   do_reset_complete,
179 /*4*/   do_work_bus,
180 /*5*/   do_intr_end
181 };
182
183 /* The master ring of all esp hosts we are managing in this driver. */
184 static struct esp *espchain;
185 static spinlock_t espchain_lock = SPIN_LOCK_UNLOCKED;
186 static int esps_running = 0;
187
188 /* Forward declarations. */
189 static irqreturn_t esp_intr(int irq, void *dev_id, struct pt_regs *pregs);
190
191 /* Debugging routines */
192 struct esp_cmdstrings {
193         u8 cmdchar;
194         char *text;
195 } esp_cmd_strings[] = {
196         /* Miscellaneous */
197         { ESP_CMD_NULL, "ESP_NOP", },
198         { ESP_CMD_FLUSH, "FIFO_FLUSH", },
199         { ESP_CMD_RC, "RSTESP", },
200         { ESP_CMD_RS, "RSTSCSI", },
201         /* Disconnected State Group */
202         { ESP_CMD_RSEL, "RESLCTSEQ", },
203         { ESP_CMD_SEL, "SLCTNATN", },
204         { ESP_CMD_SELA, "SLCTATN", },
205         { ESP_CMD_SELAS, "SLCTATNSTOP", },
206         { ESP_CMD_ESEL, "ENSLCTRESEL", },
207         { ESP_CMD_DSEL, "DISSELRESEL", },
208         { ESP_CMD_SA3, "SLCTATN3", },
209         { ESP_CMD_RSEL3, "RESLCTSEQ", },
210         /* Target State Group */
211         { ESP_CMD_SMSG, "SNDMSG", },
212         { ESP_CMD_SSTAT, "SNDSTATUS", },
213         { ESP_CMD_SDATA, "SNDDATA", },
214         { ESP_CMD_DSEQ, "DISCSEQ", },
215         { ESP_CMD_TSEQ, "TERMSEQ", },
216         { ESP_CMD_TCCSEQ, "TRGTCMDCOMPSEQ", },
217         { ESP_CMD_DCNCT, "DISC", },
218         { ESP_CMD_RMSG, "RCVMSG", },
219         { ESP_CMD_RCMD, "RCVCMD", },
220         { ESP_CMD_RDATA, "RCVDATA", },
221         { ESP_CMD_RCSEQ, "RCVCMDSEQ", },
222         /* Initiator State Group */
223         { ESP_CMD_TI, "TRANSINFO", },
224         { ESP_CMD_ICCSEQ, "INICMDSEQCOMP", },
225         { ESP_CMD_MOK, "MSGACCEPTED", },
226         { ESP_CMD_TPAD, "TPAD", },
227         { ESP_CMD_SATN, "SATN", },
228         { ESP_CMD_RATN, "RATN", },
229 };
230 #define NUM_ESP_COMMANDS  ((sizeof(esp_cmd_strings)) / (sizeof(struct esp_cmdstrings)))
231
232 /* Print textual representation of an ESP command */
233 static inline void esp_print_cmd(u8 espcmd)
234 {
235         u8 dma_bit = espcmd & ESP_CMD_DMA;
236         int i;
237
238         espcmd &= ~dma_bit;
239         for (i = 0; i < NUM_ESP_COMMANDS; i++)
240                 if (esp_cmd_strings[i].cmdchar == espcmd)
241                         break;
242         if (i == NUM_ESP_COMMANDS)
243                 printk("ESP_Unknown");
244         else
245                 printk("%s%s", esp_cmd_strings[i].text,
246                        ((dma_bit) ? "+DMA" : ""));
247 }
248
249 /* Print the status register's value */
250 static inline void esp_print_statreg(u8 statreg)
251 {
252         u8 phase;
253
254         printk("STATUS<");
255         phase = statreg & ESP_STAT_PMASK;
256         printk("%s,", (phase == ESP_DOP ? "DATA-OUT" :
257                        (phase == ESP_DIP ? "DATA-IN" :
258                         (phase == ESP_CMDP ? "COMMAND" :
259                          (phase == ESP_STATP ? "STATUS" :
260                           (phase == ESP_MOP ? "MSG-OUT" :
261                            (phase == ESP_MIP ? "MSG_IN" :
262                             "unknown")))))));
263         if (statreg & ESP_STAT_TDONE)
264                 printk("TRANS_DONE,");
265         if (statreg & ESP_STAT_TCNT)
266                 printk("TCOUNT_ZERO,");
267         if (statreg & ESP_STAT_PERR)
268                 printk("P_ERROR,");
269         if (statreg & ESP_STAT_SPAM)
270                 printk("SPAM,");
271         if (statreg & ESP_STAT_INTR)
272                 printk("IRQ,");
273         printk(">");
274 }
275
276 /* Print the interrupt register's value */
277 static inline void esp_print_ireg(u8 intreg)
278 {
279         printk("INTREG< ");
280         if (intreg & ESP_INTR_S)
281                 printk("SLCT_NATN ");
282         if (intreg & ESP_INTR_SATN)
283                 printk("SLCT_ATN ");
284         if (intreg & ESP_INTR_RSEL)
285                 printk("RSLCT ");
286         if (intreg & ESP_INTR_FDONE)
287                 printk("FDONE ");
288         if (intreg & ESP_INTR_BSERV)
289                 printk("BSERV ");
290         if (intreg & ESP_INTR_DC)
291                 printk("DISCNCT ");
292         if (intreg & ESP_INTR_IC)
293                 printk("ILL_CMD ");
294         if (intreg & ESP_INTR_SR)
295                 printk("SCSI_BUS_RESET ");
296         printk(">");
297 }
298
299 /* Print the sequence step registers contents */
300 static inline void esp_print_seqreg(u8 stepreg)
301 {
302         stepreg &= ESP_STEP_VBITS;
303         printk("STEP<%s>",
304                (stepreg == ESP_STEP_ASEL ? "SLCT_ARB_CMPLT" :
305                 (stepreg == ESP_STEP_SID ? "1BYTE_MSG_SENT" :
306                  (stepreg == ESP_STEP_NCMD ? "NOT_IN_CMD_PHASE" :
307                   (stepreg == ESP_STEP_PPC ? "CMD_BYTES_LOST" :
308                    (stepreg == ESP_STEP_FINI4 ? "CMD_SENT_OK" :
309                     "UNKNOWN"))))));
310 }
311
312 static char *phase_string(int phase)
313 {
314         switch (phase) {
315         case not_issued:
316                 return "UNISSUED";
317         case in_slct_norm:
318                 return "SLCTNORM";
319         case in_slct_stop:
320                 return "SLCTSTOP";
321         case in_slct_msg:
322                 return "SLCTMSG";
323         case in_slct_tag:
324                 return "SLCTTAG";
325         case in_slct_sneg:
326                 return "SLCTSNEG";
327         case in_datain:
328                 return "DATAIN";
329         case in_dataout:
330                 return "DATAOUT";
331         case in_data_done:
332                 return "DATADONE";
333         case in_msgin:
334                 return "MSGIN";
335         case in_msgincont:
336                 return "MSGINCONT";
337         case in_msgindone:
338                 return "MSGINDONE";
339         case in_msgout:
340                 return "MSGOUT";
341         case in_msgoutdone:
342                 return "MSGOUTDONE";
343         case in_cmdbegin:
344                 return "CMDBEGIN";
345         case in_cmdend:
346                 return "CMDEND";
347         case in_status:
348                 return "STATUS";
349         case in_freeing:
350                 return "FREEING";
351         case in_the_dark:
352                 return "CLUELESS";
353         case in_abortone:
354                 return "ABORTONE";
355         case in_abortall:
356                 return "ABORTALL";
357         case in_resetdev:
358                 return "RESETDEV";
359         case in_resetbus:
360                 return "RESETBUS";
361         case in_tgterror:
362                 return "TGTERROR";
363         default:
364                 return "UNKNOWN";
365         };
366 }
367
368 #ifdef DEBUG_STATE_MACHINE
369 static inline void esp_advance_phase(Scsi_Cmnd *s, int newphase)
370 {
371         ESPLOG(("<%s>", phase_string(newphase)));
372         s->SCp.sent_command = s->SCp.phase;
373         s->SCp.phase = newphase;
374 }
375 #else
376 #define esp_advance_phase(__s, __newphase) \
377         (__s)->SCp.sent_command = (__s)->SCp.phase; \
378         (__s)->SCp.phase = (__newphase);
379 #endif
380
381 #ifdef DEBUG_ESP_CMDS
382 static inline void esp_cmd(struct esp *esp, u8 cmd)
383 {
384         esp->espcmdlog[esp->espcmdent] = cmd;
385         esp->espcmdent = (esp->espcmdent + 1) & 31;
386         sbus_writeb(cmd, esp->eregs + ESP_CMD);
387 }
388 #else
389 #define esp_cmd(__esp, __cmd)   \
390         sbus_writeb((__cmd), ((__esp)->eregs) + ESP_CMD)
391 #endif
392
393 #define ESP_INTSOFF(__dregs)    \
394         sbus_writel(sbus_readl((__dregs)+DMA_CSR)&~(DMA_INT_ENAB), (__dregs)+DMA_CSR)
395 #define ESP_INTSON(__dregs)     \
396         sbus_writel(sbus_readl((__dregs)+DMA_CSR)|DMA_INT_ENAB, (__dregs)+DMA_CSR)
397 #define ESP_IRQ_P(__dregs)      \
398         (sbus_readl((__dregs)+DMA_CSR) & (DMA_HNDL_INTR|DMA_HNDL_ERROR))
399
400 /* How we use the various Linux SCSI data structures for operation.
401  *
402  * struct scsi_cmnd:
403  *
404  *   We keep track of the synchronous capabilities of a target
405  *   in the device member, using sync_min_period and
406  *   sync_max_offset.  These are the values we directly write
407  *   into the ESP registers while running a command.  If offset
408  *   is zero the ESP will use asynchronous transfers.
409  *   If the borken flag is set we assume we shouldn't even bother
410  *   trying to negotiate for synchronous transfer as this target
411  *   is really stupid.  If we notice the target is dropping the
412  *   bus, and we have been allowing it to disconnect, we clear
413  *   the disconnect flag.
414  */
415
416
417 /* Manipulation of the ESP command queues.  Thanks to the aha152x driver
418  * and its author, Juergen E. Fischer, for the methods used here.
419  * Note that these are per-ESP queues, not global queues like
420  * the aha152x driver uses.
421  */
422 static inline void append_SC(Scsi_Cmnd **SC, Scsi_Cmnd *new_SC)
423 {
424         Scsi_Cmnd *end;
425
426         new_SC->host_scribble = (unsigned char *) NULL;
427         if (!*SC)
428                 *SC = new_SC;
429         else {
430                 for (end=*SC;end->host_scribble;end=(Scsi_Cmnd *)end->host_scribble)
431                         ;
432                 end->host_scribble = (unsigned char *) new_SC;
433         }
434 }
435
436 static inline void prepend_SC(Scsi_Cmnd **SC, Scsi_Cmnd *new_SC)
437 {
438         new_SC->host_scribble = (unsigned char *) *SC;
439         *SC = new_SC;
440 }
441
442 static inline Scsi_Cmnd *remove_first_SC(Scsi_Cmnd **SC)
443 {
444         Scsi_Cmnd *ptr;
445         ptr = *SC;
446         if (ptr)
447                 *SC = (Scsi_Cmnd *) (*SC)->host_scribble;
448         return ptr;
449 }
450
451 static inline Scsi_Cmnd *remove_SC(Scsi_Cmnd **SC, int target, int lun)
452 {
453         Scsi_Cmnd *ptr, *prev;
454
455         for (ptr = *SC, prev = NULL;
456              ptr && ((ptr->device->id != target) || (ptr->device->lun != lun));
457              prev = ptr, ptr = (Scsi_Cmnd *) ptr->host_scribble)
458                 ;
459         if (ptr) {
460                 if (prev)
461                         prev->host_scribble=ptr->host_scribble;
462                 else
463                         *SC=(Scsi_Cmnd *)ptr->host_scribble;
464         }
465         return ptr;
466 }
467
468 /* Resetting various pieces of the ESP scsi driver chipset/buses. */
469 static void esp_reset_dma(struct esp *esp)
470 {
471         int can_do_burst16, can_do_burst32, can_do_burst64;
472         int can_do_sbus64;
473         u32 tmp;
474
475         can_do_burst16 = (esp->bursts & DMA_BURST16) != 0;
476         can_do_burst32 = (esp->bursts & DMA_BURST32) != 0;
477         can_do_burst64 = 0;
478         can_do_sbus64 = 0;
479         if (sbus_can_dma_64bit(esp->sdev))
480                 can_do_sbus64 = 1;
481         if (sbus_can_burst64(esp->sdev))
482                 can_do_burst64 = (esp->bursts & DMA_BURST64) != 0;
483
484         /* Punt the DVMA into a known state. */
485         if (esp->dma->revision != dvmahme) {
486                 tmp = sbus_readl(esp->dregs + DMA_CSR);
487                 sbus_writel(tmp | DMA_RST_SCSI, esp->dregs + DMA_CSR);
488                 sbus_writel(tmp & ~DMA_RST_SCSI, esp->dregs + DMA_CSR);
489         }
490         switch (esp->dma->revision) {
491         case dvmahme:
492                 /* This is the HME DVMA gate array. */
493
494                 sbus_writel(DMA_RESET_FAS366, esp->dregs + DMA_CSR);
495                 sbus_writel(DMA_RST_SCSI, esp->dregs + DMA_CSR);
496
497                 esp->prev_hme_dmacsr = (DMA_PARITY_OFF|DMA_2CLKS|DMA_SCSI_DISAB|DMA_INT_ENAB);
498                 esp->prev_hme_dmacsr &= ~(DMA_ENABLE|DMA_ST_WRITE|DMA_BRST_SZ);
499
500                 if (can_do_burst64)
501                         esp->prev_hme_dmacsr |= DMA_BRST64;
502                 else if (can_do_burst32)
503                         esp->prev_hme_dmacsr |= DMA_BRST32;
504
505                 if (can_do_sbus64) {
506                         esp->prev_hme_dmacsr |= DMA_SCSI_SBUS64;
507                         sbus_set_sbus64(esp->sdev, esp->bursts);
508                 }
509
510                 /* This chip is horrible. */
511                 while (sbus_readl(esp->dregs + DMA_CSR) & DMA_PEND_READ)
512                         udelay(1);
513
514                 sbus_writel(0, esp->dregs + DMA_CSR);
515                 sbus_writel(esp->prev_hme_dmacsr, esp->dregs + DMA_CSR);
516
517                 /* This is necessary to avoid having the SCSI channel
518                  * engine lock up on us.
519                  */
520                 sbus_writel(0, esp->dregs + DMA_ADDR);
521
522                 break;
523         case dvmarev2:
524                 /* This is the gate array found in the sun4m
525                  * NCR SBUS I/O subsystem.
526                  */
527                 if (esp->erev != esp100) {
528                         tmp = sbus_readl(esp->dregs + DMA_CSR);
529                         sbus_writel(tmp | DMA_3CLKS, esp->dregs + DMA_CSR);
530                 }
531                 break;
532         case dvmarev3:
533                 tmp = sbus_readl(esp->dregs + DMA_CSR);
534                 tmp &= ~DMA_3CLKS;
535                 tmp |= DMA_2CLKS;
536                 if (can_do_burst32) {
537                         tmp &= ~DMA_BRST_SZ;
538                         tmp |= DMA_BRST32;
539                 }
540                 sbus_writel(tmp, esp->dregs + DMA_CSR);
541                 break;
542         case dvmaesc1:
543                 /* This is the DMA unit found on SCSI/Ether cards. */
544                 tmp = sbus_readl(esp->dregs + DMA_CSR);
545                 tmp |= DMA_ADD_ENABLE;
546                 tmp &= ~DMA_BCNT_ENAB;
547                 if (!can_do_burst32 && can_do_burst16) {
548                         tmp |= DMA_ESC_BURST;
549                 } else {
550                         tmp &= ~(DMA_ESC_BURST);
551                 }
552                 sbus_writel(tmp, esp->dregs + DMA_CSR);
553                 break;
554         default:
555                 break;
556         };
557         ESP_INTSON(esp->dregs);
558 }
559
560 /* Reset the ESP chip, _not_ the SCSI bus. */
561 static void __init esp_reset_esp(struct esp *esp)
562 {
563         u8 family_code, version;
564         int i;
565
566         /* Now reset the ESP chip */
567         esp_cmd(esp, ESP_CMD_RC);
568         esp_cmd(esp, ESP_CMD_NULL | ESP_CMD_DMA);
569         esp_cmd(esp, ESP_CMD_NULL | ESP_CMD_DMA);
570
571         /* Reload the configuration registers */
572         sbus_writeb(esp->cfact, esp->eregs + ESP_CFACT);
573         esp->prev_stp = 0;
574         sbus_writeb(esp->prev_stp, esp->eregs + ESP_STP);
575         esp->prev_soff = 0;
576         sbus_writeb(esp->prev_soff, esp->eregs + ESP_SOFF);
577         sbus_writeb(esp->neg_defp, esp->eregs + ESP_TIMEO);
578
579         /* This is the only point at which it is reliable to read
580          * the ID-code for a fast ESP chip variants.
581          */
582         esp->max_period = ((35 * esp->ccycle) / 1000);
583         if (esp->erev == fast) {
584                 version = sbus_readb(esp->eregs + ESP_UID);
585                 family_code = (version & 0xf8) >> 3;
586                 if (family_code == 0x02)
587                         esp->erev = fas236;
588                 else if (family_code == 0x0a)
589                         esp->erev = fashme; /* Version is usually '5'. */
590                 else
591                         esp->erev = fas100a;
592                 ESPMISC(("esp%d: FAST chip is %s (family=%d, version=%d)\n",
593                          esp->esp_id,
594                          (esp->erev == fas236) ? "fas236" :
595                          ((esp->erev == fas100a) ? "fas100a" :
596                           "fasHME"), family_code, (version & 7)));
597
598                 esp->min_period = ((4 * esp->ccycle) / 1000);
599         } else {
600                 esp->min_period = ((5 * esp->ccycle) / 1000);
601         }
602         esp->max_period = (esp->max_period + 3)>>2;
603         esp->min_period = (esp->min_period + 3)>>2;
604
605         sbus_writeb(esp->config1, esp->eregs + ESP_CFG1);
606         switch (esp->erev) {
607         case esp100:
608                 /* nothing to do */
609                 break;
610         case esp100a:
611                 sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
612                 break;
613         case esp236:
614                 /* Slow 236 */
615                 sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
616                 esp->prev_cfg3 = esp->config3[0];
617                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
618                 break;
619         case fashme:
620                 esp->config2 |= (ESP_CONFIG2_HME32 | ESP_CONFIG2_HMEFENAB);
621                 /* fallthrough... */
622         case fas236:
623                 /* Fast 236 or HME */
624                 sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
625                 for (i = 0; i < 16; i++) {
626                         if (esp->erev == fashme) {
627                                 u8 cfg3;
628
629                                 cfg3 = ESP_CONFIG3_FCLOCK | ESP_CONFIG3_OBPUSH;
630                                 if (esp->scsi_id >= 8)
631                                         cfg3 |= ESP_CONFIG3_IDBIT3;
632                                 esp->config3[i] |= cfg3;
633                         } else {
634                                 esp->config3[i] |= ESP_CONFIG3_FCLK;
635                         }
636                 }
637                 esp->prev_cfg3 = esp->config3[0];
638                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
639                 if (esp->erev == fashme) {
640                         esp->radelay = 80;
641                 } else {
642                         if (esp->diff)
643                                 esp->radelay = 0;
644                         else
645                                 esp->radelay = 96;
646                 }
647                 break;
648         case fas100a:
649                 /* Fast 100a */
650                 sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
651                 for (i = 0; i < 16; i++)
652                         esp->config3[i] |= ESP_CONFIG3_FCLOCK;
653                 esp->prev_cfg3 = esp->config3[0];
654                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
655                 esp->radelay = 32;
656                 break;
657         default:
658                 panic("esp: what could it be... I wonder...");
659                 break;
660         };
661
662         /* Eat any bitrot in the chip */
663         sbus_readb(esp->eregs + ESP_INTRPT);
664         udelay(100);
665 }
666
667 /* This places the ESP into a known state at boot time. */
668 static void __init esp_bootup_reset(struct esp *esp)
669 {
670         u8 tmp;
671
672         /* Reset the DMA */
673         esp_reset_dma(esp);
674
675         /* Reset the ESP */
676         esp_reset_esp(esp);
677
678         /* Reset the SCSI bus, but tell ESP not to generate an irq */
679         tmp = sbus_readb(esp->eregs + ESP_CFG1);
680         tmp |= ESP_CONFIG1_SRRDISAB;
681         sbus_writeb(tmp, esp->eregs + ESP_CFG1);
682
683         esp_cmd(esp, ESP_CMD_RS);
684         udelay(400);
685
686         sbus_writeb(esp->config1, esp->eregs + ESP_CFG1);
687
688         /* Eat any bitrot in the chip and we are done... */
689         sbus_readb(esp->eregs + ESP_INTRPT);
690 }
691
692 static void esp_chain_add(struct esp *esp)
693 {
694         spin_lock_irq(&espchain_lock);
695         if (espchain) {
696                 struct esp *elink = espchain;
697                 while (elink->next)
698                         elink = elink->next;
699                 elink->next = esp;
700         } else {
701                 espchain = esp;
702         }
703         esp->next = NULL;
704         spin_unlock_irq(&espchain_lock);
705 }
706
707 static void esp_chain_del(struct esp *esp)
708 {
709         spin_lock_irq(&espchain_lock);
710         if (espchain == esp) {
711                 espchain = esp->next;
712         } else {
713                 struct esp *elink = espchain;
714                 while (elink->next != esp)
715                         elink = elink->next;
716                 elink->next = esp->next;
717         }
718         esp->next = NULL;
719         spin_unlock_irq(&espchain_lock);
720 }
721
722 static int __init esp_find_dvma(struct esp *esp, struct sbus_dev *dma_sdev)
723 {
724         struct sbus_dev *sdev = esp->sdev;
725         struct sbus_dma *dma;
726
727         if (dma_sdev != NULL) {
728                 for_each_dvma(dma) {
729                         if (dma->sdev == dma_sdev)
730                                 break;
731                 }
732         } else {
733                 for_each_dvma(dma) {
734                         /* If allocated already, can't use it. */
735                         if (dma->allocated)
736                                 continue;
737
738                         if (dma->sdev == NULL)
739                                 break;
740
741                         /* If bus + slot are the same and it has the
742                          * correct OBP name, it's ours.
743                          */
744                         if (sdev->bus == dma->sdev->bus &&
745                             sdev->slot == dma->sdev->slot &&
746                             (!strcmp(dma->sdev->prom_name, "dma") ||
747                              !strcmp(dma->sdev->prom_name, "espdma")))
748                                 break;
749                 }
750         }
751
752         /* If we don't know how to handle the dvma,
753          * do not use this device.
754          */
755         if (dma == NULL) {
756                 printk("Cannot find dvma for ESP%d's SCSI\n", esp->esp_id);
757                 return -1;
758         }
759         if (dma->allocated) {
760                 printk("esp%d: can't use my espdma\n", esp->esp_id);
761                 return -1;
762         }
763         dma->allocated = 1;
764         esp->dma = dma;
765         esp->dregs = dma->regs;
766
767         return 0;
768 }
769
770 static int __init esp_map_regs(struct esp *esp, int hme)
771 {
772         struct sbus_dev *sdev = esp->sdev;
773         struct resource *res;
774
775         /* On HME, two reg sets exist, first is DVMA,
776          * second is ESP registers.
777          */
778         if (hme)
779                 res = &sdev->resource[1];
780         else
781                 res = &sdev->resource[0];
782
783         esp->eregs = sbus_ioremap(res, 0, ESP_REG_SIZE, "ESP Registers");
784
785         if (esp->eregs == 0)
786                 return -1;
787         return 0;
788 }
789
790 static int __init esp_map_cmdarea(struct esp *esp)
791 {
792         struct sbus_dev *sdev = esp->sdev;
793
794         esp->esp_command = sbus_alloc_consistent(sdev, 16,
795                                                  &esp->esp_command_dvma);
796         if (esp->esp_command == NULL ||
797             esp->esp_command_dvma == 0)
798                 return -1;
799         return 0;
800 }
801
802 static int __init esp_register_irq(struct esp *esp)
803 {
804         esp->ehost->irq = esp->irq = esp->sdev->irqs[0];
805
806         /* We used to try various overly-clever things to
807          * reduce the interrupt processing overhead on
808          * sun4c/sun4m when multiple ESP's shared the
809          * same IRQ.  It was too complex and messy to
810          * sanely maintain.
811          */
812         if (request_irq(esp->ehost->irq, esp_intr,
813                         SA_SHIRQ, "ESP SCSI", esp)) {
814                 printk("esp%d: Cannot acquire irq line\n",
815                        esp->esp_id);
816                 return -1;
817         }
818
819         printk("esp%d: IRQ %s ", esp->esp_id,
820                __irq_itoa(esp->ehost->irq));
821
822         return 0;
823 }
824
825 static void __init esp_get_scsi_id(struct esp *esp)
826 {
827         struct sbus_dev *sdev = esp->sdev;
828
829         esp->scsi_id = prom_getintdefault(esp->prom_node,
830                                           "initiator-id",
831                                           -1);
832         if (esp->scsi_id == -1)
833                 esp->scsi_id = prom_getintdefault(esp->prom_node,
834                                                   "scsi-initiator-id",
835                                                   -1);
836         if (esp->scsi_id == -1)
837                 esp->scsi_id = (sdev->bus == NULL) ? 7 :
838                         prom_getintdefault(sdev->bus->prom_node,
839                                            "scsi-initiator-id",
840                                            7);
841         esp->ehost->this_id = esp->scsi_id;
842         esp->scsi_id_mask = (1 << esp->scsi_id);
843
844 }
845
846 static void __init esp_get_clock_params(struct esp *esp)
847 {
848         struct sbus_dev *sdev = esp->sdev;
849         int prom_node = esp->prom_node;
850         int sbus_prom_node;
851         unsigned int fmhz;
852         u8 ccf;
853
854         if (sdev != NULL && sdev->bus != NULL)
855                 sbus_prom_node = sdev->bus->prom_node;
856         else
857                 sbus_prom_node = 0;
858
859         /* This is getting messy but it has to be done
860          * correctly or else you get weird behavior all
861          * over the place.  We are trying to basically
862          * figure out three pieces of information.
863          *
864          * a) Clock Conversion Factor
865          *
866          *    This is a representation of the input
867          *    crystal clock frequency going into the
868          *    ESP on this machine.  Any operation whose
869          *    timing is longer than 400ns depends on this
870          *    value being correct.  For example, you'll
871          *    get blips for arbitration/selection during
872          *    high load or with multiple targets if this
873          *    is not set correctly.
874          *
875          * b) Selection Time-Out
876          *
877          *    The ESP isn't very bright and will arbitrate
878          *    for the bus and try to select a target
879          *    forever if you let it.  This value tells
880          *    the ESP when it has taken too long to
881          *    negotiate and that it should interrupt
882          *    the CPU so we can see what happened.
883          *    The value is computed as follows (from
884          *    NCR/Symbios chip docs).
885          *
886          *          (Time Out Period) *  (Input Clock)
887          *    STO = ----------------------------------
888          *          (8192) * (Clock Conversion Factor)
889          *
890          *    You usually want the time out period to be
891          *    around 250ms, I think we'll set it a little
892          *    bit higher to account for fully loaded SCSI
893          *    bus's and slow devices that don't respond so
894          *    quickly to selection attempts. (yeah, I know
895          *    this is out of spec. but there is a lot of
896          *    buggy pieces of firmware out there so bite me)
897          *
898          * c) Imperical constants for synchronous offset
899          *    and transfer period register values
900          *
901          *    This entails the smallest and largest sync
902          *    period we could ever handle on this ESP.
903          */
904
905         fmhz = prom_getintdefault(prom_node, "clock-frequency", -1);
906         if (fmhz == -1)
907                 fmhz = (!sbus_prom_node) ? 0 :
908                         prom_getintdefault(sbus_prom_node, "clock-frequency", -1);
909
910         if (fmhz <= (5000000))
911                 ccf = 0;
912         else
913                 ccf = (((5000000 - 1) + (fmhz))/(5000000));
914
915         if (!ccf || ccf > 8) {
916                 /* If we can't find anything reasonable,
917                  * just assume 20MHZ.  This is the clock
918                  * frequency of the older sun4c's where I've
919                  * been unable to find the clock-frequency
920                  * PROM property.  All other machines provide
921                  * useful values it seems.
922                  */
923                 ccf = ESP_CCF_F4;
924                 fmhz = (20000000);
925         }
926
927         if (ccf == (ESP_CCF_F7 + 1))
928                 esp->cfact = ESP_CCF_F0;
929         else if (ccf == ESP_CCF_NEVER)
930                 esp->cfact = ESP_CCF_F2;
931         else
932                 esp->cfact = ccf;
933         esp->raw_cfact = ccf;
934
935         esp->cfreq = fmhz;
936         esp->ccycle = ESP_MHZ_TO_CYCLE(fmhz);
937         esp->ctick = ESP_TICK(ccf, esp->ccycle);
938         esp->neg_defp = ESP_NEG_DEFP(fmhz, ccf);
939         esp->sync_defp = SYNC_DEFP_SLOW;
940
941         printk("SCSI ID %d Clk %dMHz CCYC=%d CCF=%d TOut %d ",
942                esp->scsi_id, (fmhz / 1000000),
943                (int)esp->ccycle, (int)ccf, (int) esp->neg_defp);
944 }
945
946 static void __init esp_get_bursts(struct esp *esp, struct sbus_dev *dma)
947 {
948         struct sbus_dev *sdev = esp->sdev;
949         u8 bursts;
950
951         bursts = prom_getintdefault(esp->prom_node, "burst-sizes", 0xff);
952
953         if (dma) {
954                 u8 tmp = prom_getintdefault(dma->prom_node,
955                                             "burst-sizes", 0xff);
956                 if (tmp != 0xff)
957                         bursts &= tmp;
958         }
959
960         if (sdev->bus) {
961                 u8 tmp = prom_getintdefault(sdev->bus->prom_node,
962                                             "burst-sizes", 0xff);
963                 if (tmp != 0xff)
964                         bursts &= tmp;
965         }
966
967         if (bursts == 0xff ||
968             (bursts & DMA_BURST16) == 0 ||
969             (bursts & DMA_BURST32) == 0)
970                 bursts = (DMA_BURST32 - 1);
971
972         esp->bursts = bursts;
973 }
974
975 static void __init esp_get_revision(struct esp *esp)
976 {
977         u8 tmp;
978
979         esp->config1 = (ESP_CONFIG1_PENABLE | (esp->scsi_id & 7));
980         esp->config2 = (ESP_CONFIG2_SCSI2ENAB | ESP_CONFIG2_REGPARITY);
981         sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
982
983         tmp = sbus_readb(esp->eregs + ESP_CFG2);
984         tmp &= ~ESP_CONFIG2_MAGIC;
985         if (tmp != (ESP_CONFIG2_SCSI2ENAB | ESP_CONFIG2_REGPARITY)) {
986                 /* If what we write to cfg2 does not come back, cfg2
987                  * is not implemented, therefore this must be a plain
988                  * esp100.
989                  */
990                 esp->erev = esp100;
991                 printk("NCR53C90(esp100)\n");
992         } else {
993                 esp->config2 = 0;
994                 esp->prev_cfg3 = esp->config3[0] = 5;
995                 sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
996                 sbus_writeb(0, esp->eregs + ESP_CFG3);
997                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
998
999                 tmp = sbus_readb(esp->eregs + ESP_CFG3);
1000                 if (tmp != 5) {
1001                         /* The cfg2 register is implemented, however
1002                          * cfg3 is not, must be esp100a.
1003                          */
1004                         esp->erev = esp100a;
1005                         printk("NCR53C90A(esp100a)\n");
1006                 } else {
1007                         int target;
1008
1009                         for (target = 0; target < 16; target++)
1010                                 esp->config3[target] = 0;
1011                         esp->prev_cfg3 = 0;
1012                         sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
1013
1014                         /* All of cfg{1,2,3} implemented, must be one of
1015                          * the fas variants, figure out which one.
1016                          */
1017                         if (esp->raw_cfact > ESP_CCF_F5) {
1018                                 esp->erev = fast;
1019                                 esp->sync_defp = SYNC_DEFP_FAST;
1020                                 printk("NCR53C9XF(espfast)\n");
1021                         } else {
1022                                 esp->erev = esp236;
1023                                 printk("NCR53C9x(esp236)\n");
1024                         }
1025                         esp->config2 = 0;
1026                         sbus_writeb(esp->config2, esp->eregs + ESP_CFG2);
1027                 }
1028         }
1029 }
1030
1031 static void __init esp_init_swstate(struct esp *esp)
1032 {
1033         int i;
1034
1035         /* Command queues... */
1036         esp->current_SC = NULL;
1037         esp->disconnected_SC = NULL;
1038         esp->issue_SC = NULL;
1039
1040         /* Target and current command state... */
1041         esp->targets_present = 0;
1042         esp->resetting_bus = 0;
1043         esp->snip = 0;
1044
1045         init_waitqueue_head(&esp->reset_queue);
1046
1047         /* Debugging... */
1048         for(i = 0; i < 32; i++)
1049                 esp->espcmdlog[i] = 0;
1050         esp->espcmdent = 0;
1051
1052         /* MSG phase state... */
1053         for(i = 0; i < 16; i++) {
1054                 esp->cur_msgout[i] = 0;
1055                 esp->cur_msgin[i] = 0;
1056         }
1057         esp->prevmsgout = esp->prevmsgin = 0;
1058         esp->msgout_len = esp->msgin_len = 0;
1059
1060         /* Clear the one behind caches to hold unmatchable values. */
1061         esp->prev_soff = esp->prev_stp = esp->prev_cfg3 = 0xff;
1062         esp->prev_hme_dmacsr = 0xffffffff;
1063 }
1064
1065 static int __init detect_one_esp(Scsi_Host_Template *tpnt, struct sbus_dev *esp_dev,
1066                                  struct sbus_dev *espdma, struct sbus_bus *sbus,
1067                                  int id, int hme)
1068 {
1069         struct Scsi_Host *esp_host = scsi_register(tpnt, sizeof(struct esp));
1070         struct esp *esp;
1071         
1072         if (!esp_host) {
1073                 printk("ESP: Cannot register SCSI host\n");
1074                 return -1;
1075         }
1076         if (hme)
1077                 esp_host->max_id = 16;
1078         esp = (struct esp *) esp_host->hostdata;
1079         esp->ehost = esp_host;
1080         esp->sdev = esp_dev;
1081         esp->esp_id = id;
1082         esp->prom_node = esp_dev->prom_node;
1083         prom_getstring(esp->prom_node, "name", esp->prom_name,
1084                        sizeof(esp->prom_name));
1085
1086         esp_chain_add(esp);
1087         if (esp_find_dvma(esp, espdma) < 0)
1088                 goto fail_unlink;
1089         if (esp_map_regs(esp, hme) < 0) {
1090                 printk("ESP registers unmappable");
1091                 goto fail_dvma_release;
1092         }
1093         if (esp_map_cmdarea(esp) < 0) {
1094                 printk("ESP DVMA transport area unmappable");
1095                 goto fail_unmap_regs;
1096         }
1097         if (esp_register_irq(esp) < 0)
1098                 goto fail_unmap_cmdarea;
1099
1100         esp_get_scsi_id(esp);
1101
1102         esp->diff = prom_getbool(esp->prom_node, "differential");
1103         if (esp->diff)
1104                 printk("Differential ");
1105
1106         esp_get_clock_params(esp);
1107         esp_get_bursts(esp, espdma);
1108         esp_get_revision(esp);
1109         esp_init_swstate(esp);
1110
1111         esp_bootup_reset(esp);
1112
1113         return 0;
1114
1115 fail_unmap_cmdarea:
1116         sbus_free_consistent(esp->sdev, 16,
1117                              (void *) esp->esp_command,
1118                              esp->esp_command_dvma);
1119
1120 fail_unmap_regs:
1121         sbus_iounmap(esp->eregs, ESP_REG_SIZE);
1122
1123 fail_dvma_release:
1124         esp->dma->allocated = 0;
1125
1126 fail_unlink:
1127         esp_chain_del(esp);
1128         scsi_unregister(esp_host);
1129         return -1;
1130 }
1131
1132 /* Detecting ESP chips on the machine.  This is the simple and easy
1133  * version.
1134  */
1135
1136 #ifdef CONFIG_SUN4
1137
1138 #include <asm/sun4paddr.h>
1139
1140 static int __init esp_detect(Scsi_Host_Template *tpnt)
1141 {
1142         static struct sbus_dev esp_dev;
1143         int esps_in_use = 0;
1144
1145         espchain = 0;
1146
1147         if (sun4_esp_physaddr) {
1148                 memset (&esp_dev, 0, sizeof(esp_dev));
1149                 esp_dev.reg_addrs[0].phys_addr = sun4_esp_physaddr;
1150                 esp_dev.irqs[0] = 4;
1151                 esp_dev.resource[0].start = sun4_esp_physaddr;
1152                 esp_dev.resource[0].end = sun4_esp_physaddr + ESP_REG_SIZE - 1;
1153                 esp_dev.resource[0].flags = IORESOURCE_IO;
1154
1155                 if (!detect_one_esp(tpnt, &esp_dev, NULL, NULL, 0, 0))
1156                         esps_in_use++;
1157                 printk("ESP: Total of 1 ESP hosts found, %d actually in use.\n", esps_in_use);
1158                 esps_running =  esps_in_use;
1159         }
1160         return esps_in_use;
1161 }
1162
1163 #else /* !CONFIG_SUN4 */
1164
1165 static int __init esp_detect(Scsi_Host_Template *tpnt)
1166 {
1167         struct sbus_bus *sbus;
1168         struct sbus_dev *esp_dev, *sbdev_iter;
1169         int nesps = 0, esps_in_use = 0;
1170
1171         espchain = 0;
1172         if (!sbus_root) {
1173 #ifdef CONFIG_PCI
1174                 return 0;
1175 #else
1176                 panic("No SBUS in esp_detect()");
1177 #endif
1178         }
1179         for_each_sbus(sbus) {
1180                 for_each_sbusdev(sbdev_iter, sbus) {
1181                         struct sbus_dev *espdma = NULL;
1182                         int hme = 0;
1183
1184                         /* Is it an esp sbus device? */
1185                         esp_dev = sbdev_iter;
1186                         if (strcmp(esp_dev->prom_name, "esp") &&
1187                             strcmp(esp_dev->prom_name, "SUNW,esp")) {
1188                                 if (!strcmp(esp_dev->prom_name, "SUNW,fas")) {
1189                                         hme = 1;
1190                                         espdma = esp_dev;
1191                                 } else {
1192                                         if (!esp_dev->child ||
1193                                             (strcmp(esp_dev->prom_name, "espdma") &&
1194                                              strcmp(esp_dev->prom_name, "dma")))
1195                                                 continue; /* nope... */
1196                                         espdma = esp_dev;
1197                                         esp_dev = esp_dev->child;
1198                                         if (strcmp(esp_dev->prom_name, "esp") &&
1199                                             strcmp(esp_dev->prom_name, "SUNW,esp"))
1200                                                 continue; /* how can this happen? */
1201                                 }
1202                         }
1203                         
1204                         if (detect_one_esp(tpnt, esp_dev, espdma, sbus, nesps++, hme) < 0)
1205                                 continue;
1206                                 
1207                         esps_in_use++;
1208                 } /* for each sbusdev */
1209         } /* for each sbus */
1210         printk("ESP: Total of %d ESP hosts found, %d actually in use.\n", nesps,
1211                esps_in_use);
1212         esps_running = esps_in_use;
1213         return esps_in_use;
1214 }
1215
1216 #endif /* !CONFIG_SUN4 */
1217
1218 /*
1219  */
1220 static int esp_release(struct Scsi_Host *host)
1221 {
1222         struct esp *esp = (struct esp *) host->hostdata;
1223
1224         ESP_INTSOFF(esp->dregs);
1225 #if 0
1226         esp_reset_dma(esp);
1227         esp_reset_esp(esp);
1228 #endif
1229
1230         free_irq(esp->ehost->irq, esp);
1231         sbus_free_consistent(esp->sdev, 16,
1232                              (void *) esp->esp_command, esp->esp_command_dvma);
1233         sbus_iounmap(esp->eregs, ESP_REG_SIZE);
1234         esp->dma->allocated = 0;
1235         esp_chain_del(esp);
1236
1237         return 0;
1238 }
1239
1240 /* The info function will return whatever useful
1241  * information the developer sees fit.  If not provided, then
1242  * the name field will be used instead.
1243  */
1244 static const char *esp_info(struct Scsi_Host *host)
1245 {
1246         struct esp *esp;
1247
1248         esp = (struct esp *) host->hostdata;
1249         switch (esp->erev) {
1250         case esp100:
1251                 return "Sparc ESP100 (NCR53C90)";
1252         case esp100a:
1253                 return "Sparc ESP100A (NCR53C90A)";
1254         case esp236:
1255                 return "Sparc ESP236";
1256         case fas236:
1257                 return "Sparc ESP236-FAST";
1258         case fashme:
1259                 return "Sparc ESP366-HME";
1260         case fas100a:
1261                 return "Sparc ESP100A-FAST";
1262         default:
1263                 return "Bogon ESP revision";
1264         };
1265 }
1266
1267 /* From Wolfgang Stanglmeier's NCR scsi driver. */
1268 struct info_str
1269 {
1270         char *buffer;
1271         int length;
1272         int offset;
1273         int pos;
1274 };
1275
1276 static void copy_mem_info(struct info_str *info, char *data, int len)
1277 {
1278         if (info->pos + len > info->length)
1279                 len = info->length - info->pos;
1280
1281         if (info->pos + len < info->offset) {
1282                 info->pos += len;
1283                 return;
1284         }
1285         if (info->pos < info->offset) {
1286                 data += (info->offset - info->pos);
1287                 len  -= (info->offset - info->pos);
1288         }
1289
1290         if (len > 0) {
1291                 memcpy(info->buffer + info->pos, data, len);
1292                 info->pos += len;
1293         }
1294 }
1295
1296 static int copy_info(struct info_str *info, char *fmt, ...)
1297 {
1298         va_list args;
1299         char buf[81];
1300         int len;
1301
1302         va_start(args, fmt);
1303         len = vsprintf(buf, fmt, args);
1304         va_end(args);
1305
1306         copy_mem_info(info, buf, len);
1307         return len;
1308 }
1309
1310 static int esp_host_info(struct esp *esp, char *ptr, off_t offset, int len)
1311 {
1312         struct scsi_device *sdev;
1313         struct info_str info;
1314         int i;
1315
1316         info.buffer     = ptr;
1317         info.length     = len;
1318         info.offset     = offset;
1319         info.pos        = 0;
1320
1321         copy_info(&info, "Sparc ESP Host Adapter:\n");
1322         copy_info(&info, "\tPROM node\t\t%08x\n", (unsigned int) esp->prom_node);
1323         copy_info(&info, "\tPROM name\t\t%s\n", esp->prom_name);
1324         copy_info(&info, "\tESP Model\t\t");
1325         switch (esp->erev) {
1326         case esp100:
1327                 copy_info(&info, "ESP100\n");
1328                 break;
1329         case esp100a:
1330                 copy_info(&info, "ESP100A\n");
1331                 break;
1332         case esp236:
1333                 copy_info(&info, "ESP236\n");
1334                 break;
1335         case fas236:
1336                 copy_info(&info, "FAS236\n");
1337                 break;
1338         case fas100a:
1339                 copy_info(&info, "FAS100A\n");
1340                 break;
1341         case fast:
1342                 copy_info(&info, "FAST\n");
1343                 break;
1344         case fashme:
1345                 copy_info(&info, "Happy Meal FAS\n");
1346                 break;
1347         case espunknown:
1348         default:
1349                 copy_info(&info, "Unknown!\n");
1350                 break;
1351         };
1352         copy_info(&info, "\tDMA Revision\t\t");
1353         switch (esp->dma->revision) {
1354         case dvmarev0:
1355                 copy_info(&info, "Rev 0\n");
1356                 break;
1357         case dvmaesc1:
1358                 copy_info(&info, "ESC Rev 1\n");
1359                 break;
1360         case dvmarev1:
1361                 copy_info(&info, "Rev 1\n");
1362                 break;
1363         case dvmarev2:
1364                 copy_info(&info, "Rev 2\n");
1365                 break;
1366         case dvmarev3:
1367                 copy_info(&info, "Rev 3\n");
1368                 break;
1369         case dvmarevplus:
1370                 copy_info(&info, "Rev 1+\n");
1371                 break;
1372         case dvmahme:
1373                 copy_info(&info, "Rev HME/FAS\n");
1374                 break;
1375         default:
1376                 copy_info(&info, "Unknown!\n");
1377                 break;
1378         };
1379         copy_info(&info, "\tLive Targets\t\t[ ");
1380         for (i = 0; i < 15; i++) {
1381                 if (esp->targets_present & (1 << i))
1382                         copy_info(&info, "%d ", i);
1383         }
1384         copy_info(&info, "]\n\n");
1385         
1386         /* Now describe the state of each existing target. */
1387         copy_info(&info, "Target #\tconfig3\t\tSync Capabilities\tDisconnect\tWide\n");
1388
1389         shost_for_each_device(sdev, esp->ehost) {
1390                 struct esp_device *esp_dev = sdev->hostdata;
1391                 uint id = sdev->id;
1392
1393                 if (!(esp->targets_present & (1 << id)))
1394                         continue;
1395
1396                 copy_info(&info, "%d\t\t", id);
1397                 copy_info(&info, "%08lx\t", esp->config3[id]);
1398                 copy_info(&info, "[%02lx,%02lx]\t\t\t",
1399                         esp_dev->sync_max_offset,
1400                         esp_dev->sync_min_period);
1401                 copy_info(&info, "%s\t\t",
1402                         esp_dev->disconnect ? "yes" : "no");
1403                 copy_info(&info, "%s\n",
1404                         (esp->config3[id] & ESP_CONFIG3_EWIDE) ? "yes" : "no");
1405         }
1406         return info.pos > info.offset? info.pos - info.offset : 0;
1407 }
1408
1409 /* ESP proc filesystem code. */
1410 static int esp_proc_info(struct Scsi_Host *host, char *buffer, char **start, off_t offset,
1411                          int length, int inout)
1412 {
1413         struct esp *esp;
1414
1415         if (inout)
1416                 return -EINVAL; /* not yet */
1417
1418         for_each_esp(esp) {
1419                 if (esp->ehost == host)
1420                         break;
1421         }
1422         if (!esp)
1423                 return -EINVAL;
1424
1425         if (start)
1426                 *start = buffer;
1427
1428         return esp_host_info(esp, buffer, offset, length);
1429 }
1430
1431 static void esp_get_dmabufs(struct esp *esp, Scsi_Cmnd *sp)
1432 {
1433         if (sp->use_sg == 0) {
1434                 sp->SCp.this_residual = sp->request_bufflen;
1435                 sp->SCp.buffer = (struct scatterlist *) sp->request_buffer;
1436                 sp->SCp.buffers_residual = 0;
1437                 if (sp->request_bufflen) {
1438                         sp->SCp.have_data_in = sbus_map_single(esp->sdev, sp->SCp.buffer,
1439                                                                sp->SCp.this_residual,
1440                                                                scsi_to_sbus_dma_dir(sp->sc_data_direction));
1441                         sp->SCp.ptr = (char *) ((unsigned long)sp->SCp.have_data_in);
1442                 } else {
1443                         sp->SCp.ptr = NULL;
1444                 }
1445         } else {
1446                 sp->SCp.buffer = (struct scatterlist *) sp->buffer;
1447                 sp->SCp.buffers_residual = sbus_map_sg(esp->sdev,
1448                                                        sp->SCp.buffer,
1449                                                        sp->use_sg,
1450                                                        scsi_to_sbus_dma_dir(sp->sc_data_direction));
1451                 sp->SCp.this_residual = sg_dma_len(sp->SCp.buffer);
1452                 sp->SCp.ptr = (char *) ((unsigned long)sg_dma_address(sp->SCp.buffer));
1453         }
1454 }
1455
1456 static void esp_release_dmabufs(struct esp *esp, Scsi_Cmnd *sp)
1457 {
1458         if (sp->use_sg) {
1459                 sbus_unmap_sg(esp->sdev, sp->buffer, sp->use_sg,
1460                               scsi_to_sbus_dma_dir(sp->sc_data_direction));
1461         } else if (sp->request_bufflen) {
1462                 sbus_unmap_single(esp->sdev,
1463                                   sp->SCp.have_data_in,
1464                                   sp->request_bufflen,
1465                                   scsi_to_sbus_dma_dir(sp->sc_data_direction));
1466         }
1467 }
1468
1469 static void esp_restore_pointers(struct esp *esp, Scsi_Cmnd *sp)
1470 {
1471         struct esp_pointers *ep = &esp->data_pointers[sp->device->id];
1472
1473         sp->SCp.ptr = ep->saved_ptr;
1474         sp->SCp.buffer = ep->saved_buffer;
1475         sp->SCp.this_residual = ep->saved_this_residual;
1476         sp->SCp.buffers_residual = ep->saved_buffers_residual;
1477 }
1478
1479 static void esp_save_pointers(struct esp *esp, Scsi_Cmnd *sp)
1480 {
1481         struct esp_pointers *ep = &esp->data_pointers[sp->device->id];
1482
1483         ep->saved_ptr = sp->SCp.ptr;
1484         ep->saved_buffer = sp->SCp.buffer;
1485         ep->saved_this_residual = sp->SCp.this_residual;
1486         ep->saved_buffers_residual = sp->SCp.buffers_residual;
1487 }
1488
1489 /* Some rules:
1490  *
1491  *   1) Never ever panic while something is live on the bus.
1492  *      If there is to be any chance of syncing the disks this
1493  *      rule is to be obeyed.
1494  *
1495  *   2) Any target that causes a foul condition will no longer
1496  *      have synchronous transfers done to it, no questions
1497  *      asked.
1498  *
1499  *   3) Keep register accesses to a minimum.  Think about some
1500  *      day when we have Xbus machines this is running on and
1501  *      the ESP chip is on the other end of the machine on a
1502  *      different board from the cpu where this is running.
1503  */
1504
1505 /* Fire off a command.  We assume the bus is free and that the only
1506  * case where we could see an interrupt is where we have disconnected
1507  * commands active and they are trying to reselect us.
1508  */
1509 static inline void esp_check_cmd(struct esp *esp, Scsi_Cmnd *sp)
1510 {
1511         switch (sp->cmd_len) {
1512         case 6:
1513         case 10:
1514         case 12:
1515                 esp->esp_slowcmd = 0;
1516                 break;
1517
1518         default:
1519                 esp->esp_slowcmd = 1;
1520                 esp->esp_scmdleft = sp->cmd_len;
1521                 esp->esp_scmdp = &sp->cmnd[0];
1522                 break;
1523         };
1524 }
1525
1526 static inline void build_sync_nego_msg(struct esp *esp, int period, int offset)
1527 {
1528         esp->cur_msgout[0] = EXTENDED_MESSAGE;
1529         esp->cur_msgout[1] = 3;
1530         esp->cur_msgout[2] = EXTENDED_SDTR;
1531         esp->cur_msgout[3] = period;
1532         esp->cur_msgout[4] = offset;
1533         esp->msgout_len = 5;
1534 }
1535
1536 /* SIZE is in bits, currently HME only supports 16 bit wide transfers. */
1537 static inline void build_wide_nego_msg(struct esp *esp, int size)
1538 {
1539         esp->cur_msgout[0] = EXTENDED_MESSAGE;
1540         esp->cur_msgout[1] = 2;
1541         esp->cur_msgout[2] = EXTENDED_WDTR;
1542         switch (size) {
1543         case 32:
1544                 esp->cur_msgout[3] = 2;
1545                 break;
1546         case 16:
1547                 esp->cur_msgout[3] = 1;
1548                 break;
1549         case 8:
1550         default:
1551                 esp->cur_msgout[3] = 0;
1552                 break;
1553         };
1554
1555         esp->msgout_len = 4;
1556 }
1557
1558 static void esp_exec_cmd(struct esp *esp)
1559 {
1560         Scsi_Cmnd *SCptr;
1561         Scsi_Device *SDptr;
1562         struct esp_device *esp_dev;
1563         volatile u8 *cmdp = esp->esp_command;
1564         u8 the_esp_command;
1565         int lun, target;
1566         int i;
1567
1568         /* Hold off if we have disconnected commands and
1569          * an IRQ is showing...
1570          */
1571         if (esp->disconnected_SC && ESP_IRQ_P(esp->dregs))
1572                 return;
1573
1574         /* Grab first member of the issue queue. */
1575         SCptr = esp->current_SC = remove_first_SC(&esp->issue_SC);
1576
1577         /* Safe to panic here because current_SC is null. */
1578         if (!SCptr)
1579                 panic("esp: esp_exec_cmd and issue queue is NULL");
1580
1581         SDptr = SCptr->device;
1582         esp_dev = SDptr->hostdata;
1583         lun = SCptr->device->lun;
1584         target = SCptr->device->id;
1585
1586         esp->snip = 0;
1587         esp->msgout_len = 0;
1588
1589         /* Send it out whole, or piece by piece?   The ESP
1590          * only knows how to automatically send out 6, 10,
1591          * and 12 byte commands.  I used to think that the
1592          * Linux SCSI code would never throw anything other
1593          * than that to us, but then again there is the
1594          * SCSI generic driver which can send us anything.
1595          */
1596         esp_check_cmd(esp, SCptr);
1597
1598         /* If arbitration/selection is successful, the ESP will leave
1599          * ATN asserted, causing the target to go into message out
1600          * phase.  The ESP will feed the target the identify and then
1601          * the target can only legally go to one of command,
1602          * datain/out, status, or message in phase, or stay in message
1603          * out phase (should we be trying to send a sync negotiation
1604          * message after the identify).  It is not allowed to drop
1605          * BSY, but some buggy targets do and we check for this
1606          * condition in the selection complete code.  Most of the time
1607          * we'll make the command bytes available to the ESP and it
1608          * will not interrupt us until it finishes command phase, we
1609          * cannot do this for command sizes the ESP does not
1610          * understand and in this case we'll get interrupted right
1611          * when the target goes into command phase.
1612          *
1613          * It is absolutely _illegal_ in the presence of SCSI-2 devices
1614          * to use the ESP select w/o ATN command.  When SCSI-2 devices are
1615          * present on the bus we _must_ always go straight to message out
1616          * phase with an identify message for the target.  Being that
1617          * selection attempts in SCSI-1 w/o ATN was an option, doing SCSI-2
1618          * selections should not confuse SCSI-1 we hope.
1619          */
1620
1621         if (esp_dev->sync) {
1622                 /* this targets sync is known */
1623 #ifndef __sparc_v9__
1624 do_sync_known:
1625 #endif
1626                 if (esp_dev->disconnect)
1627                         *cmdp++ = IDENTIFY(1, lun);
1628                 else
1629                         *cmdp++ = IDENTIFY(0, lun);
1630
1631                 if (esp->esp_slowcmd) {
1632                         the_esp_command = (ESP_CMD_SELAS | ESP_CMD_DMA);
1633                         esp_advance_phase(SCptr, in_slct_stop);
1634                 } else {
1635                         the_esp_command = (ESP_CMD_SELA | ESP_CMD_DMA);
1636                         esp_advance_phase(SCptr, in_slct_norm);
1637                 }
1638         } else if (!(esp->targets_present & (1<<target)) || !(esp_dev->disconnect)) {
1639                 /* After the bootup SCSI code sends both the
1640                  * TEST_UNIT_READY and INQUIRY commands we want
1641                  * to at least attempt allowing the device to
1642                  * disconnect.
1643                  */
1644                 ESPMISC(("esp: Selecting device for first time. target=%d "
1645                          "lun=%d\n", target, SCptr->device->lun));
1646                 if (!SDptr->borken && !esp_dev->disconnect)
1647                         esp_dev->disconnect = 1;
1648
1649                 *cmdp++ = IDENTIFY(0, lun);
1650                 esp->prevmsgout = NOP;
1651                 esp_advance_phase(SCptr, in_slct_norm);
1652                 the_esp_command = (ESP_CMD_SELA | ESP_CMD_DMA);
1653
1654                 /* Take no chances... */
1655                 esp_dev->sync_max_offset = 0;
1656                 esp_dev->sync_min_period = 0;
1657         } else {
1658                 /* Sorry, I have had way too many problems with
1659                  * various CDROM devices on ESP. -DaveM
1660                  */
1661                 int cdrom_hwbug_wkaround = 0;
1662
1663 #ifndef __sparc_v9__
1664                 /* Never allow disconnects or synchronous transfers on
1665                  * SparcStation1 and SparcStation1+.  Allowing those
1666                  * to be enabled seems to lockup the machine completely.
1667                  */
1668                 if ((idprom->id_machtype == (SM_SUN4C | SM_4C_SS1)) ||
1669                     (idprom->id_machtype == (SM_SUN4C | SM_4C_SS1PLUS))) {
1670                         /* But we are nice and allow tapes and removable
1671                          * disks (but not CDROMs) to disconnect.
1672                          */
1673                         if(SDptr->type == TYPE_TAPE ||
1674                            (SDptr->type != TYPE_ROM && SDptr->removable))
1675                                 esp_dev->disconnect = 1;
1676                         else
1677                                 esp_dev->disconnect = 0;
1678                         esp_dev->sync_max_offset = 0;
1679                         esp_dev->sync_min_period = 0;
1680                         esp_dev->sync = 1;
1681                         esp->snip = 0;
1682                         goto do_sync_known;
1683                 }
1684 #endif /* !(__sparc_v9__) */
1685
1686                 /* We've talked to this guy before,
1687                  * but never negotiated.  Let's try,
1688                  * need to attempt WIDE first, before
1689                  * sync nego, as per SCSI 2 standard.
1690                  */
1691                 if (esp->erev == fashme && !esp_dev->wide) {
1692                         if (!SDptr->borken &&
1693                            SDptr->type != TYPE_ROM &&
1694                            SDptr->removable == 0) {
1695                                 build_wide_nego_msg(esp, 16);
1696                                 esp_dev->wide = 1;
1697                                 esp->wnip = 1;
1698                                 goto after_nego_msg_built;
1699                         } else {
1700                                 esp_dev->wide = 1;
1701                                 /* Fall through and try sync. */
1702                         }
1703                 }
1704
1705                 if (!SDptr->borken) {
1706                         if ((SDptr->type == TYPE_ROM)) {
1707                                 /* Nice try sucker... */
1708                                 ESPMISC(("esp%d: Disabling sync for buggy "
1709                                          "CDROM.\n", esp->esp_id));
1710                                 cdrom_hwbug_wkaround = 1;
1711                                 build_sync_nego_msg(esp, 0, 0);
1712                         } else if (SDptr->removable != 0) {
1713                                 ESPMISC(("esp%d: Not negotiating sync/wide but "
1714                                          "allowing disconnect for removable media.\n",
1715                                          esp->esp_id));
1716                                 build_sync_nego_msg(esp, 0, 0);
1717                         } else {
1718                                 build_sync_nego_msg(esp, esp->sync_defp, 15);
1719                         }
1720                 } else {
1721                         build_sync_nego_msg(esp, 0, 0);
1722                 }
1723                 esp_dev->sync = 1;
1724                 esp->snip = 1;
1725
1726 after_nego_msg_built:
1727                 /* A fix for broken SCSI1 targets, when they disconnect
1728                  * they lock up the bus and confuse ESP.  So disallow
1729                  * disconnects for SCSI1 targets for now until we
1730                  * find a better fix.
1731                  *
1732                  * Addendum: This is funny, I figured out what was going
1733                  *           on.  The blotzed SCSI1 target would disconnect,
1734                  *           one of the other SCSI2 targets or both would be
1735                  *           disconnected as well.  The SCSI1 target would
1736                  *           stay disconnected long enough that we start
1737                  *           up a command on one of the SCSI2 targets.  As
1738                  *           the ESP is arbitrating for the bus the SCSI1
1739                  *           target begins to arbitrate as well to reselect
1740                  *           the ESP.  The SCSI1 target refuses to drop it's
1741                  *           ID bit on the data bus even though the ESP is
1742                  *           at ID 7 and is the obvious winner for any
1743                  *           arbitration.  The ESP is a poor sport and refuses
1744                  *           to lose arbitration, it will continue indefinitely
1745                  *           trying to arbitrate for the bus and can only be
1746                  *           stopped via a chip reset or SCSI bus reset.
1747                  *           Therefore _no_ disconnects for SCSI1 targets
1748                  *           thank you very much. ;-)
1749                  */
1750                 if(((SDptr->scsi_level < 3) &&
1751                     (SDptr->type != TYPE_TAPE) &&
1752                     SDptr->removable == 0) ||
1753                     cdrom_hwbug_wkaround || SDptr->borken) {
1754                         ESPMISC((KERN_INFO "esp%d: Disabling DISCONNECT for target %d "
1755                                  "lun %d\n", esp->esp_id, SCptr->device->id, SCptr->device->lun));
1756                         esp_dev->disconnect = 0;
1757                         *cmdp++ = IDENTIFY(0, lun);
1758                 } else {
1759                         *cmdp++ = IDENTIFY(1, lun);
1760                 }
1761
1762                 /* ESP fifo is only so big...
1763                  * Make this look like a slow command.
1764                  */
1765                 esp->esp_slowcmd = 1;
1766                 esp->esp_scmdleft = SCptr->cmd_len;
1767                 esp->esp_scmdp = &SCptr->cmnd[0];
1768
1769                 the_esp_command = (ESP_CMD_SELAS | ESP_CMD_DMA);
1770                 esp_advance_phase(SCptr, in_slct_msg);
1771         }
1772
1773         if (!esp->esp_slowcmd)
1774                 for (i = 0; i < SCptr->cmd_len; i++)
1775                         *cmdp++ = SCptr->cmnd[i];
1776
1777         /* HME sucks... */
1778         if (esp->erev == fashme)
1779                 sbus_writeb((target & 0xf) | (ESP_BUSID_RESELID | ESP_BUSID_CTR32BIT),
1780                             esp->eregs + ESP_BUSID);
1781         else
1782                 sbus_writeb(target & 7, esp->eregs + ESP_BUSID);
1783         if (esp->prev_soff != esp_dev->sync_max_offset ||
1784             esp->prev_stp  != esp_dev->sync_min_period ||
1785             (esp->erev > esp100a &&
1786              esp->prev_cfg3 != esp->config3[target])) {
1787                 esp->prev_soff = esp_dev->sync_max_offset;
1788                 esp->prev_stp = esp_dev->sync_min_period;
1789                 sbus_writeb(esp->prev_soff, esp->eregs + ESP_SOFF);
1790                 sbus_writeb(esp->prev_stp, esp->eregs + ESP_STP);
1791                 if (esp->erev > esp100a) {
1792                         esp->prev_cfg3 = esp->config3[target];
1793                         sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
1794                 }
1795         }
1796         i = (cmdp - esp->esp_command);
1797
1798         if (esp->erev == fashme) {
1799                 esp_cmd(esp, ESP_CMD_FLUSH); /* Grrr! */
1800
1801                 /* Set up the DMA and HME counters */
1802                 sbus_writeb(i, esp->eregs + ESP_TCLOW);
1803                 sbus_writeb(0, esp->eregs + ESP_TCMED);
1804                 sbus_writeb(0, esp->eregs + FAS_RLO);
1805                 sbus_writeb(0, esp->eregs + FAS_RHI);
1806                 esp_cmd(esp, the_esp_command);
1807
1808                 /* Talk about touchy hardware... */
1809                 esp->prev_hme_dmacsr = ((esp->prev_hme_dmacsr |
1810                                          (DMA_SCSI_DISAB | DMA_ENABLE)) &
1811                                         ~(DMA_ST_WRITE));
1812                 sbus_writel(16, esp->dregs + DMA_COUNT);
1813                 sbus_writel(esp->esp_command_dvma, esp->dregs + DMA_ADDR);
1814                 sbus_writel(esp->prev_hme_dmacsr, esp->dregs + DMA_CSR);
1815         } else {
1816                 u32 tmp;
1817
1818                 /* Set up the DMA and ESP counters */
1819                 sbus_writeb(i, esp->eregs + ESP_TCLOW);
1820                 sbus_writeb(0, esp->eregs + ESP_TCMED);
1821                 tmp = sbus_readl(esp->dregs + DMA_CSR);
1822                 tmp &= ~DMA_ST_WRITE;
1823                 tmp |= DMA_ENABLE;
1824                 sbus_writel(tmp, esp->dregs + DMA_CSR);
1825                 if (esp->dma->revision == dvmaesc1) {
1826                         if (i) /* Workaround ESC gate array SBUS rerun bug. */
1827                                 sbus_writel(PAGE_SIZE, esp->dregs + DMA_COUNT);
1828                 }
1829                 sbus_writel(esp->esp_command_dvma, esp->dregs + DMA_ADDR);
1830
1831                 /* Tell ESP to "go". */
1832                 esp_cmd(esp, the_esp_command);
1833         }
1834 }
1835
1836 /* Queue a SCSI command delivered from the mid-level Linux SCSI code. */
1837 static int esp_queue(Scsi_Cmnd *SCpnt, void (*done)(Scsi_Cmnd *))
1838 {
1839         struct esp *esp;
1840
1841         /* Set up func ptr and initial driver cmd-phase. */
1842         SCpnt->scsi_done = done;
1843         SCpnt->SCp.phase = not_issued;
1844
1845         /* We use the scratch area. */
1846         ESPQUEUE(("esp_queue: target=%d lun=%d ", SCpnt->device->id, SCpnt->device->lun));
1847         ESPDISC(("N<%02x,%02x>", SCpnt->device->id, SCpnt->device->lun));
1848
1849         esp = (struct esp *) SCpnt->device->host->hostdata;
1850         esp_get_dmabufs(esp, SCpnt);
1851         esp_save_pointers(esp, SCpnt); /* FIXME for tag queueing */
1852
1853         SCpnt->SCp.Status           = CHECK_CONDITION;
1854         SCpnt->SCp.Message          = 0xff;
1855         SCpnt->SCp.sent_command     = 0;
1856
1857         /* Place into our queue. */
1858         if (SCpnt->cmnd[0] == REQUEST_SENSE) {
1859                 ESPQUEUE(("RQSENSE\n"));
1860                 prepend_SC(&esp->issue_SC, SCpnt);
1861         } else {
1862                 ESPQUEUE(("\n"));
1863                 append_SC(&esp->issue_SC, SCpnt);
1864         }
1865
1866         /* Run it now if we can. */
1867         if (!esp->current_SC && !esp->resetting_bus)
1868                 esp_exec_cmd(esp);
1869
1870         return 0;
1871 }
1872
1873 /* Dump driver state. */
1874 static void esp_dump_cmd(Scsi_Cmnd *SCptr)
1875 {
1876         ESPLOG(("[tgt<%02x> lun<%02x> "
1877                 "pphase<%s> cphase<%s>]",
1878                 SCptr->device->id, SCptr->device->lun,
1879                 phase_string(SCptr->SCp.sent_command),
1880                 phase_string(SCptr->SCp.phase)));
1881 }
1882
1883 static void esp_dump_state(struct esp *esp)
1884 {
1885         Scsi_Cmnd *SCptr = esp->current_SC;
1886 #ifdef DEBUG_ESP_CMDS
1887         int i;
1888 #endif
1889
1890         ESPLOG(("esp%d: dumping state\n", esp->esp_id));
1891         ESPLOG(("esp%d: dma -- cond_reg<%08x> addr<%08x>\n",
1892                 esp->esp_id,
1893                 sbus_readl(esp->dregs + DMA_CSR),
1894                 sbus_readl(esp->dregs + DMA_ADDR)));
1895         ESPLOG(("esp%d: SW [sreg<%02x> sstep<%02x> ireg<%02x>]\n",
1896                 esp->esp_id, esp->sreg, esp->seqreg, esp->ireg));
1897         ESPLOG(("esp%d: HW reread [sreg<%02x> sstep<%02x> ireg<%02x>]\n",
1898                 esp->esp_id,
1899                 sbus_readb(esp->eregs + ESP_STATUS),
1900                 sbus_readb(esp->eregs + ESP_SSTEP),
1901                 sbus_readb(esp->eregs + ESP_INTRPT)));
1902 #ifdef DEBUG_ESP_CMDS
1903         printk("esp%d: last ESP cmds [", esp->esp_id);
1904         i = (esp->espcmdent - 1) & 31;
1905         printk("<"); esp_print_cmd(esp->espcmdlog[i]); printk(">");
1906         i = (i - 1) & 31;
1907         printk("<"); esp_print_cmd(esp->espcmdlog[i]); printk(">");
1908         i = (i - 1) & 31;
1909         printk("<"); esp_print_cmd(esp->espcmdlog[i]); printk(">");
1910         i = (i - 1) & 31;
1911         printk("<"); esp_print_cmd(esp->espcmdlog[i]); printk(">");
1912         printk("]\n");
1913 #endif /* (DEBUG_ESP_CMDS) */
1914
1915         if (SCptr) {
1916                 ESPLOG(("esp%d: current command ", esp->esp_id));
1917                 esp_dump_cmd(SCptr);
1918         }
1919         ESPLOG(("\n"));
1920         SCptr = esp->disconnected_SC;
1921         ESPLOG(("esp%d: disconnected ", esp->esp_id));
1922         while (SCptr) {
1923                 esp_dump_cmd(SCptr);
1924                 SCptr = (Scsi_Cmnd *) SCptr->host_scribble;
1925         }
1926         ESPLOG(("\n"));
1927 }
1928
1929 /* Abort a command.  The host_lock is acquired by caller. */
1930 static int esp_abort(Scsi_Cmnd *SCptr)
1931 {
1932         struct esp *esp = (struct esp *) SCptr->device->host->hostdata;
1933         int don;
1934
1935         ESPLOG(("esp%d: Aborting command\n", esp->esp_id));
1936         esp_dump_state(esp);
1937
1938         /* Wheee, if this is the current command on the bus, the
1939          * best we can do is assert ATN and wait for msgout phase.
1940          * This should even fix a hung SCSI bus when we lose state
1941          * in the driver and timeout because the eventual phase change
1942          * will cause the ESP to (eventually) give an interrupt.
1943          */
1944         if (esp->current_SC == SCptr) {
1945                 esp->cur_msgout[0] = ABORT;
1946                 esp->msgout_len = 1;
1947                 esp->msgout_ctr = 0;
1948                 esp_cmd(esp, ESP_CMD_SATN);
1949                 return SUCCESS;
1950         }
1951
1952         /* If it is still in the issue queue then we can safely
1953          * call the completion routine and report abort success.
1954          */
1955         don = (sbus_readl(esp->dregs + DMA_CSR) & DMA_INT_ENAB);
1956         if (don) {
1957                 ESP_INTSOFF(esp->dregs);
1958         }
1959         if (esp->issue_SC) {
1960                 Scsi_Cmnd **prev, *this;
1961                 for (prev = (&esp->issue_SC), this = esp->issue_SC;
1962                      this != NULL;
1963                      prev = (Scsi_Cmnd **) &(this->host_scribble),
1964                              this = (Scsi_Cmnd *) this->host_scribble) {
1965
1966                         if (this == SCptr) {
1967                                 *prev = (Scsi_Cmnd *) this->host_scribble;
1968                                 this->host_scribble = NULL;
1969
1970                                 esp_release_dmabufs(esp, this);
1971                                 this->result = DID_ABORT << 16;
1972                                 this->scsi_done(this);
1973
1974                                 if (don)
1975                                         ESP_INTSON(esp->dregs);
1976
1977                                 return SUCCESS;
1978                         }
1979                 }
1980         }
1981
1982         /* Yuck, the command to abort is disconnected, it is not
1983          * worth trying to abort it now if something else is live
1984          * on the bus at this time.  So, we let the SCSI code wait
1985          * a little bit and try again later.
1986          */
1987         if (esp->current_SC) {
1988                 if (don)
1989                         ESP_INTSON(esp->dregs);
1990                 return FAILED;
1991         }
1992
1993         /* It's disconnected, we have to reconnect to re-establish
1994          * the nexus and tell the device to abort.  However, we really
1995          * cannot 'reconnect' per se.  Don't try to be fancy, just
1996          * indicate failure, which causes our caller to reset the whole
1997          * bus.
1998          */
1999
2000         if (don)
2001                 ESP_INTSON(esp->dregs);
2002
2003         return FAILED;
2004 }
2005
2006 /* We've sent ESP_CMD_RS to the ESP, the interrupt had just
2007  * arrived indicating the end of the SCSI bus reset.  Our job
2008  * is to clean out the command queues and begin re-execution
2009  * of SCSI commands once more.
2010  */
2011 static int esp_finish_reset(struct esp *esp)
2012 {
2013         Scsi_Cmnd *sp = esp->current_SC;
2014
2015         /* Clean up currently executing command, if any. */
2016         if (sp != NULL) {
2017                 esp->current_SC = NULL;
2018
2019                 esp_release_dmabufs(esp, sp);
2020                 sp->result = (DID_RESET << 16);
2021
2022                 sp->scsi_done(sp);
2023         }
2024
2025         /* Clean up disconnected queue, they have been invalidated
2026          * by the bus reset.
2027          */
2028         if (esp->disconnected_SC) {
2029                 while ((sp = remove_first_SC(&esp->disconnected_SC)) != NULL) {
2030                         esp_release_dmabufs(esp, sp);
2031                         sp->result = (DID_RESET << 16);
2032
2033                         sp->scsi_done(sp);
2034                 }
2035         }
2036
2037         /* SCSI bus reset is complete. */
2038         esp->resetting_bus = 0;
2039         wake_up(&esp->reset_queue);
2040
2041         /* Ok, now it is safe to get commands going once more. */
2042         if (esp->issue_SC)
2043                 esp_exec_cmd(esp);
2044
2045         return do_intr_end;
2046 }
2047
2048 static int esp_do_resetbus(struct esp *esp)
2049 {
2050         ESPLOG(("esp%d: Resetting scsi bus\n", esp->esp_id));
2051         esp->resetting_bus = 1;
2052         esp_cmd(esp, ESP_CMD_RS);
2053
2054         return do_intr_end;
2055 }
2056
2057 /* Reset ESP chip, reset hanging bus, then kill active and
2058  * disconnected commands for targets without soft reset.
2059  *
2060  * The host_lock is acquired by caller.
2061  */
2062 static int esp_reset(Scsi_Cmnd *SCptr)
2063 {
2064         struct esp *esp = (struct esp *) SCptr->device->host->hostdata;
2065
2066         (void) esp_do_resetbus(esp);
2067
2068         spin_unlock_irq(esp->ehost->host_lock);
2069
2070         wait_event(esp->reset_queue, (esp->resetting_bus == 0));
2071
2072         spin_lock_irq(esp->ehost->host_lock);
2073
2074         return SUCCESS;
2075 }
2076
2077 /* Internal ESP done function. */
2078 static void esp_done(struct esp *esp, int error)
2079 {
2080         Scsi_Cmnd *done_SC = esp->current_SC;
2081
2082         esp->current_SC = NULL;
2083
2084         esp_release_dmabufs(esp, done_SC);
2085         done_SC->result = error;
2086
2087         done_SC->scsi_done(done_SC);
2088
2089         /* Bus is free, issue any commands in the queue. */
2090         if (esp->issue_SC && !esp->current_SC)
2091                 esp_exec_cmd(esp);
2092
2093 }
2094
2095 /* Wheee, ESP interrupt engine. */  
2096
2097 /* Forward declarations. */
2098 static int esp_do_phase_determine(struct esp *esp);
2099 static int esp_do_data_finale(struct esp *esp);
2100 static int esp_select_complete(struct esp *esp);
2101 static int esp_do_status(struct esp *esp);
2102 static int esp_do_msgin(struct esp *esp);
2103 static int esp_do_msgindone(struct esp *esp);
2104 static int esp_do_msgout(struct esp *esp);
2105 static int esp_do_cmdbegin(struct esp *esp);
2106
2107 #define sreg_datainp(__sreg)  (((__sreg) & ESP_STAT_PMASK) == ESP_DIP)
2108 #define sreg_dataoutp(__sreg) (((__sreg) & ESP_STAT_PMASK) == ESP_DOP)
2109
2110 /* Read any bytes found in the FAS366 fifo, storing them into
2111  * the ESP driver software state structure.
2112  */
2113 static void hme_fifo_read(struct esp *esp)
2114 {
2115         u8 count = 0;
2116         u8 status = esp->sreg;
2117
2118         /* Cannot safely frob the fifo for these following cases, but
2119          * we must always read the fifo when the reselect interrupt
2120          * is pending.
2121          */
2122         if (((esp->ireg & ESP_INTR_RSEL) == 0)  &&
2123             (sreg_datainp(status)               ||
2124              sreg_dataoutp(status)              ||
2125              (esp->current_SC &&
2126               esp->current_SC->SCp.phase == in_data_done))) {
2127                 ESPHME(("<wkaround_skipped>"));
2128         } else {
2129                 unsigned long fcnt = sbus_readb(esp->eregs + ESP_FFLAGS) & ESP_FF_FBYTES;
2130
2131                 /* The HME stores bytes in multiples of 2 in the fifo. */
2132                 ESPHME(("hme_fifo[fcnt=%d", (int)fcnt));
2133                 while (fcnt) {
2134                         esp->hme_fifo_workaround_buffer[count++] =
2135                                 sbus_readb(esp->eregs + ESP_FDATA);
2136                         esp->hme_fifo_workaround_buffer[count++] =
2137                                 sbus_readb(esp->eregs + ESP_FDATA);
2138                         ESPHME(("<%02x,%02x>", esp->hme_fifo_workaround_buffer[count-2], esp->hme_fifo_workaround_buffer[count-1]));
2139                         fcnt--;
2140                 }
2141                 if (sbus_readb(esp->eregs + ESP_STATUS2) & ESP_STAT2_F1BYTE) {
2142                         ESPHME(("<poke_byte>"));
2143                         sbus_writeb(0, esp->eregs + ESP_FDATA);
2144                         esp->hme_fifo_workaround_buffer[count++] =
2145                                 sbus_readb(esp->eregs + ESP_FDATA);
2146                         ESPHME(("<%02x,0x00>", esp->hme_fifo_workaround_buffer[count-1]));
2147                         ESPHME(("CMD_FLUSH"));
2148                         esp_cmd(esp, ESP_CMD_FLUSH);
2149                 } else {
2150                         ESPHME(("no_xtra_byte"));
2151                 }
2152         }
2153         ESPHME(("wkarnd_cnt=%d]", (int)count));
2154         esp->hme_fifo_workaround_count = count;
2155 }
2156
2157 static inline void hme_fifo_push(struct esp *esp, u8 *bytes, u8 count)
2158 {
2159         esp_cmd(esp, ESP_CMD_FLUSH);
2160         while (count) {
2161                 u8 tmp = *bytes++;
2162                 sbus_writeb(tmp, esp->eregs + ESP_FDATA);
2163                 sbus_writeb(0, esp->eregs + ESP_FDATA);
2164                 count--;
2165         }
2166 }
2167
2168 /* We try to avoid some interrupts by jumping ahead and see if the ESP
2169  * has gotten far enough yet.  Hence the following.
2170  */
2171 static inline int skipahead1(struct esp *esp, Scsi_Cmnd *scp,
2172                              int prev_phase, int new_phase)
2173 {
2174         if (scp->SCp.sent_command != prev_phase)
2175                 return 0;
2176         if (ESP_IRQ_P(esp->dregs)) {
2177                 /* Yes, we are able to save an interrupt. */
2178                 if (esp->erev == fashme)
2179                         esp->sreg2 = sbus_readb(esp->eregs + ESP_STATUS2);
2180                 esp->sreg = (sbus_readb(esp->eregs + ESP_STATUS) & ~(ESP_STAT_INTR));
2181                 esp->ireg = sbus_readb(esp->eregs + ESP_INTRPT);
2182                 if (esp->erev == fashme) {
2183                         /* This chip is really losing. */
2184                         ESPHME(("HME["));
2185                         /* Must latch fifo before reading the interrupt
2186                          * register else garbage ends up in the FIFO
2187                          * which confuses the driver utterly.
2188                          * Happy Meal indeed....
2189                          */
2190                         ESPHME(("fifo_workaround]"));
2191                         if (!(esp->sreg2 & ESP_STAT2_FEMPTY) ||
2192                             (esp->sreg2 & ESP_STAT2_F1BYTE))
2193                                 hme_fifo_read(esp);
2194                 }
2195                 if (!(esp->ireg & ESP_INTR_SR))
2196                         return 0;
2197                 else
2198                         return do_reset_complete;
2199         }
2200         /* Ho hum, target is taking forever... */
2201         scp->SCp.sent_command = new_phase; /* so we don't recurse... */
2202         return do_intr_end;
2203 }
2204
2205 static inline int skipahead2(struct esp *esp, Scsi_Cmnd *scp,
2206                              int prev_phase1, int prev_phase2, int new_phase)
2207 {
2208         if (scp->SCp.sent_command != prev_phase1 &&
2209             scp->SCp.sent_command != prev_phase2)
2210                 return 0;
2211         if (ESP_IRQ_P(esp->dregs)) {
2212                 /* Yes, we are able to save an interrupt. */
2213                 if (esp->erev == fashme)
2214                         esp->sreg2 = sbus_readb(esp->eregs + ESP_STATUS2);
2215                 esp->sreg = (sbus_readb(esp->eregs + ESP_STATUS) & ~(ESP_STAT_INTR));
2216                 esp->ireg = sbus_readb(esp->eregs + ESP_INTRPT);
2217                 if (esp->erev == fashme) {
2218                         /* This chip is really losing. */
2219                         ESPHME(("HME["));
2220
2221                         /* Must latch fifo before reading the interrupt
2222                          * register else garbage ends up in the FIFO
2223                          * which confuses the driver utterly.
2224                          * Happy Meal indeed....
2225                          */
2226                         ESPHME(("fifo_workaround]"));
2227                         if (!(esp->sreg2 & ESP_STAT2_FEMPTY) ||
2228                             (esp->sreg2 & ESP_STAT2_F1BYTE))
2229                                 hme_fifo_read(esp);
2230                 }
2231                 if (!(esp->ireg & ESP_INTR_SR))
2232                         return 0;
2233                 else
2234                         return do_reset_complete;
2235         }
2236         /* Ho hum, target is taking forever... */
2237         scp->SCp.sent_command = new_phase; /* so we don't recurse... */
2238         return do_intr_end;
2239 }
2240
2241 /* Now some dma helpers. */
2242 static void dma_setup(struct esp *esp, __u32 addr, int count, int write)
2243 {
2244         u32 nreg = sbus_readl(esp->dregs + DMA_CSR);
2245
2246         if (write)
2247                 nreg |= DMA_ST_WRITE;
2248         else
2249                 nreg &= ~(DMA_ST_WRITE);
2250         nreg |= DMA_ENABLE;
2251         sbus_writel(nreg, esp->dregs + DMA_CSR);
2252         if (esp->dma->revision == dvmaesc1) {
2253                 /* This ESC gate array sucks! */
2254                 __u32 src = addr;
2255                 __u32 dest = src + count;
2256
2257                 if (dest & (PAGE_SIZE - 1))
2258                         count = PAGE_ALIGN(count);
2259                 sbus_writel(count, esp->dregs + DMA_COUNT);
2260         }
2261         sbus_writel(addr, esp->dregs + DMA_ADDR);
2262 }
2263
2264 static void dma_drain(struct esp *esp)
2265 {
2266         u32 tmp;
2267
2268         if (esp->dma->revision == dvmahme)
2269                 return;
2270         if ((tmp = sbus_readl(esp->dregs + DMA_CSR)) & DMA_FIFO_ISDRAIN) {
2271                 switch (esp->dma->revision) {
2272                 default:
2273                         tmp |= DMA_FIFO_STDRAIN;
2274                         sbus_writel(tmp, esp->dregs + DMA_CSR);
2275
2276                 case dvmarev3:
2277                 case dvmaesc1:
2278                         while (sbus_readl(esp->dregs + DMA_CSR) & DMA_FIFO_ISDRAIN)
2279                                 udelay(1);
2280                 };
2281         }
2282 }
2283
2284 static void dma_invalidate(struct esp *esp)
2285 {
2286         u32 tmp;
2287
2288         if (esp->dma->revision == dvmahme) {
2289                 sbus_writel(DMA_RST_SCSI, esp->dregs + DMA_CSR);
2290
2291                 esp->prev_hme_dmacsr = ((esp->prev_hme_dmacsr |
2292                                          (DMA_PARITY_OFF | DMA_2CLKS |
2293                                           DMA_SCSI_DISAB | DMA_INT_ENAB)) &
2294                                         ~(DMA_ST_WRITE | DMA_ENABLE));
2295
2296                 sbus_writel(0, esp->dregs + DMA_CSR);
2297                 sbus_writel(esp->prev_hme_dmacsr, esp->dregs + DMA_CSR);
2298
2299                 /* This is necessary to avoid having the SCSI channel
2300                  * engine lock up on us.
2301                  */
2302                 sbus_writel(0, esp->dregs + DMA_ADDR);
2303         } else {
2304                 while ((tmp = sbus_readl(esp->dregs + DMA_CSR)) & DMA_PEND_READ)
2305                         udelay(1);
2306
2307                 tmp &= ~(DMA_ENABLE | DMA_ST_WRITE | DMA_BCNT_ENAB);
2308                 tmp |= DMA_FIFO_INV;
2309                 sbus_writel(tmp, esp->dregs + DMA_CSR);
2310                 tmp &= ~DMA_FIFO_INV;
2311                 sbus_writel(tmp, esp->dregs + DMA_CSR);
2312         }
2313 }
2314
2315 static inline void dma_flashclear(struct esp *esp)
2316 {
2317         dma_drain(esp);
2318         dma_invalidate(esp);
2319 }
2320
2321 static int dma_can_transfer(struct esp *esp, Scsi_Cmnd *sp)
2322 {
2323         __u32 base, end, sz;
2324
2325         if (esp->dma->revision == dvmarev3) {
2326                 sz = sp->SCp.this_residual;
2327                 if (sz > 0x1000000)
2328                         sz = 0x1000000;
2329         } else {
2330                 base = ((__u32)((unsigned long)sp->SCp.ptr));
2331                 base &= (0x1000000 - 1);
2332                 end = (base + sp->SCp.this_residual);
2333                 if (end > 0x1000000)
2334                         end = 0x1000000;
2335                 sz = (end - base);
2336         }
2337         return sz;
2338 }
2339
2340 /* Misc. esp helper macros. */
2341 #define esp_setcount(__eregs, __cnt, __hme) \
2342         sbus_writeb(((__cnt)&0xff), (__eregs) + ESP_TCLOW); \
2343         sbus_writeb((((__cnt)>>8)&0xff), (__eregs) + ESP_TCMED); \
2344         if (__hme) { \
2345                 sbus_writeb((((__cnt)>>16)&0xff), (__eregs) + FAS_RLO); \
2346                 sbus_writeb(0, (__eregs) + FAS_RHI); \
2347         }
2348
2349 #define esp_getcount(__eregs, __hme) \
2350         ((sbus_readb((__eregs) + ESP_TCLOW)&0xff) | \
2351          ((sbus_readb((__eregs) + ESP_TCMED)&0xff) << 8) | \
2352          ((__hme) ? sbus_readb((__eregs) + FAS_RLO) << 16 : 0))
2353
2354 #define fcount(__esp) \
2355         (((__esp)->erev == fashme) ? \
2356           (__esp)->hme_fifo_workaround_count : \
2357           sbus_readb(((__esp)->eregs) + ESP_FFLAGS) & ESP_FF_FBYTES)
2358
2359 #define fnzero(__esp) \
2360         (((__esp)->erev == fashme) ? 0 : \
2361          sbus_readb(((__esp)->eregs) + ESP_FFLAGS) & ESP_FF_ONOTZERO)
2362
2363 /* XXX speculative nops unnecessary when continuing amidst a data phase
2364  * XXX even on esp100!!!  another case of flooding the bus with I/O reg
2365  * XXX writes...
2366  */
2367 #define esp_maybe_nop(__esp) \
2368         if ((__esp)->erev == esp100) \
2369                 esp_cmd((__esp), ESP_CMD_NULL)
2370
2371 #define sreg_to_dataphase(__sreg) \
2372         ((((__sreg) & ESP_STAT_PMASK) == ESP_DOP) ? in_dataout : in_datain)
2373
2374 /* The ESP100 when in synchronous data phase, can mistake a long final
2375  * REQ pulse from the target as an extra byte, it places whatever is on
2376  * the data lines into the fifo.  For now, we will assume when this
2377  * happens that the target is a bit quirky and we don't want to
2378  * be talking synchronously to it anyways.  Regardless, we need to
2379  * tell the ESP to eat the extraneous byte so that we can proceed
2380  * to the next phase.
2381  */
2382 static int esp100_sync_hwbug(struct esp *esp, Scsi_Cmnd *sp, int fifocnt)
2383 {
2384         /* Do not touch this piece of code. */
2385         if ((!(esp->erev == esp100)) ||
2386             (!(sreg_datainp((esp->sreg = sbus_readb(esp->eregs + ESP_STATUS))) &&
2387                !fifocnt) &&
2388              !(sreg_dataoutp(esp->sreg) && !fnzero(esp)))) {
2389                 if (sp->SCp.phase == in_dataout)
2390                         esp_cmd(esp, ESP_CMD_FLUSH);
2391                 return 0;
2392         } else {
2393                 /* Async mode for this guy. */
2394                 build_sync_nego_msg(esp, 0, 0);
2395
2396                 /* Ack the bogus byte, but set ATN first. */
2397                 esp_cmd(esp, ESP_CMD_SATN);
2398                 esp_cmd(esp, ESP_CMD_MOK);
2399                 return 1;
2400         }
2401 }
2402
2403 /* This closes the window during a selection with a reselect pending, because
2404  * we use DMA for the selection process the FIFO should hold the correct
2405  * contents if we get reselected during this process.  So we just need to
2406  * ack the possible illegal cmd interrupt pending on the esp100.
2407  */
2408 static inline int esp100_reconnect_hwbug(struct esp *esp)
2409 {
2410         u8 tmp;
2411
2412         if (esp->erev != esp100)
2413                 return 0;
2414         tmp = sbus_readb(esp->eregs + ESP_INTRPT);
2415         if (tmp & ESP_INTR_SR)
2416                 return 1;
2417         return 0;
2418 }
2419
2420 /* This verifies the BUSID bits during a reselection so that we know which
2421  * target is talking to us.
2422  */
2423 static inline int reconnect_target(struct esp *esp)
2424 {
2425         int it, me = esp->scsi_id_mask, targ = 0;
2426
2427         if (2 != fcount(esp))
2428                 return -1;
2429         if (esp->erev == fashme) {
2430                 /* HME does not latch it's own BUS ID bits during
2431                  * a reselection.  Also the target number is given
2432                  * as an unsigned char, not as a sole bit number
2433                  * like the other ESP's do.
2434                  * Happy Meal indeed....
2435                  */
2436                 targ = esp->hme_fifo_workaround_buffer[0];
2437         } else {
2438                 it = sbus_readb(esp->eregs + ESP_FDATA);
2439                 if (!(it & me))
2440                         return -1;
2441                 it &= ~me;
2442                 if (it & (it - 1))
2443                         return -1;
2444                 while (!(it & 1))
2445                         targ++, it >>= 1;
2446         }
2447         return targ;
2448 }
2449
2450 /* This verifies the identify from the target so that we know which lun is
2451  * being reconnected.
2452  */
2453 static inline int reconnect_lun(struct esp *esp)
2454 {
2455         int lun;
2456
2457         if ((esp->sreg & ESP_STAT_PMASK) != ESP_MIP)
2458                 return -1;
2459         if (esp->erev == fashme)
2460                 lun = esp->hme_fifo_workaround_buffer[1];
2461         else
2462                 lun = sbus_readb(esp->eregs + ESP_FDATA);
2463
2464         /* Yes, you read this correctly.  We report lun of zero
2465          * if we see parity error.  ESP reports parity error for
2466          * the lun byte, and this is the only way to hope to recover
2467          * because the target is connected.
2468          */
2469         if (esp->sreg & ESP_STAT_PERR)
2470                 return 0;
2471
2472         /* Check for illegal bits being set in the lun. */
2473         if ((lun & 0x40) || !(lun & 0x80))
2474                 return -1;
2475
2476         return lun & 7;
2477 }
2478
2479 /* This puts the driver in a state where it can revitalize a command that
2480  * is being continued due to reselection.
2481  */
2482 static inline void esp_connect(struct esp *esp, Scsi_Cmnd *sp)
2483 {
2484         struct esp_device *esp_dev = sp->device->hostdata;
2485
2486         if (esp->prev_soff  != esp_dev->sync_max_offset ||
2487             esp->prev_stp   != esp_dev->sync_min_period ||
2488             (esp->erev > esp100a &&
2489              esp->prev_cfg3 != esp->config3[sp->device->id])) {
2490                 esp->prev_soff = esp_dev->sync_max_offset;
2491                 esp->prev_stp = esp_dev->sync_min_period;
2492                 sbus_writeb(esp->prev_soff, esp->eregs + ESP_SOFF);
2493                 sbus_writeb(esp->prev_stp, esp->eregs + ESP_STP);
2494                 if (esp->erev > esp100a) {
2495                         esp->prev_cfg3 = esp->config3[sp->device->id];
2496                         sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
2497                 }
2498         }
2499         esp->current_SC = sp;
2500 }
2501
2502 /* This will place the current working command back into the issue queue
2503  * if we are to receive a reselection amidst a selection attempt.
2504  */
2505 static inline void esp_reconnect(struct esp *esp, Scsi_Cmnd *sp)
2506 {
2507         if (!esp->disconnected_SC)
2508                 ESPLOG(("esp%d: Weird, being reselected but disconnected "
2509                         "command queue is empty.\n", esp->esp_id));
2510         esp->snip = 0;
2511         esp->current_SC = 0;
2512         sp->SCp.phase = not_issued;
2513         append_SC(&esp->issue_SC, sp);
2514 }
2515
2516 /* Begin message in phase. */
2517 static int esp_do_msgin(struct esp *esp)
2518 {
2519         /* Must be very careful with the fifo on the HME */
2520         if ((esp->erev != fashme) ||
2521             !(sbus_readb(esp->eregs + ESP_STATUS2) & ESP_STAT2_FEMPTY))
2522                 esp_cmd(esp, ESP_CMD_FLUSH);
2523         esp_maybe_nop(esp);
2524         esp_cmd(esp, ESP_CMD_TI);
2525         esp->msgin_len = 1;
2526         esp->msgin_ctr = 0;
2527         esp_advance_phase(esp->current_SC, in_msgindone);
2528         return do_work_bus;
2529 }
2530
2531 /* This uses various DMA csr fields and the fifo flags count value to
2532  * determine how many bytes were successfully sent/received by the ESP.
2533  */
2534 static inline int esp_bytes_sent(struct esp *esp, int fifo_count)
2535 {
2536         int rval = sbus_readl(esp->dregs + DMA_ADDR) - esp->esp_command_dvma;
2537
2538         if (esp->dma->revision == dvmarev1)
2539                 rval -= (4 - ((sbus_readl(esp->dregs + DMA_CSR) & DMA_READ_AHEAD)>>11));
2540         return rval - fifo_count;
2541 }
2542
2543 static inline void advance_sg(Scsi_Cmnd *sp)
2544 {
2545         ++sp->SCp.buffer;
2546         --sp->SCp.buffers_residual;
2547         sp->SCp.this_residual = sg_dma_len(sp->SCp.buffer);
2548         sp->SCp.ptr = (char *)((unsigned long)sg_dma_address(sp->SCp.buffer));
2549 }
2550
2551 /* Please note that the way I've coded these routines is that I _always_
2552  * check for a disconnect during any and all information transfer
2553  * phases.  The SCSI standard states that the target _can_ cause a BUS
2554  * FREE condition by dropping all MSG/CD/IO/BSY signals.  Also note
2555  * that during information transfer phases the target controls every
2556  * change in phase, the only thing the initiator can do is "ask" for
2557  * a message out phase by driving ATN true.  The target can, and sometimes
2558  * will, completely ignore this request so we cannot assume anything when
2559  * we try to force a message out phase to abort/reset a target.  Most of
2560  * the time the target will eventually be nice and go to message out, so
2561  * we may have to hold on to our state about what we want to tell the target
2562  * for some period of time.
2563  */
2564
2565 /* I think I have things working here correctly.  Even partial transfers
2566  * within a buffer or sub-buffer should not upset us at all no matter
2567  * how bad the target and/or ESP fucks things up.
2568  */
2569 static int esp_do_data(struct esp *esp)
2570 {
2571         Scsi_Cmnd *SCptr = esp->current_SC;
2572         int thisphase, hmuch;
2573
2574         ESPDATA(("esp_do_data: "));
2575         esp_maybe_nop(esp);
2576         thisphase = sreg_to_dataphase(esp->sreg);
2577         esp_advance_phase(SCptr, thisphase);
2578         ESPDATA(("newphase<%s> ", (thisphase == in_datain) ? "DATAIN" : "DATAOUT"));
2579         hmuch = dma_can_transfer(esp, SCptr);
2580         if (hmuch > (64 * 1024) && (esp->erev != fashme))
2581                 hmuch = (64 * 1024);
2582         ESPDATA(("hmuch<%d> ", hmuch));
2583         esp->current_transfer_size = hmuch;
2584
2585         if (esp->erev == fashme) {
2586                 u32 tmp = esp->prev_hme_dmacsr;
2587
2588                 /* Always set the ESP count registers first. */
2589                 esp_setcount(esp->eregs, hmuch, 1);
2590
2591                 /* Get the DMA csr computed. */
2592                 tmp |= (DMA_SCSI_DISAB | DMA_ENABLE);
2593                 if (thisphase == in_datain)
2594                         tmp |= DMA_ST_WRITE;
2595                 else
2596                         tmp &= ~(DMA_ST_WRITE);
2597                 esp->prev_hme_dmacsr = tmp;
2598
2599                 ESPDATA(("DMA|TI --> do_intr_end\n"));
2600                 if (thisphase == in_datain) {
2601                         sbus_writel(hmuch, esp->dregs + DMA_COUNT);
2602                         esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
2603                 } else {
2604                         esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
2605                         sbus_writel(hmuch, esp->dregs + DMA_COUNT);
2606                 }
2607                 sbus_writel((__u32)((unsigned long)SCptr->SCp.ptr), esp->dregs+DMA_ADDR);
2608                 sbus_writel(esp->prev_hme_dmacsr, esp->dregs + DMA_CSR);
2609         } else {
2610                 esp_setcount(esp->eregs, hmuch, 0);
2611                 dma_setup(esp, ((__u32)((unsigned long)SCptr->SCp.ptr)),
2612                           hmuch, (thisphase == in_datain));
2613                 ESPDATA(("DMA|TI --> do_intr_end\n"));
2614                 esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
2615         }
2616         return do_intr_end;
2617 }
2618
2619 /* See how successful the data transfer was. */
2620 static int esp_do_data_finale(struct esp *esp)
2621 {
2622         Scsi_Cmnd *SCptr = esp->current_SC;
2623         struct esp_device *esp_dev = SCptr->device->hostdata;
2624         int bogus_data = 0, bytes_sent = 0, fifocnt, ecount = 0;
2625
2626         ESPDATA(("esp_do_data_finale: "));
2627
2628         if (SCptr->SCp.phase == in_datain) {
2629                 if (esp->sreg & ESP_STAT_PERR) {
2630                         /* Yuck, parity error.  The ESP asserts ATN
2631                          * so that we can go to message out phase
2632                          * immediately and inform the target that
2633                          * something bad happened.
2634                          */
2635                         ESPLOG(("esp%d: data bad parity detected.\n",
2636                                 esp->esp_id));
2637                         esp->cur_msgout[0] = INITIATOR_ERROR;
2638                         esp->msgout_len = 1;
2639                 }
2640                 dma_drain(esp);
2641         }
2642         dma_invalidate(esp);
2643
2644         /* This could happen for the above parity error case. */
2645         if (esp->ireg != ESP_INTR_BSERV) {
2646                 /* Please go to msgout phase, please please please... */
2647                 ESPLOG(("esp%d: !BSERV after data, probably to msgout\n",
2648                         esp->esp_id));
2649                 return esp_do_phase_determine(esp);
2650         }       
2651
2652         /* Check for partial transfers and other horrible events.
2653          * Note, here we read the real fifo flags register even
2654          * on HME broken adapters because we skip the HME fifo
2655          * workaround code in esp_handle() if we are doing data
2656          * phase things.  We don't want to fuck directly with
2657          * the fifo like that, especially if doing synchronous
2658          * transfers!  Also, will need to double the count on
2659          * HME if we are doing wide transfers, as the HME fifo
2660          * will move and count 16-bit quantities during wide data.
2661          * SMCC _and_ Qlogic can both bite me.
2662          */
2663         fifocnt = (sbus_readb(esp->eregs + ESP_FFLAGS) & ESP_FF_FBYTES);
2664         if (esp->erev != fashme)
2665                 ecount = esp_getcount(esp->eregs, 0);
2666         bytes_sent = esp->current_transfer_size;
2667
2668         ESPDATA(("trans_sz(%d), ", bytes_sent));
2669         if (esp->erev == fashme) {
2670                 if (!(esp->sreg & ESP_STAT_TCNT)) {
2671                         ecount = esp_getcount(esp->eregs, 1);
2672                         bytes_sent -= ecount;
2673                 }
2674
2675                 /* Always subtract any cruft remaining in the FIFO. */
2676                 if (esp->prev_cfg3 & ESP_CONFIG3_EWIDE)
2677                         fifocnt <<= 1;
2678                 if (SCptr->SCp.phase == in_dataout)
2679                         bytes_sent -= fifocnt;
2680
2681                 /* I have an IBM disk which exhibits the following
2682                  * behavior during writes to it.  It disconnects in
2683                  * the middle of a partial transfer, the current sglist
2684                  * buffer is 1024 bytes, the disk stops data transfer
2685                  * at 512 bytes.
2686                  *
2687                  * However the FAS366 reports that 32 more bytes were
2688                  * transferred than really were.  This is precisely
2689                  * the size of a fully loaded FIFO in wide scsi mode.
2690                  * The FIFO state recorded indicates that it is empty.
2691                  *
2692                  * I have no idea if this is a bug in the FAS366 chip
2693                  * or a bug in the firmware on this IBM disk.  In any
2694                  * event the following seems to be a good workaround.  -DaveM
2695                  */
2696                 if (bytes_sent != esp->current_transfer_size &&
2697                     SCptr->SCp.phase == in_dataout) {
2698                         int mask = (64 - 1);
2699
2700                         if ((esp->prev_cfg3 & ESP_CONFIG3_EWIDE) == 0)
2701                                 mask >>= 1;
2702
2703                         if (bytes_sent & mask)
2704                                 bytes_sent -= (bytes_sent & mask);
2705                 }
2706         } else {
2707                 if (!(esp->sreg & ESP_STAT_TCNT))
2708                         bytes_sent -= ecount;
2709                 if (SCptr->SCp.phase == in_dataout)
2710                         bytes_sent -= fifocnt;
2711         }
2712
2713         ESPDATA(("bytes_sent(%d), ", bytes_sent));
2714
2715         /* If we were in synchronous mode, check for peculiarities. */
2716         if (esp->erev == fashme) {
2717                 if (esp_dev->sync_max_offset) {
2718                         if (SCptr->SCp.phase == in_dataout)
2719                                 esp_cmd(esp, ESP_CMD_FLUSH);
2720                 } else {
2721                         esp_cmd(esp, ESP_CMD_FLUSH);
2722                 }
2723         } else {
2724                 if (esp_dev->sync_max_offset)
2725                         bogus_data = esp100_sync_hwbug(esp, SCptr, fifocnt);
2726                 else
2727                         esp_cmd(esp, ESP_CMD_FLUSH);
2728         }
2729
2730         /* Until we are sure of what has happened, we are certainly
2731          * in the dark.
2732          */
2733         esp_advance_phase(SCptr, in_the_dark);
2734
2735         if (bytes_sent < 0) {
2736                 /* I've seen this happen due to lost state in this
2737                  * driver.  No idea why it happened, but allowing
2738                  * this value to be negative caused things to
2739                  * lock up.  This allows greater chance of recovery.
2740                  * In fact every time I've seen this, it has been
2741                  * a driver bug without question.
2742                  */
2743                 ESPLOG(("esp%d: yieee, bytes_sent < 0!\n", esp->esp_id));
2744                 ESPLOG(("esp%d: csz=%d fifocount=%d ecount=%d\n",
2745                         esp->esp_id,
2746                         esp->current_transfer_size, fifocnt, ecount));
2747                 ESPLOG(("esp%d: use_sg=%d ptr=%p this_residual=%d\n",
2748                         esp->esp_id,
2749                         SCptr->use_sg, SCptr->SCp.ptr, SCptr->SCp.this_residual));
2750                 ESPLOG(("esp%d: Forcing async for target %d\n", esp->esp_id, 
2751                         SCptr->device->id));
2752                 SCptr->device->borken = 1;
2753                 esp_dev->sync = 0;
2754                 bytes_sent = 0;
2755         }
2756
2757         /* Update the state of our transfer. */
2758         SCptr->SCp.ptr += bytes_sent;
2759         SCptr->SCp.this_residual -= bytes_sent;
2760         if (SCptr->SCp.this_residual < 0) {
2761                 /* shit */
2762                 ESPLOG(("esp%d: Data transfer overrun.\n", esp->esp_id));
2763                 SCptr->SCp.this_residual = 0;
2764         }
2765
2766         /* Maybe continue. */
2767         if (!bogus_data) {
2768                 ESPDATA(("!bogus_data, "));
2769
2770                 /* NO MATTER WHAT, we advance the scatterlist,
2771                  * if the target should decide to disconnect
2772                  * in between scatter chunks (which is common)
2773                  * we could die horribly!  I used to have the sg
2774                  * advance occur only if we are going back into
2775                  * (or are staying in) a data phase, you can
2776                  * imagine the hell I went through trying to
2777                  * figure this out.
2778                  */
2779                 if (SCptr->use_sg && !SCptr->SCp.this_residual)
2780                         advance_sg(SCptr);
2781                 if (sreg_datainp(esp->sreg) || sreg_dataoutp(esp->sreg)) {
2782                         ESPDATA(("to more data\n"));
2783                         return esp_do_data(esp);
2784                 }
2785                 ESPDATA(("to new phase\n"));
2786                 return esp_do_phase_determine(esp);
2787         }
2788         /* Bogus data, just wait for next interrupt. */
2789         ESPLOG(("esp%d: bogus_data during end of data phase\n",
2790                 esp->esp_id));
2791         return do_intr_end;
2792 }
2793
2794 /* We received a non-good status return at the end of
2795  * running a SCSI command.  This is used to decide if
2796  * we should clear our synchronous transfer state for
2797  * such a device when that happens.
2798  *
2799  * The idea is that when spinning up a disk or rewinding
2800  * a tape, we don't want to go into a loop re-negotiating
2801  * synchronous capabilities over and over.
2802  */
2803 static int esp_should_clear_sync(Scsi_Cmnd *sp)
2804 {
2805         u8 cmd1 = sp->cmnd[0];
2806         u8 cmd2 = sp->data_cmnd[0];
2807
2808         /* These cases are for spinning up a disk and
2809          * waiting for that spinup to complete.
2810          */
2811         if (cmd1 == START_STOP ||
2812             cmd2 == START_STOP)
2813                 return 0;
2814
2815         if (cmd1 == TEST_UNIT_READY ||
2816             cmd2 == TEST_UNIT_READY)
2817                 return 0;
2818
2819         /* One more special case for SCSI tape drives,
2820          * this is what is used to probe the device for
2821          * completion of a rewind or tape load operation.
2822          */
2823         if (sp->device->type == TYPE_TAPE) {
2824                 if (cmd1 == MODE_SENSE ||
2825                     cmd2 == MODE_SENSE)
2826                         return 0;
2827         }
2828
2829         return 1;
2830 }
2831
2832 /* Either a command is completing or a target is dropping off the bus
2833  * to continue the command in the background so we can do other work.
2834  */
2835 static int esp_do_freebus(struct esp *esp)
2836 {
2837         Scsi_Cmnd *SCptr = esp->current_SC;
2838         struct esp_device *esp_dev = SCptr->device->hostdata;
2839         int rval;
2840
2841         rval = skipahead2(esp, SCptr, in_status, in_msgindone, in_freeing);
2842         if (rval)
2843                 return rval;
2844         if (esp->ireg != ESP_INTR_DC) {
2845                 ESPLOG(("esp%d: Target will not disconnect\n", esp->esp_id));
2846                 return do_reset_bus; /* target will not drop BSY... */
2847         }
2848         esp->msgout_len = 0;
2849         esp->prevmsgout = NOP;
2850         if (esp->prevmsgin == COMMAND_COMPLETE) {
2851                 /* Normal end of nexus. */
2852                 if (esp->disconnected_SC || (esp->erev == fashme))
2853                         esp_cmd(esp, ESP_CMD_ESEL);
2854
2855                 if (SCptr->SCp.Status != GOOD &&
2856                     SCptr->SCp.Status != CONDITION_GOOD &&
2857                     ((1<<SCptr->device->id) & esp->targets_present) &&
2858                     esp_dev->sync &&
2859                     esp_dev->sync_max_offset) {
2860                         /* SCSI standard says that the synchronous capabilities
2861                          * should be renegotiated at this point.  Most likely
2862                          * we are about to request sense from this target
2863                          * in which case we want to avoid using sync
2864                          * transfers until we are sure of the current target
2865                          * state.
2866                          */
2867                         ESPMISC(("esp: Status <%d> for target %d lun %d\n",
2868                                  SCptr->SCp.Status, SCptr->device->id, SCptr->device->lun));
2869
2870                         /* But don't do this when spinning up a disk at
2871                          * boot time while we poll for completion as it
2872                          * fills up the console with messages.  Also, tapes
2873                          * can report not ready many times right after
2874                          * loading up a tape.
2875                          */
2876                         if (esp_should_clear_sync(SCptr) != 0)
2877                                 esp_dev->sync = 0;
2878                 }
2879                 ESPDISC(("F<%02x,%02x>", SCptr->device->id, SCptr->device->lun));
2880                 esp_done(esp, ((SCptr->SCp.Status & 0xff) |
2881                                ((SCptr->SCp.Message & 0xff)<<8) |
2882                                (DID_OK << 16)));
2883         } else if (esp->prevmsgin == DISCONNECT) {
2884                 /* Normal disconnect. */
2885                 esp_cmd(esp, ESP_CMD_ESEL);
2886                 ESPDISC(("D<%02x,%02x>", SCptr->device->id, SCptr->device->lun));
2887                 append_SC(&esp->disconnected_SC, SCptr);
2888                 esp->current_SC = NULL;
2889                 if (esp->issue_SC)
2890                         esp_exec_cmd(esp);
2891         } else {
2892                 /* Driver bug, we do not expect a disconnect here
2893                  * and should not have advanced the state engine
2894                  * to in_freeing.
2895                  */
2896                 ESPLOG(("esp%d: last msg not disc and not cmd cmplt.\n",
2897                         esp->esp_id));
2898                 return do_reset_bus;
2899         }
2900         return do_intr_end;
2901 }
2902
2903 /* When a reselect occurs, and we cannot find the command to
2904  * reconnect to in our queues, we do this.
2905  */
2906 static int esp_bad_reconnect(struct esp *esp)
2907 {
2908         Scsi_Cmnd *sp;
2909
2910         ESPLOG(("esp%d: Eieeee, reconnecting unknown command!\n",
2911                 esp->esp_id));
2912         ESPLOG(("QUEUE DUMP\n"));
2913         sp = esp->issue_SC;
2914         ESPLOG(("esp%d: issue_SC[", esp->esp_id));
2915         while (sp) {
2916                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2917                 sp = (Scsi_Cmnd *) sp->host_scribble;
2918         }
2919         ESPLOG(("]\n"));
2920         sp = esp->current_SC;
2921         ESPLOG(("esp%d: current_SC[", esp->esp_id));
2922         if (sp)
2923                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2924         else
2925                 ESPLOG(("<NULL>"));
2926         ESPLOG(("]\n"));
2927         sp = esp->disconnected_SC;
2928         ESPLOG(("esp%d: disconnected_SC[", esp->esp_id));
2929         while (sp) {
2930                 ESPLOG(("<%02x,%02x>", sp->device->id, sp->device->lun));
2931                 sp = (Scsi_Cmnd *) sp->host_scribble;
2932         }
2933         ESPLOG(("]\n"));
2934         return do_reset_bus;
2935 }
2936
2937 /* Do the needy when a target tries to reconnect to us. */
2938 static int esp_do_reconnect(struct esp *esp)
2939 {
2940         int lun, target;
2941         Scsi_Cmnd *SCptr;
2942
2943         /* Check for all bogus conditions first. */
2944         target = reconnect_target(esp);
2945         if (target < 0) {
2946                 ESPDISC(("bad bus bits\n"));
2947                 return do_reset_bus;
2948         }
2949         lun = reconnect_lun(esp);
2950         if (lun < 0) {
2951                 ESPDISC(("target=%2x, bad identify msg\n", target));
2952                 return do_reset_bus;
2953         }
2954
2955         /* Things look ok... */
2956         ESPDISC(("R<%02x,%02x>", target, lun));
2957
2958         /* Must not flush FIFO or DVMA on HME. */
2959         if (esp->erev != fashme) {
2960                 esp_cmd(esp, ESP_CMD_FLUSH);
2961                 if (esp100_reconnect_hwbug(esp))
2962                         return do_reset_bus;
2963                 esp_cmd(esp, ESP_CMD_NULL);
2964         }
2965
2966         SCptr = remove_SC(&esp->disconnected_SC, (u8) target, (u8) lun);
2967         if (!SCptr)
2968                 return esp_bad_reconnect(esp);
2969
2970         esp_connect(esp, SCptr);
2971         esp_cmd(esp, ESP_CMD_MOK);
2972
2973         if (esp->erev == fashme)
2974                 sbus_writeb(((SCptr->device->id & 0xf) |
2975                              (ESP_BUSID_RESELID | ESP_BUSID_CTR32BIT)),
2976                             esp->eregs + ESP_BUSID);
2977
2978         /* Reconnect implies a restore pointers operation. */
2979         esp_restore_pointers(esp, SCptr);
2980
2981         esp->snip = 0;
2982         esp_advance_phase(SCptr, in_the_dark);
2983         return do_intr_end;
2984 }
2985
2986 /* End of NEXUS (hopefully), pick up status + message byte then leave if
2987  * all goes well.
2988  */
2989 static int esp_do_status(struct esp *esp)
2990 {
2991         Scsi_Cmnd *SCptr = esp->current_SC;
2992         int intr, rval;
2993
2994         rval = skipahead1(esp, SCptr, in_the_dark, in_status);
2995         if (rval)
2996                 return rval;
2997         intr = esp->ireg;
2998         ESPSTAT(("esp_do_status: "));
2999         if (intr != ESP_INTR_DC) {
3000                 int message_out = 0; /* for parity problems */
3001
3002                 /* Ack the message. */
3003                 ESPSTAT(("ack msg, "));
3004                 esp_cmd(esp, ESP_CMD_MOK);
3005
3006                 if (esp->erev != fashme) {
3007                         dma_flashclear(esp);
3008
3009                         /* Wait till the first bits settle. */
3010                         while (esp->esp_command[0] == 0xff)
3011                                 udelay(1);
3012                 } else {
3013                         esp->esp_command[0] = esp->hme_fifo_workaround_buffer[0];
3014                         esp->esp_command[1] = esp->hme_fifo_workaround_buffer[1];
3015                 }
3016
3017                 ESPSTAT(("got something, "));
3018                 /* ESP chimes in with one of
3019                  *
3020                  * 1) function done interrupt:
3021                  *      both status and message in bytes
3022                  *      are available
3023                  *
3024                  * 2) bus service interrupt:
3025                  *      only status byte was acquired
3026                  *
3027                  * 3) Anything else:
3028                  *      can't happen, but we test for it
3029                  *      anyways
3030                  *
3031                  * ALSO: If bad parity was detected on either
3032                  *       the status _or_ the message byte then
3033                  *       the ESP has asserted ATN on the bus
3034                  *       and we must therefore wait for the
3035                  *       next phase change.
3036                  */
3037                 if (intr & ESP_INTR_FDONE) {
3038                         /* We got it all, hallejulia. */
3039                         ESPSTAT(("got both, "));
3040                         SCptr->SCp.Status = esp->esp_command[0];
3041                         SCptr->SCp.Message = esp->esp_command[1];
3042                         esp->prevmsgin = SCptr->SCp.Message;
3043                         esp->cur_msgin[0] = SCptr->SCp.Message;
3044                         if (esp->sreg & ESP_STAT_PERR) {
3045                                 /* There was bad parity for the
3046                                  * message byte, the status byte
3047                                  * was ok.
3048                                  */
3049                                 message_out = MSG_PARITY_ERROR;
3050                         }
3051                 } else if (intr == ESP_INTR_BSERV) {
3052                         /* Only got status byte. */
3053                         ESPLOG(("esp%d: got status only, ", esp->esp_id));
3054                         if (!(esp->sreg & ESP_STAT_PERR)) {
3055                                 SCptr->SCp.Status = esp->esp_command[0];
3056                                 SCptr->SCp.Message = 0xff;
3057                         } else {
3058                                 /* The status byte had bad parity.
3059                                  * we leave the scsi_pointer Status
3060                                  * field alone as we set it to a default
3061                                  * of CHECK_CONDITION in esp_queue.
3062                                  */
3063                                 message_out = INITIATOR_ERROR;
3064                         }
3065                 } else {
3066                         /* This shouldn't happen ever. */
3067                         ESPSTAT(("got bolixed\n"));
3068                         esp_advance_phase(SCptr, in_the_dark);
3069                         return esp_do_phase_determine(esp);
3070                 }
3071
3072                 if (!message_out) {
3073                         ESPSTAT(("status=%2x msg=%2x, ", SCptr->SCp.Status,
3074                                 SCptr->SCp.Message));
3075                         if (SCptr->SCp.Message == COMMAND_COMPLETE) {
3076                                 ESPSTAT(("and was COMMAND_COMPLETE\n"));
3077                                 esp_advance_phase(SCptr, in_freeing);
3078                                 return esp_do_freebus(esp);
3079                         } else {
3080                                 ESPLOG(("esp%d: and _not_ COMMAND_COMPLETE\n",
3081                                         esp->esp_id));
3082                                 esp->msgin_len = esp->msgin_ctr = 1;
3083                                 esp_advance_phase(SCptr, in_msgindone);
3084                                 return esp_do_msgindone(esp);
3085                         }
3086                 } else {
3087                         /* With luck we'll be able to let the target
3088                          * know that bad parity happened, it will know
3089                          * which byte caused the problems and send it
3090                          * again.  For the case where the status byte
3091                          * receives bad parity, I do not believe most
3092                          * targets recover very well.  We'll see.
3093                          */
3094                         ESPLOG(("esp%d: bad parity somewhere mout=%2x\n",
3095                                 esp->esp_id, message_out));
3096                         esp->cur_msgout[0] = message_out;
3097                         esp->msgout_len = esp->msgout_ctr = 1;
3098                         esp_advance_phase(SCptr, in_the_dark);
3099                         return esp_do_phase_determine(esp);
3100                 }
3101         } else {
3102                 /* If we disconnect now, all hell breaks loose. */
3103                 ESPLOG(("esp%d: whoops, disconnect\n", esp->esp_id));
3104                 esp_advance_phase(SCptr, in_the_dark);
3105                 return esp_do_phase_determine(esp);
3106         }
3107 }
3108
3109 static int esp_enter_status(struct esp *esp)
3110 {
3111         u8 thecmd = ESP_CMD_ICCSEQ;
3112
3113         esp_cmd(esp, ESP_CMD_FLUSH);
3114         if (esp->erev != fashme) {
3115                 u32 tmp;
3116
3117                 esp->esp_command[0] = esp->esp_command[1] = 0xff;
3118                 sbus_writeb(2, esp->eregs + ESP_TCLOW);
3119                 sbus_writeb(0, esp->eregs + ESP_TCMED);
3120                 tmp = sbus_readl(esp->dregs + DMA_CSR);
3121                 tmp |= (DMA_ST_WRITE | DMA_ENABLE);
3122                 sbus_writel(tmp, esp->dregs + DMA_CSR);
3123                 if (esp->dma->revision == dvmaesc1)
3124                         sbus_writel(0x100, esp->dregs + DMA_COUNT);
3125                 sbus_writel(esp->esp_command_dvma, esp->dregs + DMA_ADDR);
3126                 thecmd |= ESP_CMD_DMA;
3127         }
3128         esp_cmd(esp, thecmd);
3129         esp_advance_phase(esp->current_SC, in_status);
3130
3131         return esp_do_status(esp);
3132 }
3133
3134 static int esp_disconnect_amidst_phases(struct esp *esp)
3135 {
3136         Scsi_Cmnd *sp = esp->current_SC;
3137         struct esp_device *esp_dev = sp->device->hostdata;
3138
3139         /* This means real problems if we see this
3140          * here.  Unless we were actually trying
3141          * to force the device to abort/reset.
3142          */
3143         ESPLOG(("esp%d Disconnect amidst phases, ", esp->esp_id));
3144         ESPLOG(("pphase<%s> cphase<%s>, ",
3145                 phase_string(sp->SCp.phase),
3146                 phase_string(sp->SCp.sent_command)));
3147
3148         if (esp->disconnected_SC != NULL || (esp->erev == fashme))
3149                 esp_cmd(esp, ESP_CMD_ESEL);
3150
3151         switch (esp->cur_msgout[0]) {
3152         default:
3153                 /* We didn't expect this to happen at all. */
3154                 ESPLOG(("device is bolixed\n"));
3155                 esp_advance_phase(sp, in_tgterror);
3156                 esp_done(esp, (DID_ERROR << 16));
3157                 break;
3158
3159         case BUS_DEVICE_RESET:
3160                 ESPLOG(("device reset successful\n"));
3161                 esp_dev->sync_max_offset = 0;
3162                 esp_dev->sync_min_period = 0;
3163                 esp_dev->sync = 0;
3164                 esp_advance_phase(sp, in_resetdev);
3165                 esp_done(esp, (DID_RESET << 16));
3166                 break;
3167
3168         case ABORT:
3169                 ESPLOG(("device abort successful\n"));
3170                 esp_advance_phase(sp, in_abortone);
3171                 esp_done(esp, (DID_ABORT << 16));
3172                 break;
3173
3174         };
3175         return do_intr_end;
3176 }
3177
3178 static int esp_enter_msgout(struct esp *esp)
3179 {
3180         esp_advance_phase(esp->current_SC, in_msgout);
3181         return esp_do_msgout(esp);
3182 }
3183
3184 static int esp_enter_msgin(struct esp *esp)
3185 {
3186         esp_advance_phase(esp->current_SC, in_msgin);
3187         return esp_do_msgin(esp);
3188 }
3189
3190 static int esp_enter_cmd(struct esp *esp)
3191 {
3192         esp_advance_phase(esp->current_SC, in_cmdbegin);
3193         return esp_do_cmdbegin(esp);
3194 }
3195
3196 static int esp_enter_badphase(struct esp *esp)
3197 {
3198         ESPLOG(("esp%d: Bizarre bus phase %2x.\n", esp->esp_id,
3199                 esp->sreg & ESP_STAT_PMASK));
3200         return do_reset_bus;
3201 }
3202
3203 typedef int (*espfunc_t)(struct esp *);
3204
3205 static espfunc_t phase_vector[] = {
3206         esp_do_data,            /* ESP_DOP */
3207         esp_do_data,            /* ESP_DIP */
3208         esp_enter_cmd,          /* ESP_CMDP */
3209         esp_enter_status,       /* ESP_STATP */
3210         esp_enter_badphase,     /* ESP_STAT_PMSG */
3211         esp_enter_badphase,     /* ESP_STAT_PMSG | ESP_STAT_PIO */
3212         esp_enter_msgout,       /* ESP_MOP */
3213         esp_enter_msgin,        /* ESP_MIP */
3214 };
3215
3216 /* The target has control of the bus and we have to see where it has
3217  * taken us.
3218  */
3219 static int esp_do_phase_determine(struct esp *esp)
3220 {
3221         if ((esp->ireg & ESP_INTR_DC) != 0)
3222                 return esp_disconnect_amidst_phases(esp);
3223         return phase_vector[esp->sreg & ESP_STAT_PMASK](esp);
3224 }
3225
3226 /* First interrupt after exec'ing a cmd comes here. */
3227 static int esp_select_complete(struct esp *esp)
3228 {
3229         Scsi_Cmnd *SCptr = esp->current_SC;
3230         struct esp_device *esp_dev = SCptr->device->hostdata;
3231         int cmd_bytes_sent, fcnt;
3232
3233         if (esp->erev != fashme)
3234                 esp->seqreg = (sbus_readb(esp->eregs + ESP_SSTEP) & ESP_STEP_VBITS);
3235
3236         if (esp->erev == fashme)
3237                 fcnt = esp->hme_fifo_workaround_count;
3238         else
3239                 fcnt = (sbus_readb(esp->eregs + ESP_FFLAGS) & ESP_FF_FBYTES);
3240
3241         cmd_bytes_sent = esp_bytes_sent(esp, fcnt);
3242         dma_invalidate(esp);
3243
3244         /* Let's check to see if a reselect happened
3245          * while we we're trying to select.  This must
3246          * be checked first.
3247          */
3248         if (esp->ireg == (ESP_INTR_RSEL | ESP_INTR_FDONE)) {
3249                 esp_reconnect(esp, SCptr);
3250                 return esp_do_reconnect(esp);
3251         }
3252
3253         /* Looks like things worked, we should see a bus service &
3254          * a function complete interrupt at this point.  Note we
3255          * are doing a direct comparison because we don't want to
3256          * be fooled into thinking selection was successful if
3257          * ESP_INTR_DC is set, see below.
3258          */
3259         if (esp->ireg == (ESP_INTR_FDONE | ESP_INTR_BSERV)) {
3260                 /* target speaks... */
3261                 esp->targets_present |= (1<<SCptr->device->id);
3262
3263                 /* What if the target ignores the sdtr? */
3264                 if (esp->snip)
3265                         esp_dev->sync = 1;
3266
3267                 /* See how far, if at all, we got in getting
3268                  * the information out to the target.
3269                  */
3270                 switch (esp->seqreg) {
3271                 default:
3272
3273                 case ESP_STEP_ASEL:
3274                         /* Arbitration won, target selected, but
3275                          * we are in some phase which is not command
3276                          * phase nor is it message out phase.
3277                          *
3278                          * XXX We've confused the target, obviously.
3279                          * XXX So clear it's state, but we also end
3280                          * XXX up clearing everyone elses.  That isn't
3281                          * XXX so nice.  I'd like to just reset this
3282                          * XXX target, but if I cannot even get it's
3283                          * XXX attention and finish selection to talk
3284                          * XXX to it, there is not much more I can do.
3285                          * XXX If we have a loaded bus we're going to
3286                          * XXX spend the next second or so renegotiating
3287                          * XXX for synchronous transfers.
3288                          */
3289                         ESPLOG(("esp%d: STEP_ASEL for tgt %d\n",
3290                                 esp->esp_id, SCptr->device->id));
3291
3292                 case ESP_STEP_SID:
3293                         /* Arbitration won, target selected, went
3294                          * to message out phase, sent one message
3295                          * byte, then we stopped.  ATN is asserted
3296                          * on the SCSI bus and the target is still
3297                          * there hanging on.  This is a legal
3298                          * sequence step if we gave the ESP a select
3299                          * and stop command.
3300                          *
3301                          * XXX See above, I could set the borken flag
3302                          * XXX in the device struct and retry the
3303                          * XXX command.  But would that help for
3304                          * XXX tagged capable targets?
3305                          */
3306
3307                 case ESP_STEP_NCMD:
3308                         /* Arbitration won, target selected, maybe
3309                          * sent the one message byte in message out
3310                          * phase, but we did not go to command phase
3311                          * in the end.  Actually, we could have sent
3312                          * only some of the message bytes if we tried
3313                          * to send out the entire identify and tag
3314                          * message using ESP_CMD_SA3.
3315                          */
3316                         cmd_bytes_sent = 0;
3317                         break;
3318
3319                 case ESP_STEP_PPC:
3320                         /* No, not the powerPC pinhead.  Arbitration
3321                          * won, all message bytes sent if we went to
3322                          * message out phase, went to command phase
3323                          * but only part of the command was sent.
3324                          *
3325                          * XXX I've seen this, but usually in conjunction
3326                          * XXX with a gross error which appears to have
3327                          * XXX occurred between the time I told the
3328                          * XXX ESP to arbitrate and when I got the
3329                          * XXX interrupt.  Could I have misloaded the
3330                          * XXX command bytes into the fifo?  Actually,
3331                          * XXX I most likely missed a phase, and therefore
3332                          * XXX went into never never land and didn't even
3333                          * XXX know it.  That was the old driver though.
3334                          * XXX What is even more peculiar is that the ESP
3335                          * XXX showed the proper function complete and
3336                          * XXX bus service bits in the interrupt register.
3337                          */
3338
3339                 case ESP_STEP_FINI4:
3340                 case ESP_STEP_FINI5:
3341                 case ESP_STEP_FINI6:
3342                 case ESP_STEP_FINI7:
3343                         /* Account for the identify message */
3344                         if (SCptr->SCp.phase == in_slct_norm)
3345                                 cmd_bytes_sent -= 1;
3346                 };
3347
3348                 if (esp->erev != fashme)
3349                         esp_cmd(esp, ESP_CMD_NULL);
3350
3351                 /* Be careful, we could really get fucked during synchronous
3352                  * data transfers if we try to flush the fifo now.
3353                  */
3354                 if ((esp->erev != fashme) && /* not a Happy Meal and... */
3355                     !fcnt && /* Fifo is empty and... */
3356                     /* either we are not doing synchronous transfers or... */
3357                     (!esp_dev->sync_max_offset ||
3358                      /* We are not going into data in phase. */
3359                      ((esp->sreg & ESP_STAT_PMASK) != ESP_DIP)))
3360                         esp_cmd(esp, ESP_CMD_FLUSH); /* flush is safe */
3361
3362                 /* See how far we got if this is not a slow command. */
3363                 if (!esp->esp_slowcmd) {
3364                         if (cmd_bytes_sent < 0)
3365                                 cmd_bytes_sent = 0;
3366                         if (cmd_bytes_sent != SCptr->cmd_len) {
3367                                 /* Crapola, mark it as a slowcmd
3368                                  * so that we have some chance of
3369                                  * keeping the command alive with
3370                                  * good luck.
3371                                  *
3372                                  * XXX Actually, if we didn't send it all
3373                                  * XXX this means either we didn't set things
3374                                  * XXX up properly (driver bug) or the target
3375                                  * XXX or the ESP detected parity on one of
3376                                  * XXX the command bytes.  This makes much
3377                                  * XXX more sense, and therefore this code
3378                                  * XXX should be changed to send out a
3379                                  * XXX parity error message or if the status
3380                                  * XXX register shows no parity error then
3381                                  * XXX just expect the target to bring the
3382                                  * XXX bus into message in phase so that it
3383                                  * XXX can send us the parity error message.
3384                                  * XXX SCSI sucks...
3385                                  */
3386                                 esp->esp_slowcmd = 1;
3387                                 esp->esp_scmdp = &(SCptr->cmnd[cmd_bytes_sent]);
3388                                 esp->esp_scmdleft = (SCptr->cmd_len - cmd_bytes_sent);
3389                         }
3390                 }
3391
3392                 /* Now figure out where we went. */
3393                 esp_advance_phase(SCptr, in_the_dark);
3394                 return esp_do_phase_determine(esp);
3395         }
3396
3397         /* Did the target even make it? */
3398         if (esp->ireg == ESP_INTR_DC) {
3399                 /* wheee... nobody there or they didn't like
3400                  * what we told it to do, clean up.
3401                  */
3402
3403                 /* If anyone is off the bus, but working on
3404                  * a command in the background for us, tell
3405                  * the ESP to listen for them.
3406                  */
3407                 if (esp->disconnected_SC)
3408                         esp_cmd(esp, ESP_CMD_ESEL);
3409
3410                 if (((1<<SCptr->device->id) & esp->targets_present) &&
3411                     esp->seqreg != 0 &&
3412                     (esp->cur_msgout[0] == EXTENDED_MESSAGE) &&
3413                     (SCptr->SCp.phase == in_slct_msg ||
3414                      SCptr->SCp.phase == in_slct_stop)) {
3415                         /* shit */
3416                         esp->snip = 0;
3417                         ESPLOG(("esp%d: Failed synchronous negotiation for target %d "
3418                                 "lun %d\n", esp->esp_id, SCptr->device->id, SCptr->device->lun));
3419                         esp_dev->sync_max_offset = 0;
3420                         esp_dev->sync_min_period = 0;
3421                         esp_dev->sync = 1; /* so we don't negotiate again */
3422
3423                         /* Run the command again, this time though we
3424                          * won't try to negotiate for synchronous transfers.
3425                          *
3426                          * XXX I'd like to do something like send an
3427                          * XXX INITIATOR_ERROR or ABORT message to the
3428                          * XXX target to tell it, "Sorry I confused you,
3429                          * XXX please come back and I will be nicer next
3430                          * XXX time".  But that requires having the target
3431                          * XXX on the bus, and it has dropped BSY on us.
3432                          */
3433                         esp->current_SC = NULL;
3434                         esp_advance_phase(SCptr, not_issued);
3435                         prepend_SC(&esp->issue_SC, SCptr);
3436                         esp_exec_cmd(esp);
3437                         return do_intr_end;
3438                 }
3439
3440                 /* Ok, this is normal, this is what we see during boot
3441                  * or whenever when we are scanning the bus for targets.
3442                  * But first make sure that is really what is happening.
3443                  */
3444                 if (((1<<SCptr->device->id) & esp->targets_present)) {
3445                         ESPLOG(("esp%d: Warning, live target %d not responding to "
3446                                 "selection.\n", esp->esp_id, SCptr->device->id));
3447
3448                         /* This _CAN_ happen.  The SCSI standard states that
3449                          * the target is to _not_ respond to selection if
3450                          * _it_ detects bad parity on the bus for any reason.
3451                          * Therefore, we assume that if we've talked successfully
3452                          * to this target before, bad parity is the problem.
3453                          */
3454                         esp_done(esp, (DID_PARITY << 16));
3455                 } else {
3456                         /* Else, there really isn't anyone there. */
3457                         ESPMISC(("esp: selection failure, maybe nobody there?\n"));
3458                         ESPMISC(("esp: target %d lun %d\n",
3459                                  SCptr->device->id, SCptr->device->lun));
3460                         esp_done(esp, (DID_BAD_TARGET << 16));
3461                 }
3462                 return do_intr_end;
3463         }
3464
3465         ESPLOG(("esp%d: Selection failure.\n", esp->esp_id));
3466         printk("esp%d: Currently -- ", esp->esp_id);
3467         esp_print_ireg(esp->ireg); printk(" ");
3468         esp_print_statreg(esp->sreg); printk(" ");
3469         esp_print_seqreg(esp->seqreg); printk("\n");
3470         printk("esp%d: New -- ", esp->esp_id);
3471         esp->sreg = sbus_readb(esp->eregs + ESP_STATUS);
3472         esp->seqreg = sbus_readb(esp->eregs + ESP_SSTEP);
3473         esp->ireg = sbus_readb(esp->eregs + ESP_INTRPT);
3474         esp_print_ireg(esp->ireg); printk(" ");
3475         esp_print_statreg(esp->sreg); printk(" ");
3476         esp_print_seqreg(esp->seqreg); printk("\n");
3477         ESPLOG(("esp%d: resetting bus\n", esp->esp_id));
3478         return do_reset_bus; /* ugh... */
3479 }
3480
3481 /* Continue reading bytes for msgin phase. */
3482 static int esp_do_msgincont(struct esp *esp)
3483 {
3484         if (esp->ireg & ESP_INTR_BSERV) {
3485                 /* in the right phase too? */
3486                 if ((esp->sreg & ESP_STAT_PMASK) == ESP_MIP) {
3487                         /* phew... */
3488                         esp_cmd(esp, ESP_CMD_TI);
3489                         esp_advance_phase(esp->current_SC, in_msgindone);
3490                         return do_intr_end;
3491                 }
3492
3493                 /* We changed phase but ESP shows bus service,
3494                  * in this case it is most likely that we, the
3495                  * hacker who has been up for 20hrs straight
3496                  * staring at the screen, drowned in coffee
3497                  * smelling like retched cigarette ashes
3498                  * have miscoded something..... so, try to
3499                  * recover as best we can.
3500                  */
3501                 ESPLOG(("esp%d: message in mis-carriage.\n", esp->esp_id));
3502         }
3503         esp_advance_phase(esp->current_SC, in_the_dark);
3504         return do_phase_determine;
3505 }
3506
3507 static int check_singlebyte_msg(struct esp *esp)
3508 {
3509         esp->prevmsgin = esp->cur_msgin[0];
3510         if (esp->cur_msgin[0] & 0x80) {
3511                 /* wheee... */
3512                 ESPLOG(("esp%d: target sends identify amidst phases\n",
3513                         esp->esp_id));
3514                 esp_advance_phase(esp->current_SC, in_the_dark);
3515                 return 0;
3516         } else if (((esp->cur_msgin[0] & 0xf0) == 0x20) ||
3517                    (esp->cur_msgin[0] == EXTENDED_MESSAGE)) {
3518                 esp->msgin_len = 2;
3519                 esp_advance_phase(esp->current_SC, in_msgincont);
3520                 return 0;
3521         }
3522         esp_advance_phase(esp->current_SC, in_the_dark);
3523         switch (esp->cur_msgin[0]) {
3524         default:
3525                 /* We don't want to hear about it. */
3526                 ESPLOG(("esp%d: msg %02x which we don't know about\n", esp->esp_id,
3527                         esp->cur_msgin[0]));
3528                 return MESSAGE_REJECT;
3529
3530         case NOP:
3531                 ESPLOG(("esp%d: target %d sends a nop\n", esp->esp_id,
3532                         esp->current_SC->device->id));
3533                 return 0;
3534
3535         case RESTORE_POINTERS:
3536                 /* In this case we might also have to backup the
3537                  * "slow command" pointer.  It is rare to get such
3538                  * a save/restore pointer sequence so early in the
3539                  * bus transition sequences, but cover it.
3540                  */
3541                 if (esp->esp_slowcmd) {
3542                         esp->esp_scmdleft = esp->current_SC->cmd_len;
3543                         esp->esp_scmdp = &esp->current_SC->cmnd[0];
3544                 }
3545                 esp_restore_pointers(esp, esp->current_SC);
3546                 return 0;
3547
3548         case SAVE_POINTERS:
3549                 esp_save_pointers(esp, esp->current_SC);
3550                 return 0;
3551
3552         case COMMAND_COMPLETE:
3553         case DISCONNECT:
3554                 /* Freeing the bus, let it go. */
3555                 esp->current_SC->SCp.phase = in_freeing;
3556                 return 0;
3557
3558         case MESSAGE_REJECT:
3559                 ESPMISC(("msg reject, "));
3560                 if (esp->prevmsgout == EXTENDED_MESSAGE) {
3561                         struct esp_device *esp_dev = esp->current_SC->device->hostdata;
3562
3563                         /* Doesn't look like this target can
3564                          * do synchronous or WIDE transfers.
3565                          */
3566                         ESPSDTR(("got reject, was trying nego, clearing sync/WIDE\n"));
3567                         esp_dev->sync = 1;
3568                         esp_dev->wide = 1;
3569                         esp_dev->sync_min_period = 0;
3570                         esp_dev->sync_max_offset = 0;
3571                         return 0;
3572                 } else {
3573                         ESPMISC(("not sync nego, sending ABORT\n"));
3574                         return ABORT;
3575                 }
3576         };
3577 }
3578
3579 /* Target negotiates for synchronous transfers before we do, this
3580  * is legal although very strange.  What is even funnier is that
3581  * the SCSI2 standard specifically recommends against targets doing
3582  * this because so many initiators cannot cope with this occurring.
3583  */
3584 static int target_with_ants_in_pants(struct esp *esp,
3585                                      Scsi_Cmnd *SCptr,
3586                                      struct esp_device *esp_dev)
3587 {
3588         if (esp_dev->sync || SCptr->device->borken) {
3589                 /* sorry, no can do */
3590                 ESPSDTR(("forcing to async, "));
3591                 build_sync_nego_msg(esp, 0, 0);
3592                 esp_dev->sync = 1;
3593                 esp->snip = 1;
3594                 ESPLOG(("esp%d: hoping for msgout\n", esp->esp_id));
3595                 esp_advance_phase(SCptr, in_the_dark);
3596                 return EXTENDED_MESSAGE;
3597         }
3598
3599         /* Ok, we'll check them out... */
3600         return 0;
3601 }
3602
3603 static void sync_report(struct esp *esp)
3604 {
3605         int msg3, msg4;
3606         char *type;
3607
3608         msg3 = esp->cur_msgin[3];
3609         msg4 = esp->cur_msgin[4];
3610         if (msg4) {
3611                 int hz = 1000000000 / (msg3 * 4);
3612                 int integer = hz / 1000000;
3613                 int fraction = (hz - (integer * 1000000)) / 10000;
3614                 if ((esp->erev == fashme) &&
3615                     (esp->config3[esp->current_SC->device->id] & ESP_CONFIG3_EWIDE)) {
3616                         type = "FAST-WIDE";
3617                         integer <<= 1;
3618                         fraction <<= 1;
3619                 } else if ((msg3 * 4) < 200) {
3620                         type = "FAST";
3621                 } else {
3622                         type = "synchronous";
3623                 }
3624
3625                 /* Do not transform this back into one big printk
3626                  * again, it triggers a bug in our sparc64-gcc272
3627                  * sibling call optimization.  -DaveM
3628                  */
3629                 ESPLOG((KERN_INFO "esp%d: target %d ",
3630                         esp->esp_id, esp->current_SC->device->id));
3631                 ESPLOG(("[period %dns offset %d %d.%02dMHz ",
3632                         (int) msg3 * 4, (int) msg4,
3633                         integer, fraction));
3634                 ESPLOG(("%s SCSI%s]\n", type,
3635                         (((msg3 * 4) < 200) ? "-II" : "")));
3636         } else {
3637                 ESPLOG((KERN_INFO "esp%d: target %d asynchronous\n",
3638                         esp->esp_id, esp->current_SC->device->id));
3639         }
3640 }
3641
3642 static int check_multibyte_msg(struct esp *esp)
3643 {
3644         Scsi_Cmnd *SCptr = esp->current_SC;
3645         struct esp_device *esp_dev = SCptr->device->hostdata;
3646         u8 regval = 0;
3647         int message_out = 0;
3648
3649         ESPSDTR(("chk multibyte msg: "));
3650         if (esp->cur_msgin[2] == EXTENDED_SDTR) {
3651                 int period = esp->cur_msgin[3];
3652                 int offset = esp->cur_msgin[4];
3653
3654                 ESPSDTR(("is sync nego response, "));
3655                 if (!esp->snip) {
3656                         int rval;
3657
3658                         /* Target negotiates first! */
3659                         ESPSDTR(("target jumps the gun, "));
3660                         message_out = EXTENDED_MESSAGE; /* we must respond */
3661                         rval = target_with_ants_in_pants(esp, SCptr, esp_dev);
3662                         if (rval)
3663                                 return rval;
3664                 }
3665
3666                 ESPSDTR(("examining sdtr, "));
3667
3668                 /* Offset cannot be larger than ESP fifo size. */
3669                 if (offset > 15) {
3670                         ESPSDTR(("offset too big %2x, ", offset));
3671                         offset = 15;
3672                         ESPSDTR(("sending back new offset\n"));
3673                         build_sync_nego_msg(esp, period, offset);
3674                         return EXTENDED_MESSAGE;
3675                 }
3676
3677                 if (offset && period > esp->max_period) {
3678                         /* Yeee, async for this slow device. */
3679                         ESPSDTR(("period too long %2x, ", period));
3680                         build_sync_nego_msg(esp, 0, 0);
3681                         ESPSDTR(("hoping for msgout\n"));
3682                         esp_advance_phase(esp->current_SC, in_the_dark);
3683                         return EXTENDED_MESSAGE;
3684                 } else if (offset && period < esp->min_period) {
3685                         ESPSDTR(("period too short %2x, ", period));
3686                         period = esp->min_period;
3687                         if (esp->erev > esp236)
3688                                 regval = 4;
3689                         else
3690                                 regval = 5;
3691                 } else if (offset) {
3692                         int tmp;
3693
3694                         ESPSDTR(("period is ok, "));
3695                         tmp = esp->ccycle / 1000;
3696                         regval = (((period << 2) + tmp - 1) / tmp);
3697                         if (regval && ((esp->erev == fas100a ||
3698                                         esp->erev == fas236  ||
3699                                         esp->erev == fashme))) {
3700                                 if (period >= 50)
3701                                         regval--;
3702                         }
3703                 }
3704
3705                 if (offset) {
3706                         u8 bit;
3707
3708                         esp_dev->sync_min_period = (regval & 0x1f);
3709                         esp_dev->sync_max_offset = (offset | esp->radelay);
3710                         if (esp->erev == fas100a || esp->erev == fas236 || esp->erev == fashme) {
3711                                 if ((esp->erev == fas100a) || (esp->erev == fashme))
3712                                         bit = ESP_CONFIG3_FAST;
3713                                 else
3714                                         bit = ESP_CONFIG3_FSCSI;
3715                                 if (period < 50) {
3716                                         /* On FAS366, if using fast-20 synchronous transfers
3717                                          * we need to make sure the REQ/ACK assert/deassert
3718                                          * control bits are clear.
3719                                          */
3720                                         if (esp->erev == fashme)
3721                                                 esp_dev->sync_max_offset &= ~esp->radelay;
3722                                         esp->config3[SCptr->device->id] |= bit;
3723                                 } else {
3724                                         esp->config3[SCptr->device->id] &= ~bit;
3725                                 }
3726                                 esp->prev_cfg3 = esp->config3[SCptr->device->id];
3727                                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
3728                         }
3729                         esp->prev_soff = esp_dev->sync_max_offset;
3730                         esp->prev_stp = esp_dev->sync_min_period;
3731                         sbus_writeb(esp->prev_soff, esp->eregs + ESP_SOFF);
3732                         sbus_writeb(esp->prev_stp, esp->eregs + ESP_STP);
3733                         ESPSDTR(("soff=%2x stp=%2x cfg3=%2x\n",
3734                                  esp_dev->sync_max_offset,
3735                                  esp_dev->sync_min_period,
3736                                  esp->config3[SCptr->device->id]));
3737
3738                         esp->snip = 0;
3739                 } else if (esp_dev->sync_max_offset) {
3740                         u8 bit;
3741
3742                         /* back to async mode */
3743                         ESPSDTR(("unaccaptable sync nego, forcing async\n"));
3744                         esp_dev->sync_max_offset = 0;
3745                         esp_dev->sync_min_period = 0;
3746                         esp->prev_soff = 0;
3747                         esp->prev_stp = 0;
3748                         sbus_writeb(esp->prev_soff, esp->eregs + ESP_SOFF);
3749                         sbus_writeb(esp->prev_stp, esp->eregs + ESP_STP);
3750                         if (esp->erev == fas100a || esp->erev == fas236 || esp->erev == fashme) {
3751                                 if ((esp->erev == fas100a) || (esp->erev == fashme))
3752                                         bit = ESP_CONFIG3_FAST;
3753                                 else
3754                                         bit = ESP_CONFIG3_FSCSI;
3755                                 esp->config3[SCptr->device->id] &= ~bit;
3756                                 esp->prev_cfg3 = esp->config3[SCptr->device->id];
3757                                 sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
3758                         }
3759                 }
3760
3761                 sync_report(esp);
3762
3763                 ESPSDTR(("chk multibyte msg: sync is known, "));
3764                 esp_dev->sync = 1;
3765
3766                 if (message_out) {
3767                         ESPLOG(("esp%d: sending sdtr back, hoping for msgout\n",
3768                                 esp->esp_id));
3769                         build_sync_nego_msg(esp, period, offset);
3770                         esp_advance_phase(SCptr, in_the_dark);
3771                         return EXTENDED_MESSAGE;
3772                 }
3773
3774                 ESPSDTR(("returning zero\n"));
3775                 esp_advance_phase(SCptr, in_the_dark); /* ...or else! */
3776                 return 0;
3777         } else if (esp->cur_msgin[2] == EXTENDED_WDTR) {
3778                 int size = 8 << esp->cur_msgin[3];
3779
3780                 esp->wnip = 0;
3781                 if (esp->erev != fashme) {
3782                         ESPLOG(("esp%d: AIEEE wide msg received and not HME.\n",
3783                                 esp->esp_id));
3784                         message_out = MESSAGE_REJECT;
3785                 } else if (size > 16) {
3786                         ESPLOG(("esp%d: AIEEE wide transfer for %d size "
3787                                 "not supported.\n", esp->esp_id, size));
3788                         message_out = MESSAGE_REJECT;
3789                 } else {
3790                         /* Things look good; let's see what we got. */
3791                         if (size == 16) {
3792                                 /* Set config 3 register for this target. */
3793                                 esp->config3[SCptr->device->id] |= ESP_CONFIG3_EWIDE;
3794                         } else {
3795                                 /* Just make sure it was one byte sized. */
3796                                 if (size != 8) {
3797                                         ESPLOG(("esp%d: Aieee, wide nego of %d size.\n",
3798                                                 esp->esp_id, size));
3799                                         message_out = MESSAGE_REJECT;
3800                                         goto finish;
3801                                 }
3802                                 /* Pure paranoia. */
3803                                 esp->config3[SCptr->device->id] &= ~(ESP_CONFIG3_EWIDE);
3804                         }
3805                         esp->prev_cfg3 = esp->config3[SCptr->device->id];
3806                         sbus_writeb(esp->prev_cfg3, esp->eregs + ESP_CFG3);
3807
3808                         /* Regardless, next try for sync transfers. */
3809                         build_sync_nego_msg(esp, esp->sync_defp, 15);
3810                         esp_dev->sync = 1;
3811                         esp->snip = 1;
3812                         message_out = EXTENDED_MESSAGE;
3813                 }
3814         } else if (esp->cur_msgin[2] == EXTENDED_MODIFY_DATA_POINTER) {
3815                 ESPLOG(("esp%d: rejecting modify data ptr msg\n", esp->esp_id));
3816                 message_out = MESSAGE_REJECT;
3817         }
3818 finish:
3819         esp_advance_phase(SCptr, in_the_dark);
3820         return message_out;
3821 }
3822
3823 static int esp_do_msgindone(struct esp *esp)
3824 {
3825         Scsi_Cmnd *SCptr = esp->current_SC;
3826         int message_out = 0, it = 0, rval;
3827
3828         rval = skipahead1(esp, SCptr, in_msgin, in_msgindone);
3829         if (rval)
3830                 return rval;
3831         if (SCptr->SCp.sent_command != in_status) {
3832                 if (!(esp->ireg & ESP_INTR_DC)) {
3833                         if (esp->msgin_len && (esp->sreg & ESP_STAT_PERR)) {
3834                                 message_out = MSG_PARITY_ERROR;
3835                                 esp_cmd(esp, ESP_CMD_FLUSH);
3836                         } else if (esp->erev != fashme &&
3837                           (it = (sbus_readb(esp->eregs + ESP_FFLAGS) & ESP_FF_FBYTES)) != 1) {
3838                                 /* We certainly dropped the ball somewhere. */
3839                                 message_out = INITIATOR_ERROR;
3840                                 esp_cmd(esp, ESP_CMD_FLUSH);
3841                         } else if (!esp->msgin_len) {
3842                                 if (esp->erev == fashme)
3843                                         it = esp->hme_fifo_workaround_buffer[0];
3844                                 else
3845                                         it = sbus_readb(esp->eregs + ESP_FDATA);
3846                                 esp_advance_phase(SCptr, in_msgincont);
3847                         } else {
3848                                 /* it is ok and we want it */
3849                                 if (esp->erev == fashme)
3850                                         it = esp->cur_msgin[esp->msgin_ctr] =
3851                                                 esp->hme_fifo_workaround_buffer[0];
3852                                 else
3853                                         it = esp->cur_msgin[esp->msgin_ctr] =
3854                                                 sbus_readb(esp->eregs + ESP_FDATA);
3855                                 esp->msgin_ctr++;
3856                         }
3857                 } else {
3858                         esp_advance_phase(SCptr, in_the_dark);
3859                         return do_work_bus;
3860                 }
3861         } else {
3862                 it = esp->cur_msgin[0];
3863         }
3864         if (!message_out && esp->msgin_len) {
3865                 if (esp->msgin_ctr < esp->msgin_len) {
3866                         esp_advance_phase(SCptr, in_msgincont);
3867                 } else if (esp->msgin_len == 1) {
3868                         message_out = check_singlebyte_msg(esp);
3869                 } else if (esp->msgin_len == 2) {
3870                         if (esp->cur_msgin[0] == EXTENDED_MESSAGE) {
3871                                 if ((it + 2) >= 15) {
3872                                         message_out = MESSAGE_REJECT;
3873                                 } else {
3874                                         esp->msgin_len = (it + 2);
3875                                         esp_advance_phase(SCptr, in_msgincont);
3876                                 }
3877                         } else {
3878                                 message_out = MESSAGE_REJECT; /* foo on you */
3879                         }
3880                 } else {
3881                         message_out = check_multibyte_msg(esp);
3882                 }
3883         }
3884         if (message_out < 0) {
3885                 return -message_out;
3886         } else if (message_out) {
3887                 if (((message_out != 1) &&
3888                      ((message_out < 0x20) || (message_out & 0x80))))
3889                         esp->msgout_len = 1;
3890                 esp->cur_msgout[0] = message_out;
3891                 esp_cmd(esp, ESP_CMD_SATN);
3892                 esp_advance_phase(SCptr, in_the_dark);
3893                 esp->msgin_len = 0;
3894         }
3895         esp->sreg = sbus_readb(esp->eregs + ESP_STATUS);
3896         esp->sreg &= ~(ESP_STAT_INTR);
3897         if ((esp->sreg & (ESP_STAT_PMSG|ESP_STAT_PCD)) == (ESP_STAT_PMSG|ESP_STAT_PCD))
3898                 esp_cmd(esp, ESP_CMD_MOK);
3899         if ((SCptr->SCp.sent_command == in_msgindone) &&
3900             (SCptr->SCp.phase == in_freeing))
3901                 return esp_do_freebus(esp);
3902         return do_intr_end;
3903 }
3904
3905 static int esp_do_cmdbegin(struct esp *esp)
3906 {
3907         Scsi_Cmnd *SCptr = esp->current_SC;
3908
3909         esp_advance_phase(SCptr, in_cmdend);
3910         if (esp->erev == fashme) {
3911                 u32 tmp = sbus_readl(esp->dregs + DMA_CSR);
3912                 int i;
3913
3914                 for (i = 0; i < esp->esp_scmdleft; i++)
3915                         esp->esp_command[i] = *esp->esp_scmdp++;
3916                 esp->esp_scmdleft = 0;
3917                 esp_cmd(esp, ESP_CMD_FLUSH);
3918                 esp_setcount(esp->eregs, i, 1);
3919                 esp_cmd(esp, (ESP_CMD_DMA | ESP_CMD_TI));
3920                 tmp |= (DMA_SCSI_DISAB | DMA_ENABLE);
3921                 tmp &= ~(DMA_ST_WRITE);
3922                 sbus_writel(i, esp->dregs + DMA_COUNT);
3923                 sbus_writel(esp->esp_command_dvma, esp->dregs + DMA_ADDR);
3924                 sbus_writel(tmp, esp->dregs + DMA_CSR);
3925         } else {
3926                 u8 tmp;
3927
3928                 esp_cmd(esp, ESP_CMD_FLUSH);
3929                 tmp = *esp->esp_scmdp++;
3930                 esp->esp_scmdleft--;
3931                 sbus_writeb(tmp, esp->eregs + ESP_FDATA);
3932                 esp_cmd(esp, ESP_CMD_TI);
3933         }
3934         return do_intr_end;
3935 }
3936
3937 static int esp_do_cmddone(struct esp *esp)
3938 {
3939         if (esp->erev == fashme)
3940                 dma_invalidate(esp);
3941         else
3942                 esp_cmd(esp, ESP_CMD_NULL);
3943
3944         if (esp->ireg & ESP_INTR_BSERV) {
3945                 esp_advance_phase(esp->current_SC, in_the_dark);
3946                 return esp_do_phase_determine(esp);
3947         }
3948
3949         ESPLOG(("esp%d: in do_cmddone() but didn't get BSERV interrupt.\n",
3950                 esp->esp_id));
3951         return do_reset_bus;
3952 }
3953
3954 static int esp_do_msgout(struct esp *esp)
3955 {
3956         esp_cmd(esp, ESP_CMD_FLUSH);
3957         switch (esp->msgout_len) {
3958         case 1:
3959                 if (esp->erev == fashme)
3960                         hme_fifo_push(esp, &esp->cur_msgout[0], 1);
3961                 else
3962                         sbus_writeb(esp->cur_msgout[0], esp->eregs + ESP_FDATA);
3963
3964                 esp_cmd(esp, ESP_CMD_TI);
3965                 break;
3966
3967         case 2:
3968                 esp->esp_command[0] = esp->cur_msgout[0];
3969                 esp->esp_command[1] = esp->cur_msgout[1];
3970
3971                 if (esp->erev == fashme) {
3972                         hme_fifo_push(esp, &esp->cur_msgout[0], 2);
3973                         esp_cmd(esp, ESP_CMD_TI);
3974                 } else {
3975                         dma_setup(esp, esp->esp_command_dvma, 2, 0);
3976                         esp_setcount(esp->eregs, 2, 0);
3977                         esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
3978                 }
3979                 break;
3980
3981         case 4:
3982                 esp->esp_command[0] = esp->cur_msgout[0];
3983                 esp->esp_command[1] = esp->cur_msgout[1];
3984                 esp->esp_command[2] = esp->cur_msgout[2];
3985                 esp->esp_command[3] = esp->cur_msgout[3];
3986                 esp->snip = 1;
3987
3988                 if (esp->erev == fashme) {
3989                         hme_fifo_push(esp, &esp->cur_msgout[0], 4);
3990                         esp_cmd(esp, ESP_CMD_TI);
3991                 } else {
3992                         dma_setup(esp, esp->esp_command_dvma, 4, 0);
3993                         esp_setcount(esp->eregs, 4, 0);
3994                         esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
3995                 }
3996                 break;
3997
3998         case 5:
3999                 esp->esp_command[0] = esp->cur_msgout[0];
4000                 esp->esp_command[1] = esp->cur_msgout[1];
4001                 esp->esp_command[2] = esp->cur_msgout[2];
4002                 esp->esp_command[3] = esp->cur_msgout[3];
4003                 esp->esp_command[4] = esp->cur_msgout[4];
4004                 esp->snip = 1;
4005
4006                 if (esp->erev == fashme) {
4007                         hme_fifo_push(esp, &esp->cur_msgout[0], 5);
4008                         esp_cmd(esp, ESP_CMD_TI);
4009                 } else {
4010                         dma_setup(esp, esp->esp_command_dvma, 5, 0);
4011                         esp_setcount(esp->eregs, 5, 0);
4012                         esp_cmd(esp, ESP_CMD_DMA | ESP_CMD_TI);
4013                 }
4014                 break;
4015
4016         default:
4017                 /* whoops */
4018                 ESPMISC(("bogus msgout sending NOP\n"));
4019                 esp->cur_msgout[0] = NOP;
4020
4021                 if (esp->erev == fashme) {
4022                         hme_fifo_push(esp, &esp->cur_msgout[0], 1);
4023                 } else {
4024                         sbus_writeb(esp->cur_msgout[0], esp->eregs + ESP_FDATA);
4025                 }
4026
4027                 esp->msgout_len = 1;
4028                 esp_cmd(esp, ESP_CMD_TI);
4029                 break;
4030         };
4031
4032         esp_advance_phase(esp->current_SC, in_msgoutdone);
4033         return do_intr_end;
4034 }
4035
4036 static int esp_do_msgoutdone(struct esp *esp)
4037 {
4038         if (esp->msgout_len > 1) {
4039                 /* XXX HME/FAS ATN deassert workaround required,
4040                  * XXX no DMA flushing, only possible ESP_CMD_FLUSH
4041                  * XXX to kill the fifo.
4042                  */
4043                 if (esp->erev != fashme) {
4044                         u32 tmp;
4045
4046                         while ((tmp = sbus_readl(esp->dregs + DMA_CSR)) & DMA_PEND_READ)
4047                                 udelay(1);
4048                         tmp &= ~DMA_ENABLE;
4049                         sbus_writel(tmp, esp->dregs + DMA_CSR);
4050                         dma_invalidate(esp);
4051                 } else {
4052                         esp_cmd(esp, ESP_CMD_FLUSH);
4053                 }
4054         }
4055         if (!(esp->ireg & ESP_INTR_DC)) {
4056                 if (esp->erev != fashme)
4057                         esp_cmd(esp, ESP_CMD_NULL);
4058                 switch (esp->sreg & ESP_STAT_PMASK) {
4059                 case ESP_MOP:
4060                         /* whoops, parity error */
4061                         ESPLOG(("esp%d: still in msgout, parity error assumed\n",
4062                                 esp->esp_id));
4063                         if (esp->msgout_len > 1)
4064                                 esp_cmd(esp, ESP_CMD_SATN);
4065                         esp_advance_phase(esp->current_SC, in_msgout);
4066                         return do_work_bus;
4067
4068                 case ESP_DIP:
4069                         break;
4070
4071                 default:
4072                         /* Happy Meal fifo is touchy... */
4073                         if ((esp->erev != fashme) &&
4074                             !fcount(esp) &&
4075                             !(((struct esp_device *)esp->current_SC->device->hostdata)->sync_max_offset))
4076                                 esp_cmd(esp, ESP_CMD_FLUSH);
4077                         break;
4078
4079                 };
4080         } else {
4081                 ESPLOG(("esp%d: disconnect, resetting bus\n", esp->esp_id));
4082                 return do_reset_bus;
4083         }
4084
4085         /* If we sent out a synchronous negotiation message, update
4086          * our state.
4087          */
4088         if (esp->cur_msgout[2] == EXTENDED_MESSAGE &&
4089             esp->cur_msgout[4] == EXTENDED_SDTR) {
4090                 esp->snip = 1; /* anal retentiveness... */
4091         }
4092
4093         esp->prevmsgout = esp->cur_msgout[0];
4094         esp->msgout_len = 0;
4095         esp_advance_phase(esp->current_SC, in_the_dark);
4096         return esp_do_phase_determine(esp);
4097 }
4098
4099 static int esp_bus_unexpected(struct esp *esp)
4100 {
4101         ESPLOG(("esp%d: command in weird state %2x\n",
4102                 esp->esp_id, esp->current_SC->SCp.phase));
4103         return do_reset_bus;
4104 }
4105
4106 static espfunc_t bus_vector[] = {
4107         esp_do_data_finale,
4108         esp_do_data_finale,
4109         esp_bus_unexpected,
4110         esp_do_msgin,
4111         esp_do_msgincont,
4112         esp_do_msgindone,
4113         esp_do_msgout,
4114         esp_do_msgoutdone,
4115         esp_do_cmdbegin,
4116         esp_do_cmddone,
4117         esp_do_status,
4118         esp_do_freebus,
4119         esp_do_phase_determine,
4120         esp_bus_unexpected,
4121         esp_bus_unexpected,
4122         esp_bus_unexpected,
4123 };
4124
4125 /* This is the second tier in our dual-level SCSI state machine. */
4126 static int esp_work_bus(struct esp *esp)
4127 {
4128         Scsi_Cmnd *SCptr = esp->current_SC;
4129         unsigned int phase;
4130
4131         ESPBUS(("esp_work_bus: "));
4132         if (!SCptr) {
4133                 ESPBUS(("reconnect\n"));
4134                 return esp_do_reconnect(esp);
4135         }
4136         phase = SCptr->SCp.phase;
4137         if ((phase & 0xf0) == in_phases_mask)
4138                 return bus_vector[(phase & 0x0f)](esp);
4139         else if ((phase & 0xf0) == in_slct_mask)
4140                 return esp_select_complete(esp);
4141         else
4142                 return esp_bus_unexpected(esp);
4143 }
4144
4145 static espfunc_t isvc_vector[] = {
4146         0,
4147         esp_do_phase_determine,
4148         esp_do_resetbus,
4149         esp_finish_reset,
4150         esp_work_bus
4151 };
4152
4153 /* Main interrupt handler for an esp adapter. */
4154 static void esp_handle(struct esp *esp)
4155 {
4156         Scsi_Cmnd *SCptr;
4157         int what_next = do_intr_end;
4158
4159         SCptr = esp->current_SC;
4160
4161         /* Check for errors. */
4162         esp->sreg = sbus_readb(esp->eregs + ESP_STATUS);
4163         esp->sreg &= (~ESP_STAT_INTR);
4164         if (esp->erev == fashme) {
4165                 esp->sreg2 = sbus_readb(esp->eregs + ESP_STATUS2);
4166                 esp->seqreg = (sbus_readb(esp->eregs + ESP_SSTEP) & ESP_STEP_VBITS);
4167         }
4168
4169         if (esp->sreg & (ESP_STAT_SPAM)) {
4170                 /* Gross error, could be due to one of:
4171                  *
4172                  * - top of fifo overwritten, could be because
4173                  *   we tried to do a synchronous transfer with
4174                  *   an offset greater than ESP fifo size
4175                  *
4176                  * - top of command register overwritten
4177                  *
4178                  * - DMA setup to go in one direction, SCSI
4179                  *   bus points in the other, whoops
4180                  *
4181                  * - weird phase change during asynchronous
4182                  *   data phase while we are initiator
4183                  */
4184                 ESPLOG(("esp%d: Gross error sreg=%2x\n", esp->esp_id, esp->sreg));
4185
4186                 /* If a command is live on the bus we cannot safely
4187                  * reset the bus, so we'll just let the pieces fall
4188                  * where they may.  Here we are hoping that the
4189                  * target will be able to cleanly go away soon
4190                  * so we can safely reset things.
4191                  */
4192                 if (!SCptr) {
4193                         ESPLOG(("esp%d: No current cmd during gross error, "
4194                                 "resetting bus\n", esp->esp_id));
4195                         what_next = do_reset_bus;
4196                         goto state_machine;
4197                 }
4198         }
4199
4200         if (sbus_readl(esp->dregs + DMA_CSR) & DMA_HNDL_ERROR) {
4201                 /* A DMA gate array error.  Here we must
4202                  * be seeing one of two things.  Either the
4203                  * virtual to physical address translation
4204                  * on the SBUS could not occur, else the
4205                  * translation it did get pointed to a bogus
4206                  * page.  Ho hum...
4207                  */
4208                 ESPLOG(("esp%d: DMA error %08x\n", esp->esp_id,
4209                         sbus_readl(esp->dregs + DMA_CSR)));
4210
4211                 /* DMA gate array itself must be reset to clear the
4212                  * error condition.
4213                  */
4214                 esp_reset_dma(esp);
4215
4216                 what_next = do_reset_bus;
4217                 goto state_machine;
4218         }
4219
4220         esp->ireg = sbus_readb(esp->eregs + ESP_INTRPT);   /* Unlatch intr reg */
4221
4222         if (esp->erev == fashme) {
4223                 /* This chip is really losing. */
4224                 ESPHME(("HME["));
4225
4226                 ESPHME(("sreg2=%02x,", esp->sreg2));
4227                 /* Must latch fifo before reading the interrupt
4228                  * register else garbage ends up in the FIFO
4229                  * which confuses the driver utterly.
4230                  */
4231                 if (!(esp->sreg2 & ESP_STAT2_FEMPTY) ||
4232                     (esp->sreg2 & ESP_STAT2_F1BYTE)) {
4233                         ESPHME(("fifo_workaround]"));
4234                         hme_fifo_read(esp);
4235                 } else {
4236                         ESPHME(("no_fifo_workaround]"));
4237                 }
4238         }
4239
4240         /* No current cmd is only valid at this point when there are
4241          * commands off the bus or we are trying a reset.
4242          */
4243         if (!SCptr && !esp->disconnected_SC && !(esp->ireg & ESP_INTR_SR)) {
4244                 /* Panic is safe, since current_SC is null. */
4245                 ESPLOG(("esp%d: no command in esp_handle()\n", esp->esp_id));
4246                 panic("esp_handle: current_SC == penguin within interrupt!");
4247         }
4248
4249         if (esp->ireg & (ESP_INTR_IC)) {
4250                 /* Illegal command fed to ESP.  Outside of obvious
4251                  * software bugs that could cause this, there is
4252                  * a condition with esp100 where we can confuse the
4253                  * ESP into an erroneous illegal command interrupt
4254                  * because it does not scrape the FIFO properly
4255                  * for reselection.  See esp100_reconnect_hwbug()
4256                  * to see how we try very hard to avoid this.
4257                  */
4258                 ESPLOG(("esp%d: invalid command\n", esp->esp_id));
4259
4260                 esp_dump_state(esp);
4261
4262                 if (SCptr != NULL) {
4263                         /* Devices with very buggy firmware can drop BSY
4264                          * during a scatter list interrupt when using sync
4265                          * mode transfers.  We continue the transfer as
4266                          * expected, the target drops the bus, the ESP
4267                          * gets confused, and we get a illegal command
4268                          * interrupt because the bus is in the disconnected
4269                          * state now and ESP_CMD_TI is only allowed when
4270                          * a nexus is alive on the bus.
4271                          */
4272                         ESPLOG(("esp%d: Forcing async and disabling disconnect for "
4273                                 "target %d\n", esp->esp_id, SCptr->device->id));
4274                         SCptr->device->borken = 1; /* foo on you */
4275                 }
4276
4277                 what_next = do_reset_bus;
4278         } else if (!(esp->ireg & ~(ESP_INTR_FDONE | ESP_INTR_BSERV | ESP_INTR_DC))) {
4279                 if (SCptr) {
4280                         unsigned int phase = SCptr->SCp.phase;
4281
4282                         if (phase & in_phases_mask) {
4283                                 what_next = esp_work_bus(esp);
4284                         } else if (phase & in_slct_mask) {
4285                                 what_next = esp_select_complete(esp);
4286                         } else {
4287                                 ESPLOG(("esp%d: interrupt for no good reason...\n",
4288                                         esp->esp_id));
4289                                 what_next = do_intr_end;
4290                         }
4291                 } else {
4292                         ESPLOG(("esp%d: BSERV or FDONE or DC while SCptr==NULL\n",
4293                                 esp->esp_id));
4294                         what_next = do_reset_bus;
4295                 }
4296         } else if (esp->ireg & ESP_INTR_SR) {
4297                 ESPLOG(("esp%d: SCSI bus reset interrupt\n", esp->esp_id));
4298                 what_next = do_reset_complete;
4299         } else if (esp->ireg & (ESP_INTR_S | ESP_INTR_SATN)) {
4300                 ESPLOG(("esp%d: AIEEE we have been selected by another initiator!\n",
4301                         esp->esp_id));
4302                 what_next = do_reset_bus;
4303         } else if (esp->ireg & ESP_INTR_RSEL) {
4304                 if (SCptr == NULL) {
4305                         /* This is ok. */
4306                         what_next = esp_do_reconnect(esp);
4307                 } else if (SCptr->SCp.phase & in_slct_mask) {
4308                         /* Only selection code knows how to clean
4309                          * up properly.
4310                          */
4311                         ESPDISC(("Reselected during selection attempt\n"));
4312                         what_next = esp_select_complete(esp);
4313                 } else {
4314                         ESPLOG(("esp%d: Reselected while bus is busy\n",
4315                                 esp->esp_id));
4316                         what_next = do_reset_bus;
4317                 }
4318         }
4319
4320         /* This is tier-one in our dual level SCSI state machine. */
4321 state_machine:
4322         while (what_next != do_intr_end) {
4323                 if (what_next >= do_phase_determine &&
4324                     what_next < do_intr_end) {
4325                         what_next = isvc_vector[what_next](esp);
4326                 } else {
4327                         /* state is completely lost ;-( */
4328                         ESPLOG(("esp%d: interrupt engine loses state, resetting bus\n",
4329                                 esp->esp_id));
4330                         what_next = do_reset_bus;
4331                 }
4332         }
4333 }
4334
4335 /* Service only the ESP described by dev_id. */
4336 static irqreturn_t esp_intr(int irq, void *dev_id, struct pt_regs *pregs)
4337 {
4338         struct esp *esp = dev_id;
4339         unsigned long flags;
4340
4341         spin_lock_irqsave(esp->ehost->host_lock, flags);
4342         if (ESP_IRQ_P(esp->dregs)) {
4343                 ESP_INTSOFF(esp->dregs);
4344
4345                 ESPIRQ(("I[%d:%d](", smp_processor_id(), esp->esp_id));
4346                 esp_handle(esp);
4347                 ESPIRQ((")"));
4348
4349                 ESP_INTSON(esp->dregs);
4350         }
4351         spin_unlock_irqrestore(esp->ehost->host_lock, flags);
4352
4353         return IRQ_HANDLED;
4354 }
4355
4356 static int esp_slave_alloc(Scsi_Device *SDptr)
4357 {
4358         struct esp_device *esp_dev =
4359                 kmalloc(sizeof(struct esp_device), GFP_ATOMIC);
4360
4361         if (!esp_dev)
4362                 return -ENOMEM;
4363         memset(esp_dev, 0, sizeof(struct esp_device));
4364         SDptr->hostdata = esp_dev;
4365         return 0;
4366 }
4367
4368 static void esp_slave_destroy(Scsi_Device *SDptr)
4369 {
4370         struct esp *esp = (struct esp *) SDptr->host->hostdata;
4371
4372         esp->targets_present &= ~(1 << SDptr->id);
4373         kfree(SDptr->hostdata);
4374         SDptr->hostdata = NULL;
4375 }
4376
4377 static Scsi_Host_Template driver_template = {
4378         .proc_name              = "esp",
4379         .proc_info              = esp_proc_info,
4380         .name                   = "Sun ESP 100/100a/200",
4381         .detect                 = esp_detect,
4382         .slave_alloc            = esp_slave_alloc,
4383         .slave_destroy          = esp_slave_destroy,
4384         .release                = esp_release,
4385         .info                   = esp_info,
4386         .queuecommand           = esp_queue,
4387         .eh_abort_handler       = esp_abort,
4388         .eh_bus_reset_handler   = esp_reset,
4389         .can_queue              = 7,
4390         .this_id                = 7,
4391         .sg_tablesize           = SG_ALL,
4392         .cmd_per_lun            = 1,
4393         .use_clustering         = ENABLE_CLUSTERING,
4394 };
4395
4396 #include "scsi_module.c"
4397
4398 MODULE_LICENSE("GPL");
4399