1/*-
2 * Core routines and tables shareable across OS platforms.
3 *
4 * Copyright (c) 1994-2002 Justin T. Gibbs.
5 * Copyright (c) 2000-2002 Adaptec Inc.
6 * All rights reserved.
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
10 * are met:
11 * 1. Redistributions of source code must retain the above copyright
12 *    notice, this list of conditions, and the following disclaimer,
13 *    without modification.
14 * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15 *    substantially similar to the "NO WARRANTY" disclaimer below
16 *    ("Disclaimer") and any redistribution must be conditioned upon
17 *    including a substantially similar Disclaimer requirement for further
18 *    binary redistribution.
19 * 3. Neither the names of the above-listed copyright holders nor the names
20 *    of any contributors may be used to endorse or promote products derived
21 *    from this software without specific prior written permission.
22 *
23 * Alternatively, this software may be distributed under the terms of the
24 * GNU General Public License ("GPL") version 2 as published by the Free
25 * Software Foundation.
26 *
27 * NO WARRANTY
28 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
31 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32 * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
37 * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38 * POSSIBILITY OF SUCH DAMAGES.
39 *
40 * $Id: //depot/aic7xxx/aic7xxx/aic7xxx.c#155 $
41 */
42
43#ifdef __linux__
44#include "aic7xxx_osm.h"
45#include "aic7xxx_inline.h"
46#include "aicasm/aicasm_insformat.h"
47#else
48#include <sys/cdefs.h>
49__FBSDID("$FreeBSD$");
50#include <dev/aic7xxx/aic7xxx_osm.h>
51#include <dev/aic7xxx/aic7xxx_inline.h>
52#include <dev/aic7xxx/aicasm/aicasm_insformat.h>
53#endif
54
55/****************************** Softc Data ************************************/
56struct ahc_softc_tailq ahc_tailq = TAILQ_HEAD_INITIALIZER(ahc_tailq);
57
58/***************************** Lookup Tables **********************************/
59char *ahc_chip_names[] =
60{
61	"NONE",
62	"aic7770",
63	"aic7850",
64	"aic7855",
65	"aic7859",
66	"aic7860",
67	"aic7870",
68	"aic7880",
69	"aic7895",
70	"aic7895C",
71	"aic7890/91",
72	"aic7896/97",
73	"aic7892",
74	"aic7899"
75};
76
77/*
78 * Hardware error codes.
79 */
80struct ahc_hard_error_entry {
81        uint8_t errno;
82	char *errmesg;
83};
84
85static struct ahc_hard_error_entry ahc_hard_errors[] = {
86	{ ILLHADDR,	"Illegal Host Access" },
87	{ ILLSADDR,	"Illegal Sequencer Address referrenced" },
88	{ ILLOPCODE,	"Illegal Opcode in sequencer program" },
89	{ SQPARERR,	"Sequencer Parity Error" },
90	{ DPARERR,	"Data-path Parity Error" },
91	{ MPARERR,	"Scratch or SCB Memory Parity Error" },
92	{ PCIERRSTAT,	"PCI Error detected" },
93	{ CIOPARERR,	"CIOBUS Parity Error" },
94};
95static const u_int num_errors = NUM_ELEMENTS(ahc_hard_errors);
96
97static struct ahc_phase_table_entry ahc_phase_table[] =
98{
99	{ P_DATAOUT,	MSG_NOOP,		"in Data-out phase"	},
100	{ P_DATAIN,	MSG_INITIATOR_DET_ERR,	"in Data-in phase"	},
101	{ P_DATAOUT_DT,	MSG_NOOP,		"in DT Data-out phase"	},
102	{ P_DATAIN_DT,	MSG_INITIATOR_DET_ERR,	"in DT Data-in phase"	},
103	{ P_COMMAND,	MSG_NOOP,		"in Command phase"	},
104	{ P_MESGOUT,	MSG_NOOP,		"in Message-out phase"	},
105	{ P_STATUS,	MSG_INITIATOR_DET_ERR,	"in Status phase"	},
106	{ P_MESGIN,	MSG_PARITY_ERROR,	"in Message-in phase"	},
107	{ P_BUSFREE,	MSG_NOOP,		"while idle"		},
108	{ 0,		MSG_NOOP,		"in unknown phase"	}
109};
110
111/*
112 * In most cases we only wish to itterate over real phases, so
113 * exclude the last element from the count.
114 */
115static const u_int num_phases = NUM_ELEMENTS(ahc_phase_table) - 1;
116
117/*
118 * Valid SCSIRATE values.  (p. 3-17)
119 * Provides a mapping of tranfer periods in ns to the proper value to
120 * stick in the scsixfer reg.
121 */
122static struct ahc_syncrate ahc_syncrates[] =
123{
124      /* ultra2    fast/ultra  period     rate */
125	{ 0x42,      0x000,      9,      "80.0" },
126	{ 0x03,      0x000,     10,      "40.0" },
127	{ 0x04,      0x000,     11,      "33.0" },
128	{ 0x05,      0x100,     12,      "20.0" },
129	{ 0x06,      0x110,     15,      "16.0" },
130	{ 0x07,      0x120,     18,      "13.4" },
131	{ 0x08,      0x000,     25,      "10.0" },
132	{ 0x19,      0x010,     31,      "8.0"  },
133	{ 0x1a,      0x020,     37,      "6.67" },
134	{ 0x1b,      0x030,     43,      "5.7"  },
135	{ 0x1c,      0x040,     50,      "5.0"  },
136	{ 0x00,      0x050,     56,      "4.4"  },
137	{ 0x00,      0x060,     62,      "4.0"  },
138	{ 0x00,      0x070,     68,      "3.6"  },
139	{ 0x00,      0x000,      0,      NULL   }
140};
141
142/* Our Sequencer Program */
143#include "aic7xxx_seq.h"
144
145/**************************** Function Declarations ***************************/
146static void		ahc_force_renegotiation(struct ahc_softc *ahc,
147						struct ahc_devinfo *devinfo);
148static struct ahc_tmode_tstate*
149			ahc_alloc_tstate(struct ahc_softc *ahc,
150					 u_int scsi_id, char channel);
151#ifdef AHC_TARGET_MODE
152static void		ahc_free_tstate(struct ahc_softc *ahc,
153					u_int scsi_id, char channel, int force);
154#endif
155static struct ahc_syncrate*
156			ahc_devlimited_syncrate(struct ahc_softc *ahc,
157					        struct ahc_initiator_tinfo *,
158						u_int *period,
159						u_int *ppr_options,
160						role_t role);
161static void		ahc_update_pending_scbs(struct ahc_softc *ahc);
162static void		ahc_fetch_devinfo(struct ahc_softc *ahc,
163					  struct ahc_devinfo *devinfo);
164static void		ahc_scb_devinfo(struct ahc_softc *ahc,
165					struct ahc_devinfo *devinfo,
166					struct scb *scb);
167static void		ahc_assert_atn(struct ahc_softc *ahc);
168static void		ahc_setup_initiator_msgout(struct ahc_softc *ahc,
169						   struct ahc_devinfo *devinfo,
170						   struct scb *scb);
171static void		ahc_build_transfer_msg(struct ahc_softc *ahc,
172					       struct ahc_devinfo *devinfo);
173static void		ahc_construct_sdtr(struct ahc_softc *ahc,
174					   struct ahc_devinfo *devinfo,
175					   u_int period, u_int offset);
176static void		ahc_construct_wdtr(struct ahc_softc *ahc,
177					   struct ahc_devinfo *devinfo,
178					   u_int bus_width);
179static void		ahc_construct_ppr(struct ahc_softc *ahc,
180					  struct ahc_devinfo *devinfo,
181					  u_int period, u_int offset,
182					  u_int bus_width, u_int ppr_options);
183static void		ahc_clear_msg_state(struct ahc_softc *ahc);
184static void		ahc_handle_proto_violation(struct ahc_softc *ahc);
185static void		ahc_handle_message_phase(struct ahc_softc *ahc);
186typedef enum {
187	AHCMSG_1B,
188	AHCMSG_2B,
189	AHCMSG_EXT
190} ahc_msgtype;
191static int		ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
192				     u_int msgval, int full);
193static int		ahc_parse_msg(struct ahc_softc *ahc,
194				      struct ahc_devinfo *devinfo);
195static int		ahc_handle_msg_reject(struct ahc_softc *ahc,
196					      struct ahc_devinfo *devinfo);
197static void		ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
198						struct ahc_devinfo *devinfo);
199static void		ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
200static void		ahc_handle_devreset(struct ahc_softc *ahc,
201					    struct ahc_devinfo *devinfo,
202					    cam_status status, char *message,
203					    int verbose_level);
204#ifdef AHC_TARGET_MODE
205static void		ahc_setup_target_msgin(struct ahc_softc *ahc,
206					       struct ahc_devinfo *devinfo,
207					       struct scb *scb);
208#endif
209
210static bus_dmamap_callback_t	ahc_dmamap_cb;
211static void			ahc_build_free_scb_list(struct ahc_softc *ahc);
212static int			ahc_init_scbdata(struct ahc_softc *ahc);
213static void			ahc_fini_scbdata(struct ahc_softc *ahc);
214static void		ahc_qinfifo_requeue(struct ahc_softc *ahc,
215					    struct scb *prev_scb,
216					    struct scb *scb);
217static int		ahc_qinfifo_count(struct ahc_softc *ahc);
218static u_int		ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
219						   u_int prev, u_int scbptr);
220static void		ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
221static u_int		ahc_rem_wscb(struct ahc_softc *ahc,
222				     u_int scbpos, u_int prev);
223static void		ahc_reset_current_bus(struct ahc_softc *ahc);
224#ifdef AHC_DUMP_SEQ
225static void		ahc_dumpseq(struct ahc_softc *ahc);
226#endif
227static int		ahc_loadseq(struct ahc_softc *ahc);
228static int		ahc_check_patch(struct ahc_softc *ahc,
229					struct patch **start_patch,
230					u_int start_instr, u_int *skip_addr);
231static void		ahc_download_instr(struct ahc_softc *ahc,
232					   u_int instrptr, uint8_t *dconsts);
233static int		ahc_other_scb_timeout(struct ahc_softc *ahc,
234					      struct scb *scb,
235					      struct scb *other_scb);
236#ifdef AHC_TARGET_MODE
237static void		ahc_queue_lstate_event(struct ahc_softc *ahc,
238					       struct ahc_tmode_lstate *lstate,
239					       u_int initiator_id,
240					       u_int event_type,
241					       u_int event_arg);
242static void		ahc_update_scsiid(struct ahc_softc *ahc,
243					  u_int targid_mask);
244static int		ahc_handle_target_cmd(struct ahc_softc *ahc,
245					      struct target_cmd *cmd);
246#endif
247/************************* Sequencer Execution Control ************************/
248/*
249 * Restart the sequencer program from address zero
250 */
251void
252ahc_restart(struct ahc_softc *ahc)
253{
254
255	ahc_pause(ahc);
256
257	/* No more pending messages. */
258	ahc_clear_msg_state(ahc);
259
260	ahc_outb(ahc, SCSISIGO, 0);		/* De-assert BSY */
261	ahc_outb(ahc, MSG_OUT, MSG_NOOP);	/* No message to send */
262	ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
263	ahc_outb(ahc, LASTPHASE, P_BUSFREE);
264	ahc_outb(ahc, SAVED_SCSIID, 0xFF);
265	ahc_outb(ahc, SAVED_LUN, 0xFF);
266
267	/*
268	 * Ensure that the sequencer's idea of TQINPOS
269	 * matches our own.  The sequencer increments TQINPOS
270	 * only after it sees a DMA complete and a reset could
271	 * occur before the increment leaving the kernel to believe
272	 * the command arrived but the sequencer to not.
273	 */
274	ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
275
276	/* Always allow reselection */
277	ahc_outb(ahc, SCSISEQ,
278		 ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
279	if ((ahc->features & AHC_CMD_CHAN) != 0) {
280		/* Ensure that no DMA operations are in progress */
281		ahc_outb(ahc, CCSCBCNT, 0);
282		ahc_outb(ahc, CCSGCTL, 0);
283		ahc_outb(ahc, CCSCBCTL, 0);
284	}
285	/*
286	 * If we were in the process of DMA'ing SCB data into
287	 * an SCB, replace that SCB on the free list.  This prevents
288	 * an SCB leak.
289	 */
290	if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
291		ahc_add_curscb_to_free_list(ahc);
292		ahc_outb(ahc, SEQ_FLAGS2,
293			 ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
294	}
295
296	/*
297	 * Clear any pending sequencer interrupt.  It is no
298	 * longer relevant since we're resetting the Program
299	 * Counter.
300	 */
301	ahc_outb(ahc, CLRINT, CLRSEQINT);
302
303	ahc_outb(ahc, MWI_RESIDUAL, 0);
304	ahc_outb(ahc, SEQCTL, ahc->seqctl);
305	ahc_outb(ahc, SEQADDR0, 0);
306	ahc_outb(ahc, SEQADDR1, 0);
307
308	ahc_unpause(ahc);
309}
310
311/************************* Input/Output Queues ********************************/
312void
313ahc_run_qoutfifo(struct ahc_softc *ahc)
314{
315	struct scb *scb;
316	u_int  scb_index;
317
318	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
319	while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
320
321		scb_index = ahc->qoutfifo[ahc->qoutfifonext];
322		if ((ahc->qoutfifonext & 0x03) == 0x03) {
323			u_int modnext;
324
325			/*
326			 * Clear 32bits of QOUTFIFO at a time
327			 * so that we don't clobber an incoming
328			 * byte DMA to the array on architectures
329			 * that only support 32bit load and store
330			 * operations.
331			 */
332			modnext = ahc->qoutfifonext & ~0x3;
333			*((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
334			aic_dmamap_sync(ahc, ahc->shared_data_dmat,
335					ahc->shared_data_dmamap,
336					/*offset*/modnext, /*len*/4,
337					BUS_DMASYNC_PREREAD);
338		}
339		ahc->qoutfifonext++;
340
341		scb = ahc_lookup_scb(ahc, scb_index);
342		if (scb == NULL) {
343			printf("%s: WARNING no command for scb %d "
344			       "(cmdcmplt)\nQOUTPOS = %d\n",
345			       ahc_name(ahc), scb_index,
346			       (ahc->qoutfifonext - 1) & 0xFF);
347			continue;
348		}
349
350		/*
351		 * Save off the residual
352		 * if there is one.
353		 */
354		ahc_update_residual(ahc, scb);
355		ahc_done(ahc, scb);
356	}
357}
358
359void
360ahc_run_untagged_queues(struct ahc_softc *ahc)
361{
362	int i;
363
364	for (i = 0; i < 16; i++)
365		ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
366}
367
368void
369ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
370{
371	struct scb *scb;
372
373	if (ahc->untagged_queue_lock != 0)
374		return;
375
376	if ((scb = TAILQ_FIRST(queue)) != NULL
377	 && (scb->flags & SCB_ACTIVE) == 0) {
378		scb->flags |= SCB_ACTIVE;
379		/*
380		 * Timers are disabled while recovery is in progress.
381		 */
382		aic_scb_timer_start(scb);
383		ahc_queue_scb(ahc, scb);
384	}
385}
386
387/************************* Interrupt Handling *********************************/
388void
389ahc_handle_brkadrint(struct ahc_softc *ahc)
390{
391	/*
392	 * We upset the sequencer :-(
393	 * Lookup the error message
394	 */
395	int i;
396	int error;
397
398	error = ahc_inb(ahc, ERROR);
399	for (i = 0; error != 1 && i < num_errors; i++)
400		error >>= 1;
401	printf("%s: brkadrint, %s at seqaddr = 0x%x\n",
402	       ahc_name(ahc), ahc_hard_errors[i].errmesg,
403	       ahc_inb(ahc, SEQADDR0) |
404	       (ahc_inb(ahc, SEQADDR1) << 8));
405
406	ahc_dump_card_state(ahc);
407
408	/* Tell everyone that this HBA is no longer available */
409	ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
410		       CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
411		       CAM_NO_HBA);
412
413	/* Disable all interrupt sources by resetting the controller */
414	ahc_shutdown(ahc);
415}
416
417void
418ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
419{
420	struct scb *scb;
421	struct ahc_devinfo devinfo;
422
423	ahc_fetch_devinfo(ahc, &devinfo);
424
425	/*
426	 * Clear the upper byte that holds SEQINT status
427	 * codes and clear the SEQINT bit. We will unpause
428	 * the sequencer, if appropriate, after servicing
429	 * the request.
430	 */
431	ahc_outb(ahc, CLRINT, CLRSEQINT);
432	switch (intstat & SEQINT_MASK) {
433	case BAD_STATUS:
434	{
435		u_int  scb_index;
436		struct hardware_scb *hscb;
437
438		/*
439		 * Set the default return value to 0 (don't
440		 * send sense).  The sense code will change
441		 * this if needed.
442		 */
443		ahc_outb(ahc, RETURN_1, 0);
444
445		/*
446		 * The sequencer will notify us when a command
447		 * has an error that would be of interest to
448		 * the kernel.  This allows us to leave the sequencer
449		 * running in the common case of command completes
450		 * without error.  The sequencer will already have
451		 * dma'd the SCB back up to us, so we can reference
452		 * the in kernel copy directly.
453		 */
454		scb_index = ahc_inb(ahc, SCB_TAG);
455		scb = ahc_lookup_scb(ahc, scb_index);
456		if (scb == NULL) {
457			ahc_print_devinfo(ahc, &devinfo);
458			printf("ahc_intr - referenced scb "
459			       "not valid during seqint 0x%x scb(%d)\n",
460			       intstat, scb_index);
461			ahc_dump_card_state(ahc);
462			panic("for safety");
463			goto unpause;
464		}
465
466		hscb = scb->hscb;
467
468		/* Don't want to clobber the original sense code */
469		if ((scb->flags & SCB_SENSE) != 0) {
470			/*
471			 * Clear the SCB_SENSE Flag and have
472			 * the sequencer do a normal command
473			 * complete.
474			 */
475			scb->flags &= ~SCB_SENSE;
476			aic_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
477			break;
478		}
479		aic_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
480		/* Freeze the queue until the client sees the error. */
481		ahc_freeze_devq(ahc, scb);
482		aic_freeze_scb(scb);
483		aic_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
484		switch (hscb->shared_data.status.scsi_status) {
485		case SCSI_STATUS_OK:
486			printf("%s: Interrupted for staus of 0???\n",
487			       ahc_name(ahc));
488			break;
489		case SCSI_STATUS_CMD_TERMINATED:
490		case SCSI_STATUS_CHECK_COND:
491		{
492			struct ahc_dma_seg *sg;
493			struct scsi_sense *sc;
494			struct ahc_initiator_tinfo *targ_info;
495			struct ahc_tmode_tstate *tstate;
496			struct ahc_transinfo *tinfo;
497#ifdef AHC_DEBUG
498			if (ahc_debug & AHC_SHOW_SENSE) {
499				ahc_print_path(ahc, scb);
500				printf("SCB %d: requests Check Status\n",
501				       scb->hscb->tag);
502			}
503#endif
504
505			if (aic_perform_autosense(scb) == 0)
506				break;
507
508			targ_info = ahc_fetch_transinfo(ahc,
509							devinfo.channel,
510							devinfo.our_scsiid,
511							devinfo.target,
512							&tstate);
513			tinfo = &targ_info->curr;
514			sg = scb->sg_list;
515			sc = (struct scsi_sense *)(&hscb->shared_data.cdb);
516			/*
517			 * Save off the residual if there is one.
518			 */
519			ahc_update_residual(ahc, scb);
520#ifdef AHC_DEBUG
521			if (ahc_debug & AHC_SHOW_SENSE) {
522				ahc_print_path(ahc, scb);
523				printf("Sending Sense\n");
524			}
525#endif
526			sg->addr = ahc_get_sense_bufaddr(ahc, scb);
527			sg->len = aic_get_sense_bufsize(ahc, scb);
528			sg->len |= AHC_DMA_LAST_SEG;
529
530			/* Fixup byte order */
531			sg->addr = aic_htole32(sg->addr);
532			sg->len = aic_htole32(sg->len);
533
534			sc->opcode = REQUEST_SENSE;
535			sc->byte2 = 0;
536			if (tinfo->protocol_version <= SCSI_REV_2
537			 && SCB_GET_LUN(scb) < 8)
538				sc->byte2 = SCB_GET_LUN(scb) << 5;
539			sc->unused[0] = 0;
540			sc->unused[1] = 0;
541			sc->length = sg->len;
542			sc->control = 0;
543
544			/*
545			 * We can't allow the target to disconnect.
546			 * This will be an untagged transaction and
547			 * having the target disconnect will make this
548			 * transaction indestinguishable from outstanding
549			 * tagged transactions.
550			 */
551			hscb->control = 0;
552
553			/*
554			 * This request sense could be because the
555			 * the device lost power or in some other
556			 * way has lost our transfer negotiations.
557			 * Renegotiate if appropriate.  Unit attention
558			 * errors will be reported before any data
559			 * phases occur.
560			 */
561			if (aic_get_residual(scb)
562			 == aic_get_transfer_length(scb)) {
563				ahc_update_neg_request(ahc, &devinfo,
564						       tstate, targ_info,
565						       AHC_NEG_IF_NON_ASYNC);
566			}
567			if (tstate->auto_negotiate & devinfo.target_mask) {
568				hscb->control |= MK_MESSAGE;
569				scb->flags &= ~SCB_NEGOTIATE;
570				scb->flags |= SCB_AUTO_NEGOTIATE;
571			}
572			hscb->cdb_len = sizeof(*sc);
573			hscb->dataptr = sg->addr;
574			hscb->datacnt = sg->len;
575			hscb->sgptr = scb->sg_list_phys | SG_FULL_RESID;
576			hscb->sgptr = aic_htole32(hscb->sgptr);
577			scb->sg_count = 1;
578			scb->flags |= SCB_SENSE;
579			ahc_qinfifo_requeue_tail(ahc, scb);
580			ahc_outb(ahc, RETURN_1, SEND_SENSE);
581			/*
582			 * Ensure we have enough time to actually
583			 * retrieve the sense, but only schedule
584			 * the timer if we are not in recovery or
585			 * this is a recovery SCB that is allowed
586			 * to have an active timer.
587			 */
588			if (ahc->scb_data->recovery_scbs == 0
589			 || (scb->flags & SCB_RECOVERY_SCB) != 0)
590				aic_scb_timer_reset(scb, 5 * 1000);
591			break;
592		}
593		default:
594			break;
595		}
596		break;
597	}
598	case NO_MATCH:
599	{
600		/* Ensure we don't leave the selection hardware on */
601		ahc_outb(ahc, SCSISEQ,
602			 ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
603
604		printf("%s:%c:%d: no active SCB for reconnecting "
605		       "target - issuing BUS DEVICE RESET\n",
606		       ahc_name(ahc), devinfo.channel, devinfo.target);
607		printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
608		       "ARG_1 == 0x%x ACCUM = 0x%x\n",
609		       ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
610		       ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
611		printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
612		       "SINDEX == 0x%x\n",
613		       ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
614		       ahc_index_busy_tcl(ahc,
615			    BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
616				      ahc_inb(ahc, SAVED_LUN))),
617		       ahc_inb(ahc, SINDEX));
618		printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
619		       "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
620		       ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
621		       ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
622		       ahc_inb(ahc, SCB_CONTROL));
623		printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
624		       ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
625		printf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
626		printf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
627		ahc_dump_card_state(ahc);
628		ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
629		ahc->msgout_len = 1;
630		ahc->msgout_index = 0;
631		ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
632		ahc_outb(ahc, MSG_OUT, HOST_MSG);
633		ahc_assert_atn(ahc);
634		break;
635	}
636	case SEND_REJECT:
637	{
638		u_int rejbyte = ahc_inb(ahc, ACCUM);
639		printf("%s:%c:%d: Warning - unknown message received from "
640		       "target (0x%x).  Rejecting\n",
641		       ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
642		break;
643	}
644	case PROTO_VIOLATION:
645	{
646		ahc_handle_proto_violation(ahc);
647		break;
648	}
649	case IGN_WIDE_RES:
650		ahc_handle_ign_wide_residue(ahc, &devinfo);
651		break;
652	case PDATA_REINIT:
653		ahc_reinitialize_dataptrs(ahc);
654		break;
655	case BAD_PHASE:
656	{
657		u_int lastphase;
658
659		lastphase = ahc_inb(ahc, LASTPHASE);
660		printf("%s:%c:%d: unknown scsi bus phase %x, "
661		       "lastphase = 0x%x.  Attempting to continue\n",
662		       ahc_name(ahc), devinfo.channel, devinfo.target,
663		       lastphase, ahc_inb(ahc, SCSISIGI));
664		break;
665	}
666	case MISSED_BUSFREE:
667	{
668		u_int lastphase;
669
670		lastphase = ahc_inb(ahc, LASTPHASE);
671		printf("%s:%c:%d: Missed busfree. "
672		       "Lastphase = 0x%x, Curphase = 0x%x\n",
673		       ahc_name(ahc), devinfo.channel, devinfo.target,
674		       lastphase, ahc_inb(ahc, SCSISIGI));
675		ahc_restart(ahc);
676		return;
677	}
678	case HOST_MSG_LOOP:
679	{
680		/*
681		 * The sequencer has encountered a message phase
682		 * that requires host assistance for completion.
683		 * While handling the message phase(s), we will be
684		 * notified by the sequencer after each byte is
685		 * transfered so we can track bus phase changes.
686		 *
687		 * If this is the first time we've seen a HOST_MSG_LOOP
688		 * interrupt, initialize the state of the host message
689		 * loop.
690		 */
691		if (ahc->msg_type == MSG_TYPE_NONE) {
692			struct scb *scb;
693			u_int scb_index;
694			u_int bus_phase;
695
696			bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
697			if (bus_phase != P_MESGIN
698			 && bus_phase != P_MESGOUT) {
699				printf("ahc_intr: HOST_MSG_LOOP bad "
700				       "phase 0x%x\n",
701				      bus_phase);
702				/*
703				 * Probably transitioned to bus free before
704				 * we got here.  Just punt the message.
705				 */
706				ahc_clear_intstat(ahc);
707				ahc_restart(ahc);
708				return;
709			}
710
711			scb_index = ahc_inb(ahc, SCB_TAG);
712			scb = ahc_lookup_scb(ahc, scb_index);
713			if (devinfo.role == ROLE_INITIATOR) {
714				if (scb == NULL)
715					panic("HOST_MSG_LOOP with "
716					      "invalid SCB %x\n", scb_index);
717
718				if (bus_phase == P_MESGOUT)
719					ahc_setup_initiator_msgout(ahc,
720								   &devinfo,
721								   scb);
722				else {
723					ahc->msg_type =
724					    MSG_TYPE_INITIATOR_MSGIN;
725					ahc->msgin_index = 0;
726				}
727			}
728#ifdef AHC_TARGET_MODE
729			else {
730				if (bus_phase == P_MESGOUT) {
731					ahc->msg_type =
732					    MSG_TYPE_TARGET_MSGOUT;
733					ahc->msgin_index = 0;
734				}
735				else
736					ahc_setup_target_msgin(ahc,
737							       &devinfo,
738							       scb);
739			}
740#endif
741		}
742
743		ahc_handle_message_phase(ahc);
744		break;
745	}
746	case PERR_DETECTED:
747	{
748		/*
749		 * If we've cleared the parity error interrupt
750		 * but the sequencer still believes that SCSIPERR
751		 * is true, it must be that the parity error is
752		 * for the currently presented byte on the bus,
753		 * and we are not in a phase (data-in) where we will
754		 * eventually ack this byte.  Ack the byte and
755		 * throw it away in the hope that the target will
756		 * take us to message out to deliver the appropriate
757		 * error message.
758		 */
759		if ((intstat & SCSIINT) == 0
760		 && (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
761
762			if ((ahc->features & AHC_DT) == 0) {
763				u_int curphase;
764
765				/*
766				 * The hardware will only let you ack bytes
767				 * if the expected phase in SCSISIGO matches
768				 * the current phase.  Make sure this is
769				 * currently the case.
770				 */
771				curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
772				ahc_outb(ahc, LASTPHASE, curphase);
773				ahc_outb(ahc, SCSISIGO, curphase);
774			}
775			if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
776				int wait;
777
778				/*
779				 * In a data phase.  Faster to bitbucket
780				 * the data than to individually ack each
781				 * byte.  This is also the only strategy
782				 * that will work with AUTOACK enabled.
783				 */
784				ahc_outb(ahc, SXFRCTL1,
785					 ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
786				wait = 5000;
787				while (--wait != 0) {
788					if ((ahc_inb(ahc, SCSISIGI)
789					  & (CDI|MSGI)) != 0)
790						break;
791					aic_delay(100);
792				}
793				ahc_outb(ahc, SXFRCTL1,
794					 ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
795				if (wait == 0) {
796					struct	scb *scb;
797					u_int	scb_index;
798
799					ahc_print_devinfo(ahc, &devinfo);
800					printf("Unable to clear parity error.  "
801					       "Resetting bus.\n");
802					scb_index = ahc_inb(ahc, SCB_TAG);
803					scb = ahc_lookup_scb(ahc, scb_index);
804					if (scb != NULL)
805						aic_set_transaction_status(scb,
806						    CAM_UNCOR_PARITY);
807					ahc_reset_channel(ahc, devinfo.channel,
808							  /*init reset*/TRUE);
809				}
810			} else {
811				ahc_inb(ahc, SCSIDATL);
812			}
813		}
814		break;
815	}
816	case DATA_OVERRUN:
817	{
818		/*
819		 * When the sequencer detects an overrun, it
820		 * places the controller in "BITBUCKET" mode
821		 * and allows the target to complete its transfer.
822		 * Unfortunately, none of the counters get updated
823		 * when the controller is in this mode, so we have
824		 * no way of knowing how large the overrun was.
825		 */
826		u_int scbindex = ahc_inb(ahc, SCB_TAG);
827		u_int lastphase = ahc_inb(ahc, LASTPHASE);
828		u_int i;
829
830		scb = ahc_lookup_scb(ahc, scbindex);
831		for (i = 0; i < num_phases; i++) {
832			if (lastphase == ahc_phase_table[i].phase)
833				break;
834		}
835		ahc_print_path(ahc, scb);
836		printf("data overrun detected %s."
837		       "  Tag == 0x%x.\n",
838		       ahc_phase_table[i].phasemsg,
839  		       scb->hscb->tag);
840		ahc_print_path(ahc, scb);
841		printf("%s seen Data Phase.  Length = %ld.  NumSGs = %d.\n",
842		       ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
843		       aic_get_transfer_length(scb), scb->sg_count);
844		if (scb->sg_count > 0) {
845			for (i = 0; i < scb->sg_count; i++) {
846
847				printf("sg[%d] - Addr 0x%x%x : Length %d\n",
848				       i,
849				       (aic_le32toh(scb->sg_list[i].len) >> 24
850				        & SG_HIGH_ADDR_BITS),
851				       aic_le32toh(scb->sg_list[i].addr),
852				       aic_le32toh(scb->sg_list[i].len)
853				       & AHC_SG_LEN_MASK);
854			}
855		}
856		/*
857		 * Set this and it will take effect when the
858		 * target does a command complete.
859		 */
860		ahc_freeze_devq(ahc, scb);
861		if ((scb->flags & SCB_SENSE) == 0) {
862			aic_set_transaction_status(scb, CAM_DATA_RUN_ERR);
863		} else {
864			scb->flags &= ~SCB_SENSE;
865			aic_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
866		}
867		aic_freeze_scb(scb);
868
869		if ((ahc->features & AHC_ULTRA2) != 0) {
870			/*
871			 * Clear the channel in case we return
872			 * to data phase later.
873			 */
874			ahc_outb(ahc, SXFRCTL0,
875				 ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
876			ahc_outb(ahc, SXFRCTL0,
877				 ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
878		}
879		if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
880			u_int dscommand1;
881
882			/* Ensure HHADDR is 0 for future DMA operations. */
883			dscommand1 = ahc_inb(ahc, DSCOMMAND1);
884			ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
885			ahc_outb(ahc, HADDR, 0);
886			ahc_outb(ahc, DSCOMMAND1, dscommand1);
887		}
888		break;
889	}
890	case MKMSG_FAILED:
891	{
892		u_int scbindex;
893
894		printf("%s:%c:%d:%d: Attempt to issue message failed\n",
895		       ahc_name(ahc), devinfo.channel, devinfo.target,
896		       devinfo.lun);
897		scbindex = ahc_inb(ahc, SCB_TAG);
898		scb = ahc_lookup_scb(ahc, scbindex);
899		if (scb != NULL
900		 && (scb->flags & SCB_RECOVERY_SCB) != 0)
901			/*
902			 * Ensure that we didn't put a second instance of this
903			 * SCB into the QINFIFO.
904			 */
905			ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
906					   SCB_GET_CHANNEL(ahc, scb),
907					   SCB_GET_LUN(scb), scb->hscb->tag,
908					   ROLE_INITIATOR, /*status*/0,
909					   SEARCH_REMOVE);
910		break;
911	}
912	case NO_FREE_SCB:
913	{
914		printf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
915		ahc_dump_card_state(ahc);
916		panic("for safety");
917		break;
918	}
919	case SCB_MISMATCH:
920	{
921		u_int scbptr;
922
923		scbptr = ahc_inb(ahc, SCBPTR);
924		printf("Bogus TAG after DMA.  SCBPTR %d, tag %d, our tag %d\n",
925		       scbptr, ahc_inb(ahc, ARG_1),
926		       ahc->scb_data->hscbs[scbptr].tag);
927		ahc_dump_card_state(ahc);
928		panic("for saftey");
929		break;
930	}
931	case OUT_OF_RANGE:
932	{
933		printf("%s: BTT calculation out of range\n", ahc_name(ahc));
934		printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
935		       "ARG_1 == 0x%x ACCUM = 0x%x\n",
936		       ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
937		       ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
938		printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
939		       "SINDEX == 0x%x\n, A == 0x%x\n",
940		       ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
941		       ahc_index_busy_tcl(ahc,
942			    BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
943				      ahc_inb(ahc, SAVED_LUN))),
944		       ahc_inb(ahc, SINDEX),
945		       ahc_inb(ahc, ACCUM));
946		printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
947		       "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
948		       ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
949		       ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
950		       ahc_inb(ahc, SCB_CONTROL));
951		printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
952		       ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
953		ahc_dump_card_state(ahc);
954		panic("for safety");
955		break;
956	}
957	default:
958		printf("ahc_intr: seqint, "
959		       "intstat == 0x%x, scsisigi = 0x%x\n",
960		       intstat, ahc_inb(ahc, SCSISIGI));
961		break;
962	}
963unpause:
964	/*
965	 *  The sequencer is paused immediately on
966	 *  a SEQINT, so we should restart it when
967	 *  we're done.
968	 */
969	ahc_unpause(ahc);
970}
971
972void
973ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
974{
975	u_int	scb_index;
976	u_int	status0;
977	u_int	status;
978	struct	scb *scb;
979	char	cur_channel;
980	char	intr_channel;
981
982	if ((ahc->features & AHC_TWIN) != 0
983	 && ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
984		cur_channel = 'B';
985	else
986		cur_channel = 'A';
987	intr_channel = cur_channel;
988
989	if ((ahc->features & AHC_ULTRA2) != 0)
990		status0 = ahc_inb(ahc, SSTAT0) & IOERR;
991	else
992		status0 = 0;
993	status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
994	if (status == 0 && status0 == 0) {
995		if ((ahc->features & AHC_TWIN) != 0) {
996			/* Try the other channel */
997		 	ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
998			status = ahc_inb(ahc, SSTAT1)
999			       & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1000			intr_channel = (cur_channel == 'A') ? 'B' : 'A';
1001		}
1002		if (status == 0) {
1003			printf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
1004			ahc_outb(ahc, CLRINT, CLRSCSIINT);
1005			ahc_unpause(ahc);
1006			return;
1007		}
1008	}
1009
1010	/* Make sure the sequencer is in a safe location. */
1011	ahc_clear_critical_section(ahc);
1012
1013	scb_index = ahc_inb(ahc, SCB_TAG);
1014	scb = ahc_lookup_scb(ahc, scb_index);
1015	if (scb != NULL
1016	 && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1017		scb = NULL;
1018
1019	if ((ahc->features & AHC_ULTRA2) != 0
1020	 && (status0 & IOERR) != 0) {
1021		int now_lvd;
1022
1023		now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
1024		printf("%s: Transceiver State Has Changed to %s mode\n",
1025		       ahc_name(ahc), now_lvd ? "LVD" : "SE");
1026		ahc_outb(ahc, CLRSINT0, CLRIOERR);
1027		/*
1028		 * When transitioning to SE mode, the reset line
1029		 * glitches, triggering an arbitration bug in some
1030		 * Ultra2 controllers.  This bug is cleared when we
1031		 * assert the reset line.  Since a reset glitch has
1032		 * already occurred with this transition and a
1033		 * transceiver state change is handled just like
1034		 * a bus reset anyway, asserting the reset line
1035		 * ourselves is safe.
1036		 */
1037		ahc_reset_channel(ahc, intr_channel,
1038				 /*Initiate Reset*/now_lvd == 0);
1039	} else if ((status & SCSIRSTI) != 0) {
1040		printf("%s: Someone reset channel %c\n",
1041			ahc_name(ahc), intr_channel);
1042		if (intr_channel != cur_channel)
1043		 	ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
1044		ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
1045	} else if ((status & SCSIPERR) != 0) {
1046		/*
1047		 * Determine the bus phase and queue an appropriate message.
1048		 * SCSIPERR is latched true as soon as a parity error
1049		 * occurs.  If the sequencer acked the transfer that
1050		 * caused the parity error and the currently presented
1051		 * transfer on the bus has correct parity, SCSIPERR will
1052		 * be cleared by CLRSCSIPERR.  Use this to determine if
1053		 * we should look at the last phase the sequencer recorded,
1054		 * or the current phase presented on the bus.
1055		 */
1056		struct	ahc_devinfo devinfo;
1057		u_int	mesg_out;
1058		u_int	curphase;
1059		u_int	errorphase;
1060		u_int	lastphase;
1061		u_int	scsirate;
1062		u_int	i;
1063		u_int	sstat2;
1064		int	silent;
1065
1066		lastphase = ahc_inb(ahc, LASTPHASE);
1067		curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1068		sstat2 = ahc_inb(ahc, SSTAT2);
1069		ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
1070		/*
1071		 * For all phases save DATA, the sequencer won't
1072		 * automatically ack a byte that has a parity error
1073		 * in it.  So the only way that the current phase
1074		 * could be 'data-in' is if the parity error is for
1075		 * an already acked byte in the data phase.  During
1076		 * synchronous data-in transfers, we may actually
1077		 * ack bytes before latching the current phase in
1078		 * LASTPHASE, leading to the discrepancy between
1079		 * curphase and lastphase.
1080		 */
1081		if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
1082		 || curphase == P_DATAIN || curphase == P_DATAIN_DT)
1083			errorphase = curphase;
1084		else
1085			errorphase = lastphase;
1086
1087		for (i = 0; i < num_phases; i++) {
1088			if (errorphase == ahc_phase_table[i].phase)
1089				break;
1090		}
1091		mesg_out = ahc_phase_table[i].mesg_out;
1092		silent = FALSE;
1093		if (scb != NULL) {
1094			if (SCB_IS_SILENT(scb))
1095				silent = TRUE;
1096			else
1097				ahc_print_path(ahc, scb);
1098			scb->flags |= SCB_TRANSMISSION_ERROR;
1099		} else
1100			printf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
1101			       SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
1102		scsirate = ahc_inb(ahc, SCSIRATE);
1103		if (silent == FALSE) {
1104			printf("parity error detected %s. "
1105			       "SEQADDR(0x%x) SCSIRATE(0x%x)\n",
1106			       ahc_phase_table[i].phasemsg,
1107			       ahc_inw(ahc, SEQADDR0),
1108			       scsirate);
1109			if ((ahc->features & AHC_DT) != 0) {
1110				if ((sstat2 & CRCVALERR) != 0)
1111					printf("\tCRC Value Mismatch\n");
1112				if ((sstat2 & CRCENDERR) != 0)
1113					printf("\tNo terminal CRC packet "
1114					       "recevied\n");
1115				if ((sstat2 & CRCREQERR) != 0)
1116					printf("\tIllegal CRC packet "
1117					       "request\n");
1118				if ((sstat2 & DUAL_EDGE_ERR) != 0)
1119					printf("\tUnexpected %sDT Data Phase\n",
1120					       (scsirate & SINGLE_EDGE)
1121					     ? "" : "non-");
1122			}
1123		}
1124
1125		if ((ahc->features & AHC_DT) != 0
1126		 && (sstat2 & DUAL_EDGE_ERR) != 0) {
1127			/*
1128			 * This error applies regardless of
1129			 * data direction, so ignore the value
1130			 * in the phase table.
1131			 */
1132			mesg_out = MSG_INITIATOR_DET_ERR;
1133		}
1134
1135		/*
1136		 * We've set the hardware to assert ATN if we
1137		 * get a parity error on "in" phases, so all we
1138		 * need to do is stuff the message buffer with
1139		 * the appropriate message.  "In" phases have set
1140		 * mesg_out to something other than MSG_NOP.
1141		 */
1142		if (mesg_out != MSG_NOOP) {
1143			if (ahc->msg_type != MSG_TYPE_NONE)
1144				ahc->send_msg_perror = TRUE;
1145			else
1146				ahc_outb(ahc, MSG_OUT, mesg_out);
1147		}
1148		/*
1149		 * Force a renegotiation with this target just in
1150		 * case we are out of sync for some external reason
1151		 * unknown (or unreported) by the target.
1152		 */
1153		ahc_fetch_devinfo(ahc, &devinfo);
1154		ahc_force_renegotiation(ahc, &devinfo);
1155
1156		ahc_outb(ahc, CLRINT, CLRSCSIINT);
1157		ahc_unpause(ahc);
1158	} else if ((status & SELTO) != 0) {
1159		u_int	scbptr;
1160
1161		/* Stop the selection */
1162		ahc_outb(ahc, SCSISEQ, 0);
1163
1164		/* No more pending messages */
1165		ahc_clear_msg_state(ahc);
1166
1167		/* Clear interrupt state */
1168		ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1169		ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1170
1171		/*
1172		 * Although the driver does not care about the
1173		 * 'Selection in Progress' status bit, the busy
1174		 * LED does.  SELINGO is only cleared by a sucessfull
1175		 * selection, so we must manually clear it to insure
1176		 * the LED turns off just incase no future successful
1177		 * selections occur (e.g. no devices on the bus).
1178		 */
1179		ahc_outb(ahc, CLRSINT0, CLRSELINGO);
1180
1181		scbptr = ahc_inb(ahc, WAITING_SCBH);
1182		ahc_outb(ahc, SCBPTR, scbptr);
1183		scb_index = ahc_inb(ahc, SCB_TAG);
1184
1185		scb = ahc_lookup_scb(ahc, scb_index);
1186		if (scb == NULL) {
1187			printf("%s: ahc_intr - referenced scb not "
1188			       "valid during SELTO scb(%d, %d)\n",
1189			       ahc_name(ahc), scbptr, scb_index);
1190			ahc_dump_card_state(ahc);
1191		} else {
1192			struct ahc_devinfo devinfo;
1193#ifdef AHC_DEBUG
1194			if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
1195				ahc_print_path(ahc, scb);
1196				printf("Saw Selection Timeout for SCB 0x%x\n",
1197				       scb_index);
1198			}
1199#endif
1200			ahc_scb_devinfo(ahc, &devinfo, scb);
1201			aic_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1202			ahc_freeze_devq(ahc, scb);
1203
1204			/*
1205			 * Cancel any pending transactions on the device
1206			 * now that it seems to be missing.  This will
1207			 * also revert us to async/narrow transfers until
1208			 * we can renegotiate with the device.
1209			 */
1210			ahc_handle_devreset(ahc, &devinfo,
1211					    CAM_SEL_TIMEOUT,
1212					    "Selection Timeout",
1213					    /*verbose_level*/1);
1214		}
1215		ahc_outb(ahc, CLRINT, CLRSCSIINT);
1216		ahc_restart(ahc);
1217	} else if ((status & BUSFREE) != 0
1218		&& (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
1219		struct	ahc_devinfo devinfo;
1220		u_int	lastphase;
1221		u_int	saved_scsiid;
1222		u_int	saved_lun;
1223		u_int	target;
1224		u_int	initiator_role_id;
1225		char	channel;
1226		int	printerror;
1227
1228		/*
1229		 * Clear our selection hardware as soon as possible.
1230		 * We may have an entry in the waiting Q for this target,
1231		 * that is affected by this busfree and we don't want to
1232		 * go about selecting the target while we handle the event.
1233		 */
1234		ahc_outb(ahc, SCSISEQ,
1235			 ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
1236
1237		/*
1238		 * Disable busfree interrupts and clear the busfree
1239		 * interrupt status.  We do this here so that several
1240		 * bus transactions occur prior to clearing the SCSIINT
1241		 * latch.  It can take a bit for the clearing to take effect.
1242		 */
1243		ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1244		ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
1245
1246		/*
1247		 * Look at what phase we were last in.
1248		 * If its message out, chances are pretty good
1249		 * that the busfree was in response to one of
1250		 * our abort requests.
1251		 */
1252		lastphase = ahc_inb(ahc, LASTPHASE);
1253		saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
1254		saved_lun = ahc_inb(ahc, SAVED_LUN);
1255		target = SCSIID_TARGET(ahc, saved_scsiid);
1256		initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
1257		channel = SCSIID_CHANNEL(ahc, saved_scsiid);
1258		ahc_compile_devinfo(&devinfo, initiator_role_id,
1259				    target, saved_lun, channel, ROLE_INITIATOR);
1260		printerror = 1;
1261
1262		if (lastphase == P_MESGOUT) {
1263			u_int tag;
1264
1265			tag = SCB_LIST_NULL;
1266			if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
1267			 || ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
1268				if (ahc->msgout_buf[ahc->msgout_index - 1]
1269				 == MSG_ABORT_TAG)
1270					tag = scb->hscb->tag;
1271				ahc_print_path(ahc, scb);
1272				printf("SCB %d - Abort%s Completed.\n",
1273				       scb->hscb->tag, tag == SCB_LIST_NULL ?
1274				       "" : " Tag");
1275				ahc_abort_scbs(ahc, target, channel,
1276					       saved_lun, tag,
1277					       ROLE_INITIATOR,
1278					       CAM_REQ_ABORTED);
1279				printerror = 0;
1280			} else if (ahc_sent_msg(ahc, AHCMSG_1B,
1281						MSG_BUS_DEV_RESET, TRUE)) {
1282#ifdef __FreeBSD__
1283				/*
1284				 * Don't mark the user's request for this BDR
1285				 * as completing with CAM_BDR_SENT.  CAM3
1286				 * specifies CAM_REQ_CMP.
1287				 */
1288				if (scb != NULL
1289				 && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
1290				 && ahc_match_scb(ahc, scb, target, channel,
1291						  CAM_LUN_WILDCARD,
1292						  SCB_LIST_NULL,
1293						  ROLE_INITIATOR)) {
1294					aic_set_transaction_status(scb, CAM_REQ_CMP);
1295				}
1296#endif
1297				ahc_compile_devinfo(&devinfo,
1298						    initiator_role_id,
1299						    target,
1300						    CAM_LUN_WILDCARD,
1301						    channel,
1302						    ROLE_INITIATOR);
1303				ahc_handle_devreset(ahc, &devinfo,
1304						    CAM_BDR_SENT,
1305						    "Bus Device Reset",
1306						    /*verbose_level*/0);
1307				printerror = 0;
1308			} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1309						MSG_EXT_PPR, FALSE)) {
1310				struct ahc_initiator_tinfo *tinfo;
1311				struct ahc_tmode_tstate *tstate;
1312
1313				/*
1314				 * PPR Rejected.  Try non-ppr negotiation
1315				 * and retry command.
1316				 */
1317				tinfo = ahc_fetch_transinfo(ahc,
1318							    devinfo.channel,
1319							    devinfo.our_scsiid,
1320							    devinfo.target,
1321							    &tstate);
1322				tinfo->curr.transport_version = 2;
1323				tinfo->goal.transport_version = 2;
1324				tinfo->goal.ppr_options = 0;
1325				ahc_qinfifo_requeue_tail(ahc, scb);
1326				printerror = 0;
1327			} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1328						MSG_EXT_WDTR, FALSE)) {
1329				/*
1330				 * Negotiation Rejected.  Go-narrow and
1331				 * retry command.
1332				 */
1333				ahc_set_width(ahc, &devinfo,
1334					      MSG_EXT_WDTR_BUS_8_BIT,
1335					      AHC_TRANS_CUR|AHC_TRANS_GOAL,
1336					      /*paused*/TRUE);
1337				ahc_qinfifo_requeue_tail(ahc, scb);
1338				printerror = 0;
1339			} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1340						MSG_EXT_SDTR, FALSE)) {
1341				/*
1342				 * Negotiation Rejected.  Go-async and
1343				 * retry command.
1344				 */
1345				ahc_set_syncrate(ahc, &devinfo,
1346						/*syncrate*/NULL,
1347						/*period*/0, /*offset*/0,
1348						/*ppr_options*/0,
1349						AHC_TRANS_CUR|AHC_TRANS_GOAL,
1350						/*paused*/TRUE);
1351				ahc_qinfifo_requeue_tail(ahc, scb);
1352				printerror = 0;
1353			}
1354		}
1355		if (printerror != 0) {
1356			u_int i;
1357
1358			if (scb != NULL) {
1359				u_int tag;
1360
1361				if ((scb->hscb->control & TAG_ENB) != 0)
1362					tag = scb->hscb->tag;
1363				else
1364					tag = SCB_LIST_NULL;
1365				ahc_print_path(ahc, scb);
1366				ahc_abort_scbs(ahc, target, channel,
1367					       SCB_GET_LUN(scb), tag,
1368					       ROLE_INITIATOR,
1369					       CAM_UNEXP_BUSFREE);
1370			} else {
1371				/*
1372				 * We had not fully identified this connection,
1373				 * so we cannot abort anything.
1374				 */
1375				printf("%s: ", ahc_name(ahc));
1376			}
1377			for (i = 0; i < num_phases; i++) {
1378				if (lastphase == ahc_phase_table[i].phase)
1379					break;
1380			}
1381			if (lastphase != P_BUSFREE) {
1382				/*
1383				 * Renegotiate with this device at the
1384				 * next oportunity just in case this busfree
1385				 * is due to a negotiation mismatch with the
1386				 * device.
1387				 */
1388				ahc_force_renegotiation(ahc, &devinfo);
1389			}
1390			printf("Unexpected busfree %s\n"
1391			       "SEQADDR == 0x%x\n",
1392			       ahc_phase_table[i].phasemsg,
1393			       ahc_inb(ahc, SEQADDR0)
1394				| (ahc_inb(ahc, SEQADDR1) << 8));
1395		}
1396		ahc_outb(ahc, CLRINT, CLRSCSIINT);
1397		ahc_restart(ahc);
1398	} else {
1399		printf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
1400		       ahc_name(ahc), status);
1401		ahc_outb(ahc, CLRINT, CLRSCSIINT);
1402	}
1403}
1404
1405/*
1406 * Force renegotiation to occur the next time we initiate
1407 * a command to the current device.
1408 */
1409static void
1410ahc_force_renegotiation(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
1411{
1412	struct	ahc_initiator_tinfo *targ_info;
1413	struct	ahc_tmode_tstate *tstate;
1414
1415	targ_info = ahc_fetch_transinfo(ahc,
1416					devinfo->channel,
1417					devinfo->our_scsiid,
1418					devinfo->target,
1419					&tstate);
1420	ahc_update_neg_request(ahc, devinfo, tstate,
1421			       targ_info, AHC_NEG_IF_NON_ASYNC);
1422}
1423
1424#define AHC_MAX_STEPS 2000
1425void
1426ahc_clear_critical_section(struct ahc_softc *ahc)
1427{
1428	int	stepping;
1429	int	steps;
1430	u_int	simode0;
1431	u_int	simode1;
1432
1433	if (ahc->num_critical_sections == 0)
1434		return;
1435
1436	stepping = FALSE;
1437	steps = 0;
1438	simode0 = 0;
1439	simode1 = 0;
1440	for (;;) {
1441		struct	cs *cs;
1442		u_int	seqaddr;
1443		u_int	i;
1444
1445		seqaddr = ahc_inb(ahc, SEQADDR0)
1446			| (ahc_inb(ahc, SEQADDR1) << 8);
1447
1448		/*
1449		 * Seqaddr represents the next instruction to execute,
1450		 * so we are really executing the instruction just
1451		 * before it.
1452		 */
1453		cs = ahc->critical_sections;
1454		for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
1455
1456			if (cs->begin < seqaddr && cs->end >= seqaddr)
1457				break;
1458		}
1459
1460		if (i == ahc->num_critical_sections)
1461			break;
1462
1463		if (steps > AHC_MAX_STEPS) {
1464			printf("%s: Infinite loop in critical section\n",
1465			       ahc_name(ahc));
1466			ahc_dump_card_state(ahc);
1467			panic("critical section loop");
1468		}
1469
1470		steps++;
1471		if (stepping == FALSE) {
1472
1473			/*
1474			 * Disable all interrupt sources so that the
1475			 * sequencer will not be stuck by a pausing
1476			 * interrupt condition while we attempt to
1477			 * leave a critical section.
1478			 */
1479			simode0 = ahc_inb(ahc, SIMODE0);
1480			ahc_outb(ahc, SIMODE0, 0);
1481			simode1 = ahc_inb(ahc, SIMODE1);
1482			if ((ahc->features & AHC_DT) != 0)
1483				/*
1484				 * On DT class controllers, we
1485				 * use the enhanced busfree logic.
1486				 * Unfortunately we cannot re-enable
1487				 * busfree detection within the
1488				 * current connection, so we must
1489				 * leave it on while single stepping.
1490				 */
1491				ahc_outb(ahc, SIMODE1, simode1 & ENBUSFREE);
1492			else
1493				ahc_outb(ahc, SIMODE1, 0);
1494			ahc_outb(ahc, CLRINT, CLRSCSIINT);
1495			ahc_outb(ahc, SEQCTL, ahc->seqctl | STEP);
1496			stepping = TRUE;
1497		}
1498		if ((ahc->features & AHC_DT) != 0) {
1499			ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
1500			ahc_outb(ahc, CLRINT, CLRSCSIINT);
1501		}
1502		ahc_outb(ahc, HCNTRL, ahc->unpause);
1503		while (!ahc_is_paused(ahc))
1504			aic_delay(200);
1505	}
1506	if (stepping) {
1507		ahc_outb(ahc, SIMODE0, simode0);
1508		ahc_outb(ahc, SIMODE1, simode1);
1509		ahc_outb(ahc, SEQCTL, ahc->seqctl);
1510	}
1511}
1512
1513/*
1514 * Clear any pending interrupt status.
1515 */
1516void
1517ahc_clear_intstat(struct ahc_softc *ahc)
1518{
1519	/* Clear any interrupt conditions this may have caused */
1520	ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
1521				|CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
1522				CLRREQINIT);
1523	ahc_flush_device_writes(ahc);
1524	ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
1525 	ahc_flush_device_writes(ahc);
1526	ahc_outb(ahc, CLRINT, CLRSCSIINT);
1527	ahc_flush_device_writes(ahc);
1528}
1529
1530/**************************** Debugging Routines ******************************/
1531#ifdef AHC_DEBUG
1532uint32_t ahc_debug = AHC_DEBUG_OPTS;
1533#endif
1534
1535void
1536ahc_print_scb(struct scb *scb)
1537{
1538	int i;
1539
1540	struct hardware_scb *hscb = scb->hscb;
1541
1542	printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
1543	       (void *)scb,
1544	       hscb->control,
1545	       hscb->scsiid,
1546	       hscb->lun,
1547	       hscb->cdb_len);
1548	printf("Shared Data: ");
1549	for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
1550		printf("%#02x", hscb->shared_data.cdb[i]);
1551	printf("        dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
1552		aic_le32toh(hscb->dataptr),
1553		aic_le32toh(hscb->datacnt),
1554		aic_le32toh(hscb->sgptr),
1555		hscb->tag);
1556	if (scb->sg_count > 0) {
1557		for (i = 0; i < scb->sg_count; i++) {
1558			printf("sg[%d] - Addr 0x%x%x : Length %d\n",
1559			       i,
1560			       (aic_le32toh(scb->sg_list[i].len) >> 24
1561			        & SG_HIGH_ADDR_BITS),
1562			       aic_le32toh(scb->sg_list[i].addr),
1563			       aic_le32toh(scb->sg_list[i].len));
1564		}
1565	}
1566}
1567
1568/************************* Transfer Negotiation *******************************/
1569/*
1570 * Allocate per target mode instance (ID we respond to as a target)
1571 * transfer negotiation data structures.
1572 */
1573static struct ahc_tmode_tstate *
1574ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
1575{
1576	struct ahc_tmode_tstate *master_tstate;
1577	struct ahc_tmode_tstate *tstate;
1578	int i;
1579
1580	master_tstate = ahc->enabled_targets[ahc->our_id];
1581	if (channel == 'B') {
1582		scsi_id += 8;
1583		master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
1584	}
1585	if (ahc->enabled_targets[scsi_id] != NULL
1586	 && ahc->enabled_targets[scsi_id] != master_tstate)
1587		panic("%s: ahc_alloc_tstate - Target already allocated",
1588		      ahc_name(ahc));
1589	tstate = (struct ahc_tmode_tstate*)malloc(sizeof(*tstate),
1590						   M_DEVBUF, M_NOWAIT);
1591	if (tstate == NULL)
1592		return (NULL);
1593
1594	/*
1595	 * If we have allocated a master tstate, copy user settings from
1596	 * the master tstate (taken from SRAM or the EEPROM) for this
1597	 * channel, but reset our current and goal settings to async/narrow
1598	 * until an initiator talks to us.
1599	 */
1600	if (master_tstate != NULL) {
1601		memcpy(tstate, master_tstate, sizeof(*tstate));
1602		memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
1603		tstate->ultraenb = 0;
1604		for (i = 0; i < AHC_NUM_TARGETS; i++) {
1605			memset(&tstate->transinfo[i].curr, 0,
1606			      sizeof(tstate->transinfo[i].curr));
1607			memset(&tstate->transinfo[i].goal, 0,
1608			      sizeof(tstate->transinfo[i].goal));
1609		}
1610	} else
1611		memset(tstate, 0, sizeof(*tstate));
1612	ahc->enabled_targets[scsi_id] = tstate;
1613	return (tstate);
1614}
1615
1616#ifdef AHC_TARGET_MODE
1617/*
1618 * Free per target mode instance (ID we respond to as a target)
1619 * transfer negotiation data structures.
1620 */
1621static void
1622ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
1623{
1624	struct ahc_tmode_tstate *tstate;
1625
1626	/*
1627	 * Don't clean up our "master" tstate.
1628	 * It has our default user settings.
1629	 */
1630	if (((channel == 'B' && scsi_id == ahc->our_id_b)
1631	  || (channel == 'A' && scsi_id == ahc->our_id))
1632	 && force == FALSE)
1633		return;
1634
1635	if (channel == 'B')
1636		scsi_id += 8;
1637	tstate = ahc->enabled_targets[scsi_id];
1638	if (tstate != NULL)
1639		free(tstate, M_DEVBUF);
1640	ahc->enabled_targets[scsi_id] = NULL;
1641}
1642#endif
1643
1644/*
1645 * Called when we have an active connection to a target on the bus,
1646 * this function finds the nearest syncrate to the input period limited
1647 * by the capabilities of the bus connectivity of and sync settings for
1648 * the target.
1649 */
1650struct ahc_syncrate *
1651ahc_devlimited_syncrate(struct ahc_softc *ahc,
1652			struct ahc_initiator_tinfo *tinfo,
1653			u_int *period, u_int *ppr_options, role_t role)
1654{
1655	struct	ahc_transinfo *transinfo;
1656	u_int	maxsync;
1657
1658	if ((ahc->features & AHC_ULTRA2) != 0) {
1659		if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
1660		 && (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
1661			maxsync = AHC_SYNCRATE_DT;
1662		} else {
1663			maxsync = AHC_SYNCRATE_ULTRA;
1664			/* Can't do DT on an SE bus */
1665			*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1666		}
1667	} else if ((ahc->features & AHC_ULTRA) != 0) {
1668		maxsync = AHC_SYNCRATE_ULTRA;
1669	} else {
1670		maxsync = AHC_SYNCRATE_FAST;
1671	}
1672	/*
1673	 * Never allow a value higher than our current goal
1674	 * period otherwise we may allow a target initiated
1675	 * negotiation to go above the limit as set by the
1676	 * user.  In the case of an initiator initiated
1677	 * sync negotiation, we limit based on the user
1678	 * setting.  This allows the system to still accept
1679	 * incoming negotiations even if target initiated
1680	 * negotiation is not performed.
1681	 */
1682	if (role == ROLE_TARGET)
1683		transinfo = &tinfo->user;
1684	else
1685		transinfo = &tinfo->goal;
1686	*ppr_options &= transinfo->ppr_options;
1687	if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
1688		maxsync = MAX(maxsync, AHC_SYNCRATE_ULTRA2);
1689		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1690	}
1691	if (transinfo->period == 0) {
1692		*period = 0;
1693		*ppr_options = 0;
1694		return (NULL);
1695	}
1696	*period = MAX(*period, transinfo->period);
1697	return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
1698}
1699
1700/*
1701 * Look up the valid period to SCSIRATE conversion in our table.
1702 * Return the period and offset that should be sent to the target
1703 * if this was the beginning of an SDTR.
1704 */
1705struct ahc_syncrate *
1706ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
1707		  u_int *ppr_options, u_int maxsync)
1708{
1709	struct ahc_syncrate *syncrate;
1710
1711	if ((ahc->features & AHC_DT) == 0)
1712		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1713
1714	/* Skip all DT only entries if DT is not available */
1715	if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
1716	 && maxsync < AHC_SYNCRATE_ULTRA2)
1717		maxsync = AHC_SYNCRATE_ULTRA2;
1718
1719	for (syncrate = &ahc_syncrates[maxsync];
1720	     syncrate->rate != NULL;
1721	     syncrate++) {
1722
1723		/*
1724		 * The Ultra2 table doesn't go as low
1725		 * as for the Fast/Ultra cards.
1726		 */
1727		if ((ahc->features & AHC_ULTRA2) != 0
1728		 && (syncrate->sxfr_u2 == 0))
1729			break;
1730
1731		if (*period <= syncrate->period) {
1732			/*
1733			 * When responding to a target that requests
1734			 * sync, the requested rate may fall between
1735			 * two rates that we can output, but still be
1736			 * a rate that we can receive.  Because of this,
1737			 * we want to respond to the target with
1738			 * the same rate that it sent to us even
1739			 * if the period we use to send data to it
1740			 * is lower.  Only lower the response period
1741			 * if we must.
1742			 */
1743			if (syncrate == &ahc_syncrates[maxsync])
1744				*period = syncrate->period;
1745
1746			/*
1747			 * At some speeds, we only support
1748			 * ST transfers.
1749			 */
1750		 	if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
1751				*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1752			break;
1753		}
1754	}
1755
1756	if ((*period == 0)
1757	 || (syncrate->rate == NULL)
1758	 || ((ahc->features & AHC_ULTRA2) != 0
1759	  && (syncrate->sxfr_u2 == 0))) {
1760		/* Use asynchronous transfers. */
1761		*period = 0;
1762		syncrate = NULL;
1763		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
1764	}
1765	return (syncrate);
1766}
1767
1768/*
1769 * Convert from an entry in our syncrate table to the SCSI equivalent
1770 * sync "period" factor.
1771 */
1772u_int
1773ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
1774{
1775	struct ahc_syncrate *syncrate;
1776
1777	if ((ahc->features & AHC_ULTRA2) != 0)
1778		scsirate &= SXFR_ULTRA2;
1779	else
1780		scsirate &= SXFR;
1781
1782	syncrate = &ahc_syncrates[maxsync];
1783	while (syncrate->rate != NULL) {
1784
1785		if ((ahc->features & AHC_ULTRA2) != 0) {
1786			if (syncrate->sxfr_u2 == 0)
1787				break;
1788			else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
1789				return (syncrate->period);
1790		} else if (scsirate == (syncrate->sxfr & SXFR)) {
1791				return (syncrate->period);
1792		}
1793		syncrate++;
1794	}
1795	return (0); /* async */
1796}
1797
1798/*
1799 * Truncate the given synchronous offset to a value the
1800 * current adapter type and syncrate are capable of.
1801 */
1802void
1803ahc_validate_offset(struct ahc_softc *ahc,
1804		    struct ahc_initiator_tinfo *tinfo,
1805		    struct ahc_syncrate *syncrate,
1806		    u_int *offset, int wide, role_t role)
1807{
1808	u_int maxoffset;
1809
1810	/* Limit offset to what we can do */
1811	if (syncrate == NULL) {
1812		maxoffset = 0;
1813	} else if ((ahc->features & AHC_ULTRA2) != 0) {
1814		maxoffset = MAX_OFFSET_ULTRA2;
1815	} else {
1816		if (wide)
1817			maxoffset = MAX_OFFSET_16BIT;
1818		else
1819			maxoffset = MAX_OFFSET_8BIT;
1820	}
1821	*offset = MIN(*offset, maxoffset);
1822	if (tinfo != NULL) {
1823		if (role == ROLE_TARGET)
1824			*offset = MIN(*offset, tinfo->user.offset);
1825		else
1826			*offset = MIN(*offset, tinfo->goal.offset);
1827	}
1828}
1829
1830/*
1831 * Truncate the given transfer width parameter to a value the
1832 * current adapter type is capable of.
1833 */
1834void
1835ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
1836		   u_int *bus_width, role_t role)
1837{
1838	switch (*bus_width) {
1839	default:
1840		if (ahc->features & AHC_WIDE) {
1841			/* Respond Wide */
1842			*bus_width = MSG_EXT_WDTR_BUS_16_BIT;
1843			break;
1844		}
1845		/* FALLTHROUGH */
1846	case MSG_EXT_WDTR_BUS_8_BIT:
1847		*bus_width = MSG_EXT_WDTR_BUS_8_BIT;
1848		break;
1849	}
1850	if (tinfo != NULL) {
1851		if (role == ROLE_TARGET)
1852			*bus_width = MIN(tinfo->user.width, *bus_width);
1853		else
1854			*bus_width = MIN(tinfo->goal.width, *bus_width);
1855	}
1856}
1857
1858/*
1859 * Update the bitmask of targets for which the controller should
1860 * negotiate with at the next convenient oportunity.  This currently
1861 * means the next time we send the initial identify messages for
1862 * a new transaction.
1863 */
1864int
1865ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1866		       struct ahc_tmode_tstate *tstate,
1867		       struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
1868{
1869	u_int auto_negotiate_orig;
1870
1871	auto_negotiate_orig = tstate->auto_negotiate;
1872	if (neg_type == AHC_NEG_ALWAYS) {
1873		/*
1874		 * Force our "current" settings to be
1875		 * unknown so that unless a bus reset
1876		 * occurs the need to renegotiate is
1877		 * recorded persistently.
1878		 */
1879		if ((ahc->features & AHC_WIDE) != 0)
1880			tinfo->curr.width = AHC_WIDTH_UNKNOWN;
1881		tinfo->curr.period = AHC_PERIOD_UNKNOWN;
1882		tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
1883	}
1884	if (tinfo->curr.period != tinfo->goal.period
1885	 || tinfo->curr.width != tinfo->goal.width
1886	 || tinfo->curr.offset != tinfo->goal.offset
1887	 || tinfo->curr.ppr_options != tinfo->goal.ppr_options
1888	 || (neg_type == AHC_NEG_IF_NON_ASYNC
1889	  && (tinfo->goal.offset != 0
1890	   || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
1891	   || tinfo->goal.ppr_options != 0)))
1892		tstate->auto_negotiate |= devinfo->target_mask;
1893	else
1894		tstate->auto_negotiate &= ~devinfo->target_mask;
1895
1896	return (auto_negotiate_orig != tstate->auto_negotiate);
1897}
1898
1899/*
1900 * Update the user/goal/curr tables of synchronous negotiation
1901 * parameters as well as, in the case of a current or active update,
1902 * any data structures on the host controller.  In the case of an
1903 * active update, the specified target is currently talking to us on
1904 * the bus, so the transfer parameter update must take effect
1905 * immediately.
1906 */
1907void
1908ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
1909		 struct ahc_syncrate *syncrate, u_int period,
1910		 u_int offset, u_int ppr_options, u_int type, int paused)
1911{
1912	struct	ahc_initiator_tinfo *tinfo;
1913	struct	ahc_tmode_tstate *tstate;
1914	u_int	old_period;
1915	u_int	old_offset;
1916	u_int	old_ppr;
1917	int	active;
1918	int	update_needed;
1919
1920	active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
1921	update_needed = 0;
1922
1923	if (syncrate == NULL) {
1924		period = 0;
1925		offset = 0;
1926	}
1927
1928	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
1929				    devinfo->target, &tstate);
1930
1931	if ((type & AHC_TRANS_USER) != 0) {
1932		tinfo->user.period = period;
1933		tinfo->user.offset = offset;
1934		tinfo->user.ppr_options = ppr_options;
1935	}
1936
1937	if ((type & AHC_TRANS_GOAL) != 0) {
1938		tinfo->goal.period = period;
1939		tinfo->goal.offset = offset;
1940		tinfo->goal.ppr_options = ppr_options;
1941	}
1942
1943	old_period = tinfo->curr.period;
1944	old_offset = tinfo->curr.offset;
1945	old_ppr	   = tinfo->curr.ppr_options;
1946
1947	if ((type & AHC_TRANS_CUR) != 0
1948	 && (old_period != period
1949	  || old_offset != offset
1950	  || old_ppr != ppr_options)) {
1951		u_int	scsirate;
1952
1953		update_needed++;
1954		scsirate = tinfo->scsirate;
1955		if ((ahc->features & AHC_ULTRA2) != 0) {
1956
1957			scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
1958			if (syncrate != NULL) {
1959				scsirate |= syncrate->sxfr_u2;
1960				if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
1961					scsirate |= ENABLE_CRC;
1962				else
1963					scsirate |= SINGLE_EDGE;
1964			}
1965		} else {
1966
1967			scsirate &= ~(SXFR|SOFS);
1968			/*
1969			 * Ensure Ultra mode is set properly for
1970			 * this target.
1971			 */
1972			tstate->ultraenb &= ~devinfo->target_mask;
1973			if (syncrate != NULL) {
1974				if (syncrate->sxfr & ULTRA_SXFR) {
1975					tstate->ultraenb |=
1976						devinfo->target_mask;
1977				}
1978				scsirate |= syncrate->sxfr & SXFR;
1979				scsirate |= offset & SOFS;
1980			}
1981			if (active) {
1982				u_int sxfrctl0;
1983
1984				sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
1985				sxfrctl0 &= ~FAST20;
1986				if (tstate->ultraenb & devinfo->target_mask)
1987					sxfrctl0 |= FAST20;
1988				ahc_outb(ahc, SXFRCTL0, sxfrctl0);
1989			}
1990		}
1991		if (active) {
1992			ahc_outb(ahc, SCSIRATE, scsirate);
1993			if ((ahc->features & AHC_ULTRA2) != 0)
1994				ahc_outb(ahc, SCSIOFFSET, offset);
1995		}
1996
1997		tinfo->scsirate = scsirate;
1998		tinfo->curr.period = period;
1999		tinfo->curr.offset = offset;
2000		tinfo->curr.ppr_options = ppr_options;
2001
2002		ahc_send_async(ahc, devinfo->channel, devinfo->target,
2003			       CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
2004		if (bootverbose) {
2005			if (offset != 0) {
2006				printf("%s: target %d synchronous at %sMHz%s, "
2007				       "offset = 0x%x\n", ahc_name(ahc),
2008				       devinfo->target, syncrate->rate,
2009				       (ppr_options & MSG_EXT_PPR_DT_REQ)
2010				       ? " DT" : "", offset);
2011			} else {
2012				printf("%s: target %d using "
2013				       "asynchronous transfers\n",
2014				       ahc_name(ahc), devinfo->target);
2015			}
2016		}
2017	}
2018
2019	update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2020						tinfo, AHC_NEG_TO_GOAL);
2021
2022	if (update_needed)
2023		ahc_update_pending_scbs(ahc);
2024}
2025
2026/*
2027 * Update the user/goal/curr tables of wide negotiation
2028 * parameters as well as, in the case of a current or active update,
2029 * any data structures on the host controller.  In the case of an
2030 * active update, the specified target is currently talking to us on
2031 * the bus, so the transfer parameter update must take effect
2032 * immediately.
2033 */
2034void
2035ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2036	      u_int width, u_int type, int paused)
2037{
2038	struct	ahc_initiator_tinfo *tinfo;
2039	struct	ahc_tmode_tstate *tstate;
2040	u_int	oldwidth;
2041	int	active;
2042	int	update_needed;
2043
2044	active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
2045	update_needed = 0;
2046	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2047				    devinfo->target, &tstate);
2048
2049	if ((type & AHC_TRANS_USER) != 0)
2050		tinfo->user.width = width;
2051
2052	if ((type & AHC_TRANS_GOAL) != 0)
2053		tinfo->goal.width = width;
2054
2055	oldwidth = tinfo->curr.width;
2056	if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
2057		u_int	scsirate;
2058
2059		update_needed++;
2060		scsirate =  tinfo->scsirate;
2061		scsirate &= ~WIDEXFER;
2062		if (width == MSG_EXT_WDTR_BUS_16_BIT)
2063			scsirate |= WIDEXFER;
2064
2065		tinfo->scsirate = scsirate;
2066
2067		if (active)
2068			ahc_outb(ahc, SCSIRATE, scsirate);
2069
2070		tinfo->curr.width = width;
2071
2072		ahc_send_async(ahc, devinfo->channel, devinfo->target,
2073			       CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
2074		if (bootverbose) {
2075			printf("%s: target %d using %dbit transfers\n",
2076			       ahc_name(ahc), devinfo->target,
2077			       8 * (0x01 << width));
2078		}
2079	}
2080
2081	update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2082						tinfo, AHC_NEG_TO_GOAL);
2083	if (update_needed)
2084		ahc_update_pending_scbs(ahc);
2085}
2086
2087/*
2088 * Update the current state of tagged queuing for a given target.
2089 */
2090void
2091ahc_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2092	     ahc_queue_alg alg)
2093{
2094 	ahc_platform_set_tags(ahc, devinfo, alg);
2095 	ahc_send_async(ahc, devinfo->channel, devinfo->target,
2096 		       devinfo->lun, AC_TRANSFER_NEG, &alg);
2097}
2098
2099/*
2100 * When the transfer settings for a connection change, update any
2101 * in-transit SCBs to contain the new data so the hardware will
2102 * be set correctly during future (re)selections.
2103 */
2104static void
2105ahc_update_pending_scbs(struct ahc_softc *ahc)
2106{
2107	struct	scb *pending_scb;
2108	int	pending_scb_count;
2109	int	i;
2110	int	paused;
2111	u_int	saved_scbptr;
2112
2113	/*
2114	 * Traverse the pending SCB list and ensure that all of the
2115	 * SCBs there have the proper settings.
2116	 */
2117	pending_scb_count = 0;
2118	LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2119		struct ahc_devinfo devinfo;
2120		struct hardware_scb *pending_hscb;
2121		struct ahc_initiator_tinfo *tinfo;
2122		struct ahc_tmode_tstate *tstate;
2123
2124		ahc_scb_devinfo(ahc, &devinfo, pending_scb);
2125		tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
2126					    devinfo.our_scsiid,
2127					    devinfo.target, &tstate);
2128		pending_hscb = pending_scb->hscb;
2129		pending_hscb->control &= ~ULTRAENB;
2130		if ((tstate->ultraenb & devinfo.target_mask) != 0)
2131			pending_hscb->control |= ULTRAENB;
2132		pending_hscb->scsirate = tinfo->scsirate;
2133		pending_hscb->scsioffset = tinfo->curr.offset;
2134		if ((tstate->auto_negotiate & devinfo.target_mask) == 0
2135		 && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
2136			pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
2137			pending_hscb->control &= ~MK_MESSAGE;
2138		}
2139		ahc_sync_scb(ahc, pending_scb,
2140			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
2141		pending_scb_count++;
2142	}
2143
2144	if (pending_scb_count == 0)
2145		return;
2146
2147	if (ahc_is_paused(ahc)) {
2148		paused = 1;
2149	} else {
2150		paused = 0;
2151		ahc_pause(ahc);
2152	}
2153
2154	saved_scbptr = ahc_inb(ahc, SCBPTR);
2155	/* Ensure that the hscbs down on the card match the new information */
2156	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
2157		struct	hardware_scb *pending_hscb;
2158		u_int	control;
2159		u_int	scb_tag;
2160
2161		ahc_outb(ahc, SCBPTR, i);
2162		scb_tag = ahc_inb(ahc, SCB_TAG);
2163		pending_scb = ahc_lookup_scb(ahc, scb_tag);
2164		if (pending_scb == NULL)
2165			continue;
2166
2167		pending_hscb = pending_scb->hscb;
2168		control = ahc_inb(ahc, SCB_CONTROL);
2169		control &= ~(ULTRAENB|MK_MESSAGE);
2170		control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
2171		ahc_outb(ahc, SCB_CONTROL, control);
2172		ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
2173		ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
2174	}
2175	ahc_outb(ahc, SCBPTR, saved_scbptr);
2176
2177	if (paused == 0)
2178		ahc_unpause(ahc);
2179}
2180
2181/**************************** Pathing Information *****************************/
2182static void
2183ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2184{
2185	u_int	saved_scsiid;
2186	role_t	role;
2187	int	our_id;
2188
2189	if (ahc_inb(ahc, SSTAT0) & TARGET)
2190		role = ROLE_TARGET;
2191	else
2192		role = ROLE_INITIATOR;
2193
2194	if (role == ROLE_TARGET
2195	 && (ahc->features & AHC_MULTI_TID) != 0
2196	 && (ahc_inb(ahc, SEQ_FLAGS)
2197 	   & (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
2198		/* We were selected, so pull our id from TARGIDIN */
2199		our_id = ahc_inb(ahc, TARGIDIN) & OID;
2200	} else if ((ahc->features & AHC_ULTRA2) != 0)
2201		our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
2202	else
2203		our_id = ahc_inb(ahc, SCSIID) & OID;
2204
2205	saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
2206	ahc_compile_devinfo(devinfo,
2207			    our_id,
2208			    SCSIID_TARGET(ahc, saved_scsiid),
2209			    ahc_inb(ahc, SAVED_LUN),
2210			    SCSIID_CHANNEL(ahc, saved_scsiid),
2211			    role);
2212}
2213
2214struct ahc_phase_table_entry*
2215ahc_lookup_phase_entry(int phase)
2216{
2217	struct ahc_phase_table_entry *entry;
2218	struct ahc_phase_table_entry *last_entry;
2219
2220	/*
2221	 * num_phases doesn't include the default entry which
2222	 * will be returned if the phase doesn't match.
2223	 */
2224	last_entry = &ahc_phase_table[num_phases];
2225	for (entry = ahc_phase_table; entry < last_entry; entry++) {
2226		if (phase == entry->phase)
2227			break;
2228	}
2229	return (entry);
2230}
2231
2232void
2233ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
2234		    u_int lun, char channel, role_t role)
2235{
2236	devinfo->our_scsiid = our_id;
2237	devinfo->target = target;
2238	devinfo->lun = lun;
2239	devinfo->target_offset = target;
2240	devinfo->channel = channel;
2241	devinfo->role = role;
2242	if (channel == 'B')
2243		devinfo->target_offset += 8;
2244	devinfo->target_mask = (0x01 << devinfo->target_offset);
2245}
2246
2247void
2248ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2249{
2250	printf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
2251	       devinfo->target, devinfo->lun);
2252}
2253
2254static void
2255ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2256		struct scb *scb)
2257{
2258	role_t	role;
2259	int	our_id;
2260
2261	our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
2262	role = ROLE_INITIATOR;
2263	if ((scb->flags & SCB_TARGET_SCB) != 0)
2264		role = ROLE_TARGET;
2265	ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
2266			    SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
2267}
2268
2269
2270/************************ Message Phase Processing ****************************/
2271static void
2272ahc_assert_atn(struct ahc_softc *ahc)
2273{
2274	u_int scsisigo;
2275
2276	scsisigo = ATNO;
2277	if ((ahc->features & AHC_DT) == 0)
2278		scsisigo |= ahc_inb(ahc, SCSISIGI);
2279	ahc_outb(ahc, SCSISIGO, scsisigo);
2280}
2281
2282/*
2283 * When an initiator transaction with the MK_MESSAGE flag either reconnects
2284 * or enters the initial message out phase, we are interrupted.  Fill our
2285 * outgoing message buffer with the appropriate message and beging handing
2286 * the message phase(s) manually.
2287 */
2288static void
2289ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2290			   struct scb *scb)
2291{
2292	/*
2293	 * To facilitate adding multiple messages together,
2294	 * each routine should increment the index and len
2295	 * variables instead of setting them explicitly.
2296	 */
2297	ahc->msgout_index = 0;
2298	ahc->msgout_len = 0;
2299
2300	if ((scb->flags & SCB_DEVICE_RESET) == 0
2301	 && ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
2302		u_int identify_msg;
2303
2304		identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
2305		if ((scb->hscb->control & DISCENB) != 0)
2306			identify_msg |= MSG_IDENTIFY_DISCFLAG;
2307		ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
2308		ahc->msgout_len++;
2309
2310		if ((scb->hscb->control & TAG_ENB) != 0) {
2311			ahc->msgout_buf[ahc->msgout_index++] =
2312			    scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
2313			ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
2314			ahc->msgout_len += 2;
2315		}
2316	}
2317
2318	if (scb->flags & SCB_DEVICE_RESET) {
2319		ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
2320		ahc->msgout_len++;
2321		ahc_print_path(ahc, scb);
2322		printf("Bus Device Reset Message Sent\n");
2323		/*
2324		 * Clear our selection hardware in advance of
2325		 * the busfree.  We may have an entry in the waiting
2326		 * Q for this target, and we don't want to go about
2327		 * selecting while we handle the busfree and blow it
2328		 * away.
2329		 */
2330		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2331	} else if ((scb->flags & SCB_ABORT) != 0) {
2332		if ((scb->hscb->control & TAG_ENB) != 0)
2333			ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
2334		else
2335			ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
2336		ahc->msgout_len++;
2337		ahc_print_path(ahc, scb);
2338		printf("Abort%s Message Sent\n",
2339		       (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
2340		/*
2341		 * Clear our selection hardware in advance of
2342		 * the busfree.  We may have an entry in the waiting
2343		 * Q for this target, and we don't want to go about
2344		 * selecting while we handle the busfree and blow it
2345		 * away.
2346		 */
2347		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2348	} else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
2349		ahc_build_transfer_msg(ahc, devinfo);
2350	} else {
2351		printf("ahc_intr: AWAITING_MSG for an SCB that "
2352		       "does not have a waiting message\n");
2353		printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
2354		       devinfo->target_mask);
2355		panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
2356		      "SCB flags = %x", scb->hscb->tag, scb->hscb->control,
2357		      ahc_inb(ahc, MSG_OUT), scb->flags);
2358	}
2359
2360	/*
2361	 * Clear the MK_MESSAGE flag from the SCB so we aren't
2362	 * asked to send this message again.
2363	 */
2364	ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
2365	scb->hscb->control &= ~MK_MESSAGE;
2366	ahc->msgout_index = 0;
2367	ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2368}
2369
2370/*
2371 * Build an appropriate transfer negotiation message for the
2372 * currently active target.
2373 */
2374static void
2375ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2376{
2377	/*
2378	 * We need to initiate transfer negotiations.
2379	 * If our current and goal settings are identical,
2380	 * we want to renegotiate due to a check condition.
2381	 */
2382	struct	ahc_initiator_tinfo *tinfo;
2383	struct	ahc_tmode_tstate *tstate;
2384	struct	ahc_syncrate *rate;
2385	int	dowide;
2386	int	dosync;
2387	int	doppr;
2388	u_int	period;
2389	u_int	ppr_options;
2390	u_int	offset;
2391
2392	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2393				    devinfo->target, &tstate);
2394	/*
2395	 * Filter our period based on the current connection.
2396	 * If we can't perform DT transfers on this segment (not in LVD
2397	 * mode for instance), then our decision to issue a PPR message
2398	 * may change.
2399	 */
2400	period = tinfo->goal.period;
2401	offset = tinfo->goal.offset;
2402	ppr_options = tinfo->goal.ppr_options;
2403	/* Target initiated PPR is not allowed in the SCSI spec */
2404	if (devinfo->role == ROLE_TARGET)
2405		ppr_options = 0;
2406	rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
2407				       &ppr_options, devinfo->role);
2408	dowide = tinfo->curr.width != tinfo->goal.width;
2409	dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
2410	/*
2411	 * Only use PPR if we have options that need it, even if the device
2412	 * claims to support it.  There might be an expander in the way
2413	 * that doesn't.
2414	 */
2415	doppr = ppr_options != 0;
2416
2417	if (!dowide && !dosync && !doppr) {
2418		dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
2419		dosync = tinfo->goal.offset != 0;
2420	}
2421
2422	if (!dowide && !dosync && !doppr) {
2423		/*
2424		 * Force async with a WDTR message if we have a wide bus,
2425		 * or just issue an SDTR with a 0 offset.
2426		 */
2427		if ((ahc->features & AHC_WIDE) != 0)
2428			dowide = 1;
2429		else
2430			dosync = 1;
2431
2432		if (bootverbose) {
2433			ahc_print_devinfo(ahc, devinfo);
2434			printf("Ensuring async\n");
2435		}
2436	}
2437
2438	/* Target initiated PPR is not allowed in the SCSI spec */
2439	if (devinfo->role == ROLE_TARGET)
2440		doppr = 0;
2441
2442	/*
2443	 * Both the PPR message and SDTR message require the
2444	 * goal syncrate to be limited to what the target device
2445	 * is capable of handling (based on whether an LVD->SE
2446	 * expander is on the bus), so combine these two cases.
2447	 * Regardless, guarantee that if we are using WDTR and SDTR
2448	 * messages that WDTR comes first.
2449	 */
2450	if (doppr || (dosync && !dowide)) {
2451
2452		offset = tinfo->goal.offset;
2453		ahc_validate_offset(ahc, tinfo, rate, &offset,
2454				    doppr ? tinfo->goal.width
2455					  : tinfo->curr.width,
2456				    devinfo->role);
2457		if (doppr) {
2458			ahc_construct_ppr(ahc, devinfo, period, offset,
2459					  tinfo->goal.width, ppr_options);
2460		} else {
2461			ahc_construct_sdtr(ahc, devinfo, period, offset);
2462		}
2463	} else {
2464		ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
2465	}
2466}
2467
2468/*
2469 * Build a synchronous negotiation message in our message
2470 * buffer based on the input parameters.
2471 */
2472static void
2473ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2474		   u_int period, u_int offset)
2475{
2476	if (offset == 0)
2477		period = AHC_ASYNC_XFER_PERIOD;
2478	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2479	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR_LEN;
2480	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR;
2481	ahc->msgout_buf[ahc->msgout_index++] = period;
2482	ahc->msgout_buf[ahc->msgout_index++] = offset;
2483	ahc->msgout_len += 5;
2484	if (bootverbose) {
2485		printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
2486		       ahc_name(ahc), devinfo->channel, devinfo->target,
2487		       devinfo->lun, period, offset);
2488	}
2489}
2490
2491/*
2492 * Build a wide negotiation message in our message
2493 * buffer based on the input parameters.
2494 */
2495static void
2496ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2497		   u_int bus_width)
2498{
2499	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2500	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR_LEN;
2501	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR;
2502	ahc->msgout_buf[ahc->msgout_index++] = bus_width;
2503	ahc->msgout_len += 4;
2504	if (bootverbose) {
2505		printf("(%s:%c:%d:%d): Sending WDTR %x\n",
2506		       ahc_name(ahc), devinfo->channel, devinfo->target,
2507		       devinfo->lun, bus_width);
2508	}
2509}
2510
2511/*
2512 * Build a parallel protocol request message in our message
2513 * buffer based on the input parameters.
2514 */
2515static void
2516ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2517		  u_int period, u_int offset, u_int bus_width,
2518		  u_int ppr_options)
2519{
2520	if (offset == 0)
2521		period = AHC_ASYNC_XFER_PERIOD;
2522	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
2523	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR_LEN;
2524	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR;
2525	ahc->msgout_buf[ahc->msgout_index++] = period;
2526	ahc->msgout_buf[ahc->msgout_index++] = 0;
2527	ahc->msgout_buf[ahc->msgout_index++] = offset;
2528	ahc->msgout_buf[ahc->msgout_index++] = bus_width;
2529	ahc->msgout_buf[ahc->msgout_index++] = ppr_options;
2530	ahc->msgout_len += 8;
2531	if (bootverbose) {
2532		printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
2533		       "offset %x, ppr_options %x\n", ahc_name(ahc),
2534		       devinfo->channel, devinfo->target, devinfo->lun,
2535		       bus_width, period, offset, ppr_options);
2536	}
2537}
2538
2539/*
2540 * Clear any active message state.
2541 */
2542static void
2543ahc_clear_msg_state(struct ahc_softc *ahc)
2544{
2545	ahc->msgout_len = 0;
2546	ahc->msgin_index = 0;
2547	ahc->msg_type = MSG_TYPE_NONE;
2548	if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
2549		/*
2550		 * The target didn't care to respond to our
2551		 * message request, so clear ATN.
2552		 */
2553		ahc_outb(ahc, CLRSINT1, CLRATNO);
2554	}
2555	ahc_outb(ahc, MSG_OUT, MSG_NOOP);
2556	ahc_outb(ahc, SEQ_FLAGS2,
2557		 ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
2558}
2559
2560static void
2561ahc_handle_proto_violation(struct ahc_softc *ahc)
2562{
2563	struct	ahc_devinfo devinfo;
2564	struct	scb *scb;
2565	u_int	scbid;
2566	u_int	seq_flags;
2567	u_int	curphase;
2568	u_int	lastphase;
2569	int	found;
2570
2571	ahc_fetch_devinfo(ahc, &devinfo);
2572	scbid = ahc_inb(ahc, SCB_TAG);
2573	scb = ahc_lookup_scb(ahc, scbid);
2574	seq_flags = ahc_inb(ahc, SEQ_FLAGS);
2575	curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2576	lastphase = ahc_inb(ahc, LASTPHASE);
2577	if ((seq_flags & NOT_IDENTIFIED) != 0) {
2578
2579		/*
2580		 * The reconnecting target either did not send an
2581		 * identify message, or did, but we didn't find an SCB
2582		 * to match.
2583		 */
2584		ahc_print_devinfo(ahc, &devinfo);
2585		printf("Target did not send an IDENTIFY message. "
2586		       "LASTPHASE = 0x%x.\n", lastphase);
2587		scb = NULL;
2588	} else if (scb == NULL) {
2589		/*
2590		 * We don't seem to have an SCB active for this
2591		 * transaction.  Print an error and reset the bus.
2592		 */
2593		ahc_print_devinfo(ahc, &devinfo);
2594		printf("No SCB found during protocol violation\n");
2595		goto proto_violation_reset;
2596	} else {
2597		aic_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2598		if ((seq_flags & NO_CDB_SENT) != 0) {
2599			ahc_print_path(ahc, scb);
2600			printf("No or incomplete CDB sent to device.\n");
2601		} else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
2602			/*
2603			 * The target never bothered to provide status to
2604			 * us prior to completing the command.  Since we don't
2605			 * know the disposition of this command, we must attempt
2606			 * to abort it.  Assert ATN and prepare to send an abort
2607			 * message.
2608			 */
2609			ahc_print_path(ahc, scb);
2610			printf("Completed command without status.\n");
2611		} else {
2612			ahc_print_path(ahc, scb);
2613			printf("Unknown protocol violation.\n");
2614			ahc_dump_card_state(ahc);
2615		}
2616	}
2617	if ((lastphase & ~P_DATAIN_DT) == 0
2618	 || lastphase == P_COMMAND) {
2619proto_violation_reset:
2620		/*
2621		 * Target either went directly to data/command
2622		 * phase or didn't respond to our ATN.
2623		 * The only safe thing to do is to blow
2624		 * it away with a bus reset.
2625		 */
2626		found = ahc_reset_channel(ahc, 'A', TRUE);
2627		printf("%s: Issued Channel %c Bus Reset. "
2628		       "%d SCBs aborted\n", ahc_name(ahc), 'A', found);
2629	} else {
2630		/*
2631		 * Leave the selection hardware off in case
2632		 * this abort attempt will affect yet to
2633		 * be sent commands.
2634		 */
2635		ahc_outb(ahc, SCSISEQ,
2636			 ahc_inb(ahc, SCSISEQ) & ~ENSELO);
2637		ahc_assert_atn(ahc);
2638		ahc_outb(ahc, MSG_OUT, HOST_MSG);
2639		if (scb == NULL) {
2640			ahc_print_devinfo(ahc, &devinfo);
2641			ahc->msgout_buf[0] = MSG_ABORT_TASK;
2642			ahc->msgout_len = 1;
2643			ahc->msgout_index = 0;
2644			ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2645		} else {
2646			ahc_print_path(ahc, scb);
2647			scb->flags |= SCB_ABORT;
2648		}
2649		printf("Protocol violation %s.  Attempting to abort.\n",
2650		       ahc_lookup_phase_entry(curphase)->phasemsg);
2651	}
2652}
2653
2654/*
2655 * Manual message loop handler.
2656 */
2657static void
2658ahc_handle_message_phase(struct ahc_softc *ahc)
2659{
2660	struct	ahc_devinfo devinfo;
2661	u_int	bus_phase;
2662	int	end_session;
2663
2664	ahc_fetch_devinfo(ahc, &devinfo);
2665	end_session = FALSE;
2666	bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
2667
2668reswitch:
2669	switch (ahc->msg_type) {
2670	case MSG_TYPE_INITIATOR_MSGOUT:
2671	{
2672		int lastbyte;
2673		int phasemis;
2674		int msgdone;
2675
2676		if (ahc->msgout_len == 0)
2677			panic("HOST_MSG_LOOP interrupt with no active message");
2678
2679#ifdef AHC_DEBUG
2680		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2681			ahc_print_devinfo(ahc, &devinfo);
2682			printf("INITIATOR_MSG_OUT");
2683		}
2684#endif
2685		phasemis = bus_phase != P_MESGOUT;
2686		if (phasemis) {
2687#ifdef AHC_DEBUG
2688			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2689				printf(" PHASEMIS %s\n",
2690				       ahc_lookup_phase_entry(bus_phase)
2691							     ->phasemsg);
2692			}
2693#endif
2694			if (bus_phase == P_MESGIN) {
2695				/*
2696				 * Change gears and see if
2697				 * this messages is of interest to
2698				 * us or should be passed back to
2699				 * the sequencer.
2700				 */
2701				ahc_outb(ahc, CLRSINT1, CLRATNO);
2702				ahc->send_msg_perror = FALSE;
2703				ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
2704				ahc->msgin_index = 0;
2705				goto reswitch;
2706			}
2707			end_session = TRUE;
2708			break;
2709		}
2710
2711		if (ahc->send_msg_perror) {
2712			ahc_outb(ahc, CLRSINT1, CLRATNO);
2713			ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2714#ifdef AHC_DEBUG
2715			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2716				printf(" byte 0x%x\n", ahc->send_msg_perror);
2717#endif
2718			ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
2719			break;
2720		}
2721
2722		msgdone	= ahc->msgout_index == ahc->msgout_len;
2723		if (msgdone) {
2724			/*
2725			 * The target has requested a retry.
2726			 * Re-assert ATN, reset our message index to
2727			 * 0, and try again.
2728			 */
2729			ahc->msgout_index = 0;
2730			ahc_assert_atn(ahc);
2731		}
2732
2733		lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
2734		if (lastbyte) {
2735			/* Last byte is signified by dropping ATN */
2736			ahc_outb(ahc, CLRSINT1, CLRATNO);
2737		}
2738
2739		/*
2740		 * Clear our interrupt status and present
2741		 * the next byte on the bus.
2742		 */
2743		ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2744#ifdef AHC_DEBUG
2745		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2746			printf(" byte 0x%x\n",
2747			       ahc->msgout_buf[ahc->msgout_index]);
2748#endif
2749		ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2750		break;
2751	}
2752	case MSG_TYPE_INITIATOR_MSGIN:
2753	{
2754		int phasemis;
2755		int message_done;
2756
2757#ifdef AHC_DEBUG
2758		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2759			ahc_print_devinfo(ahc, &devinfo);
2760			printf("INITIATOR_MSG_IN");
2761		}
2762#endif
2763		phasemis = bus_phase != P_MESGIN;
2764		if (phasemis) {
2765#ifdef AHC_DEBUG
2766			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2767				printf(" PHASEMIS %s\n",
2768				       ahc_lookup_phase_entry(bus_phase)
2769							     ->phasemsg);
2770			}
2771#endif
2772			ahc->msgin_index = 0;
2773			if (bus_phase == P_MESGOUT
2774			 && (ahc->send_msg_perror == TRUE
2775			  || (ahc->msgout_len != 0
2776			   && ahc->msgout_index == 0))) {
2777				ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2778				goto reswitch;
2779			}
2780			end_session = TRUE;
2781			break;
2782		}
2783
2784		/* Pull the byte in without acking it */
2785		ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIBUSL);
2786#ifdef AHC_DEBUG
2787		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2788			printf(" byte 0x%x\n",
2789			       ahc->msgin_buf[ahc->msgin_index]);
2790#endif
2791
2792		message_done = ahc_parse_msg(ahc, &devinfo);
2793
2794		if (message_done) {
2795			/*
2796			 * Clear our incoming message buffer in case there
2797			 * is another message following this one.
2798			 */
2799			ahc->msgin_index = 0;
2800
2801			/*
2802			 * If this message illicited a response,
2803			 * assert ATN so the target takes us to the
2804			 * message out phase.
2805			 */
2806			if (ahc->msgout_len != 0) {
2807#ifdef AHC_DEBUG
2808				if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2809					ahc_print_devinfo(ahc, &devinfo);
2810					printf("Asserting ATN for response\n");
2811				}
2812#endif
2813				ahc_assert_atn(ahc);
2814			}
2815		} else
2816			ahc->msgin_index++;
2817
2818		if (message_done == MSGLOOP_TERMINATED) {
2819			end_session = TRUE;
2820		} else {
2821			/* Ack the byte */
2822			ahc_outb(ahc, CLRSINT1, CLRREQINIT);
2823			ahc_inb(ahc, SCSIDATL);
2824		}
2825		break;
2826	}
2827	case MSG_TYPE_TARGET_MSGIN:
2828	{
2829		int msgdone;
2830
2831		if (ahc->msgout_len == 0)
2832			panic("Target MSGIN with no active message");
2833
2834#ifdef AHC_DEBUG
2835		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2836			ahc_print_devinfo(ahc, &devinfo);
2837			printf("TARGET_MSG_IN");
2838		}
2839#endif
2840
2841		/*
2842		 * If we interrupted a mesgout session, the initiator
2843		 * will not know this until our first REQ.  So, we
2844		 * only honor mesgout requests after we've sent our
2845		 * first byte.
2846		 */
2847		if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0
2848		 && ahc->msgout_index > 0) {
2849
2850			/*
2851			 * Change gears and see if this messages is
2852			 * of interest to us or should be passed back
2853			 * to the sequencer.
2854			 */
2855#ifdef AHC_DEBUG
2856			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2857				printf(" Honoring ATN Request.\n");
2858#endif
2859			ahc->msg_type = MSG_TYPE_TARGET_MSGOUT;
2860
2861			/*
2862			 * Disable SCSI Programmed I/O during the
2863			 * phase change so as to avoid phantom REQs.
2864			 */
2865			ahc_outb(ahc, SXFRCTL0,
2866				 ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2867
2868			/*
2869			 * Since SPIORDY asserts when ACK is asserted
2870			 * for P_MSGOUT, and SPIORDY's assertion triggered
2871			 * our entry into this routine, wait for ACK to
2872			 * *de-assert* before changing phases.
2873			 */
2874			while ((ahc_inb(ahc, SCSISIGI) & ACKI) != 0)
2875				;
2876
2877			ahc_outb(ahc, SCSISIGO, P_MESGOUT | BSYO);
2878
2879			/*
2880			 * All phase line changes require a bus
2881			 * settle delay before REQ is asserted.
2882			 * [SCSI SPI4 10.7.1]
2883			 */
2884			ahc_flush_device_writes(ahc);
2885			aic_delay(AHC_BUSSETTLE_DELAY);
2886
2887			ahc->msgin_index = 0;
2888			/* Enable SCSI Programmed I/O to REQ for first byte */
2889			ahc_outb(ahc, SXFRCTL0,
2890				 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2891			break;
2892		}
2893
2894		msgdone = ahc->msgout_index == ahc->msgout_len;
2895		if (msgdone) {
2896			ahc_outb(ahc, SXFRCTL0,
2897				 ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2898			end_session = TRUE;
2899			break;
2900		}
2901
2902		/*
2903		 * Present the next byte on the bus.
2904		 */
2905#ifdef AHC_DEBUG
2906		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2907			printf(" byte 0x%x\n",
2908			       ahc->msgout_buf[ahc->msgout_index]);
2909#endif
2910		ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2911		ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
2912		break;
2913	}
2914	case MSG_TYPE_TARGET_MSGOUT:
2915	{
2916		int lastbyte;
2917		int msgdone;
2918
2919#ifdef AHC_DEBUG
2920		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2921			ahc_print_devinfo(ahc, &devinfo);
2922			printf("TARGET_MSG_OUT");
2923		}
2924#endif
2925		/*
2926		 * The initiator signals that this is
2927		 * the last byte by dropping ATN.
2928		 */
2929		lastbyte = (ahc_inb(ahc, SCSISIGI) & ATNI) == 0;
2930
2931		/*
2932		 * Read the latched byte, but turn off SPIOEN first
2933		 * so that we don't inadvertently cause a REQ for the
2934		 * next byte.
2935		 */
2936		ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
2937		ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIDATL);
2938
2939#ifdef AHC_DEBUG
2940		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
2941			printf(" byte 0x%x\n",
2942			       ahc->msgin_buf[ahc->msgin_index]);
2943#endif
2944
2945		msgdone = ahc_parse_msg(ahc, &devinfo);
2946		if (msgdone == MSGLOOP_TERMINATED) {
2947			/*
2948			 * The message is *really* done in that it caused
2949			 * us to go to bus free.  The sequencer has already
2950			 * been reset at this point, so pull the ejection
2951			 * handle.
2952			 */
2953			return;
2954		}
2955
2956		ahc->msgin_index++;
2957
2958		/*
2959		 * XXX Read spec about initiator dropping ATN too soon
2960		 *     and use msgdone to detect it.
2961		 */
2962		if (msgdone == MSGLOOP_MSGCOMPLETE) {
2963			ahc->msgin_index = 0;
2964
2965			/*
2966			 * If this message illicited a response, transition
2967			 * to the Message in phase and send it.
2968			 */
2969			if (ahc->msgout_len != 0) {
2970#ifdef AHC_DEBUG
2971				if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
2972					ahc_print_devinfo(ahc, &devinfo);
2973					printf(" preparing response.\n");
2974				}
2975#endif
2976				ahc_outb(ahc, SCSISIGO, P_MESGIN | BSYO);
2977
2978				/*
2979				 * All phase line changes require a bus
2980				 * settle delay before REQ is asserted.
2981				 * [SCSI SPI4 10.7.1]  When transitioning
2982				 * from an OUT to an IN phase, we must
2983				 * also wait a data release delay to allow
2984				 * the initiator time to release the data
2985				 * lines. [SCSI SPI4 10.12]
2986				 */
2987				ahc_flush_device_writes(ahc);
2988				aic_delay(AHC_BUSSETTLE_DELAY
2989					+ AHC_DATARELEASE_DELAY);
2990
2991				/*
2992				 * Enable SCSI Programmed I/O.  This will
2993				 * immediately cause SPIORDY to assert,
2994				 * and the sequencer will call our message
2995				 * loop again.
2996				 */
2997				ahc_outb(ahc, SXFRCTL0,
2998					 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
2999				ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
3000				ahc->msgin_index = 0;
3001				break;
3002			}
3003		}
3004
3005		if (lastbyte)
3006			end_session = TRUE;
3007		else {
3008			/* Ask for the next byte. */
3009			ahc_outb(ahc, SXFRCTL0,
3010				 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
3011		}
3012
3013		break;
3014	}
3015	default:
3016		panic("Unknown REQINIT message type");
3017	}
3018
3019	if (end_session) {
3020		ahc_clear_msg_state(ahc);
3021		ahc_outb(ahc, RETURN_1, EXIT_MSG_LOOP);
3022	} else
3023		ahc_outb(ahc, RETURN_1, CONT_MSG_LOOP);
3024}
3025
3026/*
3027 * See if we sent a particular extended message to the target.
3028 * If "full" is true, return true only if the target saw the full
3029 * message.  If "full" is false, return true if the target saw at
3030 * least the first byte of the message.
3031 */
3032static int
3033ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type, u_int msgval, int full)
3034{
3035	int found;
3036	u_int index;
3037
3038	found = FALSE;
3039	index = 0;
3040
3041	while (index < ahc->msgout_len) {
3042		if (ahc->msgout_buf[index] == MSG_EXTENDED) {
3043			u_int end_index;
3044
3045			end_index = index + 1 + ahc->msgout_buf[index + 1];
3046			if (ahc->msgout_buf[index+2] == msgval
3047			 && type == AHCMSG_EXT) {
3048
3049				if (full) {
3050					if (ahc->msgout_index > end_index)
3051						found = TRUE;
3052				} else if (ahc->msgout_index > index)
3053					found = TRUE;
3054			}
3055			index = end_index;
3056		} else if (ahc->msgout_buf[index] >= MSG_SIMPLE_TASK
3057			&& ahc->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
3058
3059			/* Skip tag type and tag id or residue param*/
3060			index += 2;
3061		} else {
3062			/* Single byte message */
3063			if (type == AHCMSG_1B
3064			 && ahc->msgout_buf[index] == msgval
3065			 && ahc->msgout_index > index)
3066				found = TRUE;
3067			index++;
3068		}
3069
3070		if (found)
3071			break;
3072	}
3073	return (found);
3074}
3075
3076/*
3077 * Wait for a complete incoming message, parse it, and respond accordingly.
3078 */
3079static int
3080ahc_parse_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3081{
3082	struct	ahc_initiator_tinfo *tinfo;
3083	struct	ahc_tmode_tstate *tstate;
3084	int	reject;
3085	int	done;
3086	int	response;
3087	u_int	targ_scsirate;
3088
3089	done = MSGLOOP_IN_PROG;
3090	response = FALSE;
3091	reject = FALSE;
3092	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
3093				    devinfo->target, &tstate);
3094	targ_scsirate = tinfo->scsirate;
3095
3096	/*
3097	 * Parse as much of the message as is available,
3098	 * rejecting it if we don't support it.  When
3099	 * the entire message is available and has been
3100	 * handled, return MSGLOOP_MSGCOMPLETE, indicating
3101	 * that we have parsed an entire message.
3102	 *
3103	 * In the case of extended messages, we accept the length
3104	 * byte outright and perform more checking once we know the
3105	 * extended message type.
3106	 */
3107	switch (ahc->msgin_buf[0]) {
3108	case MSG_DISCONNECT:
3109	case MSG_SAVEDATAPOINTER:
3110	case MSG_CMDCOMPLETE:
3111	case MSG_RESTOREPOINTERS:
3112	case MSG_IGN_WIDE_RESIDUE:
3113		/*
3114		 * End our message loop as these are messages
3115		 * the sequencer handles on its own.
3116		 */
3117		done = MSGLOOP_TERMINATED;
3118		break;
3119	case MSG_MESSAGE_REJECT:
3120		response = ahc_handle_msg_reject(ahc, devinfo);
3121		/* FALLTHROUGH */
3122	case MSG_NOOP:
3123		done = MSGLOOP_MSGCOMPLETE;
3124		break;
3125	case MSG_EXTENDED:
3126	{
3127		/* Wait for enough of the message to begin validation */
3128		if (ahc->msgin_index < 2)
3129			break;
3130		switch (ahc->msgin_buf[2]) {
3131		case MSG_EXT_SDTR:
3132		{
3133			struct	 ahc_syncrate *syncrate;
3134			u_int	 period;
3135			u_int	 ppr_options;
3136			u_int	 offset;
3137			u_int	 saved_offset;
3138
3139			if (ahc->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
3140				reject = TRUE;
3141				break;
3142			}
3143
3144			/*
3145			 * Wait until we have both args before validating
3146			 * and acting on this message.
3147			 *
3148			 * Add one to MSG_EXT_SDTR_LEN to account for
3149			 * the extended message preamble.
3150			 */
3151			if (ahc->msgin_index < (MSG_EXT_SDTR_LEN + 1))
3152				break;
3153
3154			period = ahc->msgin_buf[3];
3155			ppr_options = 0;
3156			saved_offset = offset = ahc->msgin_buf[4];
3157			syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3158							   &ppr_options,
3159							   devinfo->role);
3160			ahc_validate_offset(ahc, tinfo, syncrate, &offset,
3161					    targ_scsirate & WIDEXFER,
3162					    devinfo->role);
3163			if (bootverbose) {
3164				printf("(%s:%c:%d:%d): Received "
3165				       "SDTR period %x, offset %x\n\t"
3166				       "Filtered to period %x, offset %x\n",
3167				       ahc_name(ahc), devinfo->channel,
3168				       devinfo->target, devinfo->lun,
3169				       ahc->msgin_buf[3], saved_offset,
3170				       period, offset);
3171			}
3172			ahc_set_syncrate(ahc, devinfo,
3173					 syncrate, period,
3174					 offset, ppr_options,
3175					 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3176					 /*paused*/TRUE);
3177
3178			/*
3179			 * See if we initiated Sync Negotiation
3180			 * and didn't have to fall down to async
3181			 * transfers.
3182			 */
3183			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, TRUE)) {
3184				/* We started it */
3185				if (saved_offset != offset) {
3186					/* Went too low - force async */
3187					reject = TRUE;
3188				}
3189			} else {
3190				/*
3191				 * Send our own SDTR in reply
3192				 */
3193				if (bootverbose
3194				 && devinfo->role == ROLE_INITIATOR) {
3195					printf("(%s:%c:%d:%d): Target "
3196					       "Initiated SDTR\n",
3197					       ahc_name(ahc), devinfo->channel,
3198					       devinfo->target, devinfo->lun);
3199				}
3200				ahc->msgout_index = 0;
3201				ahc->msgout_len = 0;
3202				ahc_construct_sdtr(ahc, devinfo,
3203						   period, offset);
3204				ahc->msgout_index = 0;
3205				response = TRUE;
3206			}
3207			done = MSGLOOP_MSGCOMPLETE;
3208			break;
3209		}
3210		case MSG_EXT_WDTR:
3211		{
3212			u_int bus_width;
3213			u_int saved_width;
3214			u_int sending_reply;
3215
3216			sending_reply = FALSE;
3217			if (ahc->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
3218				reject = TRUE;
3219				break;
3220			}
3221
3222			/*
3223			 * Wait until we have our arg before validating
3224			 * and acting on this message.
3225			 *
3226			 * Add one to MSG_EXT_WDTR_LEN to account for
3227			 * the extended message preamble.
3228			 */
3229			if (ahc->msgin_index < (MSG_EXT_WDTR_LEN + 1))
3230				break;
3231
3232			bus_width = ahc->msgin_buf[3];
3233			saved_width = bus_width;
3234			ahc_validate_width(ahc, tinfo, &bus_width,
3235					   devinfo->role);
3236			if (bootverbose) {
3237				printf("(%s:%c:%d:%d): Received WDTR "
3238				       "%x filtered to %x\n",
3239				       ahc_name(ahc), devinfo->channel,
3240				       devinfo->target, devinfo->lun,
3241				       saved_width, bus_width);
3242			}
3243
3244			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, TRUE)) {
3245				/*
3246				 * Don't send a WDTR back to the
3247				 * target, since we asked first.
3248				 * If the width went higher than our
3249				 * request, reject it.
3250				 */
3251				if (saved_width > bus_width) {
3252					reject = TRUE;
3253					printf("(%s:%c:%d:%d): requested %dBit "
3254					       "transfers.  Rejecting...\n",
3255					       ahc_name(ahc), devinfo->channel,
3256					       devinfo->target, devinfo->lun,
3257					       8 * (0x01 << bus_width));
3258					bus_width = 0;
3259				}
3260			} else {
3261				/*
3262				 * Send our own WDTR in reply
3263				 */
3264				if (bootverbose
3265				 && devinfo->role == ROLE_INITIATOR) {
3266					printf("(%s:%c:%d:%d): Target "
3267					       "Initiated WDTR\n",
3268					       ahc_name(ahc), devinfo->channel,
3269					       devinfo->target, devinfo->lun);
3270				}
3271				ahc->msgout_index = 0;
3272				ahc->msgout_len = 0;
3273				ahc_construct_wdtr(ahc, devinfo, bus_width);
3274				ahc->msgout_index = 0;
3275				response = TRUE;
3276				sending_reply = TRUE;
3277			}
3278			/*
3279			 * After a wide message, we are async, but
3280			 * some devices don't seem to honor this portion
3281			 * of the spec.  Force a renegotiation of the
3282			 * sync component of our transfer agreement even
3283			 * if our goal is async.  By updating our width
3284			 * after forcing the negotiation, we avoid
3285			 * renegotiating for width.
3286			 */
3287			ahc_update_neg_request(ahc, devinfo, tstate,
3288					       tinfo, AHC_NEG_ALWAYS);
3289			ahc_set_width(ahc, devinfo, bus_width,
3290				      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3291				      /*paused*/TRUE);
3292			if (sending_reply == FALSE && reject == FALSE) {
3293
3294				/*
3295				 * We will always have an SDTR to send.
3296				 */
3297				ahc->msgout_index = 0;
3298				ahc->msgout_len = 0;
3299				ahc_build_transfer_msg(ahc, devinfo);
3300				ahc->msgout_index = 0;
3301				response = TRUE;
3302			}
3303			done = MSGLOOP_MSGCOMPLETE;
3304			break;
3305		}
3306		case MSG_EXT_PPR:
3307		{
3308			struct	ahc_syncrate *syncrate;
3309			u_int	period;
3310			u_int	offset;
3311			u_int	bus_width;
3312			u_int	ppr_options;
3313			u_int	saved_width;
3314			u_int	saved_offset;
3315			u_int	saved_ppr_options;
3316
3317			if (ahc->msgin_buf[1] != MSG_EXT_PPR_LEN) {
3318				reject = TRUE;
3319				break;
3320			}
3321
3322			/*
3323			 * Wait until we have all args before validating
3324			 * and acting on this message.
3325			 *
3326			 * Add one to MSG_EXT_PPR_LEN to account for
3327			 * the extended message preamble.
3328			 */
3329			if (ahc->msgin_index < (MSG_EXT_PPR_LEN + 1))
3330				break;
3331
3332			period = ahc->msgin_buf[3];
3333			offset = ahc->msgin_buf[5];
3334			bus_width = ahc->msgin_buf[6];
3335			saved_width = bus_width;
3336			ppr_options = ahc->msgin_buf[7];
3337			/*
3338			 * According to the spec, a DT only
3339			 * period factor with no DT option
3340			 * set implies async.
3341			 */
3342			if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
3343			 && period == 9)
3344				offset = 0;
3345			saved_ppr_options = ppr_options;
3346			saved_offset = offset;
3347
3348			/*
3349			 * Mask out any options we don't support
3350			 * on any controller.  Transfer options are
3351			 * only available if we are negotiating wide.
3352			 */
3353			ppr_options &= MSG_EXT_PPR_DT_REQ;
3354			if (bus_width == 0)
3355				ppr_options = 0;
3356
3357			ahc_validate_width(ahc, tinfo, &bus_width,
3358					   devinfo->role);
3359			syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
3360							   &ppr_options,
3361							   devinfo->role);
3362			ahc_validate_offset(ahc, tinfo, syncrate,
3363					    &offset, bus_width,
3364					    devinfo->role);
3365
3366			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, TRUE)) {
3367				/*
3368				 * If we are unable to do any of the
3369				 * requested options (we went too low),
3370				 * then we'll have to reject the message.
3371				 */
3372				if (saved_width > bus_width
3373				 || saved_offset != offset
3374				 || saved_ppr_options != ppr_options) {
3375					reject = TRUE;
3376					period = 0;
3377					offset = 0;
3378					bus_width = 0;
3379					ppr_options = 0;
3380					syncrate = NULL;
3381				}
3382			} else {
3383				if (devinfo->role != ROLE_TARGET)
3384					printf("(%s:%c:%d:%d): Target "
3385					       "Initiated PPR\n",
3386					       ahc_name(ahc), devinfo->channel,
3387					       devinfo->target, devinfo->lun);
3388				else
3389					printf("(%s:%c:%d:%d): Initiator "
3390					       "Initiated PPR\n",
3391					       ahc_name(ahc), devinfo->channel,
3392					       devinfo->target, devinfo->lun);
3393				ahc->msgout_index = 0;
3394				ahc->msgout_len = 0;
3395				ahc_construct_ppr(ahc, devinfo, period, offset,
3396						  bus_width, ppr_options);
3397				ahc->msgout_index = 0;
3398				response = TRUE;
3399			}
3400			if (bootverbose) {
3401				printf("(%s:%c:%d:%d): Received PPR width %x, "
3402				       "period %x, offset %x,options %x\n"
3403				       "\tFiltered to width %x, period %x, "
3404				       "offset %x, options %x\n",
3405				       ahc_name(ahc), devinfo->channel,
3406				       devinfo->target, devinfo->lun,
3407				       saved_width, ahc->msgin_buf[3],
3408				       saved_offset, saved_ppr_options,
3409				       bus_width, period, offset, ppr_options);
3410			}
3411			ahc_set_width(ahc, devinfo, bus_width,
3412				      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3413				      /*paused*/TRUE);
3414			ahc_set_syncrate(ahc, devinfo,
3415					 syncrate, period,
3416					 offset, ppr_options,
3417					 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3418					 /*paused*/TRUE);
3419			done = MSGLOOP_MSGCOMPLETE;
3420			break;
3421		}
3422		default:
3423			/* Unknown extended message.  Reject it. */
3424			reject = TRUE;
3425			break;
3426		}
3427		break;
3428	}
3429#ifdef AHC_TARGET_MODE
3430	case MSG_BUS_DEV_RESET:
3431		ahc_handle_devreset(ahc, devinfo,
3432				    CAM_BDR_SENT,
3433				    "Bus Device Reset Received",
3434				    /*verbose_level*/0);
3435		ahc_restart(ahc);
3436		done = MSGLOOP_TERMINATED;
3437		break;
3438	case MSG_ABORT_TAG:
3439	case MSG_ABORT:
3440	case MSG_CLEAR_QUEUE:
3441	{
3442		int tag;
3443
3444		/* Target mode messages */
3445		if (devinfo->role != ROLE_TARGET) {
3446			reject = TRUE;
3447			break;
3448		}
3449		tag = SCB_LIST_NULL;
3450		if (ahc->msgin_buf[0] == MSG_ABORT_TAG)
3451			tag = ahc_inb(ahc, INITIATOR_TAG);
3452		ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
3453			       devinfo->lun, tag, ROLE_TARGET,
3454			       CAM_REQ_ABORTED);
3455
3456		tstate = ahc->enabled_targets[devinfo->our_scsiid];
3457		if (tstate != NULL) {
3458			struct ahc_tmode_lstate* lstate;
3459
3460			lstate = tstate->enabled_luns[devinfo->lun];
3461			if (lstate != NULL) {
3462				ahc_queue_lstate_event(ahc, lstate,
3463						       devinfo->our_scsiid,
3464						       ahc->msgin_buf[0],
3465						       /*arg*/tag);
3466				ahc_send_lstate_events(ahc, lstate);
3467			}
3468		}
3469		ahc_restart(ahc);
3470		done = MSGLOOP_TERMINATED;
3471		break;
3472	}
3473#endif
3474	case MSG_TERM_IO_PROC:
3475	default:
3476		reject = TRUE;
3477		break;
3478	}
3479
3480	if (reject) {
3481		/*
3482		 * Setup to reject the message.
3483		 */
3484		ahc->msgout_index = 0;
3485		ahc->msgout_len = 1;
3486		ahc->msgout_buf[0] = MSG_MESSAGE_REJECT;
3487		done = MSGLOOP_MSGCOMPLETE;
3488		response = TRUE;
3489	}
3490
3491	if (done != MSGLOOP_IN_PROG && !response)
3492		/* Clear the outgoing message buffer */
3493		ahc->msgout_len = 0;
3494
3495	return (done);
3496}
3497
3498/*
3499 * Process a message reject message.
3500 */
3501static int
3502ahc_handle_msg_reject(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3503{
3504	/*
3505	 * What we care about here is if we had an
3506	 * outstanding SDTR or WDTR message for this
3507	 * target.  If we did, this is a signal that
3508	 * the target is refusing negotiation.
3509	 */
3510	struct scb *scb;
3511	struct ahc_initiator_tinfo *tinfo;
3512	struct ahc_tmode_tstate *tstate;
3513	u_int scb_index;
3514	u_int last_msg;
3515	int   response = 0;
3516
3517	scb_index = ahc_inb(ahc, SCB_TAG);
3518	scb = ahc_lookup_scb(ahc, scb_index);
3519	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
3520				    devinfo->our_scsiid,
3521				    devinfo->target, &tstate);
3522	/* Might be necessary */
3523	last_msg = ahc_inb(ahc, LAST_MSG);
3524
3525	if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
3526		/*
3527		 * Target does not support the PPR message.
3528		 * Attempt to negotiate SPI-2 style.
3529		 */
3530		if (bootverbose) {
3531			printf("(%s:%c:%d:%d): PPR Rejected. "
3532			       "Trying WDTR/SDTR\n",
3533			       ahc_name(ahc), devinfo->channel,
3534			       devinfo->target, devinfo->lun);
3535		}
3536		tinfo->goal.ppr_options = 0;
3537		tinfo->curr.transport_version = 2;
3538		tinfo->goal.transport_version = 2;
3539		ahc->msgout_index = 0;
3540		ahc->msgout_len = 0;
3541		ahc_build_transfer_msg(ahc, devinfo);
3542		ahc->msgout_index = 0;
3543		response = 1;
3544	} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
3545
3546		/* note 8bit xfers */
3547		printf("(%s:%c:%d:%d): refuses WIDE negotiation.  Using "
3548		       "8bit transfers\n", ahc_name(ahc),
3549		       devinfo->channel, devinfo->target, devinfo->lun);
3550		ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
3551			      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3552			      /*paused*/TRUE);
3553		/*
3554		 * No need to clear the sync rate.  If the target
3555		 * did not accept the command, our syncrate is
3556		 * unaffected.  If the target started the negotiation,
3557		 * but rejected our response, we already cleared the
3558		 * sync rate before sending our WDTR.
3559		 */
3560		if (tinfo->goal.offset != tinfo->curr.offset) {
3561
3562			/* Start the sync negotiation */
3563			ahc->msgout_index = 0;
3564			ahc->msgout_len = 0;
3565			ahc_build_transfer_msg(ahc, devinfo);
3566			ahc->msgout_index = 0;
3567			response = 1;
3568		}
3569	} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
3570		/* note asynch xfers and clear flag */
3571		ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL, /*period*/0,
3572				 /*offset*/0, /*ppr_options*/0,
3573				 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
3574				 /*paused*/TRUE);
3575		printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
3576		       "Using asynchronous transfers\n",
3577		       ahc_name(ahc), devinfo->channel,
3578		       devinfo->target, devinfo->lun);
3579	} else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
3580		int tag_type;
3581		int mask;
3582
3583		tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
3584
3585		if (tag_type == MSG_SIMPLE_TASK) {
3586			printf("(%s:%c:%d:%d): refuses tagged commands.  "
3587			       "Performing non-tagged I/O\n", ahc_name(ahc),
3588			       devinfo->channel, devinfo->target, devinfo->lun);
3589			ahc_set_tags(ahc, devinfo, AHC_QUEUE_NONE);
3590			mask = ~0x23;
3591		} else {
3592			printf("(%s:%c:%d:%d): refuses %s tagged commands.  "
3593			       "Performing simple queue tagged I/O only\n",
3594			       ahc_name(ahc), devinfo->channel, devinfo->target,
3595			       devinfo->lun, tag_type == MSG_ORDERED_TASK
3596			       ? "ordered" : "head of queue");
3597			ahc_set_tags(ahc, devinfo, AHC_QUEUE_BASIC);
3598			mask = ~0x03;
3599		}
3600
3601		/*
3602		 * Resend the identify for this CCB as the target
3603		 * may believe that the selection is invalid otherwise.
3604		 */
3605		ahc_outb(ahc, SCB_CONTROL,
3606			 ahc_inb(ahc, SCB_CONTROL) & mask);
3607	 	scb->hscb->control &= mask;
3608		aic_set_transaction_tag(scb, /*enabled*/FALSE,
3609					/*type*/MSG_SIMPLE_TASK);
3610		ahc_outb(ahc, MSG_OUT, MSG_IDENTIFYFLAG);
3611		ahc_assert_atn(ahc);
3612
3613		/*
3614		 * This transaction is now at the head of
3615		 * the untagged queue for this target.
3616		 */
3617		if ((ahc->flags & AHC_SCB_BTT) == 0) {
3618			struct scb_tailq *untagged_q;
3619
3620			untagged_q =
3621			    &(ahc->untagged_queues[devinfo->target_offset]);
3622			TAILQ_INSERT_HEAD(untagged_q, scb, links.tqe);
3623			scb->flags |= SCB_UNTAGGEDQ;
3624		}
3625		ahc_busy_tcl(ahc, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
3626			     scb->hscb->tag);
3627
3628		/*
3629		 * Requeue all tagged commands for this target
3630		 * currently in our posession so they can be
3631		 * converted to untagged commands.
3632		 */
3633		ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
3634				   SCB_GET_CHANNEL(ahc, scb),
3635				   SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
3636				   ROLE_INITIATOR, CAM_REQUEUE_REQ,
3637				   SEARCH_COMPLETE);
3638	} else {
3639		/*
3640		 * Otherwise, we ignore it.
3641		 */
3642		printf("%s:%c:%d: Message reject for %x -- ignored\n",
3643		       ahc_name(ahc), devinfo->channel, devinfo->target,
3644		       last_msg);
3645	}
3646	return (response);
3647}
3648
3649/*
3650 * Process an ingnore wide residue message.
3651 */
3652static void
3653ahc_handle_ign_wide_residue(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
3654{
3655	u_int scb_index;
3656	struct scb *scb;
3657
3658	scb_index = ahc_inb(ahc, SCB_TAG);
3659	scb = ahc_lookup_scb(ahc, scb_index);
3660	/*
3661	 * XXX Actually check data direction in the sequencer?
3662	 * Perhaps add datadir to some spare bits in the hscb?
3663	 */
3664	if ((ahc_inb(ahc, SEQ_FLAGS) & DPHASE) == 0
3665	 || aic_get_transfer_dir(scb) != CAM_DIR_IN) {
3666		/*
3667		 * Ignore the message if we haven't
3668		 * seen an appropriate data phase yet.
3669		 */
3670	} else {
3671		/*
3672		 * If the residual occurred on the last
3673		 * transfer and the transfer request was
3674		 * expected to end on an odd count, do
3675		 * nothing.  Otherwise, subtract a byte
3676		 * and update the residual count accordingly.
3677		 */
3678		uint32_t sgptr;
3679
3680		sgptr = ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
3681		if ((sgptr & SG_LIST_NULL) != 0
3682		 && (ahc_inb(ahc, SCB_LUN) & SCB_XFERLEN_ODD) != 0) {
3683			/*
3684			 * If the residual occurred on the last
3685			 * transfer and the transfer request was
3686			 * expected to end on an odd count, do
3687			 * nothing.
3688			 */
3689		} else {
3690			struct ahc_dma_seg *sg;
3691			uint32_t data_cnt;
3692			uint32_t data_addr;
3693			uint32_t sglen;
3694
3695			/* Pull in all of the sgptr */
3696			sgptr = ahc_inl(ahc, SCB_RESIDUAL_SGPTR);
3697			data_cnt = ahc_inl(ahc, SCB_RESIDUAL_DATACNT);
3698
3699			if ((sgptr & SG_LIST_NULL) != 0) {
3700				/*
3701				 * The residual data count is not updated
3702				 * for the command run to completion case.
3703				 * Explicitly zero the count.
3704				 */
3705				data_cnt &= ~AHC_SG_LEN_MASK;
3706			}
3707
3708			data_addr = ahc_inl(ahc, SHADDR);
3709
3710			data_cnt += 1;
3711			data_addr -= 1;
3712			sgptr &= SG_PTR_MASK;
3713
3714			sg = ahc_sg_bus_to_virt(scb, sgptr);
3715
3716			/*
3717			 * The residual sg ptr points to the next S/G
3718			 * to load so we must go back one.
3719			 */
3720			sg--;
3721			sglen = aic_le32toh(sg->len) & AHC_SG_LEN_MASK;
3722			if (sg != scb->sg_list
3723			 && sglen < (data_cnt & AHC_SG_LEN_MASK)) {
3724
3725				sg--;
3726				sglen = aic_le32toh(sg->len);
3727				/*
3728				 * Preserve High Address and SG_LIST bits
3729				 * while setting the count to 1.
3730				 */
3731				data_cnt = 1 | (sglen & (~AHC_SG_LEN_MASK));
3732				data_addr = aic_le32toh(sg->addr)
3733					  + (sglen & AHC_SG_LEN_MASK) - 1;
3734
3735				/*
3736				 * Increment sg so it points to the
3737				 * "next" sg.
3738				 */
3739				sg++;
3740				sgptr = ahc_sg_virt_to_bus(scb, sg);
3741			}
3742			ahc_outl(ahc, SCB_RESIDUAL_SGPTR, sgptr);
3743			ahc_outl(ahc, SCB_RESIDUAL_DATACNT, data_cnt);
3744			/*
3745			 * Toggle the "oddness" of the transfer length
3746			 * to handle this mid-transfer ignore wide
3747			 * residue.  This ensures that the oddness is
3748			 * correct for subsequent data transfers.
3749			 */
3750			ahc_outb(ahc, SCB_LUN,
3751				 ahc_inb(ahc, SCB_LUN) ^ SCB_XFERLEN_ODD);
3752		}
3753	}
3754}
3755
3756
3757/*
3758 * Reinitialize the data pointers for the active transfer
3759 * based on its current residual.
3760 */
3761static void
3762ahc_reinitialize_dataptrs(struct ahc_softc *ahc)
3763{
3764	struct	 scb *scb;
3765	struct	 ahc_dma_seg *sg;
3766	u_int	 scb_index;
3767	uint32_t sgptr;
3768	uint32_t resid;
3769	uint32_t dataptr;
3770
3771	scb_index = ahc_inb(ahc, SCB_TAG);
3772	scb = ahc_lookup_scb(ahc, scb_index);
3773	sgptr = (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 3) << 24)
3774	      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 2) << 16)
3775	      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 1) << 8)
3776	      |	ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
3777
3778	sgptr &= SG_PTR_MASK;
3779	sg = ahc_sg_bus_to_virt(scb, sgptr);
3780
3781	/* The residual sg_ptr always points to the next sg */
3782	sg--;
3783
3784	resid = (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 2) << 16)
3785	      | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 1) << 8)
3786	      | ahc_inb(ahc, SCB_RESIDUAL_DATACNT);
3787
3788	dataptr = aic_le32toh(sg->addr)
3789		+ (aic_le32toh(sg->len) & AHC_SG_LEN_MASK)
3790		- resid;
3791	if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
3792		u_int dscommand1;
3793
3794		dscommand1 = ahc_inb(ahc, DSCOMMAND1);
3795		ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
3796		ahc_outb(ahc, HADDR,
3797			 (aic_le32toh(sg->len) >> 24) & SG_HIGH_ADDR_BITS);
3798		ahc_outb(ahc, DSCOMMAND1, dscommand1);
3799	}
3800	ahc_outb(ahc, HADDR + 3, dataptr >> 24);
3801	ahc_outb(ahc, HADDR + 2, dataptr >> 16);
3802	ahc_outb(ahc, HADDR + 1, dataptr >> 8);
3803	ahc_outb(ahc, HADDR, dataptr);
3804	ahc_outb(ahc, HCNT + 2, resid >> 16);
3805	ahc_outb(ahc, HCNT + 1, resid >> 8);
3806	ahc_outb(ahc, HCNT, resid);
3807	if ((ahc->features & AHC_ULTRA2) == 0) {
3808		ahc_outb(ahc, STCNT + 2, resid >> 16);
3809		ahc_outb(ahc, STCNT + 1, resid >> 8);
3810		ahc_outb(ahc, STCNT, resid);
3811	}
3812}
3813
3814/*
3815 * Handle the effects of issuing a bus device reset message.
3816 */
3817static void
3818ahc_handle_devreset(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3819		    cam_status status, char *message, int verbose_level)
3820{
3821#ifdef AHC_TARGET_MODE
3822	struct ahc_tmode_tstate* tstate;
3823	u_int lun;
3824#endif
3825	int found;
3826
3827	found = ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
3828			       CAM_LUN_WILDCARD, SCB_LIST_NULL, devinfo->role,
3829			       status);
3830
3831#ifdef AHC_TARGET_MODE
3832	/*
3833	 * Send an immediate notify ccb to all target mord peripheral
3834	 * drivers affected by this action.
3835	 */
3836	tstate = ahc->enabled_targets[devinfo->our_scsiid];
3837	if (tstate != NULL) {
3838		for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
3839			struct ahc_tmode_lstate* lstate;
3840
3841			lstate = tstate->enabled_luns[lun];
3842			if (lstate == NULL)
3843				continue;
3844
3845			ahc_queue_lstate_event(ahc, lstate, devinfo->our_scsiid,
3846					       MSG_BUS_DEV_RESET, /*arg*/0);
3847			ahc_send_lstate_events(ahc, lstate);
3848		}
3849	}
3850#endif
3851
3852	/*
3853	 * Go back to async/narrow transfers and renegotiate.
3854	 */
3855	ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
3856		      AHC_TRANS_CUR, /*paused*/TRUE);
3857	ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL,
3858			 /*period*/0, /*offset*/0, /*ppr_options*/0,
3859			 AHC_TRANS_CUR, /*paused*/TRUE);
3860
3861	if (status != CAM_SEL_TIMEOUT)
3862		ahc_send_async(ahc, devinfo->channel, devinfo->target,
3863			       CAM_LUN_WILDCARD, AC_SENT_BDR, NULL);
3864
3865	if (message != NULL
3866	 && (verbose_level <= bootverbose))
3867		printf("%s: %s on %c:%d. %d SCBs aborted\n", ahc_name(ahc),
3868		       message, devinfo->channel, devinfo->target, found);
3869}
3870
3871#ifdef AHC_TARGET_MODE
3872static void
3873ahc_setup_target_msgin(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3874		       struct scb *scb)
3875{
3876
3877	/*
3878	 * To facilitate adding multiple messages together,
3879	 * each routine should increment the index and len
3880	 * variables instead of setting them explicitly.
3881	 */
3882	ahc->msgout_index = 0;
3883	ahc->msgout_len = 0;
3884
3885	if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
3886		ahc_build_transfer_msg(ahc, devinfo);
3887	else
3888		panic("ahc_intr: AWAITING target message with no message");
3889
3890	ahc->msgout_index = 0;
3891	ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
3892}
3893#endif
3894/**************************** Initialization **********************************/
3895/*
3896 * Allocate a controller structure for a new device
3897 * and perform initial initializion.
3898 */
3899struct ahc_softc *
3900ahc_alloc(void *platform_arg, char *name)
3901{
3902	struct  ahc_softc *ahc;
3903	int	i;
3904
3905#ifndef	__FreeBSD__
3906	ahc = malloc(sizeof(*ahc), M_DEVBUF, M_NOWAIT);
3907	if (!ahc) {
3908		printf("aic7xxx: cannot malloc softc!\n");
3909		free(name, M_DEVBUF);
3910		return NULL;
3911	}
3912#else
3913	ahc = device_get_softc((device_t)platform_arg);
3914#endif
3915	memset(ahc, 0, sizeof(*ahc));
3916	ahc->seep_config = malloc(sizeof(*ahc->seep_config),
3917				  M_DEVBUF, M_NOWAIT);
3918	if (ahc->seep_config == NULL) {
3919#ifndef	__FreeBSD__
3920		free(ahc, M_DEVBUF);
3921#endif
3922		free(name, M_DEVBUF);
3923		return (NULL);
3924	}
3925	LIST_INIT(&ahc->pending_scbs);
3926	LIST_INIT(&ahc->timedout_scbs);
3927	/* We don't know our unit number until the OSM sets it */
3928	ahc->name = name;
3929	ahc->unit = -1;
3930	ahc->description = NULL;
3931	ahc->channel = 'A';
3932	ahc->channel_b = 'B';
3933	ahc->chip = AHC_NONE;
3934	ahc->features = AHC_FENONE;
3935	ahc->bugs = AHC_BUGNONE;
3936	ahc->flags = AHC_FNONE;
3937	/*
3938	 * Default to all error reporting enabled with the
3939	 * sequencer operating at its fastest speed.
3940	 * The bus attach code may modify this.
3941	 */
3942	ahc->seqctl = FASTMODE;
3943
3944	for (i = 0; i < AHC_NUM_TARGETS; i++)
3945		TAILQ_INIT(&ahc->untagged_queues[i]);
3946	if (ahc_platform_alloc(ahc, platform_arg) != 0) {
3947		ahc_free(ahc);
3948		ahc = NULL;
3949	}
3950	ahc_lockinit(ahc);
3951	return (ahc);
3952}
3953
3954int
3955ahc_softc_init(struct ahc_softc *ahc)
3956{
3957
3958	/* The IRQMS bit is only valid on VL and EISA chips */
3959	if ((ahc->chip & AHC_PCI) == 0)
3960		ahc->unpause = ahc_inb(ahc, HCNTRL) & IRQMS;
3961	else
3962		ahc->unpause = 0;
3963	ahc->pause = ahc->unpause | PAUSE;
3964	/* XXX The shared scb data stuff should be deprecated */
3965	if (ahc->scb_data == NULL) {
3966		ahc->scb_data = malloc(sizeof(*ahc->scb_data),
3967				       M_DEVBUF, M_NOWAIT);
3968		if (ahc->scb_data == NULL)
3969			return (ENOMEM);
3970		memset(ahc->scb_data, 0, sizeof(*ahc->scb_data));
3971	}
3972
3973	return (0);
3974}
3975
3976void
3977ahc_softc_insert(struct ahc_softc *ahc)
3978{
3979	struct ahc_softc *list_ahc;
3980
3981#if AIC_PCI_CONFIG > 0
3982	/*
3983	 * Second Function PCI devices need to inherit some
3984	 * settings from function 0.
3985	 */
3986	if ((ahc->chip & AHC_BUS_MASK) == AHC_PCI
3987	 && (ahc->features & AHC_MULTI_FUNC) != 0) {
3988		TAILQ_FOREACH(list_ahc, &ahc_tailq, links) {
3989			aic_dev_softc_t list_pci;
3990			aic_dev_softc_t pci;
3991
3992			list_pci = list_ahc->dev_softc;
3993			pci = ahc->dev_softc;
3994			if (aic_get_pci_slot(list_pci) == aic_get_pci_slot(pci)
3995			 && aic_get_pci_bus(list_pci) == aic_get_pci_bus(pci)) {
3996				struct ahc_softc *master;
3997				struct ahc_softc *slave;
3998
3999				if (aic_get_pci_function(list_pci) == 0) {
4000					master = list_ahc;
4001					slave = ahc;
4002				} else {
4003					master = ahc;
4004					slave = list_ahc;
4005				}
4006				slave->flags &= ~AHC_BIOS_ENABLED;
4007				slave->flags |=
4008				    master->flags & AHC_BIOS_ENABLED;
4009				slave->flags &= ~AHC_PRIMARY_CHANNEL;
4010				slave->flags |=
4011				    master->flags & AHC_PRIMARY_CHANNEL;
4012				break;
4013			}
4014		}
4015	}
4016#endif
4017
4018	/*
4019	 * Insertion sort into our list of softcs.
4020	 */
4021	list_ahc = TAILQ_FIRST(&ahc_tailq);
4022	while (list_ahc != NULL
4023	    && ahc_softc_comp(ahc, list_ahc) <= 0)
4024		list_ahc = TAILQ_NEXT(list_ahc, links);
4025	if (list_ahc != NULL)
4026		TAILQ_INSERT_BEFORE(list_ahc, ahc, links);
4027	else
4028		TAILQ_INSERT_TAIL(&ahc_tailq, ahc, links);
4029	ahc->init_level++;
4030}
4031
4032void
4033ahc_set_unit(struct ahc_softc *ahc, int unit)
4034{
4035	ahc->unit = unit;
4036}
4037
4038void
4039ahc_set_name(struct ahc_softc *ahc, char *name)
4040{
4041	if (ahc->name != NULL)
4042		free(ahc->name, M_DEVBUF);
4043	ahc->name = name;
4044}
4045
4046void
4047ahc_free(struct ahc_softc *ahc)
4048{
4049	int i;
4050
4051	ahc_terminate_recovery_thread(ahc);
4052	switch (ahc->init_level) {
4053	default:
4054	case 5:
4055		ahc_shutdown(ahc);
4056		/* FALLTHROUGH */
4057	case 4:
4058		aic_dmamap_unload(ahc, ahc->shared_data_dmat,
4059				  ahc->shared_data_dmamap);
4060		/* FALLTHROUGH */
4061	case 3:
4062		aic_dmamem_free(ahc, ahc->shared_data_dmat, ahc->qoutfifo,
4063				ahc->shared_data_dmamap);
4064		aic_dmamap_destroy(ahc, ahc->shared_data_dmat,
4065				   ahc->shared_data_dmamap);
4066		/* FALLTHROUGH */
4067	case 2:
4068		aic_dma_tag_destroy(ahc, ahc->shared_data_dmat);
4069	case 1:
4070#ifndef __linux__
4071		aic_dma_tag_destroy(ahc, ahc->buffer_dmat);
4072#endif
4073		break;
4074	case 0:
4075		break;
4076	}
4077
4078#ifndef __linux__
4079	aic_dma_tag_destroy(ahc, ahc->parent_dmat);
4080#endif
4081	ahc_platform_free(ahc);
4082	ahc_fini_scbdata(ahc);
4083	for (i = 0; i < AHC_NUM_TARGETS; i++) {
4084		struct ahc_tmode_tstate *tstate;
4085
4086		tstate = ahc->enabled_targets[i];
4087		if (tstate != NULL) {
4088#ifdef AHC_TARGET_MODE
4089			int j;
4090
4091			for (j = 0; j < AHC_NUM_LUNS; j++) {
4092				struct ahc_tmode_lstate *lstate;
4093
4094				lstate = tstate->enabled_luns[j];
4095				if (lstate != NULL) {
4096					xpt_free_path(lstate->path);
4097					free(lstate, M_DEVBUF);
4098				}
4099			}
4100#endif
4101			free(tstate, M_DEVBUF);
4102		}
4103	}
4104#ifdef AHC_TARGET_MODE
4105	if (ahc->black_hole != NULL) {
4106		xpt_free_path(ahc->black_hole->path);
4107		free(ahc->black_hole, M_DEVBUF);
4108	}
4109#endif
4110	if (ahc->name != NULL)
4111		free(ahc->name, M_DEVBUF);
4112	if (ahc->seep_config != NULL)
4113		free(ahc->seep_config, M_DEVBUF);
4114#ifndef __FreeBSD__
4115	free(ahc, M_DEVBUF);
4116#endif
4117	return;
4118}
4119
4120void
4121ahc_shutdown(void *arg)
4122{
4123	struct	ahc_softc *ahc;
4124	int	i;
4125
4126	ahc = (struct ahc_softc *)arg;
4127
4128	/* This will reset most registers to 0, but not all */
4129	ahc_reset(ahc, /*reinit*/FALSE);
4130	ahc_outb(ahc, SCSISEQ, 0);
4131	ahc_outb(ahc, SXFRCTL0, 0);
4132	ahc_outb(ahc, DSPCISTATUS, 0);
4133
4134	for (i = TARG_SCSIRATE; i < SCSICONF; i++)
4135		ahc_outb(ahc, i, 0);
4136}
4137
4138/*
4139 * Reset the controller and record some information about it
4140 * that is only available just after a reset.  If "reinit" is
4141 * non-zero, this reset occured after initial configuration
4142 * and the caller requests that the chip be fully reinitialized
4143 * to a runable state.  Chip interrupts are *not* enabled after
4144 * a reinitialization.  The caller must enable interrupts via
4145 * ahc_intr_enable().
4146 */
4147int
4148ahc_reset(struct ahc_softc *ahc, int reinit)
4149{
4150	u_int	sblkctl;
4151	u_int	sxfrctl1_a, sxfrctl1_b;
4152	int	error;
4153	int	wait;
4154
4155	/*
4156	 * Preserve the value of the SXFRCTL1 register for all channels.
4157	 * It contains settings that affect termination and we don't want
4158	 * to disturb the integrity of the bus.
4159	 */
4160	ahc_pause(ahc);
4161	sxfrctl1_b = 0;
4162	if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7770) {
4163		u_int sblkctl;
4164
4165		/*
4166		 * Save channel B's settings in case this chip
4167		 * is setup for TWIN channel operation.
4168		 */
4169		sblkctl = ahc_inb(ahc, SBLKCTL);
4170		ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4171		sxfrctl1_b = ahc_inb(ahc, SXFRCTL1);
4172		ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4173	}
4174	sxfrctl1_a = ahc_inb(ahc, SXFRCTL1);
4175
4176	ahc_outb(ahc, HCNTRL, CHIPRST | ahc->pause);
4177
4178	/*
4179	 * Ensure that the reset has finished.  We delay 1000us
4180	 * prior to reading the register to make sure the chip
4181	 * has sufficiently completed its reset to handle register
4182	 * accesses.
4183	 */
4184	wait = 1000;
4185	do {
4186		aic_delay(1000);
4187	} while (--wait && !(ahc_inb(ahc, HCNTRL) & CHIPRSTACK));
4188
4189	if (wait == 0) {
4190		printf("%s: WARNING - Failed chip reset!  "
4191		       "Trying to initialize anyway.\n", ahc_name(ahc));
4192	}
4193	ahc_outb(ahc, HCNTRL, ahc->pause);
4194
4195	/* Determine channel configuration */
4196	sblkctl = ahc_inb(ahc, SBLKCTL) & (SELBUSB|SELWIDE);
4197	/* No Twin Channel PCI cards */
4198	if ((ahc->chip & AHC_PCI) != 0)
4199		sblkctl &= ~SELBUSB;
4200	switch (sblkctl) {
4201	case 0:
4202		/* Single Narrow Channel */
4203		break;
4204	case 2:
4205		/* Wide Channel */
4206		ahc->features |= AHC_WIDE;
4207		break;
4208	case 8:
4209		/* Twin Channel */
4210		ahc->features |= AHC_TWIN;
4211		break;
4212	default:
4213		printf(" Unsupported adapter type.  Ignoring\n");
4214		return(-1);
4215	}
4216
4217	/*
4218	 * Reload sxfrctl1.
4219	 *
4220	 * We must always initialize STPWEN to 1 before we
4221	 * restore the saved values.  STPWEN is initialized
4222	 * to a tri-state condition which can only be cleared
4223	 * by turning it on.
4224	 */
4225	if ((ahc->features & AHC_TWIN) != 0) {
4226		u_int sblkctl;
4227
4228		sblkctl = ahc_inb(ahc, SBLKCTL);
4229		ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4230		ahc_outb(ahc, SXFRCTL1, sxfrctl1_b);
4231		ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4232	}
4233	ahc_outb(ahc, SXFRCTL1, sxfrctl1_a);
4234
4235	error = 0;
4236	if (reinit != 0)
4237		/*
4238		 * If a recovery action has forced a chip reset,
4239		 * re-initialize the chip to our liking.
4240		 */
4241		error = ahc->bus_chip_init(ahc);
4242#ifdef AHC_DUMP_SEQ
4243	else
4244		ahc_dumpseq(ahc);
4245#endif
4246
4247	return (error);
4248}
4249
4250/*
4251 * Determine the number of SCBs available on the controller
4252 */
4253int
4254ahc_probe_scbs(struct ahc_softc *ahc) {
4255	int i;
4256
4257	for (i = 0; i < AHC_SCB_MAX; i++) {
4258
4259		ahc_outb(ahc, SCBPTR, i);
4260		ahc_outb(ahc, SCB_BASE, i);
4261		if (ahc_inb(ahc, SCB_BASE) != i)
4262			break;
4263		ahc_outb(ahc, SCBPTR, 0);
4264		if (ahc_inb(ahc, SCB_BASE) != 0)
4265			break;
4266	}
4267	return (i);
4268}
4269
4270static void
4271ahc_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
4272{
4273	bus_addr_t *baddr;
4274
4275	baddr = (bus_addr_t *)arg;
4276	*baddr = segs->ds_addr;
4277}
4278
4279static void
4280ahc_build_free_scb_list(struct ahc_softc *ahc)
4281{
4282	int scbsize;
4283	int i;
4284
4285	scbsize = 32;
4286	if ((ahc->flags & AHC_LSCBS_ENABLED) != 0)
4287		scbsize = 64;
4288
4289	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
4290		int j;
4291
4292		ahc_outb(ahc, SCBPTR, i);
4293
4294		/*
4295		 * Touch all SCB bytes to avoid parity errors
4296		 * should one of our debugging routines read
4297		 * an otherwise uninitiatlized byte.
4298		 */
4299		for (j = 0; j < scbsize; j++)
4300			ahc_outb(ahc, SCB_BASE+j, 0xFF);
4301
4302		/* Clear the control byte. */
4303		ahc_outb(ahc, SCB_CONTROL, 0);
4304
4305		/* Set the next pointer */
4306		if ((ahc->flags & AHC_PAGESCBS) != 0)
4307			ahc_outb(ahc, SCB_NEXT, i+1);
4308		else
4309			ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4310
4311		/* Make the tag number, SCSIID, and lun invalid */
4312		ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
4313		ahc_outb(ahc, SCB_SCSIID, 0xFF);
4314		ahc_outb(ahc, SCB_LUN, 0xFF);
4315	}
4316
4317	if ((ahc->flags & AHC_PAGESCBS) != 0) {
4318		/* SCB 0 heads the free list. */
4319		ahc_outb(ahc, FREE_SCBH, 0);
4320	} else {
4321		/* No free list. */
4322		ahc_outb(ahc, FREE_SCBH, SCB_LIST_NULL);
4323	}
4324
4325	/* Make sure that the last SCB terminates the free list */
4326	ahc_outb(ahc, SCBPTR, i-1);
4327	ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4328}
4329
4330static int
4331ahc_init_scbdata(struct ahc_softc *ahc)
4332{
4333	struct scb_data *scb_data;
4334
4335	scb_data = ahc->scb_data;
4336	SLIST_INIT(&scb_data->free_scbs);
4337	SLIST_INIT(&scb_data->sg_maps);
4338
4339	/* Allocate SCB resources */
4340	scb_data->scbarray =
4341	    (struct scb *)malloc(sizeof(struct scb) * AHC_SCB_MAX_ALLOC,
4342				 M_DEVBUF, M_NOWAIT);
4343	if (scb_data->scbarray == NULL)
4344		return (ENOMEM);
4345	memset(scb_data->scbarray, 0, sizeof(struct scb) * AHC_SCB_MAX_ALLOC);
4346
4347	/* Determine the number of hardware SCBs and initialize them */
4348
4349	scb_data->maxhscbs = ahc_probe_scbs(ahc);
4350	if (ahc->scb_data->maxhscbs == 0) {
4351		printf("%s: No SCB space found\n", ahc_name(ahc));
4352		return (ENXIO);
4353	}
4354
4355	/*
4356	 * Create our DMA tags.  These tags define the kinds of device
4357	 * accessible memory allocations and memory mappings we will
4358	 * need to perform during normal operation.
4359	 *
4360	 * Unless we need to further restrict the allocation, we rely
4361	 * on the restrictions of the parent dmat, hence the common
4362	 * use of MAXADDR and MAXSIZE.
4363	 */
4364
4365	/* DMA tag for our hardware scb structures */
4366	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4367			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4368			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4369			       /*highaddr*/BUS_SPACE_MAXADDR,
4370			       /*filter*/NULL, /*filterarg*/NULL,
4371			       AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4372			       /*nsegments*/1,
4373			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4374			       /*flags*/0, &scb_data->hscb_dmat) != 0) {
4375		goto error_exit;
4376	}
4377
4378	scb_data->init_level++;
4379
4380	/* Allocation for our hscbs */
4381	if (aic_dmamem_alloc(ahc, scb_data->hscb_dmat,
4382			     (void **)&scb_data->hscbs,
4383			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4384			     &scb_data->hscb_dmamap) != 0) {
4385		goto error_exit;
4386	}
4387
4388	scb_data->init_level++;
4389
4390	/* And permanently map them */
4391	aic_dmamap_load(ahc, scb_data->hscb_dmat, scb_data->hscb_dmamap,
4392			scb_data->hscbs,
4393			AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4394			ahc_dmamap_cb, &scb_data->hscb_busaddr, /*flags*/0);
4395
4396	scb_data->init_level++;
4397
4398	/* DMA tag for our sense buffers */
4399	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4400			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4401			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4402			       /*highaddr*/BUS_SPACE_MAXADDR,
4403			       /*filter*/NULL, /*filterarg*/NULL,
4404			       AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4405			       /*nsegments*/1,
4406			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4407			       /*flags*/0, &scb_data->sense_dmat) != 0) {
4408		goto error_exit;
4409	}
4410
4411	scb_data->init_level++;
4412
4413	/* Allocate them */
4414	if (aic_dmamem_alloc(ahc, scb_data->sense_dmat,
4415			     (void **)&scb_data->sense,
4416			     BUS_DMA_NOWAIT, &scb_data->sense_dmamap) != 0) {
4417		goto error_exit;
4418	}
4419
4420	scb_data->init_level++;
4421
4422	/* And permanently map them */
4423	aic_dmamap_load(ahc, scb_data->sense_dmat, scb_data->sense_dmamap,
4424			scb_data->sense,
4425			AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4426			ahc_dmamap_cb, &scb_data->sense_busaddr, /*flags*/0);
4427
4428	scb_data->init_level++;
4429
4430	/* DMA tag for our S/G structures.  We allocate in page sized chunks */
4431	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/8,
4432			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4433			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4434			       /*highaddr*/BUS_SPACE_MAXADDR,
4435			       /*filter*/NULL, /*filterarg*/NULL,
4436			       PAGE_SIZE, /*nsegments*/1,
4437			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4438			       /*flags*/0, &scb_data->sg_dmat) != 0) {
4439		goto error_exit;
4440	}
4441
4442	scb_data->init_level++;
4443
4444	/* Perform initial CCB allocation */
4445	memset(scb_data->hscbs, 0,
4446	       AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb));
4447	while (ahc_alloc_scbs(ahc) != 0)
4448		;
4449
4450	if (scb_data->numscbs == 0) {
4451		printf("%s: ahc_init_scbdata - "
4452		       "Unable to allocate initial scbs\n",
4453		       ahc_name(ahc));
4454		goto error_exit;
4455	}
4456
4457	/*
4458	 * Reserve the next queued SCB.
4459	 */
4460	ahc->next_queued_scb = ahc_get_scb(ahc);
4461
4462	/*
4463	 * Note that we were successfull
4464	 */
4465	return (0);
4466
4467error_exit:
4468
4469	return (ENOMEM);
4470}
4471
4472static void
4473ahc_fini_scbdata(struct ahc_softc *ahc)
4474{
4475	struct scb_data *scb_data;
4476
4477	scb_data = ahc->scb_data;
4478	if (scb_data == NULL)
4479		return;
4480
4481	switch (scb_data->init_level) {
4482	default:
4483	case 7:
4484	{
4485		struct sg_map_node *sg_map;
4486
4487		while ((sg_map = SLIST_FIRST(&scb_data->sg_maps))!= NULL) {
4488			SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
4489			aic_dmamap_unload(ahc, scb_data->sg_dmat,
4490					  sg_map->sg_dmamap);
4491			aic_dmamem_free(ahc, scb_data->sg_dmat,
4492					sg_map->sg_vaddr,
4493					sg_map->sg_dmamap);
4494			free(sg_map, M_DEVBUF);
4495		}
4496		aic_dma_tag_destroy(ahc, scb_data->sg_dmat);
4497	}
4498	case 6:
4499		aic_dmamap_unload(ahc, scb_data->sense_dmat,
4500				  scb_data->sense_dmamap);
4501	case 5:
4502		aic_dmamem_free(ahc, scb_data->sense_dmat, scb_data->sense,
4503				scb_data->sense_dmamap);
4504		aic_dmamap_destroy(ahc, scb_data->sense_dmat,
4505				   scb_data->sense_dmamap);
4506	case 4:
4507		aic_dma_tag_destroy(ahc, scb_data->sense_dmat);
4508	case 3:
4509		aic_dmamap_unload(ahc, scb_data->hscb_dmat,
4510				  scb_data->hscb_dmamap);
4511	case 2:
4512		aic_dmamem_free(ahc, scb_data->hscb_dmat, scb_data->hscbs,
4513				scb_data->hscb_dmamap);
4514		aic_dmamap_destroy(ahc, scb_data->hscb_dmat,
4515				   scb_data->hscb_dmamap);
4516	case 1:
4517		aic_dma_tag_destroy(ahc, scb_data->hscb_dmat);
4518		break;
4519	case 0:
4520		break;
4521	}
4522	if (scb_data->scbarray != NULL)
4523		free(scb_data->scbarray, M_DEVBUF);
4524}
4525
4526int
4527ahc_alloc_scbs(struct ahc_softc *ahc)
4528{
4529	struct scb_data *scb_data;
4530	struct scb *next_scb;
4531	struct sg_map_node *sg_map;
4532	bus_addr_t physaddr;
4533	struct ahc_dma_seg *segs;
4534	int newcount;
4535	int i;
4536
4537	scb_data = ahc->scb_data;
4538	if (scb_data->numscbs >= AHC_SCB_MAX_ALLOC)
4539		/* Can't allocate any more */
4540		return (0);
4541
4542	next_scb = &scb_data->scbarray[scb_data->numscbs];
4543
4544	sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
4545
4546	if (sg_map == NULL)
4547		return (0);
4548
4549	/* Allocate S/G space for the next batch of SCBS */
4550	if (aic_dmamem_alloc(ahc, scb_data->sg_dmat,
4551			     (void **)&sg_map->sg_vaddr,
4552			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4553			     &sg_map->sg_dmamap) != 0) {
4554		free(sg_map, M_DEVBUF);
4555		return (0);
4556	}
4557
4558	SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
4559
4560	aic_dmamap_load(ahc, scb_data->sg_dmat, sg_map->sg_dmamap,
4561			sg_map->sg_vaddr, PAGE_SIZE, ahc_dmamap_cb,
4562			&sg_map->sg_physaddr, /*flags*/0);
4563
4564	segs = sg_map->sg_vaddr;
4565	physaddr = sg_map->sg_physaddr;
4566
4567	newcount = (PAGE_SIZE / (AHC_NSEG * sizeof(struct ahc_dma_seg)));
4568	newcount = MIN(newcount, (AHC_SCB_MAX_ALLOC - scb_data->numscbs));
4569	for (i = 0; i < newcount; i++) {
4570		struct scb_platform_data *pdata;
4571#ifndef __linux__
4572		int error;
4573#endif
4574		pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
4575							   M_DEVBUF, M_NOWAIT);
4576		if (pdata == NULL)
4577			break;
4578		next_scb->platform_data = pdata;
4579		next_scb->sg_map = sg_map;
4580		next_scb->sg_list = segs;
4581		/*
4582		 * The sequencer always starts with the second entry.
4583		 * The first entry is embedded in the scb.
4584		 */
4585		next_scb->sg_list_phys = physaddr + sizeof(struct ahc_dma_seg);
4586		next_scb->ahc_softc = ahc;
4587		next_scb->flags = SCB_FLAG_NONE;
4588#ifndef __linux__
4589		error = aic_dmamap_create(ahc, ahc->buffer_dmat, /*flags*/0,
4590					  &next_scb->dmamap);
4591		if (error != 0)
4592			break;
4593#endif
4594		next_scb->hscb = &scb_data->hscbs[scb_data->numscbs];
4595		next_scb->hscb->tag = ahc->scb_data->numscbs;
4596		aic_timer_init(&next_scb->io_timer);
4597		SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs,
4598				  next_scb, links.sle);
4599		segs += AHC_NSEG;
4600		physaddr += (AHC_NSEG * sizeof(struct ahc_dma_seg));
4601		next_scb++;
4602		ahc->scb_data->numscbs++;
4603	}
4604	return (i);
4605}
4606
4607void
4608ahc_controller_info(struct ahc_softc *ahc, char *buf)
4609{
4610	int len;
4611
4612	len = sprintf(buf, "%s: ", ahc_chip_names[ahc->chip & AHC_CHIPID_MASK]);
4613	buf += len;
4614	if ((ahc->features & AHC_TWIN) != 0)
4615 		len = sprintf(buf, "Twin Channel, A SCSI Id=%d, "
4616			      "B SCSI Id=%d, primary %c, ",
4617			      ahc->our_id, ahc->our_id_b,
4618			      (ahc->flags & AHC_PRIMARY_CHANNEL) + 'A');
4619	else {
4620		const char *speed;
4621		const char *type;
4622
4623		speed = "";
4624		if ((ahc->features & AHC_ULTRA) != 0) {
4625			speed = "Ultra ";
4626		} else if ((ahc->features & AHC_DT) != 0) {
4627			speed = "Ultra160 ";
4628		} else if ((ahc->features & AHC_ULTRA2) != 0) {
4629			speed = "Ultra2 ";
4630		}
4631		if ((ahc->features & AHC_WIDE) != 0) {
4632			type = "Wide";
4633		} else {
4634			type = "Single";
4635		}
4636		len = sprintf(buf, "%s%s Channel %c, SCSI Id=%d, ",
4637			      speed, type, ahc->channel, ahc->our_id);
4638	}
4639	buf += len;
4640
4641	if ((ahc->flags & AHC_PAGESCBS) != 0)
4642		sprintf(buf, "%d/%d SCBs",
4643			ahc->scb_data->maxhscbs, AHC_MAX_QUEUE);
4644	else
4645		sprintf(buf, "%d SCBs", ahc->scb_data->maxhscbs);
4646}
4647
4648int
4649ahc_chip_init(struct ahc_softc *ahc)
4650{
4651	int	 term;
4652	int	 error;
4653	u_int	 i;
4654	u_int	 scsi_conf;
4655	u_int	 scsiseq_template;
4656	uint32_t physaddr;
4657
4658	ahc_outb(ahc, SEQ_FLAGS, 0);
4659	ahc_outb(ahc, SEQ_FLAGS2, 0);
4660
4661	/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
4662	if (ahc->features & AHC_TWIN) {
4663
4664		/*
4665		 * Setup Channel B first.
4666		 */
4667		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
4668		term = (ahc->flags & AHC_TERM_ENB_B) != 0 ? STPWEN : 0;
4669		ahc_outb(ahc, SCSIID, ahc->our_id_b);
4670		scsi_conf = ahc_inb(ahc, SCSICONF + 1);
4671		ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4672					|term|ahc->seltime_b|ENSTIMER|ACTNEGEN);
4673		if ((ahc->features & AHC_ULTRA2) != 0)
4674			ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4675		ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4676		ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4677
4678		/* Select Channel A */
4679		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
4680	}
4681	term = (ahc->flags & AHC_TERM_ENB_A) != 0 ? STPWEN : 0;
4682	if ((ahc->features & AHC_ULTRA2) != 0)
4683		ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
4684	else
4685		ahc_outb(ahc, SCSIID, ahc->our_id);
4686	scsi_conf = ahc_inb(ahc, SCSICONF);
4687	ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4688				|term|ahc->seltime
4689				|ENSTIMER|ACTNEGEN);
4690	if ((ahc->features & AHC_ULTRA2) != 0)
4691		ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4692	ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4693	ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4694
4695	/* There are no untagged SCBs active yet. */
4696	for (i = 0; i < 16; i++) {
4697		ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, 0));
4698		if ((ahc->flags & AHC_SCB_BTT) != 0) {
4699			int lun;
4700
4701			/*
4702			 * The SCB based BTT allows an entry per
4703			 * target and lun pair.
4704			 */
4705			for (lun = 1; lun < AHC_NUM_LUNS; lun++)
4706				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, lun));
4707		}
4708	}
4709
4710	/* All of our queues are empty */
4711	for (i = 0; i < 256; i++)
4712		ahc->qoutfifo[i] = SCB_LIST_NULL;
4713	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_PREREAD);
4714
4715	for (i = 0; i < 256; i++)
4716		ahc->qinfifo[i] = SCB_LIST_NULL;
4717
4718	if ((ahc->features & AHC_MULTI_TID) != 0) {
4719		ahc_outb(ahc, TARGID, 0);
4720		ahc_outb(ahc, TARGID + 1, 0);
4721	}
4722
4723	/*
4724	 * Tell the sequencer where it can find our arrays in memory.
4725	 */
4726	physaddr = ahc->scb_data->hscb_busaddr;
4727	ahc_outb(ahc, HSCB_ADDR, physaddr & 0xFF);
4728	ahc_outb(ahc, HSCB_ADDR + 1, (physaddr >> 8) & 0xFF);
4729	ahc_outb(ahc, HSCB_ADDR + 2, (physaddr >> 16) & 0xFF);
4730	ahc_outb(ahc, HSCB_ADDR + 3, (physaddr >> 24) & 0xFF);
4731
4732	physaddr = ahc->shared_data_busaddr;
4733	ahc_outb(ahc, SHARED_DATA_ADDR, physaddr & 0xFF);
4734	ahc_outb(ahc, SHARED_DATA_ADDR + 1, (physaddr >> 8) & 0xFF);
4735	ahc_outb(ahc, SHARED_DATA_ADDR + 2, (physaddr >> 16) & 0xFF);
4736	ahc_outb(ahc, SHARED_DATA_ADDR + 3, (physaddr >> 24) & 0xFF);
4737
4738	/*
4739	 * Initialize the group code to command length table.
4740	 * This overrides the values in TARG_SCSIRATE, so only
4741	 * setup the table after we have processed that information.
4742	 */
4743	ahc_outb(ahc, CMDSIZE_TABLE, 5);
4744	ahc_outb(ahc, CMDSIZE_TABLE + 1, 9);
4745	ahc_outb(ahc, CMDSIZE_TABLE + 2, 9);
4746	ahc_outb(ahc, CMDSIZE_TABLE + 3, 0);
4747	ahc_outb(ahc, CMDSIZE_TABLE + 4, 15);
4748	ahc_outb(ahc, CMDSIZE_TABLE + 5, 11);
4749	ahc_outb(ahc, CMDSIZE_TABLE + 6, 0);
4750	ahc_outb(ahc, CMDSIZE_TABLE + 7, 0);
4751
4752	if ((ahc->features & AHC_HS_MAILBOX) != 0)
4753		ahc_outb(ahc, HS_MAILBOX, 0);
4754
4755	/* Tell the sequencer of our initial queue positions */
4756	if ((ahc->features & AHC_TARGETMODE) != 0) {
4757		ahc->tqinfifonext = 1;
4758		ahc_outb(ahc, KERNEL_TQINPOS, ahc->tqinfifonext - 1);
4759		ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
4760	}
4761	ahc->qinfifonext = 0;
4762	ahc->qoutfifonext = 0;
4763	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
4764		ahc_outb(ahc, QOFF_CTLSTA, SCB_QSIZE_256);
4765		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
4766		ahc_outb(ahc, SNSCB_QOFF, ahc->qinfifonext);
4767		ahc_outb(ahc, SDSCB_QOFF, 0);
4768	} else {
4769		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
4770		ahc_outb(ahc, QINPOS, ahc->qinfifonext);
4771		ahc_outb(ahc, QOUTPOS, ahc->qoutfifonext);
4772	}
4773
4774	/* We don't have any waiting selections */
4775	ahc_outb(ahc, WAITING_SCBH, SCB_LIST_NULL);
4776
4777	/* Our disconnection list is empty too */
4778	ahc_outb(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
4779
4780	/* Message out buffer starts empty */
4781	ahc_outb(ahc, MSG_OUT, MSG_NOOP);
4782
4783	/*
4784	 * Setup the allowed SCSI Sequences based on operational mode.
4785	 * If we are a target, we'll enalbe select in operations once
4786	 * we've had a lun enabled.
4787	 */
4788	scsiseq_template = ENSELO|ENAUTOATNO|ENAUTOATNP;
4789	if ((ahc->flags & AHC_INITIATORROLE) != 0)
4790		scsiseq_template |= ENRSELI;
4791	ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq_template);
4792
4793	/* Initialize our list of free SCBs. */
4794	ahc_build_free_scb_list(ahc);
4795
4796	/*
4797	 * Tell the sequencer which SCB will be the next one it receives.
4798	 */
4799	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
4800
4801	/*
4802	 * Load the Sequencer program and Enable the adapter
4803	 * in "fast" mode.
4804	 */
4805	if (bootverbose)
4806		printf("%s: Downloading Sequencer Program...",
4807		       ahc_name(ahc));
4808
4809	error = ahc_loadseq(ahc);
4810	if (error != 0)
4811		return (error);
4812
4813	if ((ahc->features & AHC_ULTRA2) != 0) {
4814		int wait;
4815
4816		/*
4817		 * Wait for up to 500ms for our transceivers
4818		 * to settle.  If the adapter does not have
4819		 * a cable attached, the transceivers may
4820		 * never settle, so don't complain if we
4821		 * fail here.
4822		 */
4823		for (wait = 5000;
4824		     (ahc_inb(ahc, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
4825		     wait--)
4826			aic_delay(100);
4827	}
4828	ahc_restart(ahc);
4829	return (0);
4830}
4831
4832/*
4833 * Start the board, ready for normal operation
4834 */
4835int
4836ahc_init(struct ahc_softc *ahc)
4837{
4838	int	 max_targ;
4839	int	 error;
4840	u_int	 i;
4841	u_int	 scsi_conf;
4842	u_int	 ultraenb;
4843	u_int	 discenable;
4844	u_int	 tagenable;
4845	size_t	 driver_data_size;
4846
4847#ifdef AHC_DEBUG
4848	if ((ahc_debug & AHC_DEBUG_SEQUENCER) != 0)
4849		ahc->flags |= AHC_SEQUENCER_DEBUG;
4850#endif
4851
4852#ifdef AHC_PRINT_SRAM
4853	printf("Scratch Ram:");
4854	for (i = 0x20; i < 0x5f; i++) {
4855		if (((i % 8) == 0) && (i != 0)) {
4856			printf ("\n              ");
4857		}
4858		printf (" 0x%x", ahc_inb(ahc, i));
4859	}
4860	if ((ahc->features & AHC_MORE_SRAM) != 0) {
4861		for (i = 0x70; i < 0x7f; i++) {
4862			if (((i % 8) == 0) && (i != 0)) {
4863				printf ("\n              ");
4864			}
4865			printf (" 0x%x", ahc_inb(ahc, i));
4866		}
4867	}
4868	printf ("\n");
4869	/*
4870	 * Reading uninitialized scratch ram may
4871	 * generate parity errors.
4872	 */
4873	ahc_outb(ahc, CLRINT, CLRPARERR);
4874	ahc_outb(ahc, CLRINT, CLRBRKADRINT);
4875#endif
4876	max_targ = 15;
4877
4878	/*
4879	 * Assume we have a board at this stage and it has been reset.
4880	 */
4881	if ((ahc->flags & AHC_USEDEFAULTS) != 0)
4882		ahc->our_id = ahc->our_id_b = 7;
4883
4884	/*
4885	 * Default to allowing initiator operations.
4886	 */
4887	ahc->flags |= AHC_INITIATORROLE;
4888
4889	/*
4890	 * Only allow target mode features if this unit has them enabled.
4891	 */
4892	if ((AHC_TMODE_ENABLE & (0x1 << ahc->unit)) == 0)
4893		ahc->features &= ~AHC_TARGETMODE;
4894
4895#ifndef __linux__
4896	/* DMA tag for mapping buffers into device visible space. */
4897	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4898			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4899			       /*lowaddr*/ahc->flags & AHC_39BIT_ADDRESSING
4900					? (bus_addr_t)0x7FFFFFFFFFULL
4901					: BUS_SPACE_MAXADDR_32BIT,
4902			       /*highaddr*/BUS_SPACE_MAXADDR,
4903			       /*filter*/NULL, /*filterarg*/NULL,
4904			       /*maxsize*/(AHC_NSEG - 1) * PAGE_SIZE,
4905			       /*nsegments*/AHC_NSEG,
4906			       /*maxsegsz*/AHC_MAXTRANSFER_SIZE,
4907			       /*flags*/BUS_DMA_ALLOCNOW,
4908			       &ahc->buffer_dmat) != 0) {
4909		return (ENOMEM);
4910	}
4911#endif
4912
4913	ahc->init_level++;
4914
4915	/*
4916	 * DMA tag for our command fifos and other data in system memory
4917	 * the card's sequencer must be able to access.  For initiator
4918	 * roles, we need to allocate space for the qinfifo and qoutfifo.
4919	 * The qinfifo and qoutfifo are composed of 256 1 byte elements.
4920	 * When providing for the target mode role, we must additionally
4921	 * provide space for the incoming target command fifo and an extra
4922	 * byte to deal with a dma bug in some chip versions.
4923	 */
4924	driver_data_size = 2 * 256 * sizeof(uint8_t);
4925	if ((ahc->features & AHC_TARGETMODE) != 0)
4926		driver_data_size += AHC_TMODE_CMDS * sizeof(struct target_cmd)
4927				 + /*DMA WideOdd Bug Buffer*/1;
4928	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4929			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4930			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4931			       /*highaddr*/BUS_SPACE_MAXADDR,
4932			       /*filter*/NULL, /*filterarg*/NULL,
4933			       driver_data_size,
4934			       /*nsegments*/1,
4935			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4936			       /*flags*/0, &ahc->shared_data_dmat) != 0) {
4937		return (ENOMEM);
4938	}
4939
4940	ahc->init_level++;
4941
4942	/* Allocation of driver data */
4943	if (aic_dmamem_alloc(ahc, ahc->shared_data_dmat,
4944			     (void **)&ahc->qoutfifo,
4945			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4946			     &ahc->shared_data_dmamap) != 0) {
4947		return (ENOMEM);
4948	}
4949
4950	ahc->init_level++;
4951
4952	/* And permanently map it in */
4953	aic_dmamap_load(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
4954			ahc->qoutfifo, driver_data_size, ahc_dmamap_cb,
4955			&ahc->shared_data_busaddr, /*flags*/0);
4956
4957	if ((ahc->features & AHC_TARGETMODE) != 0) {
4958		ahc->targetcmds = (struct target_cmd *)ahc->qoutfifo;
4959		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[AHC_TMODE_CMDS];
4960		ahc->dma_bug_buf = ahc->shared_data_busaddr
4961				 + driver_data_size - 1;
4962		/* All target command blocks start out invalid. */
4963		for (i = 0; i < AHC_TMODE_CMDS; i++)
4964			ahc->targetcmds[i].cmd_valid = 0;
4965		ahc_sync_tqinfifo(ahc, BUS_DMASYNC_PREREAD);
4966		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[256];
4967	}
4968	ahc->qinfifo = &ahc->qoutfifo[256];
4969
4970	ahc->init_level++;
4971
4972	/* Allocate SCB data now that buffer_dmat is initialized */
4973	if (ahc->scb_data->maxhscbs == 0)
4974		if (ahc_init_scbdata(ahc) != 0)
4975			return (ENOMEM);
4976
4977	/*
4978	 * Allocate a tstate to house information for our
4979	 * initiator presence on the bus as well as the user
4980	 * data for any target mode initiator.
4981	 */
4982	if (ahc_alloc_tstate(ahc, ahc->our_id, 'A') == NULL) {
4983		printf("%s: unable to allocate ahc_tmode_tstate.  "
4984		       "Failing attach\n", ahc_name(ahc));
4985		return (ENOMEM);
4986	}
4987
4988	if ((ahc->features & AHC_TWIN) != 0) {
4989		if (ahc_alloc_tstate(ahc, ahc->our_id_b, 'B') == NULL) {
4990			printf("%s: unable to allocate ahc_tmode_tstate.  "
4991			       "Failing attach\n", ahc_name(ahc));
4992			return (ENOMEM);
4993		}
4994	}
4995
4996	/*
4997	 * Fire up a recovery thread for this controller.
4998	 */
4999	error = ahc_spawn_recovery_thread(ahc);
5000	if (error != 0)
5001		return (error);
5002
5003	if (ahc->scb_data->maxhscbs < AHC_SCB_MAX_ALLOC) {
5004		ahc->flags |= AHC_PAGESCBS;
5005	} else {
5006		ahc->flags &= ~AHC_PAGESCBS;
5007	}
5008
5009#ifdef AHC_DEBUG
5010	if (ahc_debug & AHC_SHOW_MISC) {
5011		printf("%s: hardware scb %u bytes; kernel scb %u bytes; "
5012		       "ahc_dma %u bytes\n",
5013			ahc_name(ahc),
5014			(u_int)sizeof(struct hardware_scb),
5015			(u_int)sizeof(struct scb),
5016			(u_int)sizeof(struct ahc_dma_seg));
5017	}
5018#endif /* AHC_DEBUG */
5019
5020	/*
5021	 * Look at the information that board initialization or
5022	 * the board bios has left us.
5023	 */
5024	if (ahc->features & AHC_TWIN) {
5025		scsi_conf = ahc_inb(ahc, SCSICONF + 1);
5026		if ((scsi_conf & RESET_SCSI) != 0
5027		 && (ahc->flags & AHC_INITIATORROLE) != 0)
5028			ahc->flags |= AHC_RESET_BUS_B;
5029	}
5030
5031	scsi_conf = ahc_inb(ahc, SCSICONF);
5032	if ((scsi_conf & RESET_SCSI) != 0
5033	 && (ahc->flags & AHC_INITIATORROLE) != 0)
5034		ahc->flags |= AHC_RESET_BUS_A;
5035
5036	ultraenb = 0;
5037	tagenable = ALL_TARGETS_MASK;
5038
5039	/* Grab the disconnection disable table and invert it for our needs */
5040	if ((ahc->flags & AHC_USEDEFAULTS) != 0) {
5041		printf("%s: Host Adapter Bios disabled.  Using default SCSI "
5042			"device parameters\n", ahc_name(ahc));
5043		ahc->flags |= AHC_EXTENDED_TRANS_A|AHC_EXTENDED_TRANS_B|
5044			      AHC_TERM_ENB_A|AHC_TERM_ENB_B;
5045		discenable = ALL_TARGETS_MASK;
5046		if ((ahc->features & AHC_ULTRA) != 0)
5047			ultraenb = ALL_TARGETS_MASK;
5048	} else {
5049		discenable = ~((ahc_inb(ahc, DISC_DSB + 1) << 8)
5050			   | ahc_inb(ahc, DISC_DSB));
5051		if ((ahc->features & (AHC_ULTRA|AHC_ULTRA2)) != 0)
5052			ultraenb = (ahc_inb(ahc, ULTRA_ENB + 1) << 8)
5053				      | ahc_inb(ahc, ULTRA_ENB);
5054	}
5055
5056	if ((ahc->features & (AHC_WIDE|AHC_TWIN)) == 0)
5057		max_targ = 7;
5058
5059	for (i = 0; i <= max_targ; i++) {
5060		struct ahc_initiator_tinfo *tinfo;
5061		struct ahc_tmode_tstate *tstate;
5062		u_int our_id;
5063		u_int target_id;
5064		char channel;
5065
5066		channel = 'A';
5067		our_id = ahc->our_id;
5068		target_id = i;
5069		if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
5070			channel = 'B';
5071			our_id = ahc->our_id_b;
5072			target_id = i % 8;
5073		}
5074		tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
5075					    target_id, &tstate);
5076		/* Default to async narrow across the board */
5077		memset(tinfo, 0, sizeof(*tinfo));
5078		if (ahc->flags & AHC_USEDEFAULTS) {
5079			if ((ahc->features & AHC_WIDE) != 0)
5080				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
5081
5082			/*
5083			 * These will be truncated when we determine the
5084			 * connection type we have with the target.
5085			 */
5086			tinfo->user.period = ahc_syncrates->period;
5087			tinfo->user.offset = MAX_OFFSET;
5088		} else {
5089			u_int scsirate;
5090			uint16_t mask;
5091
5092			/* Take the settings leftover in scratch RAM. */
5093			scsirate = ahc_inb(ahc, TARG_SCSIRATE + i);
5094			mask = (0x01 << i);
5095			if ((ahc->features & AHC_ULTRA2) != 0) {
5096				u_int offset;
5097				u_int maxsync;
5098
5099				if ((scsirate & SOFS) == 0x0F) {
5100					/*
5101					 * Haven't negotiated yet,
5102					 * so the format is different.
5103					 */
5104					scsirate = (scsirate & SXFR) >> 4
5105						 | (ultraenb & mask)
5106						  ? 0x08 : 0x0
5107						 | (scsirate & WIDEXFER);
5108					offset = MAX_OFFSET_ULTRA2;
5109				} else
5110					offset = ahc_inb(ahc, TARG_OFFSET + i);
5111				if ((scsirate & ~WIDEXFER) == 0 && offset != 0)
5112					/* Set to the lowest sync rate, 5MHz */
5113					scsirate |= 0x1c;
5114				maxsync = AHC_SYNCRATE_ULTRA2;
5115				if ((ahc->features & AHC_DT) != 0)
5116					maxsync = AHC_SYNCRATE_DT;
5117				tinfo->user.period =
5118				    ahc_find_period(ahc, scsirate, maxsync);
5119				if (offset == 0)
5120					tinfo->user.period = 0;
5121				else
5122					tinfo->user.offset = MAX_OFFSET;
5123				if ((scsirate & SXFR_ULTRA2) <= 8/*10MHz*/
5124				 && (ahc->features & AHC_DT) != 0)
5125					tinfo->user.ppr_options =
5126					    MSG_EXT_PPR_DT_REQ;
5127			} else if ((scsirate & SOFS) != 0) {
5128				if ((scsirate & SXFR) == 0x40
5129				 && (ultraenb & mask) != 0) {
5130					/* Treat 10MHz as a non-ultra speed */
5131					scsirate &= ~SXFR;
5132				 	ultraenb &= ~mask;
5133				}
5134				tinfo->user.period =
5135				    ahc_find_period(ahc, scsirate,
5136						    (ultraenb & mask)
5137						   ? AHC_SYNCRATE_ULTRA
5138						   : AHC_SYNCRATE_FAST);
5139				if (tinfo->user.period != 0)
5140					tinfo->user.offset = MAX_OFFSET;
5141			}
5142			if (tinfo->user.period == 0)
5143				tinfo->user.offset = 0;
5144			if ((scsirate & WIDEXFER) != 0
5145			 && (ahc->features & AHC_WIDE) != 0)
5146				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
5147			tinfo->user.protocol_version = 4;
5148			if ((ahc->features & AHC_DT) != 0)
5149				tinfo->user.transport_version = 3;
5150			else
5151				tinfo->user.transport_version = 2;
5152			tinfo->goal.protocol_version = 2;
5153			tinfo->goal.transport_version = 2;
5154			tinfo->curr.protocol_version = 2;
5155			tinfo->curr.transport_version = 2;
5156		}
5157		tstate->ultraenb = 0;
5158	}
5159	ahc->user_discenable = discenable;
5160	ahc->user_tagenable = tagenable;
5161
5162	return (ahc->bus_chip_init(ahc));
5163}
5164
5165void
5166ahc_intr_enable(struct ahc_softc *ahc, int enable)
5167{
5168	u_int hcntrl;
5169
5170	hcntrl = ahc_inb(ahc, HCNTRL);
5171	hcntrl &= ~INTEN;
5172	ahc->pause &= ~INTEN;
5173	ahc->unpause &= ~INTEN;
5174	if (enable) {
5175		hcntrl |= INTEN;
5176		ahc->pause |= INTEN;
5177		ahc->unpause |= INTEN;
5178	}
5179	ahc_outb(ahc, HCNTRL, hcntrl);
5180}
5181
5182/*
5183 * Ensure that the card is paused in a location
5184 * outside of all critical sections and that all
5185 * pending work is completed prior to returning.
5186 * This routine should only be called from outside
5187 * an interrupt context.
5188 */
5189void
5190ahc_pause_and_flushwork(struct ahc_softc *ahc)
5191{
5192	int intstat;
5193	int maxloops;
5194	int paused;
5195
5196	maxloops = 1000;
5197	ahc->flags |= AHC_ALL_INTERRUPTS;
5198	paused = FALSE;
5199	do {
5200		if (paused) {
5201			ahc_unpause(ahc);
5202			/*
5203			 * Give the sequencer some time to service
5204			 * any active selections.
5205			 */
5206			aic_delay(500);
5207		}
5208		ahc_intr(ahc);
5209		ahc_pause(ahc);
5210		paused = TRUE;
5211		ahc_outb(ahc, SCSISEQ, ahc_inb(ahc, SCSISEQ) & ~ENSELO);
5212		intstat = ahc_inb(ahc, INTSTAT);
5213		if ((intstat & INT_PEND) == 0) {
5214			ahc_clear_critical_section(ahc);
5215			intstat = ahc_inb(ahc, INTSTAT);
5216		}
5217	} while (--maxloops
5218	      && (intstat != 0xFF || (ahc->features & AHC_REMOVABLE) == 0)
5219	      && ((intstat & INT_PEND) != 0
5220	       || (ahc_inb(ahc, SSTAT0) & (SELDO|SELINGO)) != 0));
5221	if (maxloops == 0) {
5222		printf("Infinite interrupt loop, INTSTAT = %x",
5223		       ahc_inb(ahc, INTSTAT));
5224	}
5225	ahc_platform_flushwork(ahc);
5226	ahc->flags &= ~AHC_ALL_INTERRUPTS;
5227}
5228
5229int
5230ahc_suspend(struct ahc_softc *ahc)
5231{
5232
5233	ahc_pause_and_flushwork(ahc);
5234
5235	if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
5236		ahc_unpause(ahc);
5237		return (EBUSY);
5238	}
5239
5240#ifdef AHC_TARGET_MODE
5241	/*
5242	 * XXX What about ATIOs that have not yet been serviced?
5243	 * Perhaps we should just refuse to be suspended if we
5244	 * are acting in a target role.
5245	 */
5246	if (ahc->pending_device != NULL) {
5247		ahc_unpause(ahc);
5248		return (EBUSY);
5249	}
5250#endif
5251	ahc_shutdown(ahc);
5252	return (0);
5253}
5254
5255int
5256ahc_resume(struct ahc_softc *ahc)
5257{
5258
5259	ahc_reset(ahc, /*reinit*/TRUE);
5260	ahc_intr_enable(ahc, TRUE);
5261	ahc_restart(ahc);
5262	return (0);
5263}
5264
5265/************************** Busy Target Table *********************************/
5266/*
5267 * Return the untagged transaction id for a given target/channel lun.
5268 * Optionally, clear the entry.
5269 */
5270u_int
5271ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl)
5272{
5273	u_int scbid;
5274	u_int target_offset;
5275
5276	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5277		u_int saved_scbptr;
5278
5279		saved_scbptr = ahc_inb(ahc, SCBPTR);
5280		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5281		scbid = ahc_inb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl));
5282		ahc_outb(ahc, SCBPTR, saved_scbptr);
5283	} else {
5284		target_offset = TCL_TARGET_OFFSET(tcl);
5285		scbid = ahc_inb(ahc, BUSY_TARGETS + target_offset);
5286	}
5287
5288	return (scbid);
5289}
5290
5291void
5292ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl)
5293{
5294	u_int target_offset;
5295
5296	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5297		u_int saved_scbptr;
5298
5299		saved_scbptr = ahc_inb(ahc, SCBPTR);
5300		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5301		ahc_outb(ahc, SCB_64_BTT+TCL_TARGET_OFFSET(tcl), SCB_LIST_NULL);
5302		ahc_outb(ahc, SCBPTR, saved_scbptr);
5303	} else {
5304		target_offset = TCL_TARGET_OFFSET(tcl);
5305		ahc_outb(ahc, BUSY_TARGETS + target_offset, SCB_LIST_NULL);
5306	}
5307}
5308
5309void
5310ahc_busy_tcl(struct ahc_softc *ahc, u_int tcl, u_int scbid)
5311{
5312	u_int target_offset;
5313
5314	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5315		u_int saved_scbptr;
5316
5317		saved_scbptr = ahc_inb(ahc, SCBPTR);
5318		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5319		ahc_outb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl), scbid);
5320		ahc_outb(ahc, SCBPTR, saved_scbptr);
5321	} else {
5322		target_offset = TCL_TARGET_OFFSET(tcl);
5323		ahc_outb(ahc, BUSY_TARGETS + target_offset, scbid);
5324	}
5325}
5326
5327/************************** SCB and SCB queue management **********************/
5328int
5329ahc_match_scb(struct ahc_softc *ahc, struct scb *scb, int target,
5330	      char channel, int lun, u_int tag, role_t role)
5331{
5332	int targ = SCB_GET_TARGET(ahc, scb);
5333	char chan = SCB_GET_CHANNEL(ahc, scb);
5334	int slun = SCB_GET_LUN(scb);
5335	int match;
5336
5337	match = ((chan == channel) || (channel == ALL_CHANNELS));
5338	if (match != 0)
5339		match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
5340	if (match != 0)
5341		match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
5342	if (match != 0) {
5343#ifdef AHC_TARGET_MODE
5344		int group;
5345
5346		group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
5347		if (role == ROLE_INITIATOR) {
5348			match = (group != XPT_FC_GROUP_TMODE)
5349			      && ((tag == scb->hscb->tag)
5350			       || (tag == SCB_LIST_NULL));
5351		} else if (role == ROLE_TARGET) {
5352			match = (group == XPT_FC_GROUP_TMODE)
5353			      && ((tag == scb->io_ctx->csio.tag_id)
5354			       || (tag == SCB_LIST_NULL));
5355		}
5356#else /* !AHC_TARGET_MODE */
5357		match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
5358#endif /* AHC_TARGET_MODE */
5359	}
5360
5361	return match;
5362}
5363
5364void
5365ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
5366{
5367	int	target;
5368	char	channel;
5369	int	lun;
5370
5371	target = SCB_GET_TARGET(ahc, scb);
5372	lun = SCB_GET_LUN(scb);
5373	channel = SCB_GET_CHANNEL(ahc, scb);
5374
5375	ahc_search_qinfifo(ahc, target, channel, lun,
5376			   /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
5377			   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5378
5379	ahc_platform_freeze_devq(ahc, scb);
5380}
5381
5382void
5383ahc_qinfifo_requeue_tail(struct ahc_softc *ahc, struct scb *scb)
5384{
5385	struct scb *prev_scb;
5386
5387	prev_scb = NULL;
5388	if (ahc_qinfifo_count(ahc) != 0) {
5389		u_int prev_tag;
5390		uint8_t prev_pos;
5391
5392		prev_pos = ahc->qinfifonext - 1;
5393		prev_tag = ahc->qinfifo[prev_pos];
5394		prev_scb = ahc_lookup_scb(ahc, prev_tag);
5395	}
5396	ahc_qinfifo_requeue(ahc, prev_scb, scb);
5397	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5398		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5399	} else {
5400		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5401	}
5402}
5403
5404static void
5405ahc_qinfifo_requeue(struct ahc_softc *ahc, struct scb *prev_scb,
5406		    struct scb *scb)
5407{
5408	if (prev_scb == NULL) {
5409		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5410	} else {
5411		prev_scb->hscb->next = scb->hscb->tag;
5412		ahc_sync_scb(ahc, prev_scb,
5413			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5414	}
5415	ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
5416	scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5417	ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5418}
5419
5420static int
5421ahc_qinfifo_count(struct ahc_softc *ahc)
5422{
5423	uint8_t qinpos;
5424	uint8_t diff;
5425
5426	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5427		qinpos = ahc_inb(ahc, SNSCB_QOFF);
5428		ahc_outb(ahc, SNSCB_QOFF, qinpos);
5429	} else
5430		qinpos = ahc_inb(ahc, QINPOS);
5431	diff = ahc->qinfifonext - qinpos;
5432	return (diff);
5433}
5434
5435int
5436ahc_search_qinfifo(struct ahc_softc *ahc, int target, char channel,
5437		   int lun, u_int tag, role_t role, uint32_t status,
5438		   ahc_search_action action)
5439{
5440	struct	scb *scb;
5441	struct	scb *prev_scb;
5442	uint8_t qinstart;
5443	uint8_t qinpos;
5444	uint8_t qintail;
5445	uint8_t next;
5446	uint8_t prev;
5447	uint8_t curscbptr;
5448	int	found;
5449	int	have_qregs;
5450
5451	qintail = ahc->qinfifonext;
5452	have_qregs = (ahc->features & AHC_QUEUE_REGS) != 0;
5453	if (have_qregs) {
5454		qinstart = ahc_inb(ahc, SNSCB_QOFF);
5455		ahc_outb(ahc, SNSCB_QOFF, qinstart);
5456	} else
5457		qinstart = ahc_inb(ahc, QINPOS);
5458	qinpos = qinstart;
5459	found = 0;
5460	prev_scb = NULL;
5461
5462	if (action == SEARCH_COMPLETE) {
5463		/*
5464		 * Don't attempt to run any queued untagged transactions
5465		 * until we are done with the abort process.
5466		 */
5467		ahc_freeze_untagged_queues(ahc);
5468	}
5469
5470	/*
5471	 * Start with an empty queue.  Entries that are not chosen
5472	 * for removal will be re-added to the queue as we go.
5473	 */
5474	ahc->qinfifonext = qinpos;
5475	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
5476
5477	while (qinpos != qintail) {
5478		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinpos]);
5479		if (scb == NULL) {
5480			printf("qinpos = %d, SCB index = %d\n",
5481				qinpos, ahc->qinfifo[qinpos]);
5482			panic("Loop 1\n");
5483		}
5484
5485		if (ahc_match_scb(ahc, scb, target, channel, lun, tag, role)) {
5486			/*
5487			 * We found an scb that needs to be acted on.
5488			 */
5489			found++;
5490			switch (action) {
5491			case SEARCH_COMPLETE:
5492			{
5493				cam_status ostat;
5494				cam_status cstat;
5495
5496				ostat = aic_get_transaction_status(scb);
5497				if (ostat == CAM_REQ_INPROG)
5498					aic_set_transaction_status(scb, status);
5499				cstat = aic_get_transaction_status(scb);
5500				if (cstat != CAM_REQ_CMP)
5501					aic_freeze_scb(scb);
5502				if ((scb->flags & SCB_ACTIVE) == 0)
5503					printf("Inactive SCB in qinfifo\n");
5504				ahc_done(ahc, scb);
5505
5506				/* FALLTHROUGH */
5507			}
5508			case SEARCH_REMOVE:
5509				break;
5510			case SEARCH_COUNT:
5511				ahc_qinfifo_requeue(ahc, prev_scb, scb);
5512				prev_scb = scb;
5513				break;
5514			}
5515		} else {
5516			ahc_qinfifo_requeue(ahc, prev_scb, scb);
5517			prev_scb = scb;
5518		}
5519		qinpos++;
5520	}
5521
5522	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5523		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5524	} else {
5525		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5526	}
5527
5528	if (action != SEARCH_COUNT
5529	 && (found != 0)
5530	 && (qinstart != ahc->qinfifonext)) {
5531		/*
5532		 * The sequencer may be in the process of dmaing
5533		 * down the SCB at the beginning of the queue.
5534		 * This could be problematic if either the first,
5535		 * or the second SCB is removed from the queue
5536		 * (the first SCB includes a pointer to the "next"
5537		 * SCB to dma). If we have removed any entries, swap
5538		 * the first element in the queue with the next HSCB
5539		 * so the sequencer will notice that NEXT_QUEUED_SCB
5540		 * has changed during its dma attempt and will retry
5541		 * the DMA.
5542		 */
5543		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinstart]);
5544
5545		if (scb == NULL) {
5546			printf("found = %d, qinstart = %d, qinfifionext = %d\n",
5547				found, qinstart, ahc->qinfifonext);
5548			panic("First/Second Qinfifo fixup\n");
5549		}
5550		/*
5551		 * ahc_swap_with_next_hscb forces our next pointer to
5552		 * point to the reserved SCB for future commands.  Save
5553		 * and restore our original next pointer to maintain
5554		 * queue integrity.
5555		 */
5556		next = scb->hscb->next;
5557		ahc->scb_data->scbindex[scb->hscb->tag] = NULL;
5558		ahc_swap_with_next_hscb(ahc, scb);
5559		scb->hscb->next = next;
5560		ahc->qinfifo[qinstart] = scb->hscb->tag;
5561
5562		/* Tell the card about the new head of the qinfifo. */
5563		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5564
5565		/* Fixup the tail "next" pointer. */
5566		qintail = ahc->qinfifonext - 1;
5567		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qintail]);
5568		scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5569	}
5570
5571	/*
5572	 * Search waiting for selection list.
5573	 */
5574	curscbptr = ahc_inb(ahc, SCBPTR);
5575	next = ahc_inb(ahc, WAITING_SCBH);  /* Start at head of list. */
5576	prev = SCB_LIST_NULL;
5577
5578	while (next != SCB_LIST_NULL) {
5579		uint8_t scb_index;
5580
5581		ahc_outb(ahc, SCBPTR, next);
5582		scb_index = ahc_inb(ahc, SCB_TAG);
5583		if (scb_index >= ahc->scb_data->numscbs) {
5584			printf("Waiting List inconsistency. "
5585			       "SCB index == %d, yet numscbs == %d.",
5586			       scb_index, ahc->scb_data->numscbs);
5587			ahc_dump_card_state(ahc);
5588			panic("for safety");
5589		}
5590		scb = ahc_lookup_scb(ahc, scb_index);
5591		if (scb == NULL) {
5592			printf("scb_index = %d, next = %d\n",
5593				scb_index, next);
5594			panic("Waiting List traversal\n");
5595		}
5596		if (ahc_match_scb(ahc, scb, target, channel,
5597				  lun, SCB_LIST_NULL, role)) {
5598			/*
5599			 * We found an scb that needs to be acted on.
5600			 */
5601			found++;
5602			switch (action) {
5603			case SEARCH_COMPLETE:
5604			{
5605				cam_status ostat;
5606				cam_status cstat;
5607
5608				ostat = aic_get_transaction_status(scb);
5609				if (ostat == CAM_REQ_INPROG)
5610					aic_set_transaction_status(scb,
5611								   status);
5612				cstat = aic_get_transaction_status(scb);
5613				if (cstat != CAM_REQ_CMP)
5614					aic_freeze_scb(scb);
5615				if ((scb->flags & SCB_ACTIVE) == 0)
5616					printf("Inactive SCB in Wait List\n");
5617				ahc_done(ahc, scb);
5618				/* FALLTHROUGH */
5619			}
5620			case SEARCH_REMOVE:
5621				next = ahc_rem_wscb(ahc, next, prev);
5622				break;
5623			case SEARCH_COUNT:
5624				prev = next;
5625				next = ahc_inb(ahc, SCB_NEXT);
5626				break;
5627			}
5628		} else {
5629
5630			prev = next;
5631			next = ahc_inb(ahc, SCB_NEXT);
5632		}
5633	}
5634	ahc_outb(ahc, SCBPTR, curscbptr);
5635
5636	found += ahc_search_untagged_queues(ahc, /*aic_io_ctx_t*/NULL, target,
5637					    channel, lun, status, action);
5638
5639	if (action == SEARCH_COMPLETE)
5640		ahc_release_untagged_queues(ahc);
5641	return (found);
5642}
5643
5644int
5645ahc_search_untagged_queues(struct ahc_softc *ahc, aic_io_ctx_t ctx,
5646			   int target, char channel, int lun, uint32_t status,
5647			   ahc_search_action action)
5648{
5649	struct	scb *scb;
5650	int	maxtarget;
5651	int	found;
5652	int	i;
5653
5654	if (action == SEARCH_COMPLETE) {
5655		/*
5656		 * Don't attempt to run any queued untagged transactions
5657		 * until we are done with the abort process.
5658		 */
5659		ahc_freeze_untagged_queues(ahc);
5660	}
5661
5662	found = 0;
5663	i = 0;
5664	if ((ahc->flags & AHC_SCB_BTT) == 0) {
5665
5666		maxtarget = 16;
5667		if (target != CAM_TARGET_WILDCARD) {
5668
5669			i = target;
5670			if (channel == 'B')
5671				i += 8;
5672			maxtarget = i + 1;
5673		}
5674	} else {
5675		maxtarget = 0;
5676	}
5677
5678	for (; i < maxtarget; i++) {
5679		struct scb_tailq *untagged_q;
5680		struct scb *next_scb;
5681
5682		untagged_q = &(ahc->untagged_queues[i]);
5683		next_scb = TAILQ_FIRST(untagged_q);
5684		while (next_scb != NULL) {
5685
5686			scb = next_scb;
5687			next_scb = TAILQ_NEXT(scb, links.tqe);
5688
5689			/*
5690			 * The head of the list may be the currently
5691			 * active untagged command for a device.
5692			 * We're only searching for commands that
5693			 * have not been started.  A transaction
5694			 * marked active but still in the qinfifo
5695			 * is removed by the qinfifo scanning code
5696			 * above.
5697			 */
5698			if ((scb->flags & SCB_ACTIVE) != 0)
5699				continue;
5700
5701			if (ahc_match_scb(ahc, scb, target, channel, lun,
5702					  SCB_LIST_NULL, ROLE_INITIATOR) == 0
5703			 || (ctx != NULL && ctx != scb->io_ctx))
5704				continue;
5705
5706			/*
5707			 * We found an scb that needs to be acted on.
5708			 */
5709			found++;
5710			switch (action) {
5711			case SEARCH_COMPLETE:
5712			{
5713				cam_status ostat;
5714				cam_status cstat;
5715
5716				ostat = aic_get_transaction_status(scb);
5717				if (ostat == CAM_REQ_INPROG)
5718					aic_set_transaction_status(scb, status);
5719				cstat = aic_get_transaction_status(scb);
5720				if (cstat != CAM_REQ_CMP)
5721					aic_freeze_scb(scb);
5722				ahc_done(ahc, scb);
5723				break;
5724			}
5725			case SEARCH_REMOVE:
5726				scb->flags &= ~SCB_UNTAGGEDQ;
5727				TAILQ_REMOVE(untagged_q, scb, links.tqe);
5728				break;
5729			case SEARCH_COUNT:
5730				break;
5731			}
5732		}
5733	}
5734
5735	if (action == SEARCH_COMPLETE)
5736		ahc_release_untagged_queues(ahc);
5737	return (found);
5738}
5739
5740int
5741ahc_search_disc_list(struct ahc_softc *ahc, int target, char channel,
5742		     int lun, u_int tag, int stop_on_first, int remove,
5743		     int save_state)
5744{
5745	struct	scb *scbp;
5746	u_int	next;
5747	u_int	prev;
5748	u_int	count;
5749	u_int	active_scb;
5750
5751	count = 0;
5752	next = ahc_inb(ahc, DISCONNECTED_SCBH);
5753	prev = SCB_LIST_NULL;
5754
5755	if (save_state) {
5756		/* restore this when we're done */
5757		active_scb = ahc_inb(ahc, SCBPTR);
5758	} else
5759		/* Silence compiler */
5760		active_scb = SCB_LIST_NULL;
5761
5762	while (next != SCB_LIST_NULL) {
5763		u_int scb_index;
5764
5765		ahc_outb(ahc, SCBPTR, next);
5766		scb_index = ahc_inb(ahc, SCB_TAG);
5767		if (scb_index >= ahc->scb_data->numscbs) {
5768			printf("Disconnected List inconsistency. "
5769			       "SCB index == %d, yet numscbs == %d.",
5770			       scb_index, ahc->scb_data->numscbs);
5771			ahc_dump_card_state(ahc);
5772			panic("for safety");
5773		}
5774
5775		if (next == prev) {
5776			panic("Disconnected List Loop. "
5777			      "cur SCBPTR == %x, prev SCBPTR == %x.",
5778			      next, prev);
5779		}
5780		scbp = ahc_lookup_scb(ahc, scb_index);
5781		if (ahc_match_scb(ahc, scbp, target, channel, lun,
5782				  tag, ROLE_INITIATOR)) {
5783			count++;
5784			if (remove) {
5785				next =
5786				    ahc_rem_scb_from_disc_list(ahc, prev, next);
5787			} else {
5788				prev = next;
5789				next = ahc_inb(ahc, SCB_NEXT);
5790			}
5791			if (stop_on_first)
5792				break;
5793		} else {
5794			prev = next;
5795			next = ahc_inb(ahc, SCB_NEXT);
5796		}
5797	}
5798	if (save_state)
5799		ahc_outb(ahc, SCBPTR, active_scb);
5800	return (count);
5801}
5802
5803/*
5804 * Remove an SCB from the on chip list of disconnected transactions.
5805 * This is empty/unused if we are not performing SCB paging.
5806 */
5807static u_int
5808ahc_rem_scb_from_disc_list(struct ahc_softc *ahc, u_int prev, u_int scbptr)
5809{
5810	u_int next;
5811
5812	ahc_outb(ahc, SCBPTR, scbptr);
5813	next = ahc_inb(ahc, SCB_NEXT);
5814
5815	ahc_outb(ahc, SCB_CONTROL, 0);
5816
5817	ahc_add_curscb_to_free_list(ahc);
5818
5819	if (prev != SCB_LIST_NULL) {
5820		ahc_outb(ahc, SCBPTR, prev);
5821		ahc_outb(ahc, SCB_NEXT, next);
5822	} else
5823		ahc_outb(ahc, DISCONNECTED_SCBH, next);
5824
5825	return (next);
5826}
5827
5828/*
5829 * Add the SCB as selected by SCBPTR onto the on chip list of
5830 * free hardware SCBs.  This list is empty/unused if we are not
5831 * performing SCB paging.
5832 */
5833static void
5834ahc_add_curscb_to_free_list(struct ahc_softc *ahc)
5835{
5836	/*
5837	 * Invalidate the tag so that our abort
5838	 * routines don't think it's active.
5839	 */
5840	ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
5841
5842	if ((ahc->flags & AHC_PAGESCBS) != 0) {
5843		ahc_outb(ahc, SCB_NEXT, ahc_inb(ahc, FREE_SCBH));
5844		ahc_outb(ahc, FREE_SCBH, ahc_inb(ahc, SCBPTR));
5845	}
5846}
5847
5848/*
5849 * Manipulate the waiting for selection list and return the
5850 * scb that follows the one that we remove.
5851 */
5852static u_int
5853ahc_rem_wscb(struct ahc_softc *ahc, u_int scbpos, u_int prev)
5854{
5855	u_int curscb, next;
5856
5857	/*
5858	 * Select the SCB we want to abort and
5859	 * pull the next pointer out of it.
5860	 */
5861	curscb = ahc_inb(ahc, SCBPTR);
5862	ahc_outb(ahc, SCBPTR, scbpos);
5863	next = ahc_inb(ahc, SCB_NEXT);
5864
5865	/* Clear the necessary fields */
5866	ahc_outb(ahc, SCB_CONTROL, 0);
5867
5868	ahc_add_curscb_to_free_list(ahc);
5869
5870	/* update the waiting list */
5871	if (prev == SCB_LIST_NULL) {
5872		/* First in the list */
5873		ahc_outb(ahc, WAITING_SCBH, next);
5874
5875		/*
5876		 * Ensure we aren't attempting to perform
5877		 * selection for this entry.
5878		 */
5879		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
5880	} else {
5881		/*
5882		 * Select the scb that pointed to us
5883		 * and update its next pointer.
5884		 */
5885		ahc_outb(ahc, SCBPTR, prev);
5886		ahc_outb(ahc, SCB_NEXT, next);
5887	}
5888
5889	/*
5890	 * Point us back at the original scb position.
5891	 */
5892	ahc_outb(ahc, SCBPTR, curscb);
5893	return next;
5894}
5895
5896/******************************** Error Handling ******************************/
5897/*
5898 * Abort all SCBs that match the given description (target/channel/lun/tag),
5899 * setting their status to the passed in status if the status has not already
5900 * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
5901 * is paused before it is called.
5902 */
5903int
5904ahc_abort_scbs(struct ahc_softc *ahc, int target, char channel,
5905	       int lun, u_int tag, role_t role, uint32_t status)
5906{
5907	struct	scb *scbp;
5908	struct	scb *scbp_next;
5909	u_int	active_scb;
5910	int	i, j;
5911	int	maxtarget;
5912	int	minlun;
5913	int	maxlun;
5914
5915	int	found;
5916
5917	/*
5918	 * Don't attempt to run any queued untagged transactions
5919	 * until we are done with the abort process.
5920	 */
5921	ahc_freeze_untagged_queues(ahc);
5922
5923	/* restore this when we're done */
5924	active_scb = ahc_inb(ahc, SCBPTR);
5925
5926	found = ahc_search_qinfifo(ahc, target, channel, lun, SCB_LIST_NULL,
5927				   role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5928
5929	/*
5930	 * Clean out the busy target table for any untagged commands.
5931	 */
5932	i = 0;
5933	maxtarget = 16;
5934	if (target != CAM_TARGET_WILDCARD) {
5935		i = target;
5936		if (channel == 'B')
5937			i += 8;
5938		maxtarget = i + 1;
5939	}
5940
5941	if (lun == CAM_LUN_WILDCARD) {
5942
5943		/*
5944		 * Unless we are using an SCB based
5945		 * busy targets table, there is only
5946		 * one table entry for all luns of
5947		 * a target.
5948		 */
5949		minlun = 0;
5950		maxlun = 1;
5951		if ((ahc->flags & AHC_SCB_BTT) != 0)
5952			maxlun = AHC_NUM_LUNS;
5953	} else {
5954		minlun = lun;
5955		maxlun = lun + 1;
5956	}
5957
5958	if (role != ROLE_TARGET) {
5959		for (;i < maxtarget; i++) {
5960			for (j = minlun;j < maxlun; j++) {
5961				u_int scbid;
5962				u_int tcl;
5963
5964				tcl = BUILD_TCL(i << 4, j);
5965				scbid = ahc_index_busy_tcl(ahc, tcl);
5966				scbp = ahc_lookup_scb(ahc, scbid);
5967				if (scbp == NULL
5968				 || ahc_match_scb(ahc, scbp, target, channel,
5969						  lun, tag, role) == 0)
5970					continue;
5971				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, j));
5972			}
5973		}
5974
5975		/*
5976		 * Go through the disconnected list and remove any entries we
5977		 * have queued for completion, 0'ing their control byte too.
5978		 * We save the active SCB and restore it ourselves, so there
5979		 * is no reason for this search to restore it too.
5980		 */
5981		ahc_search_disc_list(ahc, target, channel, lun, tag,
5982				     /*stop_on_first*/FALSE, /*remove*/TRUE,
5983				     /*save_state*/FALSE);
5984	}
5985
5986	/*
5987	 * Go through the hardware SCB array looking for commands that
5988	 * were active but not on any list.  In some cases, these remnants
5989	 * might not still have mappings in the scbindex array (e.g. unexpected
5990	 * bus free with the same scb queued for an abort).  Don't hold this
5991	 * against them.
5992	 */
5993	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
5994		u_int scbid;
5995
5996		ahc_outb(ahc, SCBPTR, i);
5997		scbid = ahc_inb(ahc, SCB_TAG);
5998		scbp = ahc_lookup_scb(ahc, scbid);
5999		if ((scbp == NULL && scbid != SCB_LIST_NULL)
6000		 || (scbp != NULL
6001		  && ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)))
6002			ahc_add_curscb_to_free_list(ahc);
6003	}
6004
6005	/*
6006	 * Go through the pending CCB list and look for
6007	 * commands for this target that are still active.
6008	 * These are other tagged commands that were
6009	 * disconnected when the reset occurred.
6010	 */
6011	scbp_next = LIST_FIRST(&ahc->pending_scbs);
6012	while (scbp_next != NULL) {
6013		scbp = scbp_next;
6014		scbp_next = LIST_NEXT(scbp, pending_links);
6015		if (ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)) {
6016			cam_status ostat;
6017
6018			ostat = aic_get_transaction_status(scbp);
6019			if (ostat == CAM_REQ_INPROG)
6020				aic_set_transaction_status(scbp, status);
6021			if (aic_get_transaction_status(scbp) != CAM_REQ_CMP)
6022				aic_freeze_scb(scbp);
6023			if ((scbp->flags & SCB_ACTIVE) == 0)
6024				printf("Inactive SCB on pending list\n");
6025			ahc_done(ahc, scbp);
6026			found++;
6027		}
6028	}
6029	ahc_outb(ahc, SCBPTR, active_scb);
6030	ahc_platform_abort_scbs(ahc, target, channel, lun, tag, role, status);
6031	ahc_release_untagged_queues(ahc);
6032	return found;
6033}
6034
6035static void
6036ahc_reset_current_bus(struct ahc_softc *ahc)
6037{
6038	uint8_t scsiseq;
6039
6040	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENSCSIRST);
6041	scsiseq = ahc_inb(ahc, SCSISEQ);
6042	ahc_outb(ahc, SCSISEQ, scsiseq | SCSIRSTO);
6043	ahc_flush_device_writes(ahc);
6044	aic_delay(AHC_BUSRESET_DELAY);
6045	/* Turn off the bus reset */
6046	ahc_outb(ahc, SCSISEQ, scsiseq & ~SCSIRSTO);
6047
6048	ahc_clear_intstat(ahc);
6049
6050	/* Re-enable reset interrupts */
6051	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) | ENSCSIRST);
6052}
6053
6054int
6055ahc_reset_channel(struct ahc_softc *ahc, char channel, int initiate_reset)
6056{
6057	struct	ahc_devinfo devinfo;
6058	u_int	initiator, target, max_scsiid;
6059	u_int	sblkctl;
6060	u_int	scsiseq;
6061	u_int	simode1;
6062	int	found;
6063	int	restart_needed;
6064	char	cur_channel;
6065
6066	ahc->pending_device = NULL;
6067
6068	ahc_compile_devinfo(&devinfo,
6069			    CAM_TARGET_WILDCARD,
6070			    CAM_TARGET_WILDCARD,
6071			    CAM_LUN_WILDCARD,
6072			    channel, ROLE_UNKNOWN);
6073	ahc_pause(ahc);
6074
6075	/* Make sure the sequencer is in a safe location. */
6076	ahc_clear_critical_section(ahc);
6077
6078	/*
6079	 * Run our command complete fifos to ensure that we perform
6080	 * completion processing on any commands that 'completed'
6081	 * before the reset occurred.
6082	 */
6083	ahc_run_qoutfifo(ahc);
6084#ifdef AHC_TARGET_MODE
6085	/*
6086	 * XXX - In Twin mode, the tqinfifo may have commands
6087	 *	 for an unaffected channel in it.  However, if
6088	 *	 we have run out of ATIO resources to drain that
6089	 *	 queue, we may not get them all out here.  Further,
6090	 *	 the blocked transactions for the reset channel
6091	 *	 should just be killed off, irrespecitve of whether
6092	 *	 we are blocked on ATIO resources.  Write a routine
6093	 *	 to compact the tqinfifo appropriately.
6094	 */
6095	if ((ahc->flags & AHC_TARGETROLE) != 0) {
6096		ahc_run_tqinfifo(ahc, /*paused*/TRUE);
6097	}
6098#endif
6099
6100	/*
6101	 * Reset the bus if we are initiating this reset
6102	 */
6103	sblkctl = ahc_inb(ahc, SBLKCTL);
6104	cur_channel = 'A';
6105	if ((ahc->features & AHC_TWIN) != 0
6106	 && ((sblkctl & SELBUSB) != 0))
6107	    cur_channel = 'B';
6108	scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
6109	if (cur_channel != channel) {
6110		/* Case 1: Command for another bus is active
6111		 * Stealthily reset the other bus without
6112		 * upsetting the current bus.
6113		 */
6114		ahc_outb(ahc, SBLKCTL, sblkctl ^ SELBUSB);
6115		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
6116#ifdef AHC_TARGET_MODE
6117		/*
6118		 * Bus resets clear ENSELI, so we cannot
6119		 * defer re-enabling bus reset interrupts
6120		 * if we are in target mode.
6121		 */
6122		if ((ahc->flags & AHC_TARGETROLE) != 0)
6123			simode1 |= ENSCSIRST;
6124#endif
6125		ahc_outb(ahc, SIMODE1, simode1);
6126		if (initiate_reset)
6127			ahc_reset_current_bus(ahc);
6128		ahc_clear_intstat(ahc);
6129		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
6130		ahc_outb(ahc, SBLKCTL, sblkctl);
6131		restart_needed = FALSE;
6132	} else {
6133		/* Case 2: A command from this bus is active or we're idle */
6134		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
6135#ifdef AHC_TARGET_MODE
6136		/*
6137		 * Bus resets clear ENSELI, so we cannot
6138		 * defer re-enabling bus reset interrupts
6139		 * if we are in target mode.
6140		 */
6141		if ((ahc->flags & AHC_TARGETROLE) != 0)
6142			simode1 |= ENSCSIRST;
6143#endif
6144		ahc_outb(ahc, SIMODE1, simode1);
6145		if (initiate_reset)
6146			ahc_reset_current_bus(ahc);
6147		ahc_clear_intstat(ahc);
6148		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
6149		restart_needed = TRUE;
6150	}
6151
6152	/*
6153	 * Clean up all the state information for the
6154	 * pending transactions on this bus.
6155	 */
6156	found = ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, channel,
6157			       CAM_LUN_WILDCARD, SCB_LIST_NULL,
6158			       ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
6159
6160	max_scsiid = (ahc->features & AHC_WIDE) ? 15 : 7;
6161
6162#ifdef AHC_TARGET_MODE
6163	/*
6164	 * Send an immediate notify ccb to all target more peripheral
6165	 * drivers affected by this action.
6166	 */
6167	for (target = 0; target <= max_scsiid; target++) {
6168		struct ahc_tmode_tstate* tstate;
6169		u_int lun;
6170
6171		tstate = ahc->enabled_targets[target];
6172		if (tstate == NULL)
6173			continue;
6174		for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
6175			struct ahc_tmode_lstate* lstate;
6176
6177			lstate = tstate->enabled_luns[lun];
6178			if (lstate == NULL)
6179				continue;
6180
6181			ahc_queue_lstate_event(ahc, lstate, CAM_TARGET_WILDCARD,
6182					       EVENT_TYPE_BUS_RESET, /*arg*/0);
6183			ahc_send_lstate_events(ahc, lstate);
6184		}
6185	}
6186#endif
6187	/* Notify the XPT that a bus reset occurred */
6188	ahc_send_async(ahc, devinfo.channel, CAM_TARGET_WILDCARD,
6189		       CAM_LUN_WILDCARD, AC_BUS_RESET, NULL);
6190
6191	/*
6192	 * Revert to async/narrow transfers until we renegotiate.
6193	 */
6194	for (target = 0; target <= max_scsiid; target++) {
6195
6196		if (ahc->enabled_targets[target] == NULL)
6197			continue;
6198		for (initiator = 0; initiator <= max_scsiid; initiator++) {
6199			struct ahc_devinfo devinfo;
6200
6201			ahc_compile_devinfo(&devinfo, target, initiator,
6202					    CAM_LUN_WILDCARD,
6203					    channel, ROLE_UNKNOWN);
6204			ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6205				      AHC_TRANS_CUR, /*paused*/TRUE);
6206			ahc_set_syncrate(ahc, &devinfo, /*syncrate*/NULL,
6207					 /*period*/0, /*offset*/0,
6208					 /*ppr_options*/0, AHC_TRANS_CUR,
6209					 /*paused*/TRUE);
6210		}
6211	}
6212
6213	if (restart_needed)
6214		ahc_restart(ahc);
6215	else
6216		ahc_unpause(ahc);
6217	return found;
6218}
6219
6220
6221/***************************** Residual Processing ****************************/
6222/*
6223 * Calculate the residual for a just completed SCB.
6224 */
6225void
6226ahc_calc_residual(struct ahc_softc *ahc, struct scb *scb)
6227{
6228	struct hardware_scb *hscb;
6229	struct status_pkt *spkt;
6230	uint32_t sgptr;
6231	uint32_t resid_sgptr;
6232	uint32_t resid;
6233
6234	/*
6235	 * 5 cases.
6236	 * 1) No residual.
6237	 *    SG_RESID_VALID clear in sgptr.
6238	 * 2) Transferless command
6239	 * 3) Never performed any transfers.
6240	 *    sgptr has SG_FULL_RESID set.
6241	 * 4) No residual but target did not
6242	 *    save data pointers after the
6243	 *    last transfer, so sgptr was
6244	 *    never updated.
6245	 * 5) We have a partial residual.
6246	 *    Use residual_sgptr to determine
6247	 *    where we are.
6248	 */
6249
6250	hscb = scb->hscb;
6251	sgptr = aic_le32toh(hscb->sgptr);
6252	if ((sgptr & SG_RESID_VALID) == 0)
6253		/* Case 1 */
6254		return;
6255	sgptr &= ~SG_RESID_VALID;
6256
6257	if ((sgptr & SG_LIST_NULL) != 0)
6258		/* Case 2 */
6259		return;
6260
6261	spkt = &hscb->shared_data.status;
6262	resid_sgptr = aic_le32toh(spkt->residual_sg_ptr);
6263	if ((sgptr & SG_FULL_RESID) != 0) {
6264		/* Case 3 */
6265		resid = aic_get_transfer_length(scb);
6266	} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
6267		/* Case 4 */
6268		return;
6269	} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
6270		panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
6271		/* NOTREACHED */
6272		return;
6273	} else {
6274		struct ahc_dma_seg *sg;
6275
6276		/*
6277		 * Remainder of the SG where the transfer
6278		 * stopped.
6279		 */
6280		resid = aic_le32toh(spkt->residual_datacnt) & AHC_SG_LEN_MASK;
6281		sg = ahc_sg_bus_to_virt(scb, resid_sgptr & SG_PTR_MASK);
6282
6283		/* The residual sg_ptr always points to the next sg */
6284		sg--;
6285
6286		/*
6287		 * Add up the contents of all residual
6288		 * SG segments that are after the SG where
6289		 * the transfer stopped.
6290		 */
6291		while ((aic_le32toh(sg->len) & AHC_DMA_LAST_SEG) == 0) {
6292			sg++;
6293			resid += aic_le32toh(sg->len) & AHC_SG_LEN_MASK;
6294		}
6295	}
6296	if ((scb->flags & SCB_SENSE) == 0)
6297		aic_set_residual(scb, resid);
6298	else
6299		aic_set_sense_residual(scb, resid);
6300
6301#ifdef AHC_DEBUG
6302	if ((ahc_debug & AHC_SHOW_MISC) != 0) {
6303		ahc_print_path(ahc, scb);
6304		printf("Handled %sResidual of %d bytes\n",
6305		       (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
6306	}
6307#endif
6308}
6309
6310/******************************* Target Mode **********************************/
6311#ifdef AHC_TARGET_MODE
6312/*
6313 * Add a target mode event to this lun's queue
6314 */
6315static void
6316ahc_queue_lstate_event(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate,
6317		       u_int initiator_id, u_int event_type, u_int event_arg)
6318{
6319	struct ahc_tmode_event *event;
6320	int pending;
6321
6322	xpt_freeze_devq(lstate->path, /*count*/1);
6323	if (lstate->event_w_idx >= lstate->event_r_idx)
6324		pending = lstate->event_w_idx - lstate->event_r_idx;
6325	else
6326		pending = AHC_TMODE_EVENT_BUFFER_SIZE + 1
6327			- (lstate->event_r_idx - lstate->event_w_idx);
6328
6329	if (event_type == EVENT_TYPE_BUS_RESET
6330	 || event_type == MSG_BUS_DEV_RESET) {
6331		/*
6332		 * Any earlier events are irrelevant, so reset our buffer.
6333		 * This has the effect of allowing us to deal with reset
6334		 * floods (an external device holding down the reset line)
6335		 * without losing the event that is really interesting.
6336		 */
6337		lstate->event_r_idx = 0;
6338		lstate->event_w_idx = 0;
6339		xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
6340	}
6341
6342	if (pending == AHC_TMODE_EVENT_BUFFER_SIZE) {
6343		xpt_print_path(lstate->path);
6344		printf("immediate event %x:%x lost\n",
6345		       lstate->event_buffer[lstate->event_r_idx].event_type,
6346		       lstate->event_buffer[lstate->event_r_idx].event_arg);
6347		lstate->event_r_idx++;
6348		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6349			lstate->event_r_idx = 0;
6350		xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
6351	}
6352
6353	event = &lstate->event_buffer[lstate->event_w_idx];
6354	event->initiator_id = initiator_id;
6355	event->event_type = event_type;
6356	event->event_arg = event_arg;
6357	lstate->event_w_idx++;
6358	if (lstate->event_w_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6359		lstate->event_w_idx = 0;
6360}
6361
6362/*
6363 * Send any target mode events queued up waiting
6364 * for immediate notify resources.
6365 */
6366void
6367ahc_send_lstate_events(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate)
6368{
6369	struct ccb_hdr *ccbh;
6370	struct ccb_immediate_notify *inot;
6371
6372	while (lstate->event_r_idx != lstate->event_w_idx
6373	    && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
6374		struct ahc_tmode_event *event;
6375
6376		event = &lstate->event_buffer[lstate->event_r_idx];
6377		SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
6378		inot = (struct ccb_immediate_notify *)ccbh;
6379		switch (event->event_type) {
6380		case EVENT_TYPE_BUS_RESET:
6381			ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
6382			break;
6383		default:
6384			ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
6385			inot->arg = event->event_type;
6386			inot->seq_id = event->event_arg;
6387			break;
6388		}
6389		inot->initiator_id = event->initiator_id;
6390		xpt_done((union ccb *)inot);
6391		lstate->event_r_idx++;
6392		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6393			lstate->event_r_idx = 0;
6394	}
6395}
6396#endif
6397
6398/******************** Sequencer Program Patching/Download *********************/
6399
6400#ifdef AHC_DUMP_SEQ
6401void
6402ahc_dumpseq(struct ahc_softc* ahc)
6403{
6404	int i;
6405
6406	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6407	ahc_outb(ahc, SEQADDR0, 0);
6408	ahc_outb(ahc, SEQADDR1, 0);
6409	for (i = 0; i < ahc->instruction_ram_size; i++) {
6410		uint8_t ins_bytes[4];
6411
6412		ahc_insb(ahc, SEQRAM, ins_bytes, 4);
6413		printf("0x%08x\n", ins_bytes[0] << 24
6414				 | ins_bytes[1] << 16
6415				 | ins_bytes[2] << 8
6416				 | ins_bytes[3]);
6417	}
6418}
6419#endif
6420
6421static int
6422ahc_loadseq(struct ahc_softc *ahc)
6423{
6424	struct	cs cs_table[num_critical_sections];
6425	u_int	begin_set[num_critical_sections];
6426	u_int	end_set[num_critical_sections];
6427	struct	patch *cur_patch;
6428	u_int	cs_count;
6429	u_int	cur_cs;
6430	u_int	i;
6431	u_int	skip_addr;
6432	u_int	sg_prefetch_cnt;
6433	int	downloaded;
6434	uint8_t	download_consts[7];
6435
6436	/*
6437	 * Start out with 0 critical sections
6438	 * that apply to this firmware load.
6439	 */
6440	cs_count = 0;
6441	cur_cs = 0;
6442	memset(begin_set, 0, sizeof(begin_set));
6443	memset(end_set, 0, sizeof(end_set));
6444
6445	/* Setup downloadable constant table */
6446	download_consts[QOUTFIFO_OFFSET] = 0;
6447	if (ahc->targetcmds != NULL)
6448		download_consts[QOUTFIFO_OFFSET] += 32;
6449	download_consts[QINFIFO_OFFSET] = download_consts[QOUTFIFO_OFFSET] + 1;
6450	download_consts[CACHESIZE_MASK] = ahc->pci_cachesize - 1;
6451	download_consts[INVERTED_CACHESIZE_MASK] = ~(ahc->pci_cachesize - 1);
6452	sg_prefetch_cnt = ahc->pci_cachesize;
6453	if (sg_prefetch_cnt < (2 * sizeof(struct ahc_dma_seg)))
6454		sg_prefetch_cnt = 2 * sizeof(struct ahc_dma_seg);
6455	download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
6456	download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_cnt - 1);
6457	download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_cnt - 1);
6458
6459	cur_patch = patches;
6460	downloaded = 0;
6461	skip_addr = 0;
6462	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6463	ahc_outb(ahc, SEQADDR0, 0);
6464	ahc_outb(ahc, SEQADDR1, 0);
6465
6466	for (i = 0; i < sizeof(seqprog)/4; i++) {
6467		if (ahc_check_patch(ahc, &cur_patch, i, &skip_addr) == 0) {
6468			/*
6469			 * Don't download this instruction as it
6470			 * is in a patch that was removed.
6471			 */
6472			continue;
6473		}
6474
6475		if (downloaded == ahc->instruction_ram_size) {
6476			/*
6477			 * We're about to exceed the instruction
6478			 * storage capacity for this chip.  Fail
6479			 * the load.
6480			 */
6481			printf("\n%s: Program too large for instruction memory "
6482			       "size of %d!\n", ahc_name(ahc),
6483			       ahc->instruction_ram_size);
6484			return (ENOMEM);
6485		}
6486
6487		/*
6488		 * Move through the CS table until we find a CS
6489		 * that might apply to this instruction.
6490		 */
6491		for (; cur_cs < num_critical_sections; cur_cs++) {
6492			if (critical_sections[cur_cs].end <= i) {
6493				if (begin_set[cs_count] == TRUE
6494				 && end_set[cs_count] == FALSE) {
6495					cs_table[cs_count].end = downloaded;
6496				 	end_set[cs_count] = TRUE;
6497					cs_count++;
6498				}
6499				continue;
6500			}
6501			if (critical_sections[cur_cs].begin <= i
6502			 && begin_set[cs_count] == FALSE) {
6503				cs_table[cs_count].begin = downloaded;
6504				begin_set[cs_count] = TRUE;
6505			}
6506			break;
6507		}
6508		ahc_download_instr(ahc, i, download_consts);
6509		downloaded++;
6510	}
6511
6512	ahc->num_critical_sections = cs_count;
6513	if (cs_count != 0) {
6514
6515		cs_count *= sizeof(struct cs);
6516		ahc->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
6517		if (ahc->critical_sections == NULL)
6518			panic("ahc_loadseq: Could not malloc");
6519		memcpy(ahc->critical_sections, cs_table, cs_count);
6520	}
6521	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE);
6522
6523	if (bootverbose) {
6524		printf(" %d instructions downloaded\n", downloaded);
6525		printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
6526		       ahc_name(ahc), ahc->features, ahc->bugs, ahc->flags);
6527	}
6528	return (0);
6529}
6530
6531static int
6532ahc_check_patch(struct ahc_softc *ahc, struct patch **start_patch,
6533		u_int start_instr, u_int *skip_addr)
6534{
6535	struct	patch *cur_patch;
6536	struct	patch *last_patch;
6537	u_int	num_patches;
6538
6539	num_patches = sizeof(patches)/sizeof(struct patch);
6540	last_patch = &patches[num_patches];
6541	cur_patch = *start_patch;
6542
6543	while (cur_patch < last_patch && start_instr == cur_patch->begin) {
6544
6545		if (cur_patch->patch_func(ahc) == 0) {
6546
6547			/* Start rejecting code */
6548			*skip_addr = start_instr + cur_patch->skip_instr;
6549			cur_patch += cur_patch->skip_patch;
6550		} else {
6551			/* Accepted this patch.  Advance to the next
6552			 * one and wait for our intruction pointer to
6553			 * hit this point.
6554			 */
6555			cur_patch++;
6556		}
6557	}
6558
6559	*start_patch = cur_patch;
6560	if (start_instr < *skip_addr)
6561		/* Still skipping */
6562		return (0);
6563
6564	return (1);
6565}
6566
6567static void
6568ahc_download_instr(struct ahc_softc *ahc, u_int instrptr, uint8_t *dconsts)
6569{
6570	union	ins_formats instr;
6571	struct	ins_format1 *fmt1_ins;
6572	struct	ins_format3 *fmt3_ins;
6573	u_int	opcode;
6574
6575	/*
6576	 * The firmware is always compiled into a little endian format.
6577	 */
6578	instr.integer = aic_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
6579
6580	fmt1_ins = &instr.format1;
6581	fmt3_ins = NULL;
6582
6583	/* Pull the opcode */
6584	opcode = instr.format1.opcode;
6585	switch (opcode) {
6586	case AIC_OP_JMP:
6587	case AIC_OP_JC:
6588	case AIC_OP_JNC:
6589	case AIC_OP_CALL:
6590	case AIC_OP_JNE:
6591	case AIC_OP_JNZ:
6592	case AIC_OP_JE:
6593	case AIC_OP_JZ:
6594	{
6595		struct patch *cur_patch;
6596		int address_offset;
6597		u_int address;
6598		u_int skip_addr;
6599		u_int i;
6600
6601		fmt3_ins = &instr.format3;
6602		address_offset = 0;
6603		address = fmt3_ins->address;
6604		cur_patch = patches;
6605		skip_addr = 0;
6606
6607		for (i = 0; i < address;) {
6608
6609			ahc_check_patch(ahc, &cur_patch, i, &skip_addr);
6610
6611			if (skip_addr > i) {
6612				int end_addr;
6613
6614				end_addr = MIN(address, skip_addr);
6615				address_offset += end_addr - i;
6616				i = skip_addr;
6617			} else {
6618				i++;
6619			}
6620		}
6621		address -= address_offset;
6622		fmt3_ins->address = address;
6623		/* FALLTHROUGH */
6624	}
6625	case AIC_OP_OR:
6626	case AIC_OP_AND:
6627	case AIC_OP_XOR:
6628	case AIC_OP_ADD:
6629	case AIC_OP_ADC:
6630	case AIC_OP_BMOV:
6631		if (fmt1_ins->parity != 0) {
6632			fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
6633		}
6634		fmt1_ins->parity = 0;
6635		if ((ahc->features & AHC_CMD_CHAN) == 0
6636		 && opcode == AIC_OP_BMOV) {
6637			/*
6638			 * Block move was added at the same time
6639			 * as the command channel.  Verify that
6640			 * this is only a move of a single element
6641			 * and convert the BMOV to a MOV
6642			 * (AND with an immediate of FF).
6643			 */
6644			if (fmt1_ins->immediate != 1)
6645				panic("%s: BMOV not supported\n",
6646				      ahc_name(ahc));
6647			fmt1_ins->opcode = AIC_OP_AND;
6648			fmt1_ins->immediate = 0xff;
6649		}
6650		/* FALLTHROUGH */
6651	case AIC_OP_ROL:
6652		if ((ahc->features & AHC_ULTRA2) != 0) {
6653			int i, count;
6654
6655			/* Calculate odd parity for the instruction */
6656			for (i = 0, count = 0; i < 31; i++) {
6657				uint32_t mask;
6658
6659				mask = 0x01 << i;
6660				if ((instr.integer & mask) != 0)
6661					count++;
6662			}
6663			if ((count & 0x01) == 0)
6664				instr.format1.parity = 1;
6665		} else {
6666			/* Compress the instruction for older sequencers */
6667			if (fmt3_ins != NULL) {
6668				instr.integer =
6669					fmt3_ins->immediate
6670				      | (fmt3_ins->source << 8)
6671				      | (fmt3_ins->address << 16)
6672				      |	(fmt3_ins->opcode << 25);
6673			} else {
6674				instr.integer =
6675					fmt1_ins->immediate
6676				      | (fmt1_ins->source << 8)
6677				      | (fmt1_ins->destination << 16)
6678				      |	(fmt1_ins->ret << 24)
6679				      |	(fmt1_ins->opcode << 25);
6680			}
6681		}
6682		/* The sequencer is a little endian cpu */
6683		instr.integer = aic_htole32(instr.integer);
6684		ahc_outsb(ahc, SEQRAM, instr.bytes, 4);
6685		break;
6686	default:
6687		panic("Unknown opcode encountered in seq program");
6688		break;
6689	}
6690}
6691
6692int
6693ahc_print_register(ahc_reg_parse_entry_t *table, u_int num_entries,
6694		   const char *name, u_int address, u_int value,
6695		   u_int *cur_column, u_int wrap_point)
6696{
6697	int	printed;
6698	u_int	printed_mask;
6699	u_int	dummy_column;
6700
6701	if (cur_column == NULL) {
6702		dummy_column = 0;
6703		cur_column = &dummy_column;
6704	}
6705
6706	if (*cur_column >= wrap_point) {
6707		printf("\n");
6708		*cur_column = 0;
6709	}
6710	printed = printf("%s[0x%x]", name, value);
6711	if (table == NULL) {
6712		printed += printf(" ");
6713		*cur_column += printed;
6714		return (printed);
6715	}
6716	printed_mask = 0;
6717	while (printed_mask != 0xFF) {
6718		int entry;
6719
6720		for (entry = 0; entry < num_entries; entry++) {
6721			if (((value & table[entry].mask)
6722			  != table[entry].value)
6723			 || ((printed_mask & table[entry].mask)
6724			  == table[entry].mask))
6725				continue;
6726
6727			printed += printf("%s%s",
6728					  printed_mask == 0 ? ":(" : "|",
6729					  table[entry].name);
6730			printed_mask |= table[entry].mask;
6731
6732			break;
6733		}
6734		if (entry >= num_entries)
6735			break;
6736	}
6737	if (printed_mask != 0)
6738		printed += printf(") ");
6739	else
6740		printed += printf(" ");
6741	if (cur_column != NULL)
6742		*cur_column += printed;
6743	return (printed);
6744}
6745
6746void
6747ahc_dump_card_state(struct ahc_softc *ahc)
6748{
6749	struct	scb *scb;
6750	struct	scb_tailq *untagged_q;
6751	u_int	cur_col;
6752	int	paused;
6753	int	target;
6754	int	maxtarget;
6755	int	i;
6756	uint8_t last_phase;
6757	uint8_t qinpos;
6758	uint8_t qintail;
6759	uint8_t qoutpos;
6760	uint8_t scb_index;
6761	uint8_t saved_scbptr;
6762
6763	if (ahc_is_paused(ahc)) {
6764		paused = 1;
6765	} else {
6766		paused = 0;
6767		ahc_pause(ahc);
6768	}
6769
6770	saved_scbptr = ahc_inb(ahc, SCBPTR);
6771	last_phase = ahc_inb(ahc, LASTPHASE);
6772	printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
6773	       "%s: Dumping Card State %s, at SEQADDR 0x%x\n",
6774	       ahc_name(ahc), ahc_lookup_phase_entry(last_phase)->phasemsg,
6775	       ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
6776	if (paused)
6777		printf("Card was paused\n");
6778	printf("ACCUM = 0x%x, SINDEX = 0x%x, DINDEX = 0x%x, ARG_2 = 0x%x\n",
6779	       ahc_inb(ahc, ACCUM), ahc_inb(ahc, SINDEX), ahc_inb(ahc, DINDEX),
6780	       ahc_inb(ahc, ARG_2));
6781	printf("HCNT = 0x%x SCBPTR = 0x%x\n", ahc_inb(ahc, HCNT),
6782	       ahc_inb(ahc, SCBPTR));
6783	cur_col = 0;
6784	if ((ahc->features & AHC_DT) != 0)
6785		ahc_scsiphase_print(ahc_inb(ahc, SCSIPHASE), &cur_col, 50);
6786	ahc_scsisigi_print(ahc_inb(ahc, SCSISIGI), &cur_col, 50);
6787	ahc_error_print(ahc_inb(ahc, ERROR), &cur_col, 50);
6788	ahc_scsibusl_print(ahc_inb(ahc, SCSIBUSL), &cur_col, 50);
6789	ahc_lastphase_print(ahc_inb(ahc, LASTPHASE), &cur_col, 50);
6790	ahc_scsiseq_print(ahc_inb(ahc, SCSISEQ), &cur_col, 50);
6791	ahc_sblkctl_print(ahc_inb(ahc, SBLKCTL), &cur_col, 50);
6792	ahc_scsirate_print(ahc_inb(ahc, SCSIRATE), &cur_col, 50);
6793	ahc_seqctl_print(ahc_inb(ahc, SEQCTL), &cur_col, 50);
6794	ahc_seq_flags_print(ahc_inb(ahc, SEQ_FLAGS), &cur_col, 50);
6795	ahc_sstat0_print(ahc_inb(ahc, SSTAT0), &cur_col, 50);
6796	ahc_sstat1_print(ahc_inb(ahc, SSTAT1), &cur_col, 50);
6797	ahc_sstat2_print(ahc_inb(ahc, SSTAT2), &cur_col, 50);
6798	ahc_sstat3_print(ahc_inb(ahc, SSTAT3), &cur_col, 50);
6799	ahc_simode0_print(ahc_inb(ahc, SIMODE0), &cur_col, 50);
6800	ahc_simode1_print(ahc_inb(ahc, SIMODE1), &cur_col, 50);
6801	ahc_sxfrctl0_print(ahc_inb(ahc, SXFRCTL0), &cur_col, 50);
6802	ahc_dfcntrl_print(ahc_inb(ahc, DFCNTRL), &cur_col, 50);
6803	ahc_dfstatus_print(ahc_inb(ahc, DFSTATUS), &cur_col, 50);
6804	if (cur_col != 0)
6805		printf("\n");
6806	printf("STACK:");
6807	for (i = 0; i < STACK_SIZE; i++)
6808	       printf(" 0x%x", ahc_inb(ahc, STACK)|(ahc_inb(ahc, STACK) << 8));
6809	printf("\nSCB count = %d\n", ahc->scb_data->numscbs);
6810	printf("Kernel NEXTQSCB = %d\n", ahc->next_queued_scb->hscb->tag);
6811	printf("Card NEXTQSCB = %d\n", ahc_inb(ahc, NEXT_QUEUED_SCB));
6812	/* QINFIFO */
6813	printf("QINFIFO entries: ");
6814	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
6815		qinpos = ahc_inb(ahc, SNSCB_QOFF);
6816		ahc_outb(ahc, SNSCB_QOFF, qinpos);
6817	} else
6818		qinpos = ahc_inb(ahc, QINPOS);
6819	qintail = ahc->qinfifonext;
6820	while (qinpos != qintail) {
6821		printf("%d ", ahc->qinfifo[qinpos]);
6822		qinpos++;
6823	}
6824	printf("\n");
6825
6826	printf("Waiting Queue entries: ");
6827	scb_index = ahc_inb(ahc, WAITING_SCBH);
6828	i = 0;
6829	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6830		ahc_outb(ahc, SCBPTR, scb_index);
6831		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6832		scb_index = ahc_inb(ahc, SCB_NEXT);
6833	}
6834	printf("\n");
6835
6836	printf("Disconnected Queue entries: ");
6837	scb_index = ahc_inb(ahc, DISCONNECTED_SCBH);
6838	i = 0;
6839	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6840		ahc_outb(ahc, SCBPTR, scb_index);
6841		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6842		scb_index = ahc_inb(ahc, SCB_NEXT);
6843	}
6844	printf("\n");
6845
6846	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
6847	printf("QOUTFIFO entries: ");
6848	qoutpos = ahc->qoutfifonext;
6849	i = 0;
6850	while (ahc->qoutfifo[qoutpos] != SCB_LIST_NULL && i++ < 256) {
6851		printf("%d ", ahc->qoutfifo[qoutpos]);
6852		qoutpos++;
6853	}
6854	printf("\n");
6855
6856	printf("Sequencer Free SCB List: ");
6857	scb_index = ahc_inb(ahc, FREE_SCBH);
6858	i = 0;
6859	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6860		ahc_outb(ahc, SCBPTR, scb_index);
6861		printf("%d ", scb_index);
6862		scb_index = ahc_inb(ahc, SCB_NEXT);
6863	}
6864	printf("\n");
6865
6866	printf("Sequencer SCB Info: ");
6867	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
6868		ahc_outb(ahc, SCBPTR, i);
6869		cur_col = printf("\n%3d ", i);
6870
6871		ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL), &cur_col, 60);
6872		ahc_scb_scsiid_print(ahc_inb(ahc, SCB_SCSIID), &cur_col, 60);
6873		ahc_scb_lun_print(ahc_inb(ahc, SCB_LUN), &cur_col, 60);
6874		ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6875	}
6876	printf("\n");
6877
6878	printf("Pending list: ");
6879	i = 0;
6880	LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
6881		if (i++ > 256)
6882			break;
6883		cur_col = printf("\n%3d ", scb->hscb->tag);
6884		ahc_scb_control_print(scb->hscb->control, &cur_col, 60);
6885		ahc_scb_scsiid_print(scb->hscb->scsiid, &cur_col, 60);
6886		ahc_scb_lun_print(scb->hscb->lun, &cur_col, 60);
6887		if ((ahc->flags & AHC_PAGESCBS) == 0) {
6888			ahc_outb(ahc, SCBPTR, scb->hscb->tag);
6889			printf("(");
6890			ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL),
6891					      &cur_col, 60);
6892			ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6893			printf(")");
6894		}
6895	}
6896	printf("\n");
6897
6898	printf("Kernel Free SCB list: ");
6899	i = 0;
6900	SLIST_FOREACH(scb, &ahc->scb_data->free_scbs, links.sle) {
6901		if (i++ > 256)
6902			break;
6903		printf("%d ", scb->hscb->tag);
6904	}
6905	printf("\n");
6906
6907	maxtarget = (ahc->features & (AHC_WIDE|AHC_TWIN)) ? 15 : 7;
6908	for (target = 0; target <= maxtarget; target++) {
6909		untagged_q = &ahc->untagged_queues[target];
6910		if (TAILQ_FIRST(untagged_q) == NULL)
6911			continue;
6912		printf("Untagged Q(%d): ", target);
6913		i = 0;
6914		TAILQ_FOREACH(scb, untagged_q, links.tqe) {
6915			if (i++ > 256)
6916				break;
6917			printf("%d ", scb->hscb->tag);
6918		}
6919		printf("\n");
6920	}
6921
6922	ahc_platform_dump_card_state(ahc);
6923	printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
6924	ahc_outb(ahc, SCBPTR, saved_scbptr);
6925	if (paused == 0)
6926		ahc_unpause(ahc);
6927}
6928
6929/*************************** Timeout Handling *********************************/
6930void
6931ahc_timeout(struct scb *scb)
6932{
6933	struct ahc_softc *ahc;
6934
6935	ahc = scb->ahc_softc;
6936	if ((scb->flags & SCB_ACTIVE) != 0) {
6937		if ((scb->flags & SCB_TIMEDOUT) == 0) {
6938			LIST_INSERT_HEAD(&ahc->timedout_scbs, scb,
6939					 timedout_links);
6940			scb->flags |= SCB_TIMEDOUT;
6941		}
6942		ahc_wakeup_recovery_thread(ahc);
6943	}
6944}
6945
6946/*
6947 * Re-schedule a timeout for the passed in SCB if we determine that some
6948 * other SCB is in the process of recovery or an SCB with a longer
6949 * timeout is still pending.  Limit our search to just "other_scb"
6950 * if it is non-NULL.
6951 */
6952static int
6953ahc_other_scb_timeout(struct ahc_softc *ahc, struct scb *scb,
6954		      struct scb *other_scb)
6955{
6956	u_int	newtimeout;
6957	int	found;
6958
6959	ahc_print_path(ahc, scb);
6960	printf("Other SCB Timeout%s",
6961 	       (scb->flags & SCB_OTHERTCL_TIMEOUT) != 0
6962	       ? " again\n" : "\n");
6963
6964	newtimeout = aic_get_timeout(scb);
6965	scb->flags |= SCB_OTHERTCL_TIMEOUT;
6966	found = 0;
6967	if (other_scb != NULL) {
6968		if ((other_scb->flags
6969		   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
6970		 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
6971			found++;
6972			newtimeout = MAX(aic_get_timeout(other_scb),
6973					 newtimeout);
6974		}
6975	} else {
6976		LIST_FOREACH(other_scb, &ahc->pending_scbs, pending_links) {
6977			if ((other_scb->flags
6978			   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
6979			 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
6980				found++;
6981				newtimeout =
6982				    MAX(aic_get_timeout(other_scb),
6983					newtimeout);
6984			}
6985		}
6986	}
6987
6988	if (found != 0)
6989		aic_scb_timer_reset(scb, newtimeout);
6990	else {
6991		ahc_print_path(ahc, scb);
6992		printf("No other SCB worth waiting for...\n");
6993	}
6994
6995	return (found != 0);
6996}
6997
6998/*
6999 * ahc_recover_commands determines if any of the commands that have currently
7000 * timedout are the root cause for this timeout.  Innocent commands are given
7001 * a new timeout while we wait for the command executing on the bus to timeout.
7002 * This routine is invoked from a thread context so we are allowed to sleep.
7003 * Our lock is not held on entry.
7004 */
7005void
7006ahc_recover_commands(struct ahc_softc *ahc)
7007{
7008	struct	scb *scb;
7009	int	found;
7010	int	restart_needed;
7011	u_int	last_phase;
7012
7013	/*
7014	 * Pause the controller and manually flush any
7015	 * commands that have just completed but that our
7016	 * interrupt handler has yet to see.
7017	 */
7018	ahc_pause_and_flushwork(ahc);
7019
7020	if (LIST_EMPTY(&ahc->timedout_scbs) != 0) {
7021		/*
7022		 * The timedout commands have already
7023		 * completed.  This typically means
7024		 * that either the timeout value was on
7025		 * the hairy edge of what the device
7026		 * requires or - more likely - interrupts
7027		 * are not happening.
7028		 */
7029		printf("%s: Timedout SCBs already complete. "
7030		       "Interrupts may not be functioning.\n", ahc_name(ahc));
7031		ahc_unpause(ahc);
7032		return;
7033	}
7034
7035	restart_needed = 0;
7036	printf("%s: Recovery Initiated\n", ahc_name(ahc));
7037	ahc_dump_card_state(ahc);
7038
7039	last_phase = ahc_inb(ahc, LASTPHASE);
7040	while ((scb = LIST_FIRST(&ahc->timedout_scbs)) != NULL) {
7041		u_int	active_scb_index;
7042		u_int	saved_scbptr;
7043		int	target;
7044		int	lun;
7045		int	i;
7046		char	channel;
7047
7048		target = SCB_GET_TARGET(ahc, scb);
7049		channel = SCB_GET_CHANNEL(ahc, scb);
7050		lun = SCB_GET_LUN(scb);
7051
7052		ahc_print_path(ahc, scb);
7053		printf("SCB 0x%x - timed out\n", scb->hscb->tag);
7054		if (scb->sg_count > 0) {
7055			for (i = 0; i < scb->sg_count; i++) {
7056				printf("sg[%d] - Addr 0x%x : Length %d\n",
7057				       i,
7058				       scb->sg_list[i].addr,
7059				       scb->sg_list[i].len & AHC_SG_LEN_MASK);
7060			}
7061		}
7062		if (scb->flags & (SCB_DEVICE_RESET|SCB_ABORT)) {
7063			/*
7064			 * Been down this road before.
7065			 * Do a full bus reset.
7066			 */
7067			aic_set_transaction_status(scb, CAM_CMD_TIMEOUT);
7068bus_reset:
7069			found = ahc_reset_channel(ahc, channel,
7070						  /*Initiate Reset*/TRUE);
7071			printf("%s: Issued Channel %c Bus Reset. "
7072			       "%d SCBs aborted\n", ahc_name(ahc), channel,
7073			       found);
7074			continue;
7075		}
7076
7077		/*
7078		 * Remove the command from the timedout list in
7079		 * preparation for requeing it.
7080		 */
7081		LIST_REMOVE(scb, timedout_links);
7082		scb->flags &= ~SCB_TIMEDOUT;
7083
7084		/*
7085		 * If we are a target, transition to bus free and report
7086		 * the timeout.
7087		 *
7088		 * The target/initiator that is holding up the bus may not
7089		 * be the same as the one that triggered this timeout
7090		 * (different commands have different timeout lengths).
7091		 * If the bus is idle and we are actiing as the initiator
7092		 * for this request, queue a BDR message to the timed out
7093		 * target.  Otherwise, if the timed out transaction is
7094		 * active:
7095		 *   Initiator transaction:
7096		 *	Stuff the message buffer with a BDR message and assert
7097		 *	ATN in the hopes that the target will let go of the bus
7098		 *	and go to the mesgout phase.  If this fails, we'll
7099		 *	get another timeout 2 seconds later which will attempt
7100		 *	a bus reset.
7101		 *
7102		 *   Target transaction:
7103		 *	Transition to BUS FREE and report the error.
7104		 *	It's good to be the target!
7105		 */
7106		saved_scbptr = ahc_inb(ahc, SCBPTR);
7107		active_scb_index = ahc_inb(ahc, SCB_TAG);
7108
7109		if ((ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) == 0
7110		  && (active_scb_index < ahc->scb_data->numscbs)) {
7111			struct scb *active_scb;
7112
7113			/*
7114			 * If the active SCB is not us, assume that
7115			 * the active SCB has a longer timeout than
7116			 * the timedout SCB, and wait for the active
7117			 * SCB to timeout.
7118			 */
7119			active_scb = ahc_lookup_scb(ahc, active_scb_index);
7120			if (active_scb != scb) {
7121				if (ahc_other_scb_timeout(ahc, scb,
7122							  active_scb) == 0)
7123					goto bus_reset;
7124				continue;
7125			}
7126
7127			/* It's us */
7128			if ((scb->flags & SCB_TARGET_SCB) != 0) {
7129
7130				/*
7131				 * Send back any queued up transactions
7132				 * and properly record the error condition.
7133				 */
7134				ahc_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
7135					       SCB_GET_CHANNEL(ahc, scb),
7136					       SCB_GET_LUN(scb),
7137					       scb->hscb->tag,
7138					       ROLE_TARGET,
7139					       CAM_CMD_TIMEOUT);
7140
7141				/* Will clear us from the bus */
7142				restart_needed = 1;
7143				break;
7144			}
7145
7146			ahc_set_recoveryscb(ahc, active_scb);
7147			ahc_outb(ahc, MSG_OUT, HOST_MSG);
7148			ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
7149			ahc_print_path(ahc, active_scb);
7150			printf("BDR message in message buffer\n");
7151			active_scb->flags |= SCB_DEVICE_RESET;
7152			aic_scb_timer_reset(scb, 2 * 1000);
7153		} else if (last_phase != P_BUSFREE
7154			&& (ahc_inb(ahc, SSTAT1) & REQINIT) == 0) {
7155			/*
7156			 * SCB is not identified, there
7157			 * is no pending REQ, and the sequencer
7158			 * has not seen a busfree.  Looks like
7159			 * a stuck connection waiting to
7160			 * go busfree.  Reset the bus.
7161			 */
7162			printf("%s: Connection stuck awaiting busfree or "
7163			       "Identify Msg.\n", ahc_name(ahc));
7164			goto bus_reset;
7165		} else {
7166			int	 disconnected;
7167
7168			if (last_phase != P_BUSFREE
7169			 && (ahc_inb(ahc, SSTAT0) & TARGET) != 0) {
7170				/* Hung target selection.  Goto busfree */
7171				printf("%s: Hung target selection\n",
7172				       ahc_name(ahc));
7173				restart_needed = 1;
7174				break;
7175			}
7176
7177			/* XXX Shouldn't panic.  Just punt instead? */
7178			if ((scb->flags & SCB_TARGET_SCB) != 0)
7179				panic("Timed-out target SCB but bus idle");
7180
7181			if (ahc_search_qinfifo(ahc, target, channel, lun,
7182					       scb->hscb->tag, ROLE_INITIATOR,
7183					       /*status*/0, SEARCH_COUNT) > 0) {
7184				disconnected = FALSE;
7185			} else {
7186				disconnected = TRUE;
7187			}
7188
7189			if (disconnected) {
7190
7191				ahc_set_recoveryscb(ahc, scb);
7192				/*
7193				 * Actually re-queue this SCB in an attempt
7194				 * to select the device before it reconnects.
7195				 * In either case (selection or reselection),
7196				 * we will now issue a target reset to the
7197				 * timed-out device.
7198				 *
7199				 * Set the MK_MESSAGE control bit indicating
7200				 * that we desire to send a message.  We
7201				 * also set the disconnected flag since
7202				 * in the paging case there is no guarantee
7203				 * that our SCB control byte matches the
7204				 * version on the card.  We don't want the
7205				 * sequencer to abort the command thinking
7206				 * an unsolicited reselection occurred.
7207				 */
7208				scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
7209				scb->flags |= SCB_DEVICE_RESET;
7210
7211				/*
7212				 * Remove any cached copy of this SCB in the
7213				 * disconnected list in preparation for the
7214				 * queuing of our abort SCB.  We use the
7215				 * same element in the SCB, SCB_NEXT, for
7216				 * both the qinfifo and the disconnected list.
7217				 */
7218				ahc_search_disc_list(ahc, target, channel,
7219						     lun, scb->hscb->tag,
7220						     /*stop_on_first*/TRUE,
7221						     /*remove*/TRUE,
7222						     /*save_state*/FALSE);
7223
7224				/*
7225				 * In the non-paging case, the sequencer will
7226				 * never re-reference the in-core SCB.
7227				 * To make sure we are notified during
7228				 * reslection, set the MK_MESSAGE flag in
7229				 * the card's copy of the SCB.
7230				 */
7231				if ((ahc->flags & AHC_PAGESCBS) == 0) {
7232					ahc_outb(ahc, SCBPTR, scb->hscb->tag);
7233					ahc_outb(ahc, SCB_CONTROL,
7234						 ahc_inb(ahc, SCB_CONTROL)
7235						| MK_MESSAGE);
7236				}
7237
7238				/*
7239				 * Clear out any entries in the QINFIFO first
7240				 * so we are the next SCB for this target
7241				 * to run.
7242				 */
7243				ahc_search_qinfifo(ahc,
7244						   SCB_GET_TARGET(ahc, scb),
7245						   channel, SCB_GET_LUN(scb),
7246						   SCB_LIST_NULL,
7247						   ROLE_INITIATOR,
7248						   CAM_REQUEUE_REQ,
7249						   SEARCH_COMPLETE);
7250				ahc_print_path(ahc, scb);
7251				printf("Queuing a BDR SCB\n");
7252				ahc_qinfifo_requeue_tail(ahc, scb);
7253				ahc_outb(ahc, SCBPTR, saved_scbptr);
7254				aic_scb_timer_reset(scb, 2 * 1000);
7255			} else {
7256				/* Go "immediatly" to the bus reset */
7257				/* This shouldn't happen */
7258				ahc_set_recoveryscb(ahc, scb);
7259				ahc_print_path(ahc, scb);
7260				printf("SCB %d: Immediate reset.  "
7261					"Flags = 0x%x\n", scb->hscb->tag,
7262					scb->flags);
7263				goto bus_reset;
7264			}
7265		}
7266		break;
7267	}
7268
7269	/*
7270	 * Any remaining SCBs were not the "culprit", so remove
7271	 * them from the timeout list.  The timer for these commands
7272	 * will be reset once the recovery SCB completes.
7273	 */
7274	while ((scb = LIST_FIRST(&ahc->timedout_scbs)) != NULL) {
7275
7276		LIST_REMOVE(scb, timedout_links);
7277		scb->flags &= ~SCB_TIMEDOUT;
7278	}
7279
7280	if (restart_needed)
7281		ahc_restart(ahc);
7282	else
7283		ahc_unpause(ahc);
7284}
7285
7286/************************* Target Mode ****************************************/
7287#ifdef AHC_TARGET_MODE
7288cam_status
7289ahc_find_tmode_devs(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb,
7290		    struct ahc_tmode_tstate **tstate,
7291		    struct ahc_tmode_lstate **lstate,
7292		    int notfound_failure)
7293{
7294
7295	if ((ahc->features & AHC_TARGETMODE) == 0)
7296		return (CAM_REQ_INVALID);
7297
7298	/*
7299	 * Handle the 'black hole' device that sucks up
7300	 * requests to unattached luns on enabled targets.
7301	 */
7302	if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
7303	 && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
7304		*tstate = NULL;
7305		*lstate = ahc->black_hole;
7306	} else {
7307		u_int max_id;
7308
7309		max_id = (ahc->features & AHC_WIDE) ? 15 : 7;
7310		if (ccb->ccb_h.target_id > max_id)
7311			return (CAM_TID_INVALID);
7312
7313		if (ccb->ccb_h.target_lun >= AHC_NUM_LUNS)
7314			return (CAM_LUN_INVALID);
7315
7316		*tstate = ahc->enabled_targets[ccb->ccb_h.target_id];
7317		*lstate = NULL;
7318		if (*tstate != NULL)
7319			*lstate =
7320			    (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
7321	}
7322
7323	if (notfound_failure != 0 && *lstate == NULL)
7324		return (CAM_PATH_INVALID);
7325
7326	return (CAM_REQ_CMP);
7327}
7328
7329void
7330ahc_handle_en_lun(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb)
7331{
7332	struct	   ahc_tmode_tstate *tstate;
7333	struct	   ahc_tmode_lstate *lstate;
7334	struct	   ccb_en_lun *cel;
7335	cam_status status;
7336	u_int	   target;
7337	u_int	   lun;
7338	u_int	   target_mask;
7339	u_int	   our_id;
7340	int	   error;
7341	char	   channel;
7342
7343	status = ahc_find_tmode_devs(ahc, sim, ccb, &tstate, &lstate,
7344				     /*notfound_failure*/FALSE);
7345
7346	if (status != CAM_REQ_CMP) {
7347		ccb->ccb_h.status = status;
7348		return;
7349	}
7350
7351	if (cam_sim_bus(sim) == 0)
7352		our_id = ahc->our_id;
7353	else
7354		our_id = ahc->our_id_b;
7355
7356	if (ccb->ccb_h.target_id != our_id) {
7357		/*
7358		 * our_id represents our initiator ID, or
7359		 * the ID of the first target to have an
7360		 * enabled lun in target mode.  There are
7361		 * two cases that may preclude enabling a
7362		 * target id other than our_id.
7363		 *
7364		 *   o our_id is for an active initiator role.
7365		 *     Since the hardware does not support
7366		 *     reselections to the initiator role at
7367		 *     anything other than our_id, and our_id
7368		 *     is used by the hardware to indicate the
7369		 *     ID to use for both select-out and
7370		 *     reselect-out operations, the only target
7371		 *     ID we can support in this mode is our_id.
7372		 *
7373		 *   o The MULTARGID feature is not available and
7374		 *     a previous target mode ID has been enabled.
7375		 */
7376		if ((ahc->features & AHC_MULTIROLE) != 0) {
7377
7378			if ((ahc->features & AHC_MULTI_TID) != 0
7379		   	 && (ahc->flags & AHC_INITIATORROLE) != 0) {
7380				/*
7381				 * Only allow additional targets if
7382				 * the initiator role is disabled.
7383				 * The hardware cannot handle a re-select-in
7384				 * on the initiator id during a re-select-out
7385				 * on a different target id.
7386				 */
7387				status = CAM_TID_INVALID;
7388			} else if ((ahc->flags & AHC_INITIATORROLE) != 0
7389				|| ahc->enabled_luns > 0) {
7390				/*
7391				 * Only allow our target id to change
7392				 * if the initiator role is not configured
7393				 * and there are no enabled luns which
7394				 * are attached to the currently registered
7395				 * scsi id.
7396				 */
7397				status = CAM_TID_INVALID;
7398			}
7399		} else if ((ahc->features & AHC_MULTI_TID) == 0
7400			&& ahc->enabled_luns > 0) {
7401
7402			status = CAM_TID_INVALID;
7403		}
7404	}
7405
7406	if (status != CAM_REQ_CMP) {
7407		ccb->ccb_h.status = status;
7408		return;
7409	}
7410
7411	/*
7412	 * We now have an id that is valid.
7413	 * If we aren't in target mode, switch modes.
7414	 */
7415	if ((ahc->flags & AHC_TARGETROLE) == 0
7416	 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
7417		ahc_flag saved_flags;
7418
7419		printf("Configuring Target Mode\n");
7420		if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
7421			ccb->ccb_h.status = CAM_BUSY;
7422			return;
7423		}
7424		saved_flags = ahc->flags;
7425		ahc->flags |= AHC_TARGETROLE;
7426		if ((ahc->features & AHC_MULTIROLE) == 0)
7427			ahc->flags &= ~AHC_INITIATORROLE;
7428		ahc_pause(ahc);
7429		error = ahc_loadseq(ahc);
7430		if (error != 0) {
7431			/*
7432			 * Restore original configuration and notify
7433			 * the caller that we cannot support target mode.
7434			 * Since the adapter started out in this
7435			 * configuration, the firmware load will succeed,
7436			 * so there is no point in checking ahc_loadseq's
7437			 * return value.
7438			 */
7439			ahc->flags = saved_flags;
7440			(void)ahc_loadseq(ahc);
7441			ahc_restart(ahc);
7442			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
7443			return;
7444		}
7445		ahc_restart(ahc);
7446	}
7447	cel = &ccb->cel;
7448	target = ccb->ccb_h.target_id;
7449	lun = ccb->ccb_h.target_lun;
7450	channel = SIM_CHANNEL(ahc, sim);
7451	target_mask = 0x01 << target;
7452	if (channel == 'B')
7453		target_mask <<= 8;
7454
7455	if (cel->enable != 0) {
7456		u_int scsiseq;
7457
7458		/* Are we already enabled?? */
7459		if (lstate != NULL) {
7460			xpt_print_path(ccb->ccb_h.path);
7461			printf("Lun already enabled\n");
7462			ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
7463			return;
7464		}
7465
7466		if (cel->grp6_len != 0
7467		 || cel->grp7_len != 0) {
7468			/*
7469			 * Don't (yet?) support vendor
7470			 * specific commands.
7471			 */
7472			ccb->ccb_h.status = CAM_REQ_INVALID;
7473			printf("Non-zero Group Codes\n");
7474			return;
7475		}
7476
7477		/*
7478		 * Seems to be okay.
7479		 * Setup our data structures.
7480		 */
7481		if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
7482			tstate = ahc_alloc_tstate(ahc, target, channel);
7483			if (tstate == NULL) {
7484				xpt_print_path(ccb->ccb_h.path);
7485				printf("Couldn't allocate tstate\n");
7486				ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7487				return;
7488			}
7489		}
7490		lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
7491		if (lstate == NULL) {
7492			xpt_print_path(ccb->ccb_h.path);
7493			printf("Couldn't allocate lstate\n");
7494			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7495			return;
7496		}
7497		memset(lstate, 0, sizeof(*lstate));
7498		status = xpt_create_path(&lstate->path, /*periph*/NULL,
7499					 xpt_path_path_id(ccb->ccb_h.path),
7500					 xpt_path_target_id(ccb->ccb_h.path),
7501					 xpt_path_lun_id(ccb->ccb_h.path));
7502		if (status != CAM_REQ_CMP) {
7503			free(lstate, M_DEVBUF);
7504			xpt_print_path(ccb->ccb_h.path);
7505			printf("Couldn't allocate path\n");
7506			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7507			return;
7508		}
7509		SLIST_INIT(&lstate->accept_tios);
7510		SLIST_INIT(&lstate->immed_notifies);
7511		ahc_pause(ahc);
7512		if (target != CAM_TARGET_WILDCARD) {
7513			tstate->enabled_luns[lun] = lstate;
7514			ahc->enabled_luns++;
7515
7516			if ((ahc->features & AHC_MULTI_TID) != 0) {
7517				u_int targid_mask;
7518
7519				targid_mask = ahc_inb(ahc, TARGID)
7520					    | (ahc_inb(ahc, TARGID + 1) << 8);
7521
7522				targid_mask |= target_mask;
7523				ahc_outb(ahc, TARGID, targid_mask);
7524				ahc_outb(ahc, TARGID+1, (targid_mask >> 8));
7525
7526				ahc_update_scsiid(ahc, targid_mask);
7527			} else {
7528				u_int our_id;
7529				char  channel;
7530
7531				channel = SIM_CHANNEL(ahc, sim);
7532				our_id = SIM_SCSI_ID(ahc, sim);
7533
7534				/*
7535				 * This can only happen if selections
7536				 * are not enabled
7537				 */
7538				if (target != our_id) {
7539					u_int sblkctl;
7540					char  cur_channel;
7541					int   swap;
7542
7543					sblkctl = ahc_inb(ahc, SBLKCTL);
7544					cur_channel = (sblkctl & SELBUSB)
7545						    ? 'B' : 'A';
7546					if ((ahc->features & AHC_TWIN) == 0)
7547						cur_channel = 'A';
7548					swap = cur_channel != channel;
7549					if (channel == 'A')
7550						ahc->our_id = target;
7551					else
7552						ahc->our_id_b = target;
7553
7554					if (swap)
7555						ahc_outb(ahc, SBLKCTL,
7556							 sblkctl ^ SELBUSB);
7557
7558					ahc_outb(ahc, SCSIID, target);
7559
7560					if (swap)
7561						ahc_outb(ahc, SBLKCTL, sblkctl);
7562				}
7563			}
7564		} else
7565			ahc->black_hole = lstate;
7566		/* Allow select-in operations */
7567		if (ahc->black_hole != NULL && ahc->enabled_luns > 0) {
7568			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7569			scsiseq |= ENSELI;
7570			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7571			scsiseq = ahc_inb(ahc, SCSISEQ);
7572			scsiseq |= ENSELI;
7573			ahc_outb(ahc, SCSISEQ, scsiseq);
7574		}
7575		ahc_unpause(ahc);
7576		ccb->ccb_h.status = CAM_REQ_CMP;
7577		xpt_print_path(ccb->ccb_h.path);
7578		printf("Lun now enabled for target mode\n");
7579	} else {
7580		struct scb *scb;
7581		int i, empty;
7582
7583		if (lstate == NULL) {
7584			ccb->ccb_h.status = CAM_LUN_INVALID;
7585			return;
7586		}
7587
7588		ccb->ccb_h.status = CAM_REQ_CMP;
7589		LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
7590			struct ccb_hdr *ccbh;
7591
7592			ccbh = &scb->io_ctx->ccb_h;
7593			if (ccbh->func_code == XPT_CONT_TARGET_IO
7594			 && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
7595				printf("CTIO pending\n");
7596				ccb->ccb_h.status = CAM_REQ_INVALID;
7597				return;
7598			}
7599		}
7600
7601		if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
7602			printf("ATIOs pending\n");
7603			ccb->ccb_h.status = CAM_REQ_INVALID;
7604		}
7605
7606		if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
7607			printf("INOTs pending\n");
7608			ccb->ccb_h.status = CAM_REQ_INVALID;
7609		}
7610
7611		if (ccb->ccb_h.status != CAM_REQ_CMP) {
7612			return;
7613		}
7614
7615		xpt_print_path(ccb->ccb_h.path);
7616		printf("Target mode disabled\n");
7617		xpt_free_path(lstate->path);
7618		free(lstate, M_DEVBUF);
7619
7620		ahc_pause(ahc);
7621		/* Can we clean up the target too? */
7622		if (target != CAM_TARGET_WILDCARD) {
7623			tstate->enabled_luns[lun] = NULL;
7624			ahc->enabled_luns--;
7625			for (empty = 1, i = 0; i < 8; i++)
7626				if (tstate->enabled_luns[i] != NULL) {
7627					empty = 0;
7628					break;
7629				}
7630
7631			if (empty) {
7632				ahc_free_tstate(ahc, target, channel,
7633						/*force*/FALSE);
7634				if (ahc->features & AHC_MULTI_TID) {
7635					u_int targid_mask;
7636
7637					targid_mask = ahc_inb(ahc, TARGID)
7638						    | (ahc_inb(ahc, TARGID + 1)
7639						       << 8);
7640
7641					targid_mask &= ~target_mask;
7642					ahc_outb(ahc, TARGID, targid_mask);
7643					ahc_outb(ahc, TARGID+1,
7644					 	 (targid_mask >> 8));
7645					ahc_update_scsiid(ahc, targid_mask);
7646				}
7647			}
7648		} else {
7649
7650			ahc->black_hole = NULL;
7651
7652			/*
7653			 * We can't allow selections without
7654			 * our black hole device.
7655			 */
7656			empty = TRUE;
7657		}
7658		if (ahc->enabled_luns == 0) {
7659			/* Disallow select-in */
7660			u_int scsiseq;
7661
7662			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7663			scsiseq &= ~ENSELI;
7664			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7665			scsiseq = ahc_inb(ahc, SCSISEQ);
7666			scsiseq &= ~ENSELI;
7667			ahc_outb(ahc, SCSISEQ, scsiseq);
7668
7669			if ((ahc->features & AHC_MULTIROLE) == 0) {
7670				printf("Configuring Initiator Mode\n");
7671				ahc->flags &= ~AHC_TARGETROLE;
7672				ahc->flags |= AHC_INITIATORROLE;
7673				/*
7674				 * Returning to a configuration that
7675				 * fit previously will always succeed.
7676				 */
7677				(void)ahc_loadseq(ahc);
7678				ahc_restart(ahc);
7679				/*
7680				 * Unpaused.  The extra unpause
7681				 * that follows is harmless.
7682				 */
7683			}
7684		}
7685		ahc_unpause(ahc);
7686	}
7687}
7688
7689static void
7690ahc_update_scsiid(struct ahc_softc *ahc, u_int targid_mask)
7691{
7692	u_int scsiid_mask;
7693	u_int scsiid;
7694
7695	if ((ahc->features & AHC_MULTI_TID) == 0)
7696		panic("ahc_update_scsiid called on non-multitid unit\n");
7697
7698	/*
7699	 * Since we will rely on the TARGID mask
7700	 * for selection enables, ensure that OID
7701	 * in SCSIID is not set to some other ID
7702	 * that we don't want to allow selections on.
7703	 */
7704	if ((ahc->features & AHC_ULTRA2) != 0)
7705		scsiid = ahc_inb(ahc, SCSIID_ULTRA2);
7706	else
7707		scsiid = ahc_inb(ahc, SCSIID);
7708	scsiid_mask = 0x1 << (scsiid & OID);
7709	if ((targid_mask & scsiid_mask) == 0) {
7710		u_int our_id;
7711
7712		/* ffs counts from 1 */
7713		our_id = ffs(targid_mask);
7714		if (our_id == 0)
7715			our_id = ahc->our_id;
7716		else
7717			our_id--;
7718		scsiid &= TID;
7719		scsiid |= our_id;
7720	}
7721	if ((ahc->features & AHC_ULTRA2) != 0)
7722		ahc_outb(ahc, SCSIID_ULTRA2, scsiid);
7723	else
7724		ahc_outb(ahc, SCSIID, scsiid);
7725}
7726
7727void
7728ahc_run_tqinfifo(struct ahc_softc *ahc, int paused)
7729{
7730	struct target_cmd *cmd;
7731
7732	/*
7733	 * If the card supports auto-access pause,
7734	 * we can access the card directly regardless
7735	 * of whether it is paused or not.
7736	 */
7737	if ((ahc->features & AHC_AUTOPAUSE) != 0)
7738		paused = TRUE;
7739
7740	ahc_sync_tqinfifo(ahc, BUS_DMASYNC_POSTREAD);
7741	while ((cmd = &ahc->targetcmds[ahc->tqinfifonext])->cmd_valid != 0) {
7742
7743		/*
7744		 * Only advance through the queue if we
7745		 * have the resources to process the command.
7746		 */
7747		if (ahc_handle_target_cmd(ahc, cmd) != 0)
7748			break;
7749
7750		cmd->cmd_valid = 0;
7751		aic_dmamap_sync(ahc, ahc->shared_data_dmat,
7752				ahc->shared_data_dmamap,
7753				ahc_targetcmd_offset(ahc, ahc->tqinfifonext),
7754				sizeof(struct target_cmd),
7755				BUS_DMASYNC_PREREAD);
7756		ahc->tqinfifonext++;
7757
7758		/*
7759		 * Lazily update our position in the target mode incoming
7760		 * command queue as seen by the sequencer.
7761		 */
7762		if ((ahc->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
7763			if ((ahc->features & AHC_HS_MAILBOX) != 0) {
7764				u_int hs_mailbox;
7765
7766				hs_mailbox = ahc_inb(ahc, HS_MAILBOX);
7767				hs_mailbox &= ~HOST_TQINPOS;
7768				hs_mailbox |= ahc->tqinfifonext & HOST_TQINPOS;
7769				ahc_outb(ahc, HS_MAILBOX, hs_mailbox);
7770			} else {
7771				if (!paused)
7772					ahc_pause(ahc);
7773				ahc_outb(ahc, KERNEL_TQINPOS,
7774					 ahc->tqinfifonext & HOST_TQINPOS);
7775				if (!paused)
7776					ahc_unpause(ahc);
7777			}
7778		}
7779	}
7780}
7781
7782static int
7783ahc_handle_target_cmd(struct ahc_softc *ahc, struct target_cmd *cmd)
7784{
7785	struct	  ahc_tmode_tstate *tstate;
7786	struct	  ahc_tmode_lstate *lstate;
7787	struct	  ccb_accept_tio *atio;
7788	uint8_t *byte;
7789	int	  initiator;
7790	int	  target;
7791	int	  lun;
7792
7793	initiator = SCSIID_TARGET(ahc, cmd->scsiid);
7794	target = SCSIID_OUR_ID(cmd->scsiid);
7795	lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
7796
7797	byte = cmd->bytes;
7798	tstate = ahc->enabled_targets[target];
7799	lstate = NULL;
7800	if (tstate != NULL)
7801		lstate = tstate->enabled_luns[lun];
7802
7803	/*
7804	 * Commands for disabled luns go to the black hole driver.
7805	 */
7806	if (lstate == NULL)
7807		lstate = ahc->black_hole;
7808
7809	atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
7810	if (atio == NULL) {
7811		ahc->flags |= AHC_TQINFIFO_BLOCKED;
7812		/*
7813		 * Wait for more ATIOs from the peripheral driver for this lun.
7814		 */
7815		if (bootverbose)
7816			printf("%s: ATIOs exhausted\n", ahc_name(ahc));
7817		return (1);
7818	} else
7819		ahc->flags &= ~AHC_TQINFIFO_BLOCKED;
7820#ifdef AHC_DEBUG
7821	if (ahc_debug & AHC_SHOW_TQIN) {
7822		printf("Incoming command from %d for %d:%d%s\n",
7823		       initiator, target, lun,
7824		       lstate == ahc->black_hole ? "(Black Holed)" : "");
7825	}
7826#endif
7827	SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
7828
7829	if (lstate == ahc->black_hole) {
7830		/* Fill in the wildcards */
7831		atio->ccb_h.target_id = target;
7832		atio->ccb_h.target_lun = lun;
7833	}
7834
7835	/*
7836	 * Package it up and send it off to
7837	 * whomever has this lun enabled.
7838	 */
7839	atio->sense_len = 0;
7840	atio->init_id = initiator;
7841	if (byte[0] != 0xFF) {
7842		/* Tag was included */
7843		atio->tag_action = *byte++;
7844		atio->tag_id = *byte++;
7845		atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
7846	} else {
7847		atio->ccb_h.flags = 0;
7848	}
7849	byte++;
7850
7851	/* Okay.  Now determine the cdb size based on the command code */
7852	switch (*byte >> CMD_GROUP_CODE_SHIFT) {
7853	case 0:
7854		atio->cdb_len = 6;
7855		break;
7856	case 1:
7857	case 2:
7858		atio->cdb_len = 10;
7859		break;
7860	case 4:
7861		atio->cdb_len = 16;
7862		break;
7863	case 5:
7864		atio->cdb_len = 12;
7865		break;
7866	case 3:
7867	default:
7868		/* Only copy the opcode. */
7869		atio->cdb_len = 1;
7870		printf("Reserved or VU command code type encountered\n");
7871		break;
7872	}
7873
7874	memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
7875
7876	atio->ccb_h.status |= CAM_CDB_RECVD;
7877
7878	if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
7879		/*
7880		 * We weren't allowed to disconnect.
7881		 * We're hanging on the bus until a
7882		 * continue target I/O comes in response
7883		 * to this accept tio.
7884		 */
7885#ifdef AHC_DEBUG
7886		if (ahc_debug & AHC_SHOW_TQIN) {
7887			printf("Received Immediate Command %d:%d:%d - %p\n",
7888			       initiator, target, lun, ahc->pending_device);
7889		}
7890#endif
7891		ahc->pending_device = lstate;
7892		aic_freeze_ccb((union ccb *)atio);
7893		atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
7894	}
7895	xpt_done((union ccb*)atio);
7896	return (0);
7897}
7898
7899#endif
7900