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