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