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