ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / scsi / mesh.c
1 /*
2  * SCSI low-level driver for the MESH (Macintosh Enhanced SCSI Hardware)
3  * bus adaptor found on Power Macintosh computers.
4  * We assume the MESH is connected to a DBDMA (descriptor-based DMA)
5  * controller.
6  *
7  * Paul Mackerras, August 1996.
8  * Copyright (C) 1996 Paul Mackerras.
9  *
10  * Apr. 21 2002  - BenH         Rework bus reset code for new error handler
11  *                              Add delay after initial bus reset
12  *                              Add module parameters
13  *
14  * Sep. 27 2003  - BenH         Move to new driver model, fix some write posting
15  *                              issues
16  * To do:
17  * - handle aborts correctly
18  * - retry arbitration if lost (unless higher levels do this for us)
19  * - power down the chip when no device is detected
20  */
21 #include <linux/config.h>
22 #include <linux/module.h>
23 #include <linux/kernel.h>
24 #include <linux/delay.h>
25 #include <linux/types.h>
26 #include <linux/string.h>
27 #include <linux/slab.h>
28 #include <linux/blkdev.h>
29 #include <linux/proc_fs.h>
30 #include <linux/stat.h>
31 #include <linux/interrupt.h>
32 #include <linux/reboot.h>
33 #include <linux/spinlock.h>
34 #include <asm/dbdma.h>
35 #include <asm/io.h>
36 #include <asm/pgtable.h>
37 #include <asm/prom.h>
38 #include <asm/system.h>
39 #include <asm/irq.h>
40 #include <asm/hydra.h>
41 #include <asm/processor.h>
42 #include <asm/machdep.h>
43 #include <asm/pmac_feature.h>
44 #include <asm/pci-bridge.h>
45 #include <asm/macio.h>
46
47 #include <scsi/scsi.h>
48 #include <scsi/scsi_cmnd.h>
49 #include <scsi/scsi_device.h>
50 #include <scsi/scsi_host.h>
51
52 #include "mesh.h"
53
54 #if 1
55 #undef KERN_DEBUG
56 #define KERN_DEBUG KERN_WARNING
57 #endif
58
59 MODULE_AUTHOR("Paul Mackerras (paulus@samba.org)");
60 MODULE_DESCRIPTION("PowerMac MESH SCSI driver");
61 MODULE_LICENSE("GPL");
62
63 MODULE_PARM(sync_rate, "i");
64 MODULE_PARM_DESC(sync_rate, "Synchronous rate (0..10, 0=async)");
65 MODULE_PARM(sync_targets, "i");
66 MODULE_PARM_DESC(sync_targets, "Bitmask of targets allowed to set synchronous");
67 MODULE_PARM(resel_targets, "i");
68 MODULE_PARM_DESC(resel_targets, "Bitmask of targets allowed to set disconnect");
69 MODULE_PARM(debug_targets, "i");
70 MODULE_PARM_DESC(debug_targets, "Bitmask of debugged targets");
71 MODULE_PARM(init_reset_delay, "i");
72 MODULE_PARM_DESC(init_reset_delay, "Initial bus reset delay (0=no reset)");
73
74 static int sync_rate = CONFIG_SCSI_MESH_SYNC_RATE;
75 static int sync_targets = 0xff;
76 static int resel_targets = 0xff;
77 static int debug_targets = 0;   /* print debug for these targets */
78 static int init_reset_delay = CONFIG_SCSI_MESH_RESET_DELAY_MS;
79
80 static int mesh_sync_period = 100;
81 static int mesh_sync_offset = 0;
82 static unsigned char use_active_neg = 0;  /* bit mask for SEQ_ACTIVE_NEG if used */
83
84 #define ALLOW_SYNC(tgt)         ((sync_targets >> (tgt)) & 1)
85 #define ALLOW_RESEL(tgt)        ((resel_targets >> (tgt)) & 1)
86 #define ALLOW_DEBUG(tgt)        ((debug_targets >> (tgt)) & 1)
87 #define DEBUG_TARGET(cmd)       ((cmd) && ALLOW_DEBUG((cmd)->device->id))
88
89 #undef MESH_DBG
90 #define N_DBG_LOG       50
91 #define N_DBG_SLOG      20
92 #define NUM_DBG_EVENTS  13
93 #undef  DBG_USE_TB              /* bombs on 601 */
94
95 struct dbglog {
96         char    *fmt;
97         u32     tb;
98         u8      phase;
99         u8      bs0;
100         u8      bs1;
101         u8      tgt;
102         int     d;
103 };
104
105 enum mesh_phase {
106         idle,
107         arbitrating,
108         selecting,
109         commanding,
110         dataing,
111         statusing,
112         busfreeing,
113         disconnecting,
114         reselecting,
115         sleeping
116 };
117
118 enum msg_phase {
119         msg_none,
120         msg_out,
121         msg_out_xxx,
122         msg_out_last,
123         msg_in,
124         msg_in_bad,
125 };
126
127 enum sdtr_phase {
128         do_sdtr,
129         sdtr_sent,
130         sdtr_done
131 };
132
133 struct mesh_target {
134         enum sdtr_phase sdtr_state;
135         int     sync_params;
136         int     data_goes_out;          /* guess as to data direction */
137         struct scsi_cmnd *current_req;
138         u32     saved_ptr;
139 #ifdef MESH_DBG
140         int     log_ix;
141         int     n_log;
142         struct dbglog log[N_DBG_LOG];
143 #endif
144 };
145
146 struct mesh_state {
147         volatile struct mesh_regs *mesh;
148         int     meshintr;
149         volatile struct dbdma_regs *dma;
150         int     dmaintr;
151         struct  Scsi_Host *host;
152         struct  mesh_state *next;
153         struct scsi_cmnd *request_q;
154         struct scsi_cmnd *request_qtail;
155         enum mesh_phase phase;          /* what we're currently trying to do */
156         enum msg_phase msgphase;
157         int     conn_tgt;               /* target we're connected to */
158         struct scsi_cmnd *current_req;          /* req we're currently working on */
159         int     data_ptr;
160         int     dma_started;
161         int     dma_count;
162         int     stat;
163         int     aborting;
164         int     expect_reply;
165         int     n_msgin;
166         u8      msgin[16];
167         int     n_msgout;
168         int     last_n_msgout;
169         u8      msgout[16];
170         struct dbdma_cmd *dma_cmds;     /* space for dbdma commands, aligned */
171         dma_addr_t dma_cmd_bus;
172         void    *dma_cmd_space;
173         int     dma_cmd_size;
174         int     clk_freq;
175         struct mesh_target tgts[8];
176         struct macio_dev *mdev;
177         struct pci_dev* pdev;
178 #ifdef MESH_DBG
179         int     log_ix;
180         int     n_log;
181         struct dbglog log[N_DBG_SLOG];
182 #endif
183 };
184
185 /*
186  * Driver is too messy, we need a few prototypes...
187  */
188 static void mesh_done(struct mesh_state *ms, int start_next);
189 static void mesh_interrupt(int irq, void *dev_id, struct pt_regs *ptregs);
190 static void cmd_complete(struct mesh_state *ms);
191 static void set_dma_cmds(struct mesh_state *ms, struct scsi_cmnd *cmd);
192 static void halt_dma(struct mesh_state *ms);
193 static void phase_mismatch(struct mesh_state *ms);
194
195
196 /*
197  * Some debugging & logging routines
198  */
199
200 #ifdef MESH_DBG
201
202 static inline u32 readtb(void)
203 {
204         u32 tb;
205
206 #ifdef DBG_USE_TB
207         /* Beware: if you enable this, it will crash on 601s. */
208         asm ("mftb %0" : "=r" (tb) : );
209 #else
210         tb = 0;
211 #endif
212         return tb;
213 }
214
215 static void dlog(struct mesh_state *ms, char *fmt, int a)
216 {
217         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
218         struct dbglog *tlp, *slp;
219
220         tlp = &tp->log[tp->log_ix];
221         slp = &ms->log[ms->log_ix];
222         tlp->fmt = fmt;
223         tlp->tb = readtb();
224         tlp->phase = (ms->msgphase << 4) + ms->phase;
225         tlp->bs0 = ms->mesh->bus_status0;
226         tlp->bs1 = ms->mesh->bus_status1;
227         tlp->tgt = ms->conn_tgt;
228         tlp->d = a;
229         *slp = *tlp;
230         if (++tp->log_ix >= N_DBG_LOG)
231                 tp->log_ix = 0;
232         if (tp->n_log < N_DBG_LOG)
233                 ++tp->n_log;
234         if (++ms->log_ix >= N_DBG_SLOG)
235                 ms->log_ix = 0;
236         if (ms->n_log < N_DBG_SLOG)
237                 ++ms->n_log;
238 }
239
240 static void dumplog(struct mesh_state *ms, int t)
241 {
242         struct mesh_target *tp = &ms->tgts[t];
243         struct dbglog *lp;
244         int i;
245
246         if (tp->n_log == 0)
247                 return;
248         i = tp->log_ix - tp->n_log;
249         if (i < 0)
250                 i += N_DBG_LOG;
251         tp->n_log = 0;
252         do {
253                 lp = &tp->log[i];
254                 printk(KERN_DEBUG "mesh log %d: bs=%.2x%.2x ph=%.2x ",
255                        t, lp->bs1, lp->bs0, lp->phase);
256 #ifdef DBG_USE_TB
257                 printk("tb=%10u ", lp->tb);
258 #endif
259                 printk(lp->fmt, lp->d);
260                 printk("\n");
261                 if (++i >= N_DBG_LOG)
262                         i = 0;
263         } while (i != tp->log_ix);
264 }
265
266 static void dumpslog(struct mesh_state *ms)
267 {
268         struct dbglog *lp;
269         int i;
270
271         if (ms->n_log == 0)
272                 return;
273         i = ms->log_ix - ms->n_log;
274         if (i < 0)
275                 i += N_DBG_SLOG;
276         ms->n_log = 0;
277         do {
278                 lp = &ms->log[i];
279                 printk(KERN_DEBUG "mesh log: bs=%.2x%.2x ph=%.2x t%d ",
280                        lp->bs1, lp->bs0, lp->phase, lp->tgt);
281 #ifdef DBG_USE_TB
282                 printk("tb=%10u ", lp->tb);
283 #endif
284                 printk(lp->fmt, lp->d);
285                 printk("\n");
286                 if (++i >= N_DBG_SLOG)
287                         i = 0;
288         } while (i != ms->log_ix);
289 }
290
291 #else
292
293 static inline void dlog(struct mesh_state *ms, char *fmt, int a)
294 {}
295 static inline void dumplog(struct mesh_state *ms, int tgt)
296 {}
297 static inline void dumpslog(struct mesh_state *ms)
298 {}
299
300 #endif /* MESH_DBG */
301
302 #define MKWORD(a, b, c, d)      (((a) << 24) + ((b) << 16) + ((c) << 8) + (d))
303
304 static void
305 mesh_dump_regs(struct mesh_state *ms)
306 {
307         volatile struct mesh_regs *mr = ms->mesh;
308         volatile struct dbdma_regs *md = ms->dma;
309         int t;
310         struct mesh_target *tp;
311
312         printk(KERN_DEBUG "mesh: state at %p, regs at %p, dma at %p\n",
313                ms, mr, md);
314         printk(KERN_DEBUG "    ct=%4x seq=%2x bs=%4x fc=%2x "
315                "exc=%2x err=%2x im=%2x int=%2x sp=%2x\n",
316                (mr->count_hi << 8) + mr->count_lo, mr->sequence,
317                (mr->bus_status1 << 8) + mr->bus_status0, mr->fifo_count,
318                mr->exception, mr->error, mr->intr_mask, mr->interrupt,
319                mr->sync_params);
320         while(in_8(&mr->fifo_count))
321                 printk(KERN_DEBUG " fifo data=%.2x\n",in_8(&mr->fifo));
322         printk(KERN_DEBUG "    dma stat=%x cmdptr=%x\n",
323                in_le32(&md->status), in_le32(&md->cmdptr));
324         printk(KERN_DEBUG "    phase=%d msgphase=%d conn_tgt=%d data_ptr=%d\n",
325                ms->phase, ms->msgphase, ms->conn_tgt, ms->data_ptr);
326         printk(KERN_DEBUG "    dma_st=%d dma_ct=%d n_msgout=%d\n",
327                ms->dma_started, ms->dma_count, ms->n_msgout);
328         for (t = 0; t < 8; ++t) {
329                 tp = &ms->tgts[t];
330                 if (tp->current_req == NULL)
331                         continue;
332                 printk(KERN_DEBUG "    target %d: req=%p goes_out=%d saved_ptr=%d\n",
333                        t, tp->current_req, tp->data_goes_out, tp->saved_ptr);
334         }
335 }
336
337
338 /*
339  * Flush write buffers on the bus path to the mesh
340  */
341 static inline void mesh_flush_io(volatile struct mesh_regs *mr)
342 {
343         (void)in_8(&mr->mesh_id);
344 }
345
346
347 /*
348  * Complete a SCSI command
349  */
350 static void mesh_completed(struct mesh_state *ms, struct scsi_cmnd *cmd)
351 {
352         (*cmd->scsi_done)(cmd);
353 }
354
355
356 /* Called with  meshinterrupt disabled, initialize the chipset
357  * and eventually do the initial bus reset. The lock must not be
358  * held since we can schedule.
359  */
360 static void mesh_init(struct mesh_state *ms)
361 {
362         volatile struct mesh_regs *mr = ms->mesh;
363         volatile struct dbdma_regs *md = ms->dma;
364
365         mesh_flush_io(mr);
366         udelay(100);
367
368         /* Reset controller */
369         out_le32(&md->control, (RUN|PAUSE|FLUSH|WAKE) << 16);   /* stop dma */
370         out_8(&mr->exception, 0xff);    /* clear all exception bits */
371         out_8(&mr->error, 0xff);        /* clear all error bits */
372         out_8(&mr->sequence, SEQ_RESETMESH);
373         mesh_flush_io(mr);
374         udelay(10);
375         out_8(&mr->intr_mask, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
376         out_8(&mr->source_id, ms->host->this_id);
377         out_8(&mr->sel_timeout, 25);    /* 250ms */
378         out_8(&mr->sync_params, ASYNC_PARAMS);
379
380         if (init_reset_delay) {
381                 printk(KERN_INFO "mesh: performing initial bus reset...\n");
382                 
383                 /* Reset bus */
384                 out_8(&mr->bus_status1, BS1_RST);       /* assert RST */
385                 mesh_flush_io(mr);
386                 udelay(30);                     /* leave it on for >= 25us */
387                 out_8(&mr->bus_status1, 0);     /* negate RST */
388                 mesh_flush_io(mr);
389
390                 /* Wait for bus to come back */
391                 current->state = TASK_UNINTERRUPTIBLE;
392                 schedule_timeout((init_reset_delay * HZ) / 1000);
393         }
394         
395         /* Reconfigure controller */
396         out_8(&mr->interrupt, 0xff);    /* clear all interrupt bits */
397         out_8(&mr->sequence, SEQ_FLUSHFIFO);
398         mesh_flush_io(mr);
399         udelay(1);
400         out_8(&mr->sync_params, ASYNC_PARAMS);
401         out_8(&mr->sequence, SEQ_ENBRESEL);
402
403         ms->phase = idle;
404         ms->msgphase = msg_none;
405 }
406
407
408 static void mesh_start_cmd(struct mesh_state *ms, struct scsi_cmnd *cmd)
409 {
410         volatile struct mesh_regs *mr = ms->mesh;
411         int t, id;
412
413         id = cmd->device->id;
414         ms->current_req = cmd;
415         ms->tgts[id].data_goes_out = cmd->sc_data_direction == DMA_TO_DEVICE;
416         ms->tgts[id].current_req = cmd;
417
418 #if 1
419         if (DEBUG_TARGET(cmd)) {
420                 int i;
421                 printk(KERN_DEBUG "mesh_start: %p ser=%lu tgt=%d cmd=",
422                        cmd, cmd->serial_number, id);
423                 for (i = 0; i < cmd->cmd_len; ++i)
424                         printk(" %x", cmd->cmnd[i]);
425                 printk(" use_sg=%d buffer=%p bufflen=%u\n",
426                        cmd->use_sg, cmd->request_buffer, cmd->request_bufflen);
427         }
428 #endif
429         if (ms->dma_started)
430                 panic("mesh: double DMA start !\n");
431
432         ms->phase = arbitrating;
433         ms->msgphase = msg_none;
434         ms->data_ptr = 0;
435         ms->dma_started = 0;
436         ms->n_msgout = 0;
437         ms->last_n_msgout = 0;
438         ms->expect_reply = 0;
439         ms->conn_tgt = id;
440         ms->tgts[id].saved_ptr = 0;
441         ms->stat = DID_OK;
442         ms->aborting = 0;
443 #ifdef MESH_DBG
444         ms->tgts[id].n_log = 0;
445         dlog(ms, "start cmd=%x", (int) cmd);
446 #endif
447
448         /* Off we go */
449         dlog(ms, "about to arb, intr/exc/err/fc=%.8x",
450              MKWORD(mr->interrupt, mr->exception, mr->error, mr->fifo_count));
451         out_8(&mr->interrupt, INT_CMDDONE);
452         out_8(&mr->sequence, SEQ_ENBRESEL);
453         mesh_flush_io(mr);
454         udelay(1);
455
456         if (in_8(&mr->bus_status1) & (BS1_BSY | BS1_SEL)) {
457                 /*
458                  * Some other device has the bus or is arbitrating for it -
459                  * probably a target which is about to reselect us.
460                  */
461                 dlog(ms, "busy b4 arb, intr/exc/err/fc=%.8x",
462                      MKWORD(mr->interrupt, mr->exception,
463                             mr->error, mr->fifo_count));
464                 for (t = 100; t > 0; --t) {
465                         if ((in_8(&mr->bus_status1) & (BS1_BSY | BS1_SEL)) == 0)
466                                 break;
467                         if (in_8(&mr->interrupt) != 0) {
468                                 dlog(ms, "intr b4 arb, intr/exc/err/fc=%.8x",
469                                      MKWORD(mr->interrupt, mr->exception,
470                                             mr->error, mr->fifo_count));
471                                 mesh_interrupt(0, (void *)ms, 0);
472                                 if (ms->phase != arbitrating)
473                                         return;
474                         }
475                         udelay(1);
476                 }
477                 if (in_8(&mr->bus_status1) & (BS1_BSY | BS1_SEL)) {
478                         /* XXX should try again in a little while */
479                         ms->stat = DID_BUS_BUSY;
480                         ms->phase = idle;
481                         mesh_done(ms, 0);
482                         return;
483                 }
484         }
485
486         /*
487          * Apparently the mesh has a bug where it will assert both its
488          * own bit and the target's bit on the bus during arbitration.
489          */
490         out_8(&mr->dest_id, mr->source_id);
491
492         /*
493          * There appears to be a race with reselection sometimes,
494          * where a target reselects us just as we issue the
495          * arbitrate command.  It seems that then the arbitrate
496          * command just hangs waiting for the bus to be free
497          * without giving us a reselection exception.
498          * The only way I have found to get it to respond correctly
499          * is this: disable reselection before issuing the arbitrate
500          * command, then after issuing it, if it looks like a target
501          * is trying to reselect us, reset the mesh and then enable
502          * reselection.
503          */
504         out_8(&mr->sequence, SEQ_DISRESEL);
505         if (in_8(&mr->interrupt) != 0) {
506                 dlog(ms, "intr after disresel, intr/exc/err/fc=%.8x",
507                      MKWORD(mr->interrupt, mr->exception,
508                             mr->error, mr->fifo_count));
509                 mesh_interrupt(0, (void *)ms, 0);
510                 if (ms->phase != arbitrating)
511                         return;
512                 dlog(ms, "after intr after disresel, intr/exc/err/fc=%.8x",
513                      MKWORD(mr->interrupt, mr->exception,
514                             mr->error, mr->fifo_count));
515         }
516
517         out_8(&mr->sequence, SEQ_ARBITRATE);
518
519         for (t = 230; t > 0; --t) {
520                 if (in_8(&mr->interrupt) != 0)
521                         break;
522                 udelay(1);
523         }
524         dlog(ms, "after arb, intr/exc/err/fc=%.8x",
525              MKWORD(mr->interrupt, mr->exception, mr->error, mr->fifo_count));
526         if (in_8(&mr->interrupt) == 0 && (in_8(&mr->bus_status1) & BS1_SEL)
527             && (in_8(&mr->bus_status0) & BS0_IO)) {
528                 /* looks like a reselection - try resetting the mesh */
529                 dlog(ms, "resel? after arb, intr/exc/err/fc=%.8x",
530                      MKWORD(mr->interrupt, mr->exception, mr->error, mr->fifo_count));
531                 out_8(&mr->sequence, SEQ_RESETMESH);
532                 mesh_flush_io(mr);
533                 udelay(10);
534                 out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
535                 out_8(&mr->intr_mask, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
536                 out_8(&mr->sequence, SEQ_ENBRESEL);
537                 mesh_flush_io(mr);
538                 for (t = 10; t > 0 && in_8(&mr->interrupt) == 0; --t)
539                         udelay(1);
540                 dlog(ms, "tried reset after arb, intr/exc/err/fc=%.8x",
541                      MKWORD(mr->interrupt, mr->exception, mr->error, mr->fifo_count));
542 #ifndef MESH_MULTIPLE_HOSTS
543                 if (in_8(&mr->interrupt) == 0 && (in_8(&mr->bus_status1) & BS1_SEL)
544                     && (in_8(&mr->bus_status0) & BS0_IO)) {
545                         printk(KERN_ERR "mesh: controller not responding"
546                                " to reselection!\n");
547                         /*
548                          * If this is a target reselecting us, and the
549                          * mesh isn't responding, the higher levels of
550                          * the scsi code will eventually time out and
551                          * reset the bus.
552                          */
553                 }
554 #endif
555         }
556 }
557
558 /*
559  * Start the next command for a MESH.
560  * Should be called with interrupts disabled.
561  */
562 static void mesh_start(struct mesh_state *ms)
563 {
564         struct scsi_cmnd *cmd, *prev, *next;
565
566         if (ms->phase != idle || ms->current_req != NULL) {
567                 printk(KERN_ERR "inappropriate mesh_start (phase=%d, ms=%p)",
568                        ms->phase, ms);
569                 return;
570         }
571
572         while (ms->phase == idle) {
573                 prev = NULL;
574                 for (cmd = ms->request_q; ; cmd = (struct scsi_cmnd *) cmd->host_scribble) {
575                         if (cmd == NULL)
576                                 return;
577                         if (ms->tgts[cmd->device->id].current_req == NULL)
578                                 break;
579                         prev = cmd;
580                 }
581                 next = (struct scsi_cmnd *) cmd->host_scribble;
582                 if (prev == NULL)
583                         ms->request_q = next;
584                 else
585                         prev->host_scribble = (void *) next;
586                 if (next == NULL)
587                         ms->request_qtail = prev;
588
589                 mesh_start_cmd(ms, cmd);
590         }
591 }
592
593 static void mesh_done(struct mesh_state *ms, int start_next)
594 {
595         struct scsi_cmnd *cmd;
596         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
597
598         cmd = ms->current_req;
599         ms->current_req = 0;
600         tp->current_req = 0;
601         if (cmd) {
602                 cmd->result = (ms->stat << 16) + cmd->SCp.Status;
603                 if (ms->stat == DID_OK)
604                         cmd->result += (cmd->SCp.Message << 8);
605                 if (DEBUG_TARGET(cmd)) {
606                         printk(KERN_DEBUG "mesh_done: result = %x, data_ptr=%d, buflen=%d\n",
607                                cmd->result, ms->data_ptr, cmd->request_bufflen);
608                         if ((cmd->cmnd[0] == 0 || cmd->cmnd[0] == 0x12 || cmd->cmnd[0] == 3)
609                             && cmd->request_buffer != 0) {
610                                 unsigned char *b = cmd->request_buffer;
611                                 printk(KERN_DEBUG "buffer = %x %x %x %x %x %x %x %x\n",
612                                        b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]);
613                         }
614                 }
615                 cmd->SCp.this_residual -= ms->data_ptr;
616                 mesh_completed(ms, cmd);
617         }
618         if (start_next) {
619                 out_8(&ms->mesh->sequence, SEQ_ENBRESEL);
620                 mesh_flush_io(ms->mesh);
621                 udelay(1);
622                 ms->phase = idle;
623                 mesh_start(ms);
624         }
625 }
626
627 static inline void add_sdtr_msg(struct mesh_state *ms)
628 {
629         int i = ms->n_msgout;
630
631         ms->msgout[i] = EXTENDED_MESSAGE;
632         ms->msgout[i+1] = 3;
633         ms->msgout[i+2] = EXTENDED_SDTR;
634         ms->msgout[i+3] = mesh_sync_period/4;
635         ms->msgout[i+4] = (ALLOW_SYNC(ms->conn_tgt)? mesh_sync_offset: 0);
636         ms->n_msgout = i + 5;
637 }
638
639 static void set_sdtr(struct mesh_state *ms, int period, int offset)
640 {
641         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
642         volatile struct mesh_regs *mr = ms->mesh;
643         int v, tr;
644
645         tp->sdtr_state = sdtr_done;
646         if (offset == 0) {
647                 /* asynchronous */
648                 if (SYNC_OFF(tp->sync_params))
649                         printk(KERN_INFO "mesh: target %d now asynchronous\n",
650                                ms->conn_tgt);
651                 tp->sync_params = ASYNC_PARAMS;
652                 out_8(&mr->sync_params, ASYNC_PARAMS);
653                 return;
654         }
655         /*
656          * We need to compute ceil(clk_freq * period / 500e6) - 2
657          * without incurring overflow.
658          */
659         v = (ms->clk_freq / 5000) * period;
660         if (v <= 250000) {
661                 /* special case: sync_period == 5 * clk_period */
662                 v = 0;
663                 /* units of tr are 100kB/s */
664                 tr = (ms->clk_freq + 250000) / 500000;
665         } else {
666                 /* sync_period == (v + 2) * 2 * clk_period */
667                 v = (v + 99999) / 100000 - 2;
668                 if (v > 15)
669                         v = 15; /* oops */
670                 tr = ((ms->clk_freq / (v + 2)) + 199999) / 200000;
671         }
672         if (offset > 15)
673                 offset = 15;    /* can't happen */
674         tp->sync_params = SYNC_PARAMS(offset, v);
675         out_8(&mr->sync_params, tp->sync_params);
676         printk(KERN_INFO "mesh: target %d synchronous at %d.%d MB/s\n",
677                ms->conn_tgt, tr/10, tr%10);
678 }
679
680 static void start_phase(struct mesh_state *ms)
681 {
682         int i, seq, nb;
683         volatile struct mesh_regs *mr = ms->mesh;
684         volatile struct dbdma_regs *md = ms->dma;
685         struct scsi_cmnd *cmd = ms->current_req;
686         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
687
688         dlog(ms, "start_phase nmo/exc/fc/seq = %.8x",
689              MKWORD(ms->n_msgout, mr->exception, mr->fifo_count, mr->sequence));
690         out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
691         seq = use_active_neg + (ms->n_msgout? SEQ_ATN: 0);
692         switch (ms->msgphase) {
693         case msg_none:
694                 break;
695
696         case msg_in:
697                 out_8(&mr->count_hi, 0);
698                 out_8(&mr->count_lo, 1);
699                 out_8(&mr->sequence, SEQ_MSGIN + seq);
700                 ms->n_msgin = 0;
701                 return;
702
703         case msg_out:
704                 /*
705                  * To make sure ATN drops before we assert ACK for
706                  * the last byte of the message, we have to do the
707                  * last byte specially.
708                  */
709                 if (ms->n_msgout <= 0) {
710                         printk(KERN_ERR "mesh: msg_out but n_msgout=%d\n",
711                                ms->n_msgout);
712                         mesh_dump_regs(ms);
713                         ms->msgphase = msg_none;
714                         break;
715                 }
716                 if (ALLOW_DEBUG(ms->conn_tgt)) {
717                         printk(KERN_DEBUG "mesh: sending %d msg bytes:",
718                                ms->n_msgout);
719                         for (i = 0; i < ms->n_msgout; ++i)
720                                 printk(" %x", ms->msgout[i]);
721                         printk("\n");
722                 }
723                 dlog(ms, "msgout msg=%.8x", MKWORD(ms->n_msgout, ms->msgout[0],
724                                                 ms->msgout[1], ms->msgout[2]));
725                 out_8(&mr->count_hi, 0);
726                 out_8(&mr->sequence, SEQ_FLUSHFIFO);
727                 mesh_flush_io(mr);
728                 udelay(1);
729                 /*
730                  * If ATN is not already asserted, we assert it, then
731                  * issue a SEQ_MSGOUT to get the mesh to drop ACK.
732                  */
733                 if ((in_8(&mr->bus_status0) & BS0_ATN) == 0) {
734                         dlog(ms, "bus0 was %.2x explictly asserting ATN", mr->bus_status0);
735                         out_8(&mr->bus_status0, BS0_ATN); /* explicit ATN */
736                         mesh_flush_io(mr);
737                         udelay(1);
738                         out_8(&mr->count_lo, 1);
739                         out_8(&mr->sequence, SEQ_MSGOUT + seq);
740                         out_8(&mr->bus_status0, 0); /* release explicit ATN */
741                         dlog(ms,"hace: after explicit ATN bus0=%.2x",mr->bus_status0);
742                 }
743                 if (ms->n_msgout == 1) {
744                         /*
745                          * We can't issue the SEQ_MSGOUT without ATN
746                          * until the target has asserted REQ.  The logic
747                          * in cmd_complete handles both situations:
748                          * REQ already asserted or not.
749                          */
750                         cmd_complete(ms);
751                 } else {
752                         out_8(&mr->count_lo, ms->n_msgout - 1);
753                         out_8(&mr->sequence, SEQ_MSGOUT + seq);
754                         for (i = 0; i < ms->n_msgout - 1; ++i)
755                                 out_8(&mr->fifo, ms->msgout[i]);
756                 }
757                 return;
758
759         default:
760                 printk(KERN_ERR "mesh bug: start_phase msgphase=%d\n",
761                        ms->msgphase);
762         }
763
764         switch (ms->phase) {
765         case selecting:
766                 out_8(&mr->dest_id, ms->conn_tgt);
767                 out_8(&mr->sequence, SEQ_SELECT + SEQ_ATN);
768                 break;
769         case commanding:
770                 out_8(&mr->sync_params, tp->sync_params);
771                 out_8(&mr->count_hi, 0);
772                 if (cmd) {
773                         out_8(&mr->count_lo, cmd->cmd_len);
774                         out_8(&mr->sequence, SEQ_COMMAND + seq);
775                         for (i = 0; i < cmd->cmd_len; ++i)
776                                 out_8(&mr->fifo, cmd->cmnd[i]);
777                 } else {
778                         out_8(&mr->count_lo, 6);
779                         out_8(&mr->sequence, SEQ_COMMAND + seq);
780                         for (i = 0; i < 6; ++i)
781                                 out_8(&mr->fifo, 0);
782                 }
783                 break;
784         case dataing:
785                 /* transfer data, if any */
786                 if (!ms->dma_started) {
787                         set_dma_cmds(ms, cmd);
788                         out_le32(&md->cmdptr, virt_to_phys(ms->dma_cmds));
789                         out_le32(&md->control, (RUN << 16) | RUN);
790                         ms->dma_started = 1;
791                 }
792                 nb = ms->dma_count;
793                 if (nb > 0xfff0)
794                         nb = 0xfff0;
795                 ms->dma_count -= nb;
796                 ms->data_ptr += nb;
797                 out_8(&mr->count_lo, nb);
798                 out_8(&mr->count_hi, nb >> 8);
799                 out_8(&mr->sequence, (tp->data_goes_out?
800                                 SEQ_DATAOUT: SEQ_DATAIN) + SEQ_DMA_MODE + seq);
801                 break;
802         case statusing:
803                 out_8(&mr->count_hi, 0);
804                 out_8(&mr->count_lo, 1);
805                 out_8(&mr->sequence, SEQ_STATUS + seq);
806                 break;
807         case busfreeing:
808         case disconnecting:
809                 out_8(&mr->sequence, SEQ_ENBRESEL);
810                 mesh_flush_io(mr);
811                 udelay(1);
812                 dlog(ms, "enbresel intr/exc/err/fc=%.8x",
813                      MKWORD(mr->interrupt, mr->exception, mr->error,
814                             mr->fifo_count));
815                 out_8(&mr->sequence, SEQ_BUSFREE);
816                 break;
817         default:
818                 printk(KERN_ERR "mesh: start_phase called with phase=%d\n",
819                        ms->phase);
820                 dumpslog(ms);
821         }
822
823 }
824
825 static inline void get_msgin(struct mesh_state *ms)
826 {
827         volatile struct mesh_regs *mr = ms->mesh;
828         int i, n;
829
830         n = mr->fifo_count;
831         if (n != 0) {
832                 i = ms->n_msgin;
833                 ms->n_msgin = i + n;
834                 for (; n > 0; --n)
835                         ms->msgin[i++] = in_8(&mr->fifo);
836         }
837 }
838
839 static inline int msgin_length(struct mesh_state *ms)
840 {
841         int b, n;
842
843         n = 1;
844         if (ms->n_msgin > 0) {
845                 b = ms->msgin[0];
846                 if (b == 1) {
847                         /* extended message */
848                         n = ms->n_msgin < 2? 2: ms->msgin[1] + 2;
849                 } else if (0x20 <= b && b <= 0x2f) {
850                         /* 2-byte message */
851                         n = 2;
852                 }
853         }
854         return n;
855 }
856
857 static void reselected(struct mesh_state *ms)
858 {
859         volatile struct mesh_regs *mr = ms->mesh;
860         struct scsi_cmnd *cmd;
861         struct mesh_target *tp;
862         int b, t, prev;
863
864         switch (ms->phase) {
865         case idle:
866                 break;
867         case arbitrating:
868                 if ((cmd = ms->current_req) != NULL) {
869                         /* put the command back on the queue */
870                         cmd->host_scribble = (void *) ms->request_q;
871                         if (ms->request_q == NULL)
872                                 ms->request_qtail = cmd;
873                         ms->request_q = cmd;
874                         tp = &ms->tgts[cmd->device->id];
875                         tp->current_req = NULL;
876                 }
877                 break;
878         case busfreeing:
879                 ms->phase = reselecting;
880                 mesh_done(ms, 0);
881                 break;
882         case disconnecting:
883                 break;
884         default:
885                 printk(KERN_ERR "mesh: reselected in phase %d/%d tgt %d\n",
886                        ms->msgphase, ms->phase, ms->conn_tgt);
887                 dumplog(ms, ms->conn_tgt);
888                 dumpslog(ms);
889         }
890
891         if (ms->dma_started) {
892                 printk(KERN_ERR "mesh: reselected with DMA started !\n");
893                 halt_dma(ms);
894         }
895         ms->current_req = NULL;
896         ms->phase = dataing;
897         ms->msgphase = msg_in;
898         ms->n_msgout = 0;
899         ms->last_n_msgout = 0;
900         prev = ms->conn_tgt;
901
902         /*
903          * We seem to get abortive reselections sometimes.
904          */
905         while ((in_8(&mr->bus_status1) & BS1_BSY) == 0) {
906                 static int mesh_aborted_resels;
907                 mesh_aborted_resels++;
908                 out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
909                 mesh_flush_io(mr);
910                 udelay(1);
911                 out_8(&mr->sequence, SEQ_ENBRESEL);
912                 mesh_flush_io(mr);
913                 udelay(5);
914                 dlog(ms, "extra resel err/exc/fc = %.6x",
915                      MKWORD(0, mr->error, mr->exception, mr->fifo_count));
916         }
917         out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
918         mesh_flush_io(mr);
919         udelay(1);
920         out_8(&mr->sequence, SEQ_ENBRESEL);
921         mesh_flush_io(mr);
922         udelay(1);
923         out_8(&mr->sync_params, ASYNC_PARAMS);
924
925         /*
926          * Find out who reselected us.
927          */
928         if (in_8(&mr->fifo_count) == 0) {
929                 printk(KERN_ERR "mesh: reselection but nothing in fifo?\n");
930                 ms->conn_tgt = ms->host->this_id;
931                 goto bogus;
932         }
933         /* get the last byte in the fifo */
934         do {
935                 b = in_8(&mr->fifo);
936                 dlog(ms, "reseldata %x", b);
937         } while (in_8(&mr->fifo_count));
938         for (t = 0; t < 8; ++t)
939                 if ((b & (1 << t)) != 0 && t != ms->host->this_id)
940                         break;
941         if (b != (1 << t) + (1 << ms->host->this_id)) {
942                 printk(KERN_ERR "mesh: bad reselection data %x\n", b);
943                 ms->conn_tgt = ms->host->this_id;
944                 goto bogus;
945         }
946
947
948         /*
949          * Set up to continue with that target's transfer.
950          */
951         ms->conn_tgt = t;
952         tp = &ms->tgts[t];
953         out_8(&mr->sync_params, tp->sync_params);
954         if (ALLOW_DEBUG(t)) {
955                 printk(KERN_DEBUG "mesh: reselected by target %d\n", t);
956                 printk(KERN_DEBUG "mesh: saved_ptr=%x goes_out=%d cmd=%p\n",
957                        tp->saved_ptr, tp->data_goes_out, tp->current_req);
958         }
959         ms->current_req = tp->current_req;
960         if (tp->current_req == NULL) {
961                 printk(KERN_ERR "mesh: reselected by tgt %d but no cmd!\n", t);
962                 goto bogus;
963         }
964         ms->data_ptr = tp->saved_ptr;
965         dlog(ms, "resel prev tgt=%d", prev);
966         dlog(ms, "resel err/exc=%.4x", MKWORD(0, 0, mr->error, mr->exception));
967         start_phase(ms);
968         return;
969
970 bogus:
971         dumplog(ms, ms->conn_tgt);
972         dumpslog(ms);
973         ms->data_ptr = 0;
974         ms->aborting = 1;
975         start_phase(ms);
976 }
977
978 static void do_abort(struct mesh_state *ms)
979 {
980         ms->msgout[0] = ABORT;
981         ms->n_msgout = 1;
982         ms->aborting = 1;
983         ms->stat = DID_ABORT;
984         dlog(ms, "abort", 0);
985 }
986
987 static void handle_reset(struct mesh_state *ms)
988 {
989         int tgt;
990         struct mesh_target *tp;
991         struct scsi_cmnd *cmd;
992         volatile struct mesh_regs *mr = ms->mesh;
993
994         for (tgt = 0; tgt < 8; ++tgt) {
995                 tp = &ms->tgts[tgt];
996                 if ((cmd = tp->current_req) != NULL) {
997                         cmd->result = DID_RESET << 16;
998                         tp->current_req = NULL;
999                         mesh_completed(ms, cmd);
1000                 }
1001                 ms->tgts[tgt].sdtr_state = do_sdtr;
1002                 ms->tgts[tgt].sync_params = ASYNC_PARAMS;
1003         }
1004         ms->current_req = NULL;
1005         while ((cmd = ms->request_q) != NULL) {
1006                 ms->request_q = (struct scsi_cmnd *) cmd->host_scribble;
1007                 cmd->result = DID_RESET << 16;
1008                 mesh_completed(ms, cmd);
1009         }
1010         ms->phase = idle;
1011         ms->msgphase = msg_none;
1012         out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
1013         out_8(&mr->sequence, SEQ_FLUSHFIFO);
1014         mesh_flush_io(mr);
1015         udelay(1);
1016         out_8(&mr->sync_params, ASYNC_PARAMS);
1017         out_8(&mr->sequence, SEQ_ENBRESEL);
1018 }
1019
1020 static irqreturn_t do_mesh_interrupt(int irq, void *dev_id, struct pt_regs *ptregs)
1021 {
1022         unsigned long flags;
1023         struct Scsi_Host *dev = ((struct mesh_state *)dev_id)->host;
1024         
1025         spin_lock_irqsave(dev->host_lock, flags);
1026         mesh_interrupt(irq, dev_id, ptregs);
1027         spin_unlock_irqrestore(dev->host_lock, flags);
1028         return IRQ_HANDLED;
1029 }
1030
1031 static void handle_error(struct mesh_state *ms)
1032 {
1033         int err, exc, count;
1034         volatile struct mesh_regs *mr = ms->mesh;
1035
1036         err = in_8(&mr->error);
1037         exc = in_8(&mr->exception);
1038         out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
1039         dlog(ms, "error err/exc/fc/cl=%.8x",
1040              MKWORD(err, exc, mr->fifo_count, mr->count_lo));
1041         if (err & ERR_SCSIRESET) {
1042                 /* SCSI bus was reset */
1043                 printk(KERN_INFO "mesh: SCSI bus reset detected: "
1044                        "waiting for end...");
1045                 while ((in_8(&mr->bus_status1) & BS1_RST) != 0)
1046                         udelay(1);
1047                 printk("done\n");
1048                 handle_reset(ms);
1049                 /* request_q is empty, no point in mesh_start() */
1050                 return;
1051         }
1052         if (err & ERR_UNEXPDISC) {
1053                 /* Unexpected disconnect */
1054                 if (exc & EXC_RESELECTED) {
1055                         reselected(ms);
1056                         return;
1057                 }
1058                 if (!ms->aborting) {
1059                         printk(KERN_WARNING "mesh: target %d aborted\n",
1060                                ms->conn_tgt);
1061                         dumplog(ms, ms->conn_tgt);
1062                         dumpslog(ms);
1063                 }
1064                 out_8(&mr->interrupt, INT_CMDDONE);
1065                 ms->stat = DID_ABORT;
1066                 mesh_done(ms, 1);
1067                 return;
1068         }
1069         if (err & ERR_PARITY) {
1070                 if (ms->msgphase == msg_in) {
1071                         printk(KERN_ERR "mesh: msg parity error, target %d\n",
1072                                ms->conn_tgt);
1073                         ms->msgout[0] = MSG_PARITY_ERROR;
1074                         ms->n_msgout = 1;
1075                         ms->msgphase = msg_in_bad;
1076                         cmd_complete(ms);
1077                         return;
1078                 }
1079                 if (ms->stat == DID_OK) {
1080                         printk(KERN_ERR "mesh: parity error, target %d\n",
1081                                ms->conn_tgt);
1082                         ms->stat = DID_PARITY;
1083                 }
1084                 count = (mr->count_hi << 8) + mr->count_lo;
1085                 if (count == 0) {
1086                         cmd_complete(ms);
1087                 } else {
1088                         /* reissue the data transfer command */
1089                         out_8(&mr->sequence, mr->sequence);
1090                 }
1091                 return;
1092         }
1093         if (err & ERR_SEQERR) {
1094                 if (exc & EXC_RESELECTED) {
1095                         /* This can happen if we issue a command to
1096                            get the bus just after the target reselects us. */
1097                         static int mesh_resel_seqerr;
1098                         mesh_resel_seqerr++;
1099                         reselected(ms);
1100                         return;
1101                 }
1102                 if (exc == EXC_PHASEMM) {
1103                         static int mesh_phasemm_seqerr;
1104                         mesh_phasemm_seqerr++;
1105                         phase_mismatch(ms);
1106                         return;
1107                 }
1108                 printk(KERN_ERR "mesh: sequence error (err=%x exc=%x)\n",
1109                        err, exc);
1110         } else {
1111                 printk(KERN_ERR "mesh: unknown error %x (exc=%x)\n", err, exc);
1112         }
1113         mesh_dump_regs(ms);
1114         dumplog(ms, ms->conn_tgt);
1115         if (ms->phase > selecting && (in_8(&mr->bus_status1) & BS1_BSY)) {
1116                 /* try to do what the target wants */
1117                 do_abort(ms);
1118                 phase_mismatch(ms);
1119                 return;
1120         }
1121         ms->stat = DID_ERROR;
1122         mesh_done(ms, 1);
1123 }
1124
1125 static void handle_exception(struct mesh_state *ms)
1126 {
1127         int exc;
1128         volatile struct mesh_regs *mr = ms->mesh;
1129
1130         exc = in_8(&mr->exception);
1131         out_8(&mr->interrupt, INT_EXCEPTION | INT_CMDDONE);
1132         if (exc & EXC_RESELECTED) {
1133                 static int mesh_resel_exc;
1134                 mesh_resel_exc++;
1135                 reselected(ms);
1136         } else if (exc == EXC_ARBLOST) {
1137                 printk(KERN_DEBUG "mesh: lost arbitration\n");
1138                 ms->stat = DID_BUS_BUSY;
1139                 mesh_done(ms, 1);
1140         } else if (exc == EXC_SELTO) {
1141                 /* selection timed out */
1142                 ms->stat = DID_BAD_TARGET;
1143                 mesh_done(ms, 1);
1144         } else if (exc == EXC_PHASEMM) {
1145                 /* target wants to do something different:
1146                    find out what it wants and do it. */
1147                 phase_mismatch(ms);
1148         } else {
1149                 printk(KERN_ERR "mesh: can't cope with exception %x\n", exc);
1150                 mesh_dump_regs(ms);
1151                 dumplog(ms, ms->conn_tgt);
1152                 do_abort(ms);
1153                 phase_mismatch(ms);
1154         }
1155 }
1156
1157 static void handle_msgin(struct mesh_state *ms)
1158 {
1159         int i, code;
1160         struct scsi_cmnd *cmd = ms->current_req;
1161         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
1162
1163         if (ms->n_msgin == 0)
1164                 return;
1165         code = ms->msgin[0];
1166         if (ALLOW_DEBUG(ms->conn_tgt)) {
1167                 printk(KERN_DEBUG "got %d message bytes:", ms->n_msgin);
1168                 for (i = 0; i < ms->n_msgin; ++i)
1169                         printk(" %x", ms->msgin[i]);
1170                 printk("\n");
1171         }
1172         dlog(ms, "msgin msg=%.8x",
1173              MKWORD(ms->n_msgin, code, ms->msgin[1], ms->msgin[2]));
1174
1175         ms->expect_reply = 0;
1176         ms->n_msgout = 0;
1177         if (ms->n_msgin < msgin_length(ms))
1178                 goto reject;
1179         if (cmd)
1180                 cmd->SCp.Message = code;
1181         switch (code) {
1182         case COMMAND_COMPLETE:
1183                 break;
1184         case EXTENDED_MESSAGE:
1185                 switch (ms->msgin[2]) {
1186                 case EXTENDED_MODIFY_DATA_POINTER:
1187                         ms->data_ptr += (ms->msgin[3] << 24) + ms->msgin[6]
1188                                 + (ms->msgin[4] << 16) + (ms->msgin[5] << 8);
1189                         break;
1190                 case EXTENDED_SDTR:
1191                         if (tp->sdtr_state != sdtr_sent) {
1192                                 /* reply with an SDTR */
1193                                 add_sdtr_msg(ms);
1194                                 /* limit period to at least his value,
1195                                    offset to no more than his */
1196                                 if (ms->msgout[3] < ms->msgin[3])
1197                                         ms->msgout[3] = ms->msgin[3];
1198                                 if (ms->msgout[4] > ms->msgin[4])
1199                                         ms->msgout[4] = ms->msgin[4];
1200                                 set_sdtr(ms, ms->msgout[3], ms->msgout[4]);
1201                                 ms->msgphase = msg_out;
1202                         } else {
1203                                 set_sdtr(ms, ms->msgin[3], ms->msgin[4]);
1204                         }
1205                         break;
1206                 default:
1207                         goto reject;
1208                 }
1209                 break;
1210         case SAVE_POINTERS:
1211                 tp->saved_ptr = ms->data_ptr;
1212                 break;
1213         case RESTORE_POINTERS:
1214                 ms->data_ptr = tp->saved_ptr;
1215                 break;
1216         case DISCONNECT:
1217                 ms->phase = disconnecting;
1218                 break;
1219         case ABORT:
1220                 break;
1221         case MESSAGE_REJECT:
1222                 if (tp->sdtr_state == sdtr_sent)
1223                         set_sdtr(ms, 0, 0);
1224                 break;
1225         case NOP:
1226                 break;
1227         default:
1228                 if (IDENTIFY_BASE <= code && code <= IDENTIFY_BASE + 7) {
1229                         if (cmd == NULL) {
1230                                 do_abort(ms);
1231                                 ms->msgphase = msg_out;
1232                         } else if (code != cmd->device->lun + IDENTIFY_BASE) {
1233                                 printk(KERN_WARNING "mesh: lun mismatch "
1234                                        "(%d != %d) on reselection from "
1235                                        "target %d\n", i, cmd->device->lun,
1236                                        ms->conn_tgt);
1237                         }
1238                         break;
1239                 }
1240                 goto reject;
1241         }
1242         return;
1243
1244  reject:
1245         printk(KERN_WARNING "mesh: rejecting message from target %d:",
1246                ms->conn_tgt);
1247         for (i = 0; i < ms->n_msgin; ++i)
1248                 printk(" %x", ms->msgin[i]);
1249         printk("\n");
1250         ms->msgout[0] = MESSAGE_REJECT;
1251         ms->n_msgout = 1;
1252         ms->msgphase = msg_out;
1253 }
1254
1255 /*
1256  * Set up DMA commands for transferring data.
1257  */
1258 static void set_dma_cmds(struct mesh_state *ms, struct scsi_cmnd *cmd)
1259 {
1260         int i, dma_cmd, total, off, dtot;
1261         struct scatterlist *scl;
1262         struct dbdma_cmd *dcmds;
1263
1264         dma_cmd = ms->tgts[ms->conn_tgt].data_goes_out?
1265                 OUTPUT_MORE: INPUT_MORE;
1266         dcmds = ms->dma_cmds;
1267         dtot = 0;
1268         if (cmd) {
1269                 cmd->SCp.this_residual = cmd->request_bufflen;
1270                 if (cmd->use_sg > 0) {
1271                         int nseg;
1272                         total = 0;
1273                         scl = (struct scatterlist *) cmd->buffer;
1274                         off = ms->data_ptr;
1275                         nseg = pci_map_sg(ms->pdev, scl, cmd->use_sg,
1276                                           cmd->sc_data_direction);
1277                         for (i = 0; i <nseg; ++i, ++scl) {
1278                                 u32 dma_addr = sg_dma_address(scl);
1279                                 u32 dma_len = sg_dma_len(scl);
1280                                 
1281                                 total += scl->length;
1282                                 if (off >= dma_len) {
1283                                         off -= dma_len;
1284                                         continue;
1285                                 }
1286                                 if (dma_len > 0xffff)
1287                                         panic("mesh: scatterlist element >= 64k");
1288                                 st_le16(&dcmds->req_count, dma_len - off);
1289                                 st_le16(&dcmds->command, dma_cmd);
1290                                 st_le32(&dcmds->phy_addr, dma_addr + off);
1291                                 dcmds->xfer_status = 0;
1292                                 ++dcmds;
1293                                 dtot += dma_len - off;
1294                                 off = 0;
1295                         }
1296                 } else if (ms->data_ptr < cmd->request_bufflen) {
1297                         dtot = cmd->request_bufflen - ms->data_ptr;
1298                         if (dtot > 0xffff)
1299                                 panic("mesh: transfer size >= 64k");
1300                         st_le16(&dcmds->req_count, dtot);
1301                         /* XXX Use pci DMA API here ... */
1302                         st_le32(&dcmds->phy_addr,
1303                                 virt_to_phys(cmd->request_buffer) + ms->data_ptr);
1304                         dcmds->xfer_status = 0;
1305                         ++dcmds;
1306                 }
1307         }
1308         if (dtot == 0) {
1309                 /* Either the target has overrun our buffer,
1310                    or the caller didn't provide a buffer. */
1311                 static char mesh_extra_buf[64];
1312
1313                 dtot = sizeof(mesh_extra_buf);
1314                 st_le16(&dcmds->req_count, dtot);
1315                 st_le32(&dcmds->phy_addr, virt_to_phys(mesh_extra_buf));
1316                 dcmds->xfer_status = 0;
1317                 ++dcmds;
1318         }
1319         dma_cmd += OUTPUT_LAST - OUTPUT_MORE;
1320         st_le16(&dcmds[-1].command, dma_cmd);
1321         memset(dcmds, 0, sizeof(*dcmds));
1322         st_le16(&dcmds->command, DBDMA_STOP);
1323         ms->dma_count = dtot;
1324 }
1325
1326 static void halt_dma(struct mesh_state *ms)
1327 {
1328         volatile struct dbdma_regs *md = ms->dma;
1329         volatile struct mesh_regs *mr = ms->mesh;
1330         struct scsi_cmnd *cmd = ms->current_req;
1331         int t, nb;
1332
1333         if (!ms->tgts[ms->conn_tgt].data_goes_out) {
1334                 /* wait a little while until the fifo drains */
1335                 t = 50;
1336                 while (t > 0 && in_8(&mr->fifo_count) != 0
1337                        && (in_le32(&md->status) & ACTIVE) != 0) {
1338                         --t;
1339                         udelay(1);
1340                 }
1341         }
1342         out_le32(&md->control, RUN << 16);      /* turn off RUN bit */
1343         nb = (mr->count_hi << 8) + mr->count_lo;
1344         dlog(ms, "halt_dma fc/count=%.6x",
1345              MKWORD(0, mr->fifo_count, 0, nb));
1346         if (ms->tgts[ms->conn_tgt].data_goes_out)
1347                 nb += mr->fifo_count;
1348         /* nb is the number of bytes not yet transferred
1349            to/from the target. */
1350         ms->data_ptr -= nb;
1351         dlog(ms, "data_ptr %x", ms->data_ptr);
1352         if (ms->data_ptr < 0) {
1353                 printk(KERN_ERR "mesh: halt_dma: data_ptr=%d (nb=%d, ms=%p)\n",
1354                        ms->data_ptr, nb, ms);
1355                 ms->data_ptr = 0;
1356 #ifdef MESH_DBG
1357                 dumplog(ms, ms->conn_tgt);
1358                 dumpslog(ms);
1359 #endif /* MESH_DBG */
1360         } else if (cmd && cmd->request_bufflen != 0 &&
1361                    ms->data_ptr > cmd->request_bufflen) {
1362                 printk(KERN_DEBUG "mesh: target %d overrun, "
1363                        "data_ptr=%x total=%x goes_out=%d\n",
1364                        ms->conn_tgt, ms->data_ptr, cmd->request_bufflen,
1365                        ms->tgts[ms->conn_tgt].data_goes_out);
1366         }
1367         if (cmd->use_sg != 0) {
1368                 struct scatterlist *sg;
1369                 sg = (struct scatterlist *)cmd->request_buffer;
1370                 pci_unmap_sg(ms->pdev, sg, cmd->use_sg, cmd->sc_data_direction);
1371         }
1372         ms->dma_started = 0;
1373 }
1374
1375 static void phase_mismatch(struct mesh_state *ms)
1376 {
1377         volatile struct mesh_regs *mr = ms->mesh;
1378         int phase;
1379
1380         dlog(ms, "phasemm ch/cl/seq/fc=%.8x",
1381              MKWORD(mr->count_hi, mr->count_lo, mr->sequence, mr->fifo_count));
1382         phase = in_8(&mr->bus_status0) & BS0_PHASE;
1383         if (ms->msgphase == msg_out_xxx && phase == BP_MSGOUT) {
1384                 /* output the last byte of the message, without ATN */
1385                 out_8(&mr->count_lo, 1);
1386                 out_8(&mr->sequence, SEQ_MSGOUT + use_active_neg);
1387                 mesh_flush_io(mr);
1388                 udelay(1);
1389                 out_8(&mr->fifo, ms->msgout[ms->n_msgout-1]);
1390                 ms->msgphase = msg_out_last;
1391                 return;
1392         }
1393
1394         if (ms->msgphase == msg_in) {
1395                 get_msgin(ms);
1396                 if (ms->n_msgin)
1397                         handle_msgin(ms);
1398         }
1399
1400         if (ms->dma_started)
1401                 halt_dma(ms);
1402         if (mr->fifo_count) {
1403                 out_8(&mr->sequence, SEQ_FLUSHFIFO);
1404                 mesh_flush_io(mr);
1405                 udelay(1);
1406         }
1407
1408         ms->msgphase = msg_none;
1409         switch (phase) {
1410         case BP_DATAIN:
1411                 ms->tgts[ms->conn_tgt].data_goes_out = 0;
1412                 ms->phase = dataing;
1413                 break;
1414         case BP_DATAOUT:
1415                 ms->tgts[ms->conn_tgt].data_goes_out = 1;
1416                 ms->phase = dataing;
1417                 break;
1418         case BP_COMMAND:
1419                 ms->phase = commanding;
1420                 break;
1421         case BP_STATUS:
1422                 ms->phase = statusing;
1423                 break;
1424         case BP_MSGIN:
1425                 ms->msgphase = msg_in;
1426                 ms->n_msgin = 0;
1427                 break;
1428         case BP_MSGOUT:
1429                 ms->msgphase = msg_out;
1430                 if (ms->n_msgout == 0) {
1431                         if (ms->aborting) {
1432                                 do_abort(ms);
1433                         } else {
1434                                 if (ms->last_n_msgout == 0) {
1435                                         printk(KERN_DEBUG
1436                                                "mesh: no msg to repeat\n");
1437                                         ms->msgout[0] = NOP;
1438                                         ms->last_n_msgout = 1;
1439                                 }
1440                                 ms->n_msgout = ms->last_n_msgout;
1441                         }
1442                 }
1443                 break;
1444         default:
1445                 printk(KERN_DEBUG "mesh: unknown scsi phase %x\n", phase);
1446                 ms->stat = DID_ERROR;
1447                 mesh_done(ms, 1);
1448                 return;
1449         }
1450
1451         start_phase(ms);
1452 }
1453
1454 static void cmd_complete(struct mesh_state *ms)
1455 {
1456         volatile struct mesh_regs *mr = ms->mesh;
1457         struct scsi_cmnd *cmd = ms->current_req;
1458         struct mesh_target *tp = &ms->tgts[ms->conn_tgt];
1459         int seq, n, t;
1460
1461         dlog(ms, "cmd_complete fc=%x", mr->fifo_count);
1462         seq = use_active_neg + (ms->n_msgout? SEQ_ATN: 0);
1463         switch (ms->msgphase) {
1464         case msg_out_xxx:
1465                 /* huh?  we expected a phase mismatch */
1466                 ms->n_msgin = 0;
1467                 ms->msgphase = msg_in;
1468                 /* fall through */
1469
1470         case msg_in:
1471                 /* should have some message bytes in fifo */
1472                 get_msgin(ms);
1473                 n = msgin_length(ms);
1474                 if (ms->n_msgin < n) {
1475                         out_8(&mr->count_lo, n - ms->n_msgin);
1476                         out_8(&mr->sequence, SEQ_MSGIN + seq);
1477                 } else {
1478                         ms->msgphase = msg_none;
1479                         handle_msgin(ms);
1480                         start_phase(ms);
1481                 }
1482                 break;
1483
1484         case msg_in_bad:
1485                 out_8(&mr->sequence, SEQ_FLUSHFIFO);
1486                 mesh_flush_io(mr);
1487                 udelay(1);
1488                 out_8(&mr->count_lo, 1);
1489                 out_8(&mr->sequence, SEQ_MSGIN + SEQ_ATN + use_active_neg);
1490                 break;
1491
1492         case msg_out:
1493                 /*
1494                  * To get the right timing on ATN wrt ACK, we have
1495                  * to get the MESH to drop ACK, wait until REQ gets
1496                  * asserted, then drop ATN.  To do this we first
1497                  * issue a SEQ_MSGOUT with ATN and wait for REQ,
1498                  * then change the command to a SEQ_MSGOUT w/o ATN.
1499                  * If we don't see REQ in a reasonable time, we
1500                  * change the command to SEQ_MSGIN with ATN,
1501                  * wait for the phase mismatch interrupt, then
1502                  * issue the SEQ_MSGOUT without ATN.
1503                  */
1504                 out_8(&mr->count_lo, 1);
1505                 out_8(&mr->sequence, SEQ_MSGOUT + use_active_neg + SEQ_ATN);
1506                 t = 30;         /* wait up to 30us */
1507                 while ((in_8(&mr->bus_status0) & BS0_REQ) == 0 && --t >= 0)
1508                         udelay(1);
1509                 dlog(ms, "last_mbyte err/exc/fc/cl=%.8x",
1510                      MKWORD(mr->error, mr->exception,
1511                             mr->fifo_count, mr->count_lo));
1512                 if (in_8(&mr->interrupt) & (INT_ERROR | INT_EXCEPTION)) {
1513                         /* whoops, target didn't do what we expected */
1514                         ms->last_n_msgout = ms->n_msgout;
1515                         ms->n_msgout = 0;
1516                         if (in_8(&mr->interrupt) & INT_ERROR) {
1517                                 printk(KERN_ERR "mesh: error %x in msg_out\n",
1518                                        in_8(&mr->error));
1519                                 handle_error(ms);
1520                                 return;
1521                         }
1522                         if (in_8(&mr->exception) != EXC_PHASEMM)
1523                                 printk(KERN_ERR "mesh: exc %x in msg_out\n",
1524                                        in_8(&mr->exception));
1525                         else
1526                                 printk(KERN_DEBUG "mesh: bs0=%x in msg_out\n",
1527                                        in_8(&mr->bus_status0));
1528                         handle_exception(ms);
1529                         return;
1530                 }
1531                 if (in_8(&mr->bus_status0) & BS0_REQ) {
1532                         out_8(&mr->sequence, SEQ_MSGOUT + use_active_neg);
1533                         mesh_flush_io(mr);
1534                         udelay(1);
1535                         out_8(&mr->fifo, ms->msgout[ms->n_msgout-1]);
1536                         ms->msgphase = msg_out_last;
1537                 } else {
1538                         out_8(&mr->sequence, SEQ_MSGIN + use_active_neg + SEQ_ATN);
1539                         ms->msgphase = msg_out_xxx;
1540                 }
1541                 break;
1542
1543         case msg_out_last:
1544                 ms->last_n_msgout = ms->n_msgout;
1545                 ms->n_msgout = 0;
1546                 ms->msgphase = ms->expect_reply? msg_in: msg_none;
1547                 start_phase(ms);
1548                 break;
1549
1550         case msg_none:
1551                 switch (ms->phase) {
1552                 case idle:
1553                         printk(KERN_ERR "mesh: interrupt in idle phase?\n");
1554                         dumpslog(ms);
1555                         return;
1556                 case selecting:
1557                         dlog(ms, "Selecting phase at command completion",0);
1558                         ms->msgout[0] = IDENTIFY(ALLOW_RESEL(ms->conn_tgt),
1559                                                  (cmd? cmd->device->lun: 0));
1560                         ms->n_msgout = 1;
1561                         ms->expect_reply = 0;
1562                         if (ms->aborting) {
1563                                 ms->msgout[0] = ABORT;
1564                                 ms->n_msgout++;
1565                         } else if (tp->sdtr_state == do_sdtr) {
1566                                 /* add SDTR message */
1567                                 add_sdtr_msg(ms);
1568                                 ms->expect_reply = 1;
1569                                 tp->sdtr_state = sdtr_sent;
1570                         }
1571                         ms->msgphase = msg_out;
1572                         /*
1573                          * We need to wait for REQ before dropping ATN.
1574                          * We wait for at most 30us, then fall back to
1575                          * a scheme where we issue a SEQ_COMMAND with ATN,
1576                          * which will give us a phase mismatch interrupt
1577                          * when REQ does come, and then we send the message.
1578                          */
1579                         t = 230;                /* wait up to 230us */
1580                         while ((in_8(&mr->bus_status0) & BS0_REQ) == 0) {
1581                                 if (--t < 0) {
1582                                         dlog(ms, "impatient for req", ms->n_msgout);
1583                                         ms->msgphase = msg_none;
1584                                         break;
1585                                 }
1586                                 udelay(1);
1587                         }
1588                         break;
1589                 case dataing:
1590                         if (ms->dma_count != 0) {
1591                                 start_phase(ms);
1592                                 return;
1593                         }
1594                         /*
1595                          * We can get a phase mismatch here if the target
1596                          * changes to the status phase, even though we have
1597                          * had a command complete interrupt.  Then, if we
1598                          * issue the SEQ_STATUS command, we'll get a sequence
1599                          * error interrupt.  Which isn't so bad except that
1600                          * occasionally the mesh actually executes the
1601                          * SEQ_STATUS *as well as* giving us the sequence
1602                          * error and phase mismatch exception.
1603                          */
1604                         out_8(&mr->sequence, 0);
1605                         out_8(&mr->interrupt,
1606                               INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
1607                         halt_dma(ms);
1608                         break;
1609                 case statusing:
1610                         if (cmd) {
1611                                 cmd->SCp.Status = mr->fifo;
1612                                 if (DEBUG_TARGET(cmd))
1613                                         printk(KERN_DEBUG "mesh: status is %x\n",
1614                                                cmd->SCp.Status);
1615                         }
1616                         ms->msgphase = msg_in;
1617                         break;
1618                 case busfreeing:
1619                         mesh_done(ms, 1);
1620                         return;
1621                 case disconnecting:
1622                         ms->current_req = 0;
1623                         ms->phase = idle;
1624                         mesh_start(ms);
1625                         return;
1626                 default:
1627                         break;
1628                 }
1629                 ++ms->phase;
1630                 start_phase(ms);
1631                 break;
1632         }
1633 }
1634
1635
1636 /*
1637  * Called by midlayer with host locked to queue a new
1638  * request
1639  */
1640 static int mesh_queue(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *))
1641 {
1642         struct mesh_state *ms;
1643
1644         cmd->scsi_done = done;
1645         cmd->host_scribble = NULL;
1646
1647         ms = (struct mesh_state *) cmd->device->host->hostdata;
1648
1649         if (ms->request_q == NULL)
1650                 ms->request_q = cmd;
1651         else
1652                 ms->request_qtail->host_scribble = (void *) cmd;
1653         ms->request_qtail = cmd;
1654
1655         if (ms->phase == idle)
1656                 mesh_start(ms);
1657
1658         return 0;
1659 }
1660
1661 /*
1662  * Called to handle interrupts, either call by the interrupt
1663  * handler (do_mesh_interrupt) or by other functions in
1664  * exceptional circumstances
1665  */
1666 static void mesh_interrupt(int irq, void *dev_id, struct pt_regs *ptregs)
1667 {
1668         struct mesh_state *ms = (struct mesh_state *) dev_id;
1669         volatile struct mesh_regs *mr = ms->mesh;
1670         int intr;
1671
1672 #if 0
1673         if (ALLOW_DEBUG(ms->conn_tgt))
1674                 printk(KERN_DEBUG "mesh_intr, bs0=%x int=%x exc=%x err=%x "
1675                        "phase=%d msgphase=%d\n", mr->bus_status0,
1676                        mr->interrupt, mr->exception, mr->error,
1677                        ms->phase, ms->msgphase);
1678 #endif
1679         while ((intr = in_8(&mr->interrupt)) != 0) {
1680                 dlog(ms, "interrupt intr/err/exc/seq=%.8x", 
1681                      MKWORD(intr, mr->error, mr->exception, mr->sequence));
1682                 if (intr & INT_ERROR) {
1683                         handle_error(ms);
1684                 } else if (intr & INT_EXCEPTION) {
1685                         handle_exception(ms);
1686                 } else if (intr & INT_CMDDONE) {
1687                         out_8(&mr->interrupt, INT_CMDDONE);
1688                         cmd_complete(ms);
1689                 }
1690         }
1691 }
1692
1693 /* Todo: here we can at least try to remove the command from the
1694  * queue if it isn't connected yet, and for pending command, assert
1695  * ATN until the bus gets freed.
1696  */
1697 static int mesh_abort(struct scsi_cmnd *cmd)
1698 {
1699         struct mesh_state *ms = (struct mesh_state *) cmd->device->host->hostdata;
1700
1701         printk(KERN_DEBUG "mesh_abort(%p)\n", cmd);
1702         mesh_dump_regs(ms);
1703         dumplog(ms, cmd->device->id);
1704         dumpslog(ms);
1705         return FAILED;
1706 }
1707
1708 /*
1709  * Called by the midlayer with the lock held to reset the
1710  * SCSI host and bus.
1711  * The midlayer will wait for devices to come back, we don't need
1712  * to do that ourselves
1713  */
1714 static int mesh_host_reset(struct scsi_cmnd *cmd)
1715 {
1716         struct mesh_state *ms = (struct mesh_state *) cmd->device->host->hostdata;
1717         volatile struct mesh_regs *mr = ms->mesh;
1718         volatile struct dbdma_regs *md = ms->dma;
1719
1720         printk(KERN_DEBUG "mesh_host_reset\n");
1721
1722         /* Reset the controller & dbdma channel */
1723         out_le32(&md->control, (RUN|PAUSE|FLUSH|WAKE) << 16);   /* stop dma */
1724         out_8(&mr->exception, 0xff);    /* clear all exception bits */
1725         out_8(&mr->error, 0xff);        /* clear all error bits */
1726         out_8(&mr->sequence, SEQ_RESETMESH);
1727         mesh_flush_io(mr);
1728         udelay(1);
1729         out_8(&mr->intr_mask, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
1730         out_8(&mr->source_id, ms->host->this_id);
1731         out_8(&mr->sel_timeout, 25);    /* 250ms */
1732         out_8(&mr->sync_params, ASYNC_PARAMS);
1733
1734         /* Reset the bus */
1735         out_8(&mr->bus_status1, BS1_RST);       /* assert RST */
1736         mesh_flush_io(mr);
1737         udelay(30);                     /* leave it on for >= 25us */
1738         out_8(&mr->bus_status1, 0);     /* negate RST */
1739
1740         /* Complete pending commands */
1741         handle_reset(ms);
1742         
1743         return SUCCESS;
1744 }
1745
1746 static void set_mesh_power(struct mesh_state *ms, int state)
1747 {
1748         if (_machine != _MACH_Pmac)
1749                 return;
1750         if (state) {
1751                 pmac_call_feature(PMAC_FTR_MESH_ENABLE, macio_get_of_node(ms->mdev), 0, 1);
1752                 set_current_state(TASK_UNINTERRUPTIBLE);
1753                 schedule_timeout(HZ/5);
1754         } else {
1755                 pmac_call_feature(PMAC_FTR_MESH_ENABLE, macio_get_of_node(ms->mdev), 0, 0);
1756                 set_current_state(TASK_UNINTERRUPTIBLE);
1757                 schedule_timeout(HZ/100);
1758         }
1759 }                       
1760
1761
1762 #ifdef CONFIG_PM
1763 static int mesh_suspend(struct macio_dev *mdev, u32 state)
1764 {
1765         struct mesh_state *ms = (struct mesh_state *)macio_get_drvdata(mdev);
1766         unsigned long flags;
1767
1768         if (state == mdev->ofdev.dev.power_state || state < 2)
1769                 return 0;
1770
1771         scsi_block_requests(ms->host);
1772         spin_lock_irqsave(ms->host->host_lock, flags);
1773         while(ms->phase != idle) {
1774                 spin_unlock_irqrestore(ms->host->host_lock, flags);
1775                 current->state = TASK_UNINTERRUPTIBLE;
1776                 schedule_timeout(HZ/100);
1777                 spin_lock_irqsave(ms->host->host_lock, flags);
1778         }
1779         ms->phase = sleeping;
1780         spin_unlock_irqrestore(ms->host->host_lock, flags);
1781         disable_irq(ms->meshintr);
1782         set_mesh_power(ms, 0);
1783
1784         mdev->ofdev.dev.power_state = state;
1785
1786         return 0;
1787 }
1788
1789 static int mesh_resume(struct macio_dev *mdev)
1790 {
1791         struct mesh_state *ms = (struct mesh_state *)macio_get_drvdata(mdev);
1792         unsigned long flags;
1793
1794         if (mdev->ofdev.dev.power_state == 0)
1795                 return 0;
1796
1797         set_mesh_power(ms, 1);
1798         mesh_init(ms);
1799         spin_lock_irqsave(ms->host->host_lock, flags);
1800         mesh_start(ms);
1801         spin_unlock_irqrestore(ms->host->host_lock, flags);
1802         enable_irq(ms->meshintr);
1803         scsi_unblock_requests(ms->host);
1804
1805         mdev->ofdev.dev.power_state = 0;
1806
1807         return 0;
1808 }
1809
1810 #endif /* CONFIG_PM */
1811
1812 /*
1813  * If we leave drives set for synchronous transfers (especially
1814  * CDROMs), and reboot to MacOS, it gets confused, poor thing.
1815  * So, on reboot we reset the SCSI bus.
1816  */
1817 static int mesh_shutdown(struct macio_dev *mdev)
1818 {
1819         struct mesh_state *ms = (struct mesh_state *)macio_get_drvdata(mdev);
1820         volatile struct mesh_regs *mr;
1821         unsigned long flags;
1822
1823         printk(KERN_INFO "resetting MESH scsi bus(es)\n");
1824         spin_lock_irqsave(ms->host->host_lock, flags);
1825         mr = ms->mesh;
1826         out_8(&mr->intr_mask, 0);
1827         out_8(&mr->interrupt, INT_ERROR | INT_EXCEPTION | INT_CMDDONE);
1828         out_8(&mr->bus_status1, BS1_RST);
1829         mesh_flush_io(mr);
1830         udelay(30);
1831         out_8(&mr->bus_status1, 0);
1832         spin_unlock_irqrestore(ms->host->host_lock, flags);
1833
1834         return 0;
1835 }
1836
1837 static struct scsi_host_template mesh_template = {
1838         .proc_name                      = "mesh",
1839         .name                           = "MESH",
1840         .queuecommand                   = mesh_queue,
1841         .eh_abort_handler               = mesh_abort,
1842         .eh_host_reset_handler          = mesh_host_reset,
1843         .can_queue                      = 20,
1844         .this_id                        = 7,
1845         .sg_tablesize                   = SG_ALL,
1846         .cmd_per_lun                    = 2,
1847         .use_clustering                 = DISABLE_CLUSTERING,
1848 };
1849
1850 static int mesh_probe(struct macio_dev *mdev, const struct of_match *match)
1851 {
1852         struct device_node *mesh = macio_get_of_node(mdev);
1853         struct pci_dev* pdev = macio_get_pci_dev(mdev);
1854         int tgt, *cfp, minper;
1855         struct mesh_state *ms;
1856         struct Scsi_Host *mesh_host;
1857         void *dma_cmd_space;
1858         dma_addr_t dma_cmd_bus;
1859
1860         switch (mdev->bus->chip->type) {
1861         case macio_heathrow:
1862         case macio_gatwick:
1863         case macio_paddington:
1864                 use_active_neg = 0;
1865                 break;
1866         default:
1867                 use_active_neg = SEQ_ACTIVE_NEG;
1868         }
1869
1870         if (macio_resource_count(mdev) != 2 || macio_irq_count(mdev) != 2) {
1871                 printk(KERN_ERR "mesh: expected 2 addrs and 2 intrs"
1872                        " (got %d,%d)\n", mesh->n_addrs, mesh->n_intrs);
1873                 return -ENODEV;
1874         }
1875
1876         if (macio_request_resources(mdev, "mesh") != 0) {
1877                 printk(KERN_ERR "mesh: unable to request memory resources");
1878                 return -EBUSY;
1879         }
1880         mesh_host = scsi_host_alloc(&mesh_template, sizeof(struct mesh_state));
1881         if (mesh_host == NULL) {
1882                 printk(KERN_ERR "mesh: couldn't register host");
1883                 goto out_release;
1884         }
1885         
1886         /* Old junk for root discovery, that will die ultimately */
1887 #if !defined(MODULE)
1888         note_scsi_host(mesh, mesh_host);
1889 #endif
1890
1891         mesh_host->base = macio_resource_start(mdev, 0);
1892         mesh_host->irq = macio_irq(mdev, 0);
1893         ms = (struct mesh_state *) mesh_host->hostdata;
1894         macio_set_drvdata(mdev, ms);
1895         ms->host = mesh_host;
1896         ms->mdev = mdev;
1897         ms->pdev = pdev;
1898         
1899         ms->mesh = (volatile struct mesh_regs *)
1900                 ioremap(macio_resource_start(mdev, 0), 0x1000);
1901         if (ms->mesh == NULL) {
1902                 printk(KERN_ERR "mesh: can't map registers\n");
1903                 goto out_free;
1904         }               
1905         ms->dma = (volatile struct dbdma_regs *)
1906                 ioremap(macio_resource_start(mdev, 1), 0x1000);
1907         if (ms->dma == NULL) {
1908                 printk(KERN_ERR "mesh: can't map registers\n");
1909                 iounmap((void *)ms->mesh);
1910                 goto out_free;
1911         }
1912
1913         ms->meshintr = macio_irq(mdev, 0);
1914         ms->dmaintr = macio_irq(mdev, 1);
1915
1916         /* Space for dma command list: +1 for stop command,
1917          * +1 to allow for aligning.
1918          */
1919         ms->dma_cmd_size = (mesh_host->sg_tablesize + 2) * sizeof(struct dbdma_cmd);
1920
1921         /* We use the PCI APIs for now until the generic one gets fixed
1922          * enough or until we get some macio-specific versions
1923          */
1924         dma_cmd_space = pci_alloc_consistent(macio_get_pci_dev(mdev),
1925                                              ms->dma_cmd_size,
1926                                              &dma_cmd_bus);
1927         if (dma_cmd_space == NULL) {
1928                 printk(KERN_ERR "mesh: can't allocate DMA table\n");
1929                 goto out_unmap;
1930         }
1931         memset(dma_cmd_space, 0, ms->dma_cmd_size);
1932
1933         ms->dma_cmds = (struct dbdma_cmd *) DBDMA_ALIGN(dma_cmd_space);
1934         ms->dma_cmd_space = dma_cmd_space;
1935         ms->dma_cmd_bus = dma_cmd_bus + ((unsigned long)ms->dma_cmds)
1936                 - (unsigned long)dma_cmd_space;
1937         ms->current_req = NULL;
1938         for (tgt = 0; tgt < 8; ++tgt) {
1939                 ms->tgts[tgt].sdtr_state = do_sdtr;
1940                 ms->tgts[tgt].sync_params = ASYNC_PARAMS;
1941                 ms->tgts[tgt].current_req = 0;
1942         }
1943
1944         if ((cfp = (int *) get_property(mesh, "clock-frequency", NULL)))
1945                 ms->clk_freq = *cfp;
1946         else {
1947                 printk(KERN_INFO "mesh: assuming 50MHz clock frequency\n");
1948                 ms->clk_freq = 50000000;
1949         }
1950
1951         /* The maximum sync rate is clock / 5; increase
1952          * mesh_sync_period if necessary.
1953          */
1954         minper = 1000000000 / (ms->clk_freq / 5); /* ns */
1955         if (mesh_sync_period < minper)
1956                 mesh_sync_period = minper;
1957
1958         /* Power up the chip */
1959         set_mesh_power(ms, 1);
1960
1961         /* Set it up */
1962         mesh_init(ms);
1963
1964         /* XXX FIXME: error should be fatal */
1965         if (request_irq(ms->meshintr, do_mesh_interrupt, 0, "MESH", ms))
1966                 printk(KERN_ERR "MESH: can't get irq %d\n", ms->meshintr);
1967
1968         /* XXX FIXME: handle failure */
1969         scsi_add_host(mesh_host, &mdev->ofdev.dev);
1970         scsi_scan_host(mesh_host);
1971
1972         return 0;
1973
1974 out_unmap:
1975         iounmap((void *)ms->dma);
1976         iounmap((void *)ms->mesh);
1977 out_free:
1978         scsi_host_put(mesh_host);
1979 out_release:
1980         macio_release_resources(mdev);
1981
1982         return -ENODEV;
1983 }
1984
1985 static int mesh_remove(struct macio_dev *mdev)
1986 {
1987         struct mesh_state *ms = (struct mesh_state *)macio_get_drvdata(mdev);
1988         struct Scsi_Host *mesh_host = ms->host;
1989
1990         scsi_remove_host(mesh_host);
1991
1992         free_irq(ms->meshintr, ms);
1993
1994         /* Reset scsi bus */
1995         mesh_shutdown(mdev);
1996
1997         /* Shut down chip & termination */
1998         set_mesh_power(ms, 0);
1999
2000         /* Unmap registers & dma controller */
2001         iounmap((void *) ms->mesh);
2002         iounmap((void *) ms->dma);
2003
2004         /* Free DMA commands memory */
2005         pci_free_consistent(macio_get_pci_dev(mdev), ms->dma_cmd_size,
2006                           ms->dma_cmd_space, ms->dma_cmd_bus);
2007
2008         /* Release memory resources */
2009         macio_release_resources(mdev);
2010
2011         scsi_host_put(mesh_host);
2012
2013         return 0;
2014 }
2015
2016
2017 static struct of_match mesh_match[] = 
2018 {
2019         {
2020         .name           = "mesh",
2021         .type           = OF_ANY_MATCH,
2022         .compatible     = OF_ANY_MATCH
2023         },
2024         {
2025         .name           = OF_ANY_MATCH,
2026         .type           = "scsi",
2027         .compatible     = "chrp,mesh0"
2028         },
2029         {},
2030 };
2031
2032 static struct macio_driver mesh_driver = 
2033 {
2034         .name           = "mesh",
2035         .match_table    = mesh_match,
2036         .probe          = mesh_probe,
2037         .remove         = mesh_remove,
2038         .shutdown       = mesh_shutdown,
2039 #ifdef CONFIG_PM
2040         .suspend        = mesh_suspend,
2041         .resume         = mesh_resume,
2042 #endif
2043 };
2044
2045
2046 static int __init init_mesh(void)
2047 {
2048
2049         /* Calculate sync rate from module parameters */
2050         if (sync_rate > 10)
2051                 sync_rate = 10;
2052         if (sync_rate > 0) {
2053                 printk(KERN_INFO "mesh: configured for synchronous %d MB/s\n", sync_rate);
2054                 mesh_sync_period = 1000 / sync_rate;    /* ns */
2055                 mesh_sync_offset = 15;
2056         } else
2057                 printk(KERN_INFO "mesh: configured for asynchronous\n");
2058
2059         return macio_register_driver(&mesh_driver);
2060 }
2061
2062 static void __exit exit_mesh(void)
2063 {
2064         return macio_unregister_driver(&mesh_driver);
2065 }
2066
2067 module_init(init_mesh);
2068 module_exit(exit_mesh);