xref: /netbsd-src/sys/dev/ic/aic6360.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: aic6360.c,v 1.101 2017/10/28 04:53:55 riastradh Exp $	*/
2 
3 /*
4  * Copyright (c) 1994, 1995, 1996 Charles M. Hannum.  All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. All advertising materials mentioning features or use of this software
15  *    must display the following acknowledgement:
16  *	This product includes software developed by Charles M. Hannum.
17  * 4. The name of the author may not be used to endorse or promote products
18  *    derived from this software without specific prior written permission.
19  *
20  * Copyright (c) 1994 Jarle Greipsland
21  * All rights reserved.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the above copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. The name of the author may not be used to endorse or promote products
32  *    derived from this software without specific prior written permission.
33  *
34  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
35  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
36  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
37  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
38  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
39  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
40  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
41  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
42  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
43  * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
44  * POSSIBILITY OF SUCH DAMAGE.
45  */
46 
47 /*
48  * Acknowledgements: Many of the algorithms used in this driver are
49  * inspired by the work of Julian Elischer (julian@tfs.com) and
50  * Charles Hannum (mycroft@duality.gnu.ai.mit.edu).  Thanks a million!
51  */
52 
53 /* TODO list:
54  * 1) Get the DMA stuff working.
55  * 2) Get the iov/uio stuff working. Is this a good thing ???
56  * 3) Get the synch stuff working.
57  * 4) Rewrite it to use malloc for the acb structs instead of static alloc.?
58  */
59 
60 #include <sys/cdefs.h>
61 __KERNEL_RCSID(0, "$NetBSD: aic6360.c,v 1.101 2017/10/28 04:53:55 riastradh Exp $");
62 
63 #include "opt_ddb.h"
64 
65 /*
66  * A few customizable items:
67  */
68 
69 /* Use doubleword transfers to/from SCSI chip.  Note: This requires
70  * motherboard support.  Basicly, some motherboard chipsets are able to
71  * split a 32 bit I/O operation into two 16 bit I/O operations,
72  * transparently to the processor.  This speeds up some things, notably long
73  * data transfers.
74  */
75 #define AIC_USE_DWORDS		0
76 
77 /* Synchronous data transfers? */
78 #define AIC_USE_SYNCHRONOUS	0
79 #define AIC_SYNC_REQ_ACK_OFS 	8
80 
81 /* Wide data transfers? */
82 #define	AIC_USE_WIDE		0
83 #define	AIC_MAX_WIDTH		0
84 
85 /* Max attempts made to transmit a message */
86 #define AIC_MSG_MAX_ATTEMPT	3 /* Not used now XXX */
87 
88 /* Use DMA (else we do programmed I/O using string instructions) (not yet!)*/
89 #define AIC_USE_EISA_DMA	0
90 #define AIC_USE_ISA_DMA		0
91 
92 /* How to behave on the (E)ISA bus when/if DMAing (on<<4) + off in us */
93 #define EISA_BRST_TIM ((15<<4) + 1)	/* 15us on, 1us off */
94 
95 /* Some spin loop parameters (essentially how long to wait some places)
96  * The problem(?) is that sometimes we expect either to be able to transmit a
97  * byte or to get a new one from the SCSI bus pretty soon.  In order to avoid
98  * returning from the interrupt just to get yanked back for the next byte we
99  * may spin in the interrupt routine waiting for this byte to come.  How long?
100  * This is really (SCSI) device and processor dependent.  Tuneable, I guess.
101  */
102 #define AIC_MSGIN_SPIN		1 	/* Will spinwait upto ?ms for a new msg byte */
103 #define AIC_MSGOUT_SPIN		1
104 
105 /* Include debug functions?  At the end of this file there are a bunch of
106  * functions that will print out various information regarding queued SCSI
107  * commands, driver state and chip contents.  You can call them from the
108  * kernel debugger.  If you set AIC_DEBUG to 0 they are not included (the
109  * kernel uses less memory) but you lose the debugging facilities.
110  */
111 #define AIC_DEBUG		1
112 
113 #define	AIC_ABORT_TIMEOUT	2000	/* time to wait for abort */
114 
115 /* End of customizable parameters */
116 
117 #if AIC_USE_EISA_DMA || AIC_USE_ISA_DMA
118 #error "I said not yet! Start paying attention... grumble"
119 #endif
120 
121 #include <sys/param.h>
122 #include <sys/systm.h>
123 #include <sys/callout.h>
124 #include <sys/kernel.h>
125 #include <sys/errno.h>
126 #include <sys/ioctl.h>
127 #include <sys/device.h>
128 #include <sys/buf.h>
129 #include <sys/proc.h>
130 #include <sys/queue.h>
131 
132 #include <sys/bus.h>
133 #include <sys/intr.h>
134 
135 #include <dev/scsipi/scsi_spc.h>
136 #include <dev/scsipi/scsi_all.h>
137 #include <dev/scsipi/scsipi_all.h>
138 #include <dev/scsipi/scsi_message.h>
139 #include <dev/scsipi/scsiconf.h>
140 
141 #include <dev/ic/aic6360reg.h>
142 #include <dev/ic/aic6360var.h>
143 
144 #include "ioconf.h"
145 
146 #ifndef DDB
147 #define	Debugger() panic("should call debugger here (aic6360.c)")
148 #endif /* ! DDB */
149 
150 #if AIC_DEBUG
151 int aic_debug = 0x00; /* AIC_SHOWSTART|AIC_SHOWMISC|AIC_SHOWTRACE; */
152 #endif
153 
154 static void	aic_minphys(struct buf *);
155 static void	aic_done(struct aic_softc *, struct aic_acb *);
156 static void	aic_dequeue(struct aic_softc *, struct aic_acb *);
157 static void	aic_scsipi_request(struct scsipi_channel *,
158 				   scsipi_adapter_req_t, void *);
159 static int	aic_poll(struct aic_softc *, struct scsipi_xfer *, int);
160 static void	aic_select(struct aic_softc *, struct aic_acb *);
161 static void	aic_timeout(void *);
162 static void	aic_sched(struct aic_softc *);
163 static void	aic_scsi_reset(struct aic_softc *);
164 static void	aic_reset(struct aic_softc *);
165 static void	aic_free_acb(struct aic_softc *, struct aic_acb *);
166 static struct aic_acb* aic_get_acb(struct aic_softc *);
167 static int	aic_reselect(struct aic_softc *, int);
168 static void	aic_sense(struct aic_softc *, struct aic_acb *);
169 static void	aic_msgin(struct aic_softc *);
170 static void	aic_abort(struct aic_softc *, struct aic_acb *);
171 static void	aic_msgout(struct aic_softc *);
172 static int	aic_dataout_pio(struct aic_softc *, u_char *, int);
173 static int	aic_datain_pio(struct aic_softc *, u_char *, int);
174 static void	aic_update_xfer_mode(struct aic_softc *, int);
175 #if AIC_DEBUG
176 static void	aic_print_acb(struct aic_acb *);
177 void	aic_dump_driver(struct aic_softc *);
178 void	aic_dump6360(struct aic_softc *);
179 static void	aic_show_scsi_cmd(struct aic_acb *);
180 void	aic_print_active_acb(void);
181 #endif
182 
183 /*
184  * INITIALIZATION ROUTINES (probe, attach ++)
185  */
186 
187 /* Do the real search-for-device.
188  * Prerequisite: sc->sc_iobase should be set to the proper value
189  */
190 int
191 aic_find(bus_space_tag_t iot, bus_space_handle_t ioh)
192 {
193 	char chip_id[sizeof(IDSTRING)];	/* For chips that support it */
194 	int i;
195 
196 	/* Remove aic6360 from possible powerdown mode */
197 	bus_space_write_1(iot, ioh, DMACNTRL0, 0);
198 
199 	/* Thanks to mark@aggregate.com for the new method for detecting
200 	 * whether the chip is present or not.  Bonus: may also work for
201 	 * the AIC-6260!
202  	 */
203 	AIC_TRACE(("aic: probing for aic-chip\n"));
204  	/*
205  	 * Linux also init's the stack to 1-16 and then clears it,
206      	 *  6260's don't appear to have an ID reg - mpg
207  	 */
208 	/* Push the sequence 0,1,..,15 on the stack */
209 #define STSIZE 16
210 	bus_space_write_1(iot, ioh, DMACNTRL1, 0); /* Reset stack pointer */
211 	for (i = 0; i < STSIZE; i++)
212 		bus_space_write_1(iot, ioh, STACK, i);
213 
214 	/* See if we can pull out the same sequence */
215 	bus_space_write_1(iot, ioh, DMACNTRL1, 0);
216  	for (i = 0; i < STSIZE && bus_space_read_1(iot, ioh, STACK) == i; i++)
217 		;
218 	if (i != STSIZE) {
219 		AIC_START(("STACK futzed at %d.\n", i));
220 		return 0;
221 	}
222 
223 	/* See if we can pull the id string out of the ID register,
224 	 * now only used for informational purposes.
225 	 */
226 	memset(chip_id, 0, sizeof(chip_id));
227 	bus_space_read_multi_1(iot, ioh, ID, chip_id, sizeof(IDSTRING) - 1);
228 	AIC_START(("AIC found ID: %s ",chip_id));
229 	AIC_START(("chip revision %d\n",
230 	    (int)bus_space_read_1(iot, ioh, REV)));
231 
232 	return 1;
233 }
234 
235 /*
236  * Attach the AIC6360, fill out some high and low level data structures
237  */
238 void
239 aicattach(struct aic_softc *sc)
240 {
241 	struct scsipi_adapter *adapt = &sc->sc_adapter;
242 	struct scsipi_channel *chan = &sc->sc_channel;
243 
244 	AIC_TRACE(("aicattach  "));
245 	sc->sc_state = AIC_INIT;
246 
247 	sc->sc_initiator = 7;
248 	sc->sc_freq = 20;	/* XXXX Assume 20 MHz. */
249 
250 	/*
251 	 * These are the bounds of the sync period, based on the frequency of
252 	 * the chip's clock input and the size and offset of the sync period
253 	 * register.
254 	 *
255 	 * For a 20MHz clock, this gives us 25, or 100nS, or 10MB/s, as a
256 	 * maximum transfer rate, and 112.5, or 450nS, or 2.22MB/s, as a
257 	 * minimum transfer rate.
258 	 */
259 	sc->sc_minsync = (2 * 250) / sc->sc_freq;
260 	sc->sc_maxsync = (9 * 250) / sc->sc_freq;
261 
262 	/*
263 	 * Fill in the scsipi_adapter.
264 	 */
265 	adapt->adapt_dev = sc->sc_dev;
266 	adapt->adapt_nchannels = 1;
267 	adapt->adapt_openings = 8;
268 	adapt->adapt_max_periph = 1;
269 	adapt->adapt_request = aic_scsipi_request;
270 	adapt->adapt_minphys = aic_minphys;
271 
272 	/*
273 	 * Fill in the scsipi_channel.
274 	 */
275 	chan->chan_adapter = adapt;
276 	chan->chan_bustype = &scsi_bustype;
277 	chan->chan_channel = 0;
278 	chan->chan_ntargets = 8;
279 	chan->chan_nluns = 8;
280 	chan->chan_id = sc->sc_initiator;
281 
282 	/*
283 	 * Add reference to adapter so that we drop the reference after
284 	 * config_found() to make sure the adapter is disabled.
285 	 */
286 	if (scsipi_adapter_addref(adapt) != 0) {
287 		aprint_error_dev(sc->sc_dev, "unable to enable controller\n");
288 		return;
289 	}
290 
291 	aic_init(sc, 1);	/* Init chip and driver */
292 
293 	/*
294 	 * Ask the adapter what subunits are present
295 	 */
296 	sc->sc_child = config_found(sc->sc_dev, &sc->sc_channel, scsiprint);
297 	scsipi_adapter_delref(adapt);
298 }
299 
300 int
301 aic_detach(device_t self, int flags)
302 {
303 	struct aic_softc *sc = device_private(self);
304 	int rv = 0;
305 
306 	if (sc->sc_child != NULL)
307 		rv = config_detach(sc->sc_child, flags);
308 
309 	return (rv);
310 }
311 
312 /* Initialize AIC6360 chip itself
313  * The following conditions should hold:
314  * aic_isa_probe should have succeeded, i.e. the iobase address in aic_softc
315  * must be valid.
316  */
317 static void
318 aic_reset(struct aic_softc *sc)
319 {
320 	bus_space_tag_t iot = sc->sc_iot;
321 	bus_space_handle_t ioh = sc->sc_ioh;
322 
323 	/*
324 	 * Doc. recommends to clear these two registers before
325 	 * operations commence
326 	 */
327 	bus_space_write_1(iot, ioh, SCSITEST, 0);
328 	bus_space_write_1(iot, ioh, TEST, 0);
329 
330 	/* Reset SCSI-FIFO and abort any transfers */
331 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | CLRCH | CLRSTCNT);
332 
333 	/* Reset DMA-FIFO */
334 	bus_space_write_1(iot, ioh, DMACNTRL0, RSTFIFO);
335 	bus_space_write_1(iot, ioh, DMACNTRL1, 0);
336 
337 	/* Disable all selection features */
338 	bus_space_write_1(iot, ioh, SCSISEQ, 0);
339 	bus_space_write_1(iot, ioh, SXFRCTL1, 0);
340 
341 	/* Disable some interrupts */
342 	bus_space_write_1(iot, ioh, SIMODE0, 0x00);
343 	/* Clear a slew of interrupts */
344 	bus_space_write_1(iot, ioh, CLRSINT0, 0x7f);
345 
346 	/* Disable some more interrupts */
347 	bus_space_write_1(iot, ioh, SIMODE1, 0x00);
348 	/* Clear another slew of interrupts */
349 	bus_space_write_1(iot, ioh, CLRSINT1, 0xef);
350 
351 	/* Disable synchronous transfers */
352 	bus_space_write_1(iot, ioh, SCSIRATE, 0);
353 
354 	/* Haven't seen ant errors (yet) */
355 	bus_space_write_1(iot, ioh, CLRSERR, 0x07);
356 
357 	/* Set our SCSI-ID */
358 	bus_space_write_1(iot, ioh, SCSIID, sc->sc_initiator << OID_S);
359 	bus_space_write_1(iot, ioh, BRSTCNTRL, EISA_BRST_TIM);
360 }
361 
362 /* Pull the SCSI RST line for 500 us */
363 static void
364 aic_scsi_reset(struct aic_softc *sc)
365 {
366 	bus_space_tag_t iot = sc->sc_iot;
367 	bus_space_handle_t ioh = sc->sc_ioh;
368 
369 	bus_space_write_1(iot, ioh, SCSISEQ, SCSIRSTO);
370 	delay(500);
371 	bus_space_write_1(iot, ioh, SCSISEQ, 0);
372 	delay(50);
373 }
374 
375 /*
376  * Initialize aic SCSI driver.
377  */
378 void
379 aic_init(struct aic_softc *sc, int bus_reset)
380 {
381 	struct aic_acb *acb;
382 	int r;
383 
384 	if (bus_reset) {
385 		aic_reset(sc);
386 		aic_scsi_reset(sc);
387 	}
388 	aic_reset(sc);
389 
390 	if (sc->sc_state == AIC_INIT) {
391 		/* First time through; initialize. */
392 		TAILQ_INIT(&sc->ready_list);
393 		TAILQ_INIT(&sc->nexus_list);
394 		TAILQ_INIT(&sc->free_list);
395 		sc->sc_nexus = NULL;
396 		acb = sc->sc_acb;
397 		memset(acb, 0, sizeof(sc->sc_acb));
398 		for (r = 0; r < sizeof(sc->sc_acb) / sizeof(*acb); r++) {
399 			TAILQ_INSERT_TAIL(&sc->free_list, acb, chain);
400 			acb++;
401 		}
402 		memset(&sc->sc_tinfo, 0, sizeof(sc->sc_tinfo));
403 	} else {
404 		/* Cancel any active commands. */
405 		sc->sc_state = AIC_CLEANING;
406 		if ((acb = sc->sc_nexus) != NULL) {
407 			acb->xs->error = XS_DRIVER_STUFFUP;
408 			callout_stop(&acb->xs->xs_callout);
409 			aic_done(sc, acb);
410 		}
411 		while ((acb = sc->nexus_list.tqh_first) != NULL) {
412 			acb->xs->error = XS_DRIVER_STUFFUP;
413 			callout_stop(&acb->xs->xs_callout);
414 			aic_done(sc, acb);
415 		}
416 	}
417 
418 	sc->sc_prevphase = PH_INVALID;
419 	for (r = 0; r < 8; r++) {
420 		struct aic_tinfo *ti = &sc->sc_tinfo[r];
421 
422 		ti->flags = 0;
423 		ti->period = ti->offset = 0;
424 		ti->width = 0;
425 	}
426 
427 	sc->sc_state = AIC_IDLE;
428 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, DMACNTRL0, INTEN);
429 }
430 
431 static void
432 aic_free_acb(struct aic_softc *sc, struct aic_acb *acb)
433 {
434 	int s;
435 
436 	s = splbio();
437 	acb->flags = 0;
438 	TAILQ_INSERT_HEAD(&sc->free_list, acb, chain);
439 	splx(s);
440 }
441 
442 static struct aic_acb *
443 aic_get_acb(struct aic_softc *sc)
444 {
445 	struct aic_acb *acb;
446 	int s;
447 
448 	s = splbio();
449 	acb = TAILQ_FIRST(&sc->free_list);
450 	if (acb != NULL) {
451 		TAILQ_REMOVE(&sc->free_list, acb, chain);
452 		acb->flags |= ACB_ALLOC;
453 	}
454 	splx(s);
455 	return (acb);
456 }
457 
458 /*
459  * DRIVER FUNCTIONS CALLABLE FROM HIGHER LEVEL DRIVERS
460  */
461 
462 /*
463  * Expected sequence:
464  * 1) Command inserted into ready list
465  * 2) Command selected for execution
466  * 3) Command won arbitration and has selected target device
467  * 4) Send message out (identify message, eventually also sync.negotiations)
468  * 5) Send command
469  * 5a) Receive disconnect message, disconnect.
470  * 5b) Reselected by target
471  * 5c) Receive identify message from target.
472  * 6) Send or receive data
473  * 7) Receive status
474  * 8) Receive message (command complete etc.)
475  * 9) If status == SCSI_CHECK construct a synthetic request sense SCSI cmd.
476  *    Repeat 2-8 (no disconnects please...)
477  */
478 
479 /*
480  * Perform a request from the SCSIPI midlayer.
481  */
482 static void
483 aic_scsipi_request(struct scsipi_channel *chan, scsipi_adapter_req_t req,
484     void *arg)
485 {
486 	struct scsipi_xfer *xs;
487 	struct scsipi_periph *periph;
488 	struct aic_softc *sc = device_private(chan->chan_adapter->adapt_dev);
489 	struct aic_acb *acb;
490 	int s, flags;
491 
492 	AIC_TRACE(("aic_request  "));
493 
494 	switch (req) {
495 	case ADAPTER_REQ_RUN_XFER:
496 		xs = arg;
497 		periph = xs->xs_periph;
498 
499 		AIC_CMDS(("[0x%x, %d]->%d ", (int)xs->cmd->opcode, xs->cmdlen,
500 		    periph->periph_target));
501 
502 		if (!device_is_active(sc->sc_dev)) {
503 			xs->error = XS_DRIVER_STUFFUP;
504 			scsipi_done(xs);
505 			return;
506 		}
507 
508 		flags = xs->xs_control;
509 		acb = aic_get_acb(sc);
510 #ifdef DIAGNOSTIC
511 		/*
512 		 * This should never happen as we track the resources
513 		 * in the mid-layer.
514 		 */
515 		if (acb == NULL) {
516 			scsipi_printaddr(periph);
517 			printf("unable to allocate acb\n");
518 			panic("aic_scsipi_request");
519 		}
520 #endif
521 
522 		/* Initialize acb */
523 		acb->xs = xs;
524 		acb->timeout = xs->timeout;
525 
526 		if (xs->xs_control & XS_CTL_RESET) {
527 			acb->flags |= ACB_RESET;
528 			acb->scsipi_cmd_length = 0;
529 			acb->data_length = 0;
530 		} else {
531 			memcpy(&acb->scsipi_cmd, xs->cmd, xs->cmdlen);
532 			acb->scsipi_cmd_length = xs->cmdlen;
533 			acb->data_addr = xs->data;
534 			acb->data_length = xs->datalen;
535 		}
536 		acb->target_stat = 0;
537 
538 		s = splbio();
539 
540 		TAILQ_INSERT_TAIL(&sc->ready_list, acb, chain);
541 		if (sc->sc_state == AIC_IDLE)
542 			aic_sched(sc);
543 
544 		splx(s);
545 
546 		if ((flags & XS_CTL_POLL) == 0)
547 			return;
548 
549 		/* Not allowed to use interrupts, use polling instead */
550 		if (aic_poll(sc, xs, acb->timeout)) {
551 			aic_timeout(acb);
552 			if (aic_poll(sc, xs, acb->timeout))
553 				aic_timeout(acb);
554 		}
555 		return;
556 
557 	case ADAPTER_REQ_GROW_RESOURCES:
558 		/* XXX Not supported. */
559 		return;
560 
561 	case ADAPTER_REQ_SET_XFER_MODE:
562 	    {
563 		struct aic_tinfo *ti;
564 		struct scsipi_xfer_mode *xm = arg;
565 
566 		ti = &sc->sc_tinfo[xm->xm_target];
567 		ti->flags &= ~(DO_SYNC|DO_WIDE);
568 		ti->period = 0;
569 		ti->offset = 0;
570 
571 #if AIC_USE_SYNCHRONOUS
572 		if (xm->xm_mode & PERIPH_CAP_SYNC) {
573 			ti->flags |= DO_SYNC;
574 			ti->period = sc->sc_minsync;
575 			ti->offset = AIC_SYNC_REQ_ACK_OFS;
576 		}
577 #endif
578 #if AIC_USE_WIDE
579 		if (xm->xm_mode & PERIPH_CAP_WIDE16) {
580 			ti->flags |= DO_WIDE;
581 			ti->width = AIC_MAX_WIDTH;
582 		}
583 #endif
584 		/*
585 		 * If we're not going to negotiate, send the notification
586 		 * now, since it won't happen later.
587 		 */
588 		if ((ti->flags & (DO_SYNC|DO_WIDE)) == 0)
589 			aic_update_xfer_mode(sc, xm->xm_target);
590 		return;
591 	    }
592 	}
593 }
594 
595 static void
596 aic_update_xfer_mode(struct aic_softc *sc, int target)
597 {
598 	struct scsipi_xfer_mode xm;
599 	struct aic_tinfo *ti = &sc->sc_tinfo[target];
600 
601 	xm.xm_target = target;
602 	xm.xm_mode = 0;
603 	xm.xm_period = 0;
604 	xm.xm_offset = 0;
605 
606 	if (ti->offset != 0) {
607 		xm.xm_mode |= PERIPH_CAP_SYNC;
608 		xm.xm_period = ti->period;
609 		xm.xm_offset = ti->offset;
610 	}
611 	switch (ti->width) {
612 	case 2:
613 		xm.xm_mode |= PERIPH_CAP_WIDE32;
614 		break;
615 	case 1:
616 		xm.xm_mode |= PERIPH_CAP_WIDE16;
617 		break;
618 	}
619 
620 	scsipi_async_event(&sc->sc_channel, ASYNC_EVENT_XFER_MODE, &xm);
621 }
622 
623 /*
624  * Adjust transfer size in buffer structure
625  */
626 static void
627 aic_minphys(struct buf *bp)
628 {
629 
630 	AIC_TRACE(("aic_minphys  "));
631 	if (bp->b_bcount > (AIC_NSEG << PGSHIFT))
632 		bp->b_bcount = (AIC_NSEG << PGSHIFT);
633 	minphys(bp);
634 }
635 
636 /*
637  * Used when interrupt driven I/O isn't allowed, e.g. during boot.
638  */
639 static int
640 aic_poll(struct aic_softc *sc, struct scsipi_xfer *xs, int count)
641 {
642 	bus_space_tag_t iot = sc->sc_iot;
643 	bus_space_handle_t ioh = sc->sc_ioh;
644 
645 	AIC_TRACE(("aic_poll  "));
646 	while (count) {
647 		/*
648 		 * If we had interrupts enabled, would we
649 		 * have got an interrupt?
650 		 */
651 		if ((bus_space_read_1(iot, ioh, DMASTAT) & INTSTAT) != 0)
652 			aicintr(sc);
653 		if ((xs->xs_status & XS_STS_DONE) != 0)
654 			return 0;
655 		delay(1000);
656 		count--;
657 	}
658 	return 1;
659 }
660 
661 /*
662  * LOW LEVEL SCSI UTILITIES
663  */
664 
665 static inline void
666 aic_sched_msgout(struct aic_softc *sc, u_char m)
667 {
668 	bus_space_tag_t iot = sc->sc_iot;
669 	bus_space_handle_t ioh = sc->sc_ioh;
670 
671 	if (sc->sc_msgpriq == 0)
672 		bus_space_write_1(iot, ioh, SCSISIG, sc->sc_phase | ATNO);
673 	sc->sc_msgpriq |= m;
674 }
675 
676 /*
677  * Set synchronous transfer offset and period.
678  */
679 #if !AIC_USE_SYNCHRONOUS
680 /* ARGSUSED */
681 #endif
682 static inline void
683 aic_setsync(struct aic_softc *sc, struct aic_tinfo *ti)
684 {
685 #if AIC_USE_SYNCHRONOUS
686 	bus_space_tag_t iot = sc->sc_iot;
687 	bus_space_handle_t ioh = sc->sc_ioh;
688 
689 	if (ti->offset != 0)
690 		bus_space_write_1(iot, ioh, SCSIRATE,
691 		    ((ti->period * sc->sc_freq) / 250 - 2) << 4 | ti->offset);
692 	else
693 		bus_space_write_1(iot, ioh, SCSIRATE, 0);
694 #endif
695 }
696 
697 /*
698  * Start a selection.  This is used by aic_sched() to select an idle target,
699  * and by aic_done() to immediately reselect a target to get sense information.
700  */
701 static void
702 aic_select(struct aic_softc *sc, struct aic_acb *acb)
703 {
704 	struct scsipi_periph *periph = acb->xs->xs_periph;
705 	int target = periph->periph_target;
706 	struct aic_tinfo *ti = &sc->sc_tinfo[target];
707 	bus_space_tag_t iot = sc->sc_iot;
708 	bus_space_handle_t ioh = sc->sc_ioh;
709 
710 	bus_space_write_1(iot, ioh, SCSIID,
711 	    sc->sc_initiator << OID_S | target);
712 	aic_setsync(sc, ti);
713 	bus_space_write_1(iot, ioh, SXFRCTL1, STIMO_256ms | ENSTIMER);
714 
715 	/* Always enable reselections. */
716 	bus_space_write_1(iot, ioh, SIMODE0, ENSELDI | ENSELDO);
717 	bus_space_write_1(iot, ioh, SIMODE1, ENSCSIRST | ENSELTIMO);
718 	bus_space_write_1(iot, ioh, SCSISEQ, ENRESELI | ENSELO | ENAUTOATNO);
719 
720 	sc->sc_state = AIC_SELECTING;
721 }
722 
723 static int
724 aic_reselect(struct aic_softc *sc, int message)
725 {
726 	u_char selid, target, lun;
727 	struct aic_acb *acb;
728 	struct scsipi_periph *periph;
729 	struct aic_tinfo *ti;
730 
731 	/*
732 	 * The SCSI chip made a snapshot of the data bus while the reselection
733 	 * was being negotiated.  This enables us to determine which target did
734 	 * the reselect.
735 	 */
736 	selid = sc->sc_selid & ~(1 << sc->sc_initiator);
737 	if (selid & (selid - 1)) {
738 		aprint_error_dev(sc->sc_dev,
739 		    "reselect with invalid selid %02x; "
740 		    "sending DEVICE RESET\n", selid);
741 		AIC_BREAK();
742 		goto reset;
743 	}
744 
745 	/* Search wait queue for disconnected cmd
746 	 * The list should be short, so I haven't bothered with
747 	 * any more sophisticated structures than a simple
748 	 * singly linked list.
749 	 */
750 	target = ffs(selid) - 1;
751 	lun = message & 0x07;
752 	for (acb = sc->nexus_list.tqh_first; acb != NULL;
753 	     acb = acb->chain.tqe_next) {
754 		periph = acb->xs->xs_periph;
755 		if (periph->periph_target == target &&
756 		    periph->periph_lun == lun)
757 			break;
758 	}
759 	if (acb == NULL) {
760 		printf("%s: reselect from target %d lun %d with no nexus; "
761 		    "sending ABORT\n", device_xname(sc->sc_dev), target, lun);
762 		AIC_BREAK();
763 		goto abort;
764 	}
765 
766 	/* Make this nexus active again. */
767 	TAILQ_REMOVE(&sc->nexus_list, acb, chain);
768 	sc->sc_state = AIC_CONNECTED;
769 	sc->sc_nexus = acb;
770 	ti = &sc->sc_tinfo[target];
771 	ti->lubusy |= (1 << lun);
772 	aic_setsync(sc, ti);
773 
774 	if (acb->flags & ACB_RESET)
775 		aic_sched_msgout(sc, SEND_DEV_RESET);
776 	else if (acb->flags & ACB_ABORT)
777 		aic_sched_msgout(sc, SEND_ABORT);
778 
779 	/* Do an implicit RESTORE POINTERS. */
780 	sc->sc_dp = acb->data_addr;
781 	sc->sc_dleft = acb->data_length;
782 	sc->sc_cp = (u_char *)&acb->scsipi_cmd;
783 	sc->sc_cleft = acb->scsipi_cmd_length;
784 
785 	return (0);
786 
787 reset:
788 	aic_sched_msgout(sc, SEND_DEV_RESET);
789 	return (1);
790 
791 abort:
792 	aic_sched_msgout(sc, SEND_ABORT);
793 	return (1);
794 }
795 
796 /*
797  * Schedule a SCSI operation.  This has now been pulled out of the interrupt
798  * handler so that we may call it from aic_scsipi_request and aic_done.  This
799  * may save us an unnecessary interrupt just to get things going.  Should only
800  * be called when state == AIC_IDLE and at bio pl.
801  */
802 static void
803 aic_sched(struct aic_softc *sc)
804 {
805 	struct aic_acb *acb;
806 	struct scsipi_periph *periph;
807 	struct aic_tinfo *ti;
808 	bus_space_tag_t iot = sc->sc_iot;
809 	bus_space_handle_t ioh = sc->sc_ioh;
810 
811 	if (!device_is_active(sc->sc_dev))
812 		return;
813 
814 	/*
815 	 * Find first acb in ready queue that is for a target/lunit pair that
816 	 * is not busy.
817 	 */
818 	bus_space_write_1(iot, ioh, CLRSINT1,
819 	    CLRSELTIMO | CLRBUSFREE | CLRSCSIPERR);
820 	for (acb = sc->ready_list.tqh_first; acb != NULL;
821 	    acb = acb->chain.tqe_next) {
822 		periph = acb->xs->xs_periph;
823 		ti = &sc->sc_tinfo[periph->periph_target];
824 		if ((ti->lubusy & (1 << periph->periph_lun)) == 0) {
825 			AIC_MISC(("selecting %d:%d  ",
826 			    periph->periph_target, periph->periph_lun));
827 			TAILQ_REMOVE(&sc->ready_list, acb, chain);
828 			sc->sc_nexus = acb;
829 			aic_select(sc, acb);
830 			return;
831 		} else
832 			AIC_MISC(("%d:%d busy\n",
833 			    periph->periph_target, periph->periph_lun));
834 	}
835 	AIC_MISC(("idle  "));
836 	/* Nothing to start; just enable reselections and wait. */
837 	bus_space_write_1(iot, ioh, SIMODE0, ENSELDI);
838 	bus_space_write_1(iot, ioh, SIMODE1, ENSCSIRST);
839 	bus_space_write_1(iot, ioh, SCSISEQ, ENRESELI);
840 }
841 
842 static void
843 aic_sense(struct aic_softc *sc, struct aic_acb *acb)
844 {
845 	struct scsipi_xfer *xs = acb->xs;
846 	struct scsipi_periph *periph = xs->xs_periph;
847 	struct aic_tinfo *ti = &sc->sc_tinfo[periph->periph_target];
848 	struct scsi_request_sense *ss = (void *)&acb->scsipi_cmd;
849 
850 	AIC_MISC(("requesting sense  "));
851 	/* Next, setup a request sense command block */
852 	memset(ss, 0, sizeof(*ss));
853 	ss->opcode = SCSI_REQUEST_SENSE;
854 	ss->byte2 = periph->periph_lun << 5;
855 	ss->length = sizeof(struct scsi_sense_data);
856 	acb->scsipi_cmd_length = sizeof(*ss);
857 	acb->data_addr = (char *)&xs->sense.scsi_sense;
858 	acb->data_length = sizeof(struct scsi_sense_data);
859 	acb->flags |= ACB_SENSE;
860 	ti->senses++;
861 	if (acb->flags & ACB_NEXUS)
862 		ti->lubusy &= ~(1 << periph->periph_lun);
863 	if (acb == sc->sc_nexus) {
864 		aic_select(sc, acb);
865 	} else {
866 		aic_dequeue(sc, acb);
867 		TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
868 		if (sc->sc_state == AIC_IDLE)
869 			aic_sched(sc);
870 	}
871 }
872 
873 /*
874  * POST PROCESSING OF SCSI_CMD (usually current)
875  */
876 static void
877 aic_done(struct aic_softc *sc, struct aic_acb *acb)
878 {
879 	struct scsipi_xfer *xs = acb->xs;
880 	struct scsipi_periph *periph = xs->xs_periph;
881 	struct aic_tinfo *ti = &sc->sc_tinfo[periph->periph_target];
882 
883 	AIC_TRACE(("aic_done  "));
884 
885 	/*
886 	 * Now, if we've come here with no error code, i.e. we've kept the
887 	 * initial XS_NOERROR, and the status code signals that we should
888 	 * check sense, we'll need to set up a request sense cmd block and
889 	 * push the command back into the ready queue *before* any other
890 	 * commands for this target/lunit, else we lose the sense info.
891 	 * We don't support chk sense conditions for the request sense cmd.
892 	 */
893 	if (xs->error == XS_NOERROR) {
894 		if (acb->flags & ACB_ABORT) {
895 			xs->error = XS_DRIVER_STUFFUP;
896 		} else if (acb->flags & ACB_SENSE) {
897 			xs->error = XS_SENSE;
898 		} else if (acb->target_stat == SCSI_CHECK) {
899 			/* First, save the return values */
900 			xs->resid = acb->data_length;
901 			xs->status = acb->target_stat;
902 			aic_sense(sc, acb);
903 			return;
904 		} else {
905 			xs->resid = acb->data_length;
906 		}
907 	}
908 
909 #if AIC_DEBUG
910 	if ((aic_debug & AIC_SHOWMISC) != 0) {
911 		if (xs->resid != 0)
912 			printf("resid=%d ", xs->resid);
913 		if (xs->error == XS_SENSE)
914 			printf("sense=0x%02x\n", xs->sense.scsi_sense.response_code);
915 		else
916 			printf("error=%d\n", xs->error);
917 	}
918 #endif
919 
920 	/*
921 	 * Remove the ACB from whatever queue it happens to be on.
922 	 */
923 	if (acb->flags & ACB_NEXUS)
924 		ti->lubusy &= ~(1 << periph->periph_lun);
925 	if (acb == sc->sc_nexus) {
926 		sc->sc_nexus = NULL;
927 		sc->sc_state = AIC_IDLE;
928 		aic_sched(sc);
929 	} else
930 		aic_dequeue(sc, acb);
931 
932 	aic_free_acb(sc, acb);
933 	ti->cmds++;
934 	scsipi_done(xs);
935 }
936 
937 static void
938 aic_dequeue(struct aic_softc *sc, struct aic_acb *acb)
939 {
940 
941 	if (acb->flags & ACB_NEXUS) {
942 		TAILQ_REMOVE(&sc->nexus_list, acb, chain);
943 	} else {
944 		TAILQ_REMOVE(&sc->ready_list, acb, chain);
945 	}
946 }
947 
948 /*
949  * INTERRUPT/PROTOCOL ENGINE
950  */
951 
952 /*
953  * Precondition:
954  * The SCSI bus is already in the MSGI phase and there is a message byte
955  * on the bus, along with an asserted REQ signal.
956  */
957 static void
958 aic_msgin(struct aic_softc *sc)
959 {
960 	bus_space_tag_t iot = sc->sc_iot;
961 	bus_space_handle_t ioh = sc->sc_ioh;
962 	u_char sstat1;
963 	int n;
964 
965 	AIC_TRACE(("aic_msgin  "));
966 
967 	if (sc->sc_prevphase == PH_MSGIN) {
968 		/* This is a continuation of the previous message. */
969 		n = sc->sc_imp - sc->sc_imess;
970 		goto nextbyte;
971 	}
972 
973 	/* This is a new MESSAGE IN phase.  Clean up our state. */
974 	sc->sc_flags &= ~AIC_DROP_MSGIN;
975 
976 nextmsg:
977 	n = 0;
978 	sc->sc_imp = &sc->sc_imess[n];
979 
980 nextbyte:
981 	/*
982 	 * Read a whole message, but don't ack the last byte.  If we reject the
983 	 * message, we have to assert ATN during the message transfer phase
984 	 * itself.
985 	 */
986 	for (;;) {
987 		for (;;) {
988 			sstat1 = bus_space_read_1(iot, ioh, SSTAT1);
989 			if ((sstat1 & (REQINIT | PHASECHG | BUSFREE)) != 0)
990 				break;
991 			/* Wait for REQINIT.  XXX Need timeout. */
992 		}
993 		if ((sstat1 & (PHASECHG | BUSFREE)) != 0) {
994 			/*
995 			 * Target left MESSAGE IN, probably because it
996 			 * a) noticed our ATN signal, or
997 			 * b) ran out of messages.
998 			 */
999 			goto out;
1000 		}
1001 
1002 		/* If parity error, just dump everything on the floor. */
1003 		if ((sstat1 & SCSIPERR) != 0) {
1004 			sc->sc_flags |= AIC_DROP_MSGIN;
1005 			aic_sched_msgout(sc, SEND_PARITY_ERROR);
1006 		}
1007 
1008 		/* Gather incoming message bytes if needed. */
1009 		if ((sc->sc_flags & AIC_DROP_MSGIN) == 0) {
1010 			if (n >= AIC_MAX_MSG_LEN) {
1011 				(void) bus_space_read_1(iot, ioh, SCSIDAT);
1012 				sc->sc_flags |= AIC_DROP_MSGIN;
1013 				aic_sched_msgout(sc, SEND_REJECT);
1014 			} else {
1015 				*sc->sc_imp++ = bus_space_read_1(iot, ioh,
1016 				    SCSIDAT);
1017 				n++;
1018 				/*
1019 				 * This testing is suboptimal, but most
1020 				 * messages will be of the one byte variety, so
1021 				 * it should not affect performance
1022 				 * significantly.
1023 				 */
1024 				if (n == 1 && MSG_IS1BYTE(sc->sc_imess[0]))
1025 					break;
1026 				if (n == 2 && MSG_IS2BYTE(sc->sc_imess[0]))
1027 					break;
1028 				if (n >= 3 && MSG_ISEXTENDED(sc->sc_imess[0]) &&
1029 				    n == sc->sc_imess[1] + 2)
1030 					break;
1031 			}
1032 		} else
1033 			(void) bus_space_read_1(iot, ioh, SCSIDAT);
1034 
1035 		/*
1036 		 * If we reach this spot we're either:
1037 		 * a) in the middle of a multi-byte message, or
1038 		 * b) dropping bytes.
1039 		 */
1040 		bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | SPIOEN);
1041 		/* Ack the last byte read. */
1042 		(void) bus_space_read_1(iot, ioh, SCSIDAT);
1043 		bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
1044 		while ((bus_space_read_1(iot, ioh, SCSISIG) & ACKI) != 0)
1045 			;
1046 	}
1047 
1048 	AIC_MISC(("n=%d imess=0x%02x  ", n, sc->sc_imess[0]));
1049 
1050 	/* We now have a complete message.  Parse it. */
1051 	switch (sc->sc_state) {
1052 		struct aic_acb *acb;
1053 		struct aic_tinfo *ti;
1054 
1055 	case AIC_CONNECTED:
1056 		AIC_ASSERT(sc->sc_nexus != NULL);
1057 		acb = sc->sc_nexus;
1058 		ti = &sc->sc_tinfo[acb->xs->xs_periph->periph_target];
1059 
1060 		switch (sc->sc_imess[0]) {
1061 		case MSG_CMDCOMPLETE:
1062 #if 0
1063 			/* impossible dleft is unsigned */
1064 			if (sc->sc_dleft < 0) {
1065 				periph = acb->xs->xs_periph;
1066 				printf("%s: %ld extra bytes from %d:%d\n",
1067 				    device_xname(sc->sc_dev),
1068 				    (long)-sc->sc_dleft,
1069 				    periph->periph_target, periph->periph_lun);
1070 				sc->sc_dleft = 0;
1071 			}
1072 #endif
1073 			acb->xs->resid = acb->data_length = sc->sc_dleft;
1074 			sc->sc_state = AIC_CMDCOMPLETE;
1075 			break;
1076 
1077 		case MSG_PARITY_ERROR:
1078 			/* Resend the last message. */
1079 			aic_sched_msgout(sc, sc->sc_lastmsg);
1080 			break;
1081 
1082 		case MSG_MESSAGE_REJECT:
1083 			AIC_MISC(("message rejected %02x  ", sc->sc_lastmsg));
1084 			switch (sc->sc_lastmsg) {
1085 #if AIC_USE_SYNCHRONOUS + AIC_USE_WIDE
1086 			case SEND_IDENTIFY:
1087 				ti->flags &= ~(DO_SYNC | DO_WIDE);
1088 				ti->period = ti->offset = 0;
1089 				aic_setsync(sc, ti);
1090 				ti->width = 0;
1091 				break;
1092 #endif
1093 #if AIC_USE_SYNCHRONOUS
1094 			case SEND_SDTR:
1095 				ti->flags &= ~DO_SYNC;
1096 				ti->period = ti->offset = 0;
1097 				aic_setsync(sc, ti);
1098 				aic_update_xfer_mode(sc,
1099 				    acb->xs->xs_periph->periph_target);
1100 				break;
1101 #endif
1102 #if AIC_USE_WIDE
1103 			case SEND_WDTR:
1104 				ti->flags &= ~DO_WIDE;
1105 				ti->width = 0;
1106 				aic_update_xfer_mode(sc,
1107 				    acb->xs->xs_periph->periph_target);
1108 				break;
1109 #endif
1110 			case SEND_INIT_DET_ERR:
1111 				aic_sched_msgout(sc, SEND_ABORT);
1112 				break;
1113 			}
1114 			break;
1115 
1116 		case MSG_NOOP:
1117 			break;
1118 
1119 		case MSG_DISCONNECT:
1120 			ti->dconns++;
1121 			sc->sc_state = AIC_DISCONNECT;
1122 			break;
1123 
1124 		case MSG_SAVEDATAPOINTER:
1125 			acb->data_addr = sc->sc_dp;
1126 			acb->data_length = sc->sc_dleft;
1127 			break;
1128 
1129 		case MSG_RESTOREPOINTERS:
1130 			sc->sc_dp = acb->data_addr;
1131 			sc->sc_dleft = acb->data_length;
1132 			sc->sc_cp = (u_char *)&acb->scsipi_cmd;
1133 			sc->sc_cleft = acb->scsipi_cmd_length;
1134 			break;
1135 
1136 		case MSG_EXTENDED:
1137 			switch (sc->sc_imess[2]) {
1138 #if AIC_USE_SYNCHRONOUS
1139 			case MSG_EXT_SDTR:
1140 				if (sc->sc_imess[1] != 3)
1141 					goto reject;
1142 				ti->period = sc->sc_imess[3];
1143 				ti->offset = sc->sc_imess[4];
1144 				ti->flags &= ~DO_SYNC;
1145 				if (ti->offset == 0) {
1146 				} else if (ti->period < sc->sc_minsync ||
1147 					   ti->period > sc->sc_maxsync ||
1148 					   ti->offset > 8) {
1149 					ti->period = ti->offset = 0;
1150 					aic_sched_msgout(sc, SEND_SDTR);
1151 				} else {
1152 					aic_update_xfer_mode(sc,
1153 					    acb->xs->xs_periph->periph_target);
1154 				}
1155 				aic_setsync(sc, ti);
1156 				break;
1157 #endif
1158 
1159 #if AIC_USE_WIDE
1160 			case MSG_EXT_WDTR:
1161 				if (sc->sc_imess[1] != 2)
1162 					goto reject;
1163 				ti->width = sc->sc_imess[3];
1164 				ti->flags &= ~DO_WIDE;
1165 				if (ti->width == 0) {
1166 				} else if (ti->width > AIC_MAX_WIDTH) {
1167 					ti->width = 0;
1168 					aic_sched_msgout(sc, SEND_WDTR);
1169 				} else {
1170 					aic_update_xfer_mode(sc,
1171 					    acb->xs->xs_periph->periph_target);
1172 				}
1173 				break;
1174 #endif
1175 
1176 			default:
1177 				printf("%s: unrecognized MESSAGE EXTENDED; "
1178 				    "sending REJECT\n",
1179 				    device_xname(sc->sc_dev));
1180 				AIC_BREAK();
1181 				goto reject;
1182 			}
1183 			break;
1184 
1185 		default:
1186 			printf("%s: unrecognized MESSAGE; sending REJECT\n",
1187 			    device_xname(sc->sc_dev));
1188 			AIC_BREAK();
1189 		reject:
1190 			aic_sched_msgout(sc, SEND_REJECT);
1191 			break;
1192 		}
1193 		break;
1194 
1195 	case AIC_RESELECTED:
1196 		if (!MSG_ISIDENTIFY(sc->sc_imess[0])) {
1197 			printf("%s: reselect without IDENTIFY; "
1198 			    "sending DEVICE RESET\n", device_xname(sc->sc_dev));
1199 			AIC_BREAK();
1200 			goto reset;
1201 		}
1202 
1203 		(void) aic_reselect(sc, sc->sc_imess[0]);
1204 		break;
1205 
1206 	default:
1207 		aprint_error_dev(sc->sc_dev,
1208 		    "unexpected MESSAGE IN; sending DEVICE RESET\n");
1209 		AIC_BREAK();
1210 	reset:
1211 		aic_sched_msgout(sc, SEND_DEV_RESET);
1212 		break;
1213 
1214 #ifdef notdef
1215 	abort:
1216 		aic_sched_msgout(sc, SEND_ABORT);
1217 		break;
1218 #endif
1219 	}
1220 
1221 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | SPIOEN);
1222 	/* Ack the last message byte. */
1223 	(void) bus_space_read_1(iot, ioh, SCSIDAT);
1224 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
1225 	while ((bus_space_read_1(iot, ioh, SCSISIG) & ACKI) != 0)
1226 		;
1227 
1228 	/* Go get the next message, if any. */
1229 	goto nextmsg;
1230 
1231 out:
1232 	AIC_MISC(("n=%d imess=0x%02x  ", n, sc->sc_imess[0]));
1233 }
1234 
1235 /*
1236  * Send the highest priority, scheduled message.
1237  */
1238 static void
1239 aic_msgout(struct aic_softc *sc)
1240 {
1241 	bus_space_tag_t iot = sc->sc_iot;
1242 	bus_space_handle_t ioh = sc->sc_ioh;
1243 #if AIC_USE_SYNCHRONOUS
1244 	struct aic_tinfo *ti;
1245 #endif
1246 	u_char sstat1;
1247 	int n;
1248 
1249 	AIC_TRACE(("aic_msgout  "));
1250 
1251 	/* Reset the FIFO. */
1252 	bus_space_write_1(iot, ioh, DMACNTRL0, RSTFIFO);
1253 	/* Enable REQ/ACK protocol. */
1254 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | SPIOEN);
1255 
1256 	if (sc->sc_prevphase == PH_MSGOUT) {
1257 		if (sc->sc_omp == sc->sc_omess) {
1258 			/*
1259 			 * This is a retransmission.
1260 			 *
1261 			 * We get here if the target stayed in MESSAGE OUT
1262 			 * phase.  Section 5.1.9.2 of the SCSI 2 spec indicates
1263 			 * that all of the previously transmitted messages must
1264 			 * be sent again, in the same order.  Therefore, we
1265 			 * requeue all the previously transmitted messages, and
1266 			 * start again from the top.  Our simple priority
1267 			 * scheme keeps the messages in the right order.
1268 			 */
1269 			AIC_MISC(("retransmitting  "));
1270 			sc->sc_msgpriq |= sc->sc_msgoutq;
1271 			/*
1272 			 * Set ATN.  If we're just sending a trivial 1-byte
1273 			 * message, we'll clear ATN later on anyway.
1274 			 */
1275 			bus_space_write_1(iot, ioh, SCSISIG, PH_MSGOUT | ATNO);
1276 		} else {
1277 			/* This is a continuation of the previous message. */
1278 			n = sc->sc_omp - sc->sc_omess;
1279 			goto nextbyte;
1280 		}
1281 	}
1282 
1283 	/* No messages transmitted so far. */
1284 	sc->sc_msgoutq = 0;
1285 	sc->sc_lastmsg = 0;
1286 
1287 nextmsg:
1288 	/* Pick up highest priority message. */
1289 	sc->sc_currmsg = sc->sc_msgpriq & -sc->sc_msgpriq;
1290 	sc->sc_msgpriq &= ~sc->sc_currmsg;
1291 	sc->sc_msgoutq |= sc->sc_currmsg;
1292 
1293 	/* Build the outgoing message data. */
1294 	switch (sc->sc_currmsg) {
1295 	case SEND_IDENTIFY:
1296 		AIC_ASSERT(sc->sc_nexus != NULL);
1297 		sc->sc_omess[0] =
1298 		    MSG_IDENTIFY(sc->sc_nexus->xs->xs_periph->periph_lun, 1);
1299 		n = 1;
1300 		break;
1301 
1302 #if AIC_USE_SYNCHRONOUS
1303 	case SEND_SDTR:
1304 		AIC_ASSERT(sc->sc_nexus != NULL);
1305 		ti = &sc->sc_tinfo[sc->sc_nexus->xs->xs_periph->periph_target];
1306 		sc->sc_omess[4] = MSG_EXTENDED;
1307 		sc->sc_omess[3] = 3;
1308 		sc->sc_omess[2] = MSG_EXT_SDTR;
1309 		sc->sc_omess[1] = ti->period >> 2;
1310 		sc->sc_omess[0] = ti->offset;
1311 		n = 5;
1312 		break;
1313 #endif
1314 
1315 #if AIC_USE_WIDE
1316 	case SEND_WDTR:
1317 		AIC_ASSERT(sc->sc_nexus != NULL);
1318 		ti = &sc->sc_tinfo[sc->sc_nexus->xs->xs_periph->periph_target];
1319 		sc->sc_omess[3] = MSG_EXTENDED;
1320 		sc->sc_omess[2] = 2;
1321 		sc->sc_omess[1] = MSG_EXT_WDTR;
1322 		sc->sc_omess[0] = ti->width;
1323 		n = 4;
1324 		break;
1325 #endif
1326 
1327 	case SEND_DEV_RESET:
1328 		sc->sc_flags |= AIC_ABORTING;
1329 		sc->sc_omess[0] = MSG_BUS_DEV_RESET;
1330 		n = 1;
1331 		break;
1332 
1333 	case SEND_REJECT:
1334 		sc->sc_omess[0] = MSG_MESSAGE_REJECT;
1335 		n = 1;
1336 		break;
1337 
1338 	case SEND_PARITY_ERROR:
1339 		sc->sc_omess[0] = MSG_PARITY_ERROR;
1340 		n = 1;
1341 		break;
1342 
1343 	case SEND_INIT_DET_ERR:
1344 		sc->sc_omess[0] = MSG_INITIATOR_DET_ERR;
1345 		n = 1;
1346 		break;
1347 
1348 	case SEND_ABORT:
1349 		sc->sc_flags |= AIC_ABORTING;
1350 		sc->sc_omess[0] = MSG_ABORT;
1351 		n = 1;
1352 		break;
1353 
1354 	default:
1355 		aprint_error_dev(sc->sc_dev,
1356 		    "unexpected MESSAGE OUT; sending NOOP\n");
1357 		AIC_BREAK();
1358 		sc->sc_omess[0] = MSG_NOOP;
1359 		n = 1;
1360 		break;
1361 	}
1362 	sc->sc_omp = &sc->sc_omess[n];
1363 
1364 nextbyte:
1365 	/* Send message bytes. */
1366 	for (;;) {
1367 		for (;;) {
1368 			sstat1 = bus_space_read_1(iot, ioh, SSTAT1);
1369 			if ((sstat1 & (REQINIT | PHASECHG | BUSFREE)) != 0)
1370 				break;
1371 			/* Wait for REQINIT.  XXX Need timeout. */
1372 		}
1373 		if ((sstat1 & (PHASECHG | BUSFREE)) != 0) {
1374 			/*
1375 			 * Target left MESSAGE OUT, possibly to reject
1376 			 * our message.
1377 			 *
1378 			 * If this is the last message being sent, then we
1379 			 * deassert ATN, since either the target is going to
1380 			 * ignore this message, or it's going to ask for a
1381 			 * retransmission via MESSAGE PARITY ERROR (in which
1382 			 * case we reassert ATN anyway).
1383 			 */
1384 			if (sc->sc_msgpriq == 0)
1385 				bus_space_write_1(iot, ioh, CLRSINT1, CLRATNO);
1386 			goto out;
1387 		}
1388 
1389 		/* Clear ATN before last byte if this is the last message. */
1390 		if (n == 1 && sc->sc_msgpriq == 0)
1391 			bus_space_write_1(iot, ioh, CLRSINT1, CLRATNO);
1392 		/* Send message byte. */
1393 		bus_space_write_1(iot, ioh, SCSIDAT, *--sc->sc_omp);
1394 		--n;
1395 		/* Keep track of the last message we've sent any bytes of. */
1396 		sc->sc_lastmsg = sc->sc_currmsg;
1397 		/* Wait for ACK to be negated.  XXX Need timeout. */
1398 		while ((bus_space_read_1(iot, ioh, SCSISIG) & ACKI) != 0)
1399 			;
1400 
1401 		if (n == 0)
1402 			break;
1403 	}
1404 
1405 	/* We get here only if the entire message has been transmitted. */
1406 	if (sc->sc_msgpriq != 0) {
1407 		/* There are more outgoing messages. */
1408 		goto nextmsg;
1409 	}
1410 
1411 	/*
1412 	 * The last message has been transmitted.  We need to remember the last
1413 	 * message transmitted (in case the target switches to MESSAGE IN phase
1414 	 * and sends a MESSAGE REJECT), and the list of messages transmitted
1415 	 * this time around (in case the target stays in MESSAGE OUT phase to
1416 	 * request a retransmit).
1417 	 */
1418 
1419 out:
1420 	/* Disable REQ/ACK protocol. */
1421 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
1422 }
1423 
1424 /* aic_dataout_pio: perform a data transfer using the FIFO datapath in the
1425  * aic6360
1426  * Precondition: The SCSI bus should be in the DOUT phase, with REQ asserted
1427  * and ACK deasserted (i.e. waiting for a data byte)
1428  * This new revision has been optimized (I tried) to make the common case fast,
1429  * and the rarer cases (as a result) somewhat more comlex
1430  */
1431 static int
1432 aic_dataout_pio(struct aic_softc *sc, u_char *p, int n)
1433 {
1434 	bus_space_tag_t iot = sc->sc_iot;
1435 	bus_space_handle_t ioh = sc->sc_ioh;
1436 	u_char dmastat = 0;
1437 	int out = 0;
1438 #define DOUTAMOUNT 128		/* Full FIFO */
1439 
1440 	AIC_MISC(("%02x%02x  ", bus_space_read_1(iot, ioh, FIFOSTAT),
1441 	    bus_space_read_1(iot, ioh, SSTAT2)));
1442 
1443 	/* Clear host FIFO and counter. */
1444 	bus_space_write_1(iot, ioh, DMACNTRL0, RSTFIFO | WRITE);
1445 	/* Enable FIFOs. */
1446 	bus_space_write_1(iot, ioh, DMACNTRL0, ENDMA | DWORDPIO | WRITE);
1447 	bus_space_write_1(iot, ioh, SXFRCTL0, SCSIEN | DMAEN | CHEN);
1448 
1449 	/* Turn off ENREQINIT for now. */
1450 	bus_space_write_1(iot, ioh, SIMODE1,
1451 	    ENSCSIRST | ENSCSIPERR | ENBUSFREE | ENPHASECHG);
1452 
1453 	/* I have tried to make the main loop as tight as possible.  This
1454 	 * means that some of the code following the loop is a bit more
1455 	 * complex than otherwise.
1456 	 */
1457 	while (n > 0) {
1458 		for (;;) {
1459 			dmastat = bus_space_read_1(iot, ioh, DMASTAT);
1460 			if ((dmastat & (DFIFOEMP | INTSTAT)) != 0)
1461 				break;
1462 		}
1463 
1464 		if ((dmastat & INTSTAT) != 0)
1465 			goto phasechange;
1466 
1467 		if (n >= DOUTAMOUNT) {
1468 			n -= DOUTAMOUNT;
1469 			out += DOUTAMOUNT;
1470 
1471 #if AIC_USE_DWORDS
1472 			bus_space_write_multi_4(iot, ioh, DMADATALONG,
1473 			    (u_int32_t *) p, DOUTAMOUNT >> 2);
1474 #else
1475 			bus_space_write_multi_2(iot, ioh, DMADATA,
1476 			    (u_int16_t *) p, DOUTAMOUNT >> 1);
1477 #endif
1478 
1479 			p += DOUTAMOUNT;
1480 		} else {
1481 			int xfer;
1482 
1483 			xfer = n;
1484 			AIC_MISC(("%d> ", xfer));
1485 
1486 			n -= xfer;
1487 			out += xfer;
1488 
1489 #if AIC_USE_DWORDS
1490 			if (xfer >= 12) {
1491 				bus_space_write_multi_4(iot, ioh, DMADATALONG,
1492 				    (u_int32_t *) p, xfer >> 2);
1493 				p += xfer & ~3;
1494 				xfer &= 3;
1495 			}
1496 #else
1497 			if (xfer >= 8) {
1498 				bus_space_write_multi_2(iot, ioh, DMADATA,
1499 				    (u_int16_t *) p, xfer >> 1);
1500 				p += xfer & ~1;
1501 				xfer &= 1;
1502 			}
1503 #endif
1504 
1505 			if (xfer > 0) {
1506 				bus_space_write_1(iot, ioh, DMACNTRL0,
1507 				    ENDMA | B8MODE | WRITE);
1508 				bus_space_write_multi_1(iot, ioh, DMADATA,
1509 				    p, xfer);
1510 				p += xfer;
1511 				bus_space_write_1(iot, ioh, DMACNTRL0,
1512 				    ENDMA | DWORDPIO | WRITE);
1513 			}
1514 		}
1515 	}
1516 
1517 	if (out == 0) {
1518 		bus_space_write_1(iot, ioh, SXFRCTL1, BITBUCKET);
1519 		for (;;) {
1520 			if ((bus_space_read_1(iot, ioh, DMASTAT) & INTSTAT)
1521 			    != 0)
1522 				break;
1523 		}
1524 		bus_space_write_1(iot, ioh, SXFRCTL1, 0);
1525 		AIC_MISC(("extra data  "));
1526 	} else {
1527 		/* See the bytes off chip */
1528 		for (;;) {
1529 			dmastat = bus_space_read_1(iot, ioh, DMASTAT);
1530 			if ((dmastat & INTSTAT) != 0)
1531 				goto phasechange;
1532 			if ((dmastat & DFIFOEMP) != 0 &&
1533 			    (bus_space_read_1(iot, ioh, SSTAT2) & SEMPTY) != 0)
1534 				break;
1535 		}
1536 	}
1537 
1538 phasechange:
1539 	if ((dmastat & INTSTAT) != 0) {
1540 		/* Some sort of phase change. */
1541 		int amount;
1542 
1543 		/* Stop transfers, do some accounting */
1544 		amount = bus_space_read_1(iot, ioh, FIFOSTAT)
1545 		    + (bus_space_read_1(iot, ioh, SSTAT2) & 15);
1546 		if (amount > 0) {
1547 			out -= amount;
1548 			bus_space_write_1(iot, ioh, DMACNTRL0,
1549 			    RSTFIFO | WRITE);
1550 			bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | CLRCH);
1551 			AIC_MISC(("+%d ", amount));
1552 		}
1553 	}
1554 
1555 	/* Turn on ENREQINIT again. */
1556 	bus_space_write_1(iot, ioh, SIMODE1,
1557 	    ENSCSIRST | ENSCSIPERR | ENBUSFREE | ENREQINIT | ENPHASECHG);
1558 
1559 	/* Stop the FIFO data path. */
1560 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
1561 	bus_space_write_1(iot, ioh, DMACNTRL0, 0);
1562 
1563 	return out;
1564 }
1565 
1566 /* aic_datain_pio: perform data transfers using the FIFO datapath in the
1567  * aic6360
1568  * Precondition: The SCSI bus should be in the DIN phase, with REQ asserted
1569  * and ACK deasserted (i.e. at least one byte is ready).
1570  * For now, uses a pretty dumb algorithm, hangs around until all data has been
1571  * transferred.  This, is OK for fast targets, but not so smart for slow
1572  * targets which don't disconnect or for huge transfers.
1573  */
1574 static int
1575 aic_datain_pio(struct aic_softc *sc, u_char *p, int n)
1576 {
1577 	bus_space_tag_t iot = sc->sc_iot;
1578 	bus_space_handle_t ioh = sc->sc_ioh;
1579 	u_char dmastat;
1580 	int in = 0;
1581 #define DINAMOUNT 128		/* Full FIFO */
1582 
1583 	AIC_MISC(("%02x%02x  ", bus_space_read_1(iot, ioh, FIFOSTAT),
1584 	    bus_space_read_1(iot, ioh, SSTAT2)));
1585 
1586 	/* Clear host FIFO and counter. */
1587 	bus_space_write_1(iot, ioh, DMACNTRL0, RSTFIFO);
1588 	/* Enable FIFOs. */
1589 	bus_space_write_1(iot, ioh, DMACNTRL0, ENDMA | DWORDPIO);
1590 	bus_space_write_1(iot, ioh, SXFRCTL0, SCSIEN | DMAEN | CHEN);
1591 
1592 	/* Turn off ENREQINIT for now. */
1593 	bus_space_write_1(iot, ioh, SIMODE1,
1594 	    ENSCSIRST | ENSCSIPERR | ENBUSFREE | ENPHASECHG);
1595 
1596 	/* We leave this loop if one or more of the following is true:
1597 	 * a) phase != PH_DATAIN && FIFOs are empty
1598 	 * b) SCSIRSTI is set (a reset has occurred) or busfree is detected.
1599 	 */
1600 	while (n > 0) {
1601 		/* Wait for fifo half full or phase mismatch */
1602 		for (;;) {
1603 			dmastat = bus_space_read_1(iot, ioh, DMASTAT);
1604 			if ((dmastat & (DFIFOFULL | INTSTAT)) != 0)
1605 				break;
1606 		}
1607 
1608 		if ((dmastat & DFIFOFULL) != 0) {
1609 			n -= DINAMOUNT;
1610 			in += DINAMOUNT;
1611 
1612 #if AIC_USE_DWORDS
1613 			bus_space_read_multi_4(iot, ioh, DMADATALONG,
1614 			    (u_int32_t *) p, DINAMOUNT >> 2);
1615 #else
1616 			bus_space_read_multi_2(iot, ioh, DMADATA,
1617 			    (u_int16_t *) p, DINAMOUNT >> 1);
1618 #endif
1619 
1620 			p += DINAMOUNT;
1621 		} else {
1622 			int xfer;
1623 
1624 			xfer = min(bus_space_read_1(iot, ioh, FIFOSTAT), n);
1625 			AIC_MISC((">%d ", xfer));
1626 
1627 			n -= xfer;
1628 			in += xfer;
1629 
1630 #if AIC_USE_DWORDS
1631 			if (xfer >= 12) {
1632 				bus_space_read_multi_4(iot, ioh, DMADATALONG,
1633 				    (u_int32_t *) p, xfer >> 2);
1634 				p += xfer & ~3;
1635 				xfer &= 3;
1636 			}
1637 #else
1638 			if (xfer >= 8) {
1639 				bus_space_read_multi_2(iot, ioh, DMADATA,
1640 				    (u_int16_t *) p, xfer >> 1);
1641 				p += xfer & ~1;
1642 				xfer &= 1;
1643 			}
1644 #endif
1645 
1646 			if (xfer > 0) {
1647 				bus_space_write_1(iot, ioh, DMACNTRL0,
1648 				    ENDMA | B8MODE);
1649 				bus_space_read_multi_1(iot, ioh, DMADATA,
1650 				    p, xfer);
1651 				p += xfer;
1652 				bus_space_write_1(iot, ioh, DMACNTRL0,
1653 				    ENDMA | DWORDPIO);
1654 			}
1655 		}
1656 
1657 		if ((dmastat & INTSTAT) != 0)
1658 			goto phasechange;
1659 	}
1660 
1661 	/* Some SCSI-devices are rude enough to transfer more data than what
1662 	 * was requested, e.g. 2048 bytes from a CD-ROM instead of the
1663 	 * requested 512.  Test for progress, i.e. real transfers.  If no real
1664 	 * transfers have been performed (n is probably already zero) and the
1665 	 * FIFO is not empty, waste some bytes....
1666 	 */
1667 	if (in == 0) {
1668 		bus_space_write_1(iot, ioh, SXFRCTL1, BITBUCKET);
1669 		for (;;) {
1670 			if ((bus_space_read_1(iot, ioh, DMASTAT) & INTSTAT)
1671 			    != 0)
1672 				break;
1673 		}
1674 		bus_space_write_1(iot, ioh, SXFRCTL1, 0);
1675 		AIC_MISC(("extra data  "));
1676 	}
1677 
1678 phasechange:
1679 	/* Turn on ENREQINIT again. */
1680 	bus_space_write_1(iot, ioh, SIMODE1,
1681 	    ENSCSIRST | ENSCSIPERR | ENBUSFREE | ENREQINIT | ENPHASECHG);
1682 
1683 	/* Stop the FIFO data path. */
1684 	bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
1685 	bus_space_write_1(iot, ioh, DMACNTRL0, 0);
1686 
1687 	return in;
1688 }
1689 
1690 /*
1691  * This is the workhorse routine of the driver.
1692  * Deficiencies (for now):
1693  * 1) always uses programmed I/O
1694  */
1695 int
1696 aicintr(void *arg)
1697 {
1698 	struct aic_softc *sc = arg;
1699 	bus_space_tag_t iot = sc->sc_iot;
1700 	bus_space_handle_t ioh = sc->sc_ioh;
1701 	u_char sstat0, sstat1;
1702 	struct aic_acb *acb;
1703 	struct scsipi_periph *periph;
1704 	struct aic_tinfo *ti;
1705 	int n;
1706 
1707 	if (!device_is_active(sc->sc_dev))
1708 		return (0);
1709 
1710 	/*
1711 	 * Clear INTEN.  We enable it again before returning.  This makes the
1712 	 * interrupt esssentially level-triggered.
1713 	 */
1714 	bus_space_write_1(iot, ioh, DMACNTRL0, 0);
1715 
1716 	AIC_TRACE(("aicintr  "));
1717 
1718 loop:
1719 	/*
1720 	 * First check for abnormal conditions, such as reset.
1721 	 */
1722 	sstat1 = bus_space_read_1(iot, ioh, SSTAT1);
1723 	AIC_MISC(("sstat1:0x%02x ", sstat1));
1724 
1725 	if ((sstat1 & SCSIRSTI) != 0) {
1726 		printf("%s: SCSI bus reset\n", device_xname(sc->sc_dev));
1727 		goto reset;
1728 	}
1729 
1730 	/*
1731 	 * Check for less serious errors.
1732 	 */
1733 	if ((sstat1 & SCSIPERR) != 0) {
1734 		printf("%s: SCSI bus parity error\n", device_xname(sc->sc_dev));
1735 		bus_space_write_1(iot, ioh, CLRSINT1, CLRSCSIPERR);
1736 		if (sc->sc_prevphase == PH_MSGIN) {
1737 			sc->sc_flags |= AIC_DROP_MSGIN;
1738 			aic_sched_msgout(sc, SEND_PARITY_ERROR);
1739 		} else
1740 			aic_sched_msgout(sc, SEND_INIT_DET_ERR);
1741 	}
1742 
1743 	/*
1744 	 * If we're not already busy doing something test for the following
1745 	 * conditions:
1746 	 * 1) We have been reselected by something
1747 	 * 2) We have selected something successfully
1748 	 * 3) Our selection process has timed out
1749 	 * 4) This is really a bus free interrupt just to get a new command
1750 	 *    going?
1751 	 * 5) Spurious interrupt?
1752 	 */
1753 	switch (sc->sc_state) {
1754 	case AIC_IDLE:
1755 	case AIC_SELECTING:
1756 		sstat0 = bus_space_read_1(iot, ioh, SSTAT0);
1757 		AIC_MISC(("sstat0:0x%02x ", sstat0));
1758 
1759 		if ((sstat0 & TARGET) != 0) {
1760 			/*
1761 			 * We don't currently support target mode.
1762 			 */
1763 			printf("%s: target mode selected; going to BUS FREE\n",
1764 			    device_xname(sc->sc_dev));
1765 			bus_space_write_1(iot, ioh, SCSISIG, 0);
1766 
1767 			goto sched;
1768 		} else if ((sstat0 & SELDI) != 0) {
1769 			AIC_MISC(("reselected  "));
1770 
1771 			/*
1772 			 * If we're trying to select a target ourselves,
1773 			 * push our command back into the ready list.
1774 			 */
1775 			if (sc->sc_state == AIC_SELECTING) {
1776 				AIC_MISC(("backoff selector  "));
1777 				AIC_ASSERT(sc->sc_nexus != NULL);
1778 				acb = sc->sc_nexus;
1779 				sc->sc_nexus = NULL;
1780 				TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
1781 			}
1782 
1783 			/* Save reselection ID. */
1784 			sc->sc_selid = bus_space_read_1(iot, ioh, SELID);
1785 
1786 			sc->sc_state = AIC_RESELECTED;
1787 		} else if ((sstat0 & SELDO) != 0) {
1788 			AIC_MISC(("selected  "));
1789 
1790 			/* We have selected a target. Things to do:
1791 			 * a) Determine what message(s) to send.
1792 			 * b) Verify that we're still selecting the target.
1793 			 * c) Mark device as busy.
1794 			 */
1795 			if (sc->sc_state != AIC_SELECTING) {
1796 				printf("%s: selection out while idle; "
1797 				    "resetting\n", device_xname(sc->sc_dev));
1798 				AIC_BREAK();
1799 				goto reset;
1800 			}
1801 			AIC_ASSERT(sc->sc_nexus != NULL);
1802 			acb = sc->sc_nexus;
1803 			periph = acb->xs->xs_periph;
1804 			ti = &sc->sc_tinfo[periph->periph_target];
1805 
1806 			sc->sc_msgpriq = SEND_IDENTIFY;
1807 			if (acb->flags & ACB_RESET)
1808 				sc->sc_msgpriq |= SEND_DEV_RESET;
1809 			else if (acb->flags & ACB_ABORT)
1810 				sc->sc_msgpriq |= SEND_ABORT;
1811 			else {
1812 #if AIC_USE_SYNCHRONOUS
1813 				if ((ti->flags & DO_SYNC) != 0)
1814 					sc->sc_msgpriq |= SEND_SDTR;
1815 #endif
1816 #if AIC_USE_WIDE
1817 				if ((ti->flags & DO_WIDE) != 0)
1818 					sc->sc_msgpriq |= SEND_WDTR;
1819 #endif
1820 			}
1821 
1822 			acb->flags |= ACB_NEXUS;
1823 			ti->lubusy |= (1 << periph->periph_lun);
1824 
1825 			/* Do an implicit RESTORE POINTERS. */
1826 			sc->sc_dp = acb->data_addr;
1827 			sc->sc_dleft = acb->data_length;
1828 			sc->sc_cp = (u_char *)&acb->scsipi_cmd;
1829 			sc->sc_cleft = acb->scsipi_cmd_length;
1830 
1831 			/* On our first connection, schedule a timeout. */
1832 			if ((acb->xs->xs_control & XS_CTL_POLL) == 0)
1833 				callout_reset(&acb->xs->xs_callout,
1834 				    mstohz(acb->timeout), aic_timeout, acb);
1835 
1836 			sc->sc_state = AIC_CONNECTED;
1837 		} else if ((sstat1 & SELTO) != 0) {
1838 			AIC_MISC(("selection timeout  "));
1839 
1840 			if (sc->sc_state != AIC_SELECTING) {
1841 				printf("%s: selection timeout while idle; "
1842 				    "resetting\n", device_xname(sc->sc_dev));
1843 				AIC_BREAK();
1844 				goto reset;
1845 			}
1846 			AIC_ASSERT(sc->sc_nexus != NULL);
1847 			acb = sc->sc_nexus;
1848 
1849 			bus_space_write_1(iot, ioh, SXFRCTL1, 0);
1850 			bus_space_write_1(iot, ioh, SCSISEQ, ENRESELI);
1851 			bus_space_write_1(iot, ioh, CLRSINT1, CLRSELTIMO);
1852 			delay(250);
1853 
1854 			acb->xs->error = XS_SELTIMEOUT;
1855 			goto finish;
1856 		} else {
1857 			if (sc->sc_state != AIC_IDLE) {
1858 				printf("%s: BUS FREE while not idle; "
1859 				    "state=%d\n",
1860 				    device_xname(sc->sc_dev), sc->sc_state);
1861 				AIC_BREAK();
1862 				goto out;
1863 			}
1864 
1865 			goto sched;
1866 		}
1867 
1868 		/*
1869 		 * Turn off selection stuff, and prepare to catch bus free
1870 		 * interrupts, parity errors, and phase changes.
1871 		 */
1872 		bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | CLRSTCNT | CLRCH);
1873 		bus_space_write_1(iot, ioh, SXFRCTL1, 0);
1874 		bus_space_write_1(iot, ioh, SCSISEQ, ENAUTOATNP);
1875 		bus_space_write_1(iot, ioh, CLRSINT0, CLRSELDI | CLRSELDO);
1876 		bus_space_write_1(iot, ioh, CLRSINT1,
1877 		    CLRBUSFREE | CLRPHASECHG);
1878 		bus_space_write_1(iot, ioh, SIMODE0, 0);
1879 		bus_space_write_1(iot, ioh, SIMODE1,
1880 		    ENSCSIRST | ENSCSIPERR | ENBUSFREE | ENREQINIT |
1881 		    ENPHASECHG);
1882 
1883 		sc->sc_flags = 0;
1884 		sc->sc_prevphase = PH_INVALID;
1885 		goto dophase;
1886 	}
1887 
1888 	if ((sstat1 & BUSFREE) != 0) {
1889 		/* We've gone to BUS FREE phase. */
1890 		bus_space_write_1(iot, ioh, CLRSINT1,
1891 		    CLRBUSFREE | CLRPHASECHG);
1892 
1893 		switch (sc->sc_state) {
1894 		case AIC_RESELECTED:
1895 			goto sched;
1896 
1897 		case AIC_CONNECTED:
1898 			AIC_ASSERT(sc->sc_nexus != NULL);
1899 			acb = sc->sc_nexus;
1900 
1901 #if AIC_USE_SYNCHRONOUS + AIC_USE_WIDE
1902 			if (sc->sc_prevphase == PH_MSGOUT) {
1903 				/*
1904 				 * If the target went to BUS FREE phase during
1905 				 * or immediately after sending a SDTR or WDTR
1906 				 * message, disable negotiation.
1907 				 */
1908 				periph = acb->xs->xs_periph;
1909 				ti = &sc->sc_tinfo[periph->periph_target];
1910 				switch (sc->sc_lastmsg) {
1911 #if AIC_USE_SYNCHRONOUS
1912 				case SEND_SDTR:
1913 					ti->flags &= ~DO_SYNC;
1914 					ti->period = ti->offset = 0;
1915 					break;
1916 #endif
1917 #if AIC_USE_WIDE
1918 				case SEND_WDTR:
1919 					ti->flags &= ~DO_WIDE;
1920 					ti->width = 0;
1921 					break;
1922 #endif
1923 				}
1924 			}
1925 #endif
1926 
1927 			if ((sc->sc_flags & AIC_ABORTING) == 0) {
1928 				/*
1929 				 * Section 5.1.1 of the SCSI 2 spec suggests
1930 				 * issuing a REQUEST SENSE following an
1931 				 * unexpected disconnect.  Some devices go into
1932 				 * a contingent allegiance condition when
1933 				 * disconnecting, and this is necessary to
1934 				 * clean up their state.
1935 				 */
1936 				aprint_error_dev(sc->sc_dev,
1937 				    "unexpected disconnect; "
1938 				    "sending REQUEST SENSE\n");
1939 				AIC_BREAK();
1940 				aic_sense(sc, acb);
1941 				goto out;
1942 			}
1943 
1944 			acb->xs->error = XS_DRIVER_STUFFUP;
1945 			goto finish;
1946 
1947 		case AIC_DISCONNECT:
1948 			AIC_ASSERT(sc->sc_nexus != NULL);
1949 			acb = sc->sc_nexus;
1950 #if 1 /* XXXX */
1951 			acb->data_addr = sc->sc_dp;
1952 			acb->data_length = sc->sc_dleft;
1953 #endif
1954 			TAILQ_INSERT_HEAD(&sc->nexus_list, acb, chain);
1955 			sc->sc_nexus = NULL;
1956 			goto sched;
1957 
1958 		case AIC_CMDCOMPLETE:
1959 			AIC_ASSERT(sc->sc_nexus != NULL);
1960 			acb = sc->sc_nexus;
1961 			goto finish;
1962 		}
1963 	}
1964 
1965 	bus_space_write_1(iot, ioh, CLRSINT1, CLRPHASECHG);
1966 
1967 dophase:
1968 	if ((sstat1 & REQINIT) == 0) {
1969 		/* Wait for REQINIT. */
1970 		goto out;
1971 	}
1972 
1973 	sc->sc_phase = bus_space_read_1(iot, ioh, SCSISIG) & PH_MASK;
1974 	bus_space_write_1(iot, ioh, SCSISIG, sc->sc_phase);
1975 
1976 	switch (sc->sc_phase) {
1977 	case PH_MSGOUT:
1978 		if (sc->sc_state != AIC_CONNECTED &&
1979 		    sc->sc_state != AIC_RESELECTED)
1980 			break;
1981 		aic_msgout(sc);
1982 		sc->sc_prevphase = PH_MSGOUT;
1983 		goto loop;
1984 
1985 	case PH_MSGIN:
1986 		if (sc->sc_state != AIC_CONNECTED &&
1987 		    sc->sc_state != AIC_RESELECTED)
1988 			break;
1989 		aic_msgin(sc);
1990 		sc->sc_prevphase = PH_MSGIN;
1991 		goto loop;
1992 
1993 	case PH_CMD:
1994 		if (sc->sc_state != AIC_CONNECTED)
1995 			break;
1996 #if AIC_DEBUG
1997 		if ((aic_debug & AIC_SHOWMISC) != 0) {
1998 			AIC_ASSERT(sc->sc_nexus != NULL);
1999 			acb = sc->sc_nexus;
2000 			printf("cmd=0x%02x+%d ",
2001 			    acb->scsipi_cmd.opcode, acb->scsipi_cmd_length-1);
2002 		}
2003 #endif
2004 		n = aic_dataout_pio(sc, sc->sc_cp, sc->sc_cleft);
2005 		sc->sc_cp += n;
2006 		sc->sc_cleft -= n;
2007 		sc->sc_prevphase = PH_CMD;
2008 		goto loop;
2009 
2010 	case PH_DATAOUT:
2011 		if (sc->sc_state != AIC_CONNECTED)
2012 			break;
2013 		AIC_MISC(("dataout %ld ", (long)sc->sc_dleft));
2014 		n = aic_dataout_pio(sc, sc->sc_dp, sc->sc_dleft);
2015 		sc->sc_dp += n;
2016 		sc->sc_dleft -= n;
2017 		sc->sc_prevphase = PH_DATAOUT;
2018 		goto loop;
2019 
2020 	case PH_DATAIN:
2021 		if (sc->sc_state != AIC_CONNECTED)
2022 			break;
2023 		AIC_MISC(("datain %ld ", (long)sc->sc_dleft));
2024 		n = aic_datain_pio(sc, sc->sc_dp, sc->sc_dleft);
2025 		sc->sc_dp += n;
2026 		sc->sc_dleft -= n;
2027 		sc->sc_prevphase = PH_DATAIN;
2028 		goto loop;
2029 
2030 	case PH_STAT:
2031 		if (sc->sc_state != AIC_CONNECTED)
2032 			break;
2033 		AIC_ASSERT(sc->sc_nexus != NULL);
2034 		acb = sc->sc_nexus;
2035 		bus_space_write_1(iot, ioh, SXFRCTL0, CHEN | SPIOEN);
2036 		acb->target_stat = bus_space_read_1(iot, ioh, SCSIDAT);
2037 		bus_space_write_1(iot, ioh, SXFRCTL0, CHEN);
2038 		AIC_MISC(("target_stat=0x%02x  ", acb->target_stat));
2039 		sc->sc_prevphase = PH_STAT;
2040 		goto loop;
2041 	}
2042 
2043 	aprint_error_dev(sc->sc_dev, "unexpected bus phase; resetting\n");
2044 	AIC_BREAK();
2045 reset:
2046 	aic_init(sc, 1);
2047 	return 1;
2048 
2049 finish:
2050 	callout_stop(&acb->xs->xs_callout);
2051 	aic_done(sc, acb);
2052 	goto out;
2053 
2054 sched:
2055 	sc->sc_state = AIC_IDLE;
2056 	aic_sched(sc);
2057 	goto out;
2058 
2059 out:
2060 	bus_space_write_1(iot, ioh, DMACNTRL0, INTEN);
2061 	return 1;
2062 }
2063 
2064 static void
2065 aic_abort(struct aic_softc *sc, struct aic_acb *acb)
2066 {
2067 
2068 	/* 2 secs for the abort */
2069 	acb->timeout = AIC_ABORT_TIMEOUT;
2070 	acb->flags |= ACB_ABORT;
2071 
2072 	if (acb == sc->sc_nexus) {
2073 		/*
2074 		 * If we're still selecting, the message will be scheduled
2075 		 * after selection is complete.
2076 		 */
2077 		if (sc->sc_state == AIC_CONNECTED)
2078 			aic_sched_msgout(sc, SEND_ABORT);
2079 	} else {
2080 		aic_dequeue(sc, acb);
2081 		TAILQ_INSERT_HEAD(&sc->ready_list, acb, chain);
2082 		if (sc->sc_state == AIC_IDLE)
2083 			aic_sched(sc);
2084 	}
2085 }
2086 
2087 static void
2088 aic_timeout(void *arg)
2089 {
2090 	struct aic_acb *acb = arg;
2091 	struct scsipi_xfer *xs = acb->xs;
2092 	struct scsipi_periph *periph = xs->xs_periph;
2093 	struct aic_softc *sc =
2094 	    device_private(periph->periph_channel->chan_adapter->adapt_dev);
2095 	int s;
2096 
2097 	scsipi_printaddr(periph);
2098 	printf("timed out");
2099 
2100 	s = splbio();
2101 
2102 	if (acb->flags & ACB_ABORT) {
2103 		/* abort timed out */
2104 		printf(" AGAIN\n");
2105 		/* XXX Must reset! */
2106 	} else {
2107 		/* abort the operation that has timed out */
2108 		printf("\n");
2109 		acb->xs->error = XS_TIMEOUT;
2110 		aic_abort(sc, acb);
2111 	}
2112 
2113 	splx(s);
2114 }
2115 
2116 #ifdef AIC_DEBUG
2117 /*
2118  * The following functions are mostly used for debugging purposes, either
2119  * directly called from the driver or from the kernel debugger.
2120  */
2121 
2122 static void
2123 aic_show_scsi_cmd(struct aic_acb *acb)
2124 {
2125 	u_char  *b = (u_char *)&acb->scsipi_cmd;
2126 	struct scsipi_periph *periph = acb->xs->xs_periph;
2127 	int i;
2128 
2129 	scsipi_printaddr(periph);
2130 	if ((acb->xs->xs_control & XS_CTL_RESET) == 0) {
2131 		for (i = 0; i < acb->scsipi_cmd_length; i++) {
2132 			if (i)
2133 				printf(",");
2134 			printf("%x", b[i]);
2135 		}
2136 		printf("\n");
2137 	} else
2138 		printf("RESET\n");
2139 }
2140 
2141 static void
2142 aic_print_acb(struct aic_acb *acb)
2143 {
2144 
2145 	printf("acb@%p xs=%p flags=%x", acb, acb->xs, acb->flags);
2146 	printf(" dp=%p dleft=%d target_stat=%x\n",
2147 	       acb->data_addr, acb->data_length, acb->target_stat);
2148 	aic_show_scsi_cmd(acb);
2149 }
2150 
2151 void
2152 aic_print_active_acb(void)
2153 {
2154 	struct aic_acb *acb;
2155 	struct aic_softc *sc = device_lookup_private(&aic_cd, 0);
2156 
2157 	printf("ready list:\n");
2158 	for (acb = sc->ready_list.tqh_first; acb != NULL;
2159 	    acb = acb->chain.tqe_next)
2160 		aic_print_acb(acb);
2161 	printf("nexus:\n");
2162 	if (sc->sc_nexus != NULL)
2163 		aic_print_acb(sc->sc_nexus);
2164 	printf("nexus list:\n");
2165 	for (acb = sc->nexus_list.tqh_first; acb != NULL;
2166 	    acb = acb->chain.tqe_next)
2167 		aic_print_acb(acb);
2168 }
2169 
2170 void
2171 aic_dump6360(struct aic_softc *sc)
2172 {
2173 	bus_space_tag_t iot = sc->sc_iot;
2174 	bus_space_handle_t ioh = sc->sc_ioh;
2175 
2176 	printf("aic6360: SCSISEQ=%x SXFRCTL0=%x SXFRCTL1=%x SCSISIG=%x\n",
2177 	    bus_space_read_1(iot, ioh, SCSISEQ),
2178 	    bus_space_read_1(iot, ioh, SXFRCTL0),
2179 	    bus_space_read_1(iot, ioh, SXFRCTL1),
2180 	    bus_space_read_1(iot, ioh, SCSISIG));
2181 	printf("         SSTAT0=%x SSTAT1=%x SSTAT2=%x SSTAT3=%x SSTAT4=%x\n",
2182 	    bus_space_read_1(iot, ioh, SSTAT0),
2183 	    bus_space_read_1(iot, ioh, SSTAT1),
2184 	    bus_space_read_1(iot, ioh, SSTAT2),
2185 	    bus_space_read_1(iot, ioh, SSTAT3),
2186 	    bus_space_read_1(iot, ioh, SSTAT4));
2187 	printf("         SIMODE0=%x SIMODE1=%x DMACNTRL0=%x DMACNTRL1=%x "
2188 	    "DMASTAT=%x\n",
2189 	    bus_space_read_1(iot, ioh, SIMODE0),
2190 	    bus_space_read_1(iot, ioh, SIMODE1),
2191 	    bus_space_read_1(iot, ioh, DMACNTRL0),
2192 	    bus_space_read_1(iot, ioh, DMACNTRL1),
2193 	    bus_space_read_1(iot, ioh, DMASTAT));
2194 	printf("         FIFOSTAT=%d SCSIBUS=0x%x\n",
2195 	    bus_space_read_1(iot, ioh, FIFOSTAT),
2196 	    bus_space_read_1(iot, ioh, SCSIBUS));
2197 }
2198 
2199 void
2200 aic_dump_driver(struct aic_softc *sc)
2201 {
2202 	struct aic_tinfo *ti;
2203 	int i;
2204 
2205 	printf("nexus=%p prevphase=%x\n", sc->sc_nexus, sc->sc_prevphase);
2206 	printf("state=%x msgin=%x msgpriq=%x msgoutq=%x lastmsg=%x "
2207 	    "currmsg=%x\n",
2208 	    sc->sc_state, sc->sc_imess[0],
2209 	    sc->sc_msgpriq, sc->sc_msgoutq, sc->sc_lastmsg, sc->sc_currmsg);
2210 	for (i = 0; i < 7; i++) {
2211 		ti = &sc->sc_tinfo[i];
2212 		printf("tinfo%d: %d cmds %d disconnects %d timeouts",
2213 		    i, ti->cmds, ti->dconns, ti->touts);
2214 		printf(" %d senses flags=%x\n", ti->senses, ti->flags);
2215 	}
2216 }
2217 #endif
2218