xref: /freebsd/sys/dev/aic7xxx/aic7xxx.c (revision 5608fd23c27fa1e8ee595d7b678cbfd35d657fbe)
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 ************************************/
56 struct ahc_softc_tailq ahc_tailq = TAILQ_HEAD_INITIALIZER(ahc_tailq);
57 
58 /***************************** Lookup Tables **********************************/
59 char *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  */
80 struct ahc_hard_error_entry {
81         uint8_t errno;
82 	char *errmesg;
83 };
84 
85 static 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 };
95 static const u_int num_errors = NUM_ELEMENTS(ahc_hard_errors);
96 
97 static 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  */
115 static 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  */
122 static 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 ***************************/
146 static void		ahc_force_renegotiation(struct ahc_softc *ahc,
147 						struct ahc_devinfo *devinfo);
148 static struct ahc_tmode_tstate*
149 			ahc_alloc_tstate(struct ahc_softc *ahc,
150 					 u_int scsi_id, char channel);
151 #ifdef AHC_TARGET_MODE
152 static void		ahc_free_tstate(struct ahc_softc *ahc,
153 					u_int scsi_id, char channel, int force);
154 #endif
155 static 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);
161 static void		ahc_update_pending_scbs(struct ahc_softc *ahc);
162 static void		ahc_fetch_devinfo(struct ahc_softc *ahc,
163 					  struct ahc_devinfo *devinfo);
164 static void		ahc_scb_devinfo(struct ahc_softc *ahc,
165 					struct ahc_devinfo *devinfo,
166 					struct scb *scb);
167 static void		ahc_assert_atn(struct ahc_softc *ahc);
168 static void		ahc_setup_initiator_msgout(struct ahc_softc *ahc,
169 						   struct ahc_devinfo *devinfo,
170 						   struct scb *scb);
171 static void		ahc_build_transfer_msg(struct ahc_softc *ahc,
172 					       struct ahc_devinfo *devinfo);
173 static void		ahc_construct_sdtr(struct ahc_softc *ahc,
174 					   struct ahc_devinfo *devinfo,
175 					   u_int period, u_int offset);
176 static void		ahc_construct_wdtr(struct ahc_softc *ahc,
177 					   struct ahc_devinfo *devinfo,
178 					   u_int bus_width);
179 static 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);
183 static void		ahc_clear_msg_state(struct ahc_softc *ahc);
184 static void		ahc_handle_proto_violation(struct ahc_softc *ahc);
185 static void		ahc_handle_message_phase(struct ahc_softc *ahc);
186 typedef enum {
187 	AHCMSG_1B,
188 	AHCMSG_2B,
189 	AHCMSG_EXT
190 } ahc_msgtype;
191 static int		ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
192 				     u_int msgval, int full);
193 static int		ahc_parse_msg(struct ahc_softc *ahc,
194 				      struct ahc_devinfo *devinfo);
195 static int		ahc_handle_msg_reject(struct ahc_softc *ahc,
196 					      struct ahc_devinfo *devinfo);
197 static void		ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
198 						struct ahc_devinfo *devinfo);
199 static void		ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
200 static 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
205 static void		ahc_setup_target_msgin(struct ahc_softc *ahc,
206 					       struct ahc_devinfo *devinfo,
207 					       struct scb *scb);
208 #endif
209 
210 static bus_dmamap_callback_t	ahc_dmamap_cb;
211 static void			ahc_build_free_scb_list(struct ahc_softc *ahc);
212 static int			ahc_init_scbdata(struct ahc_softc *ahc);
213 static void			ahc_fini_scbdata(struct ahc_softc *ahc);
214 static void		ahc_qinfifo_requeue(struct ahc_softc *ahc,
215 					    struct scb *prev_scb,
216 					    struct scb *scb);
217 static int		ahc_qinfifo_count(struct ahc_softc *ahc);
218 static u_int		ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
219 						   u_int prev, u_int scbptr);
220 static void		ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
221 static u_int		ahc_rem_wscb(struct ahc_softc *ahc,
222 				     u_int scbpos, u_int prev);
223 static void		ahc_reset_current_bus(struct ahc_softc *ahc);
224 #ifdef AHC_DUMP_SEQ
225 static void		ahc_dumpseq(struct ahc_softc *ahc);
226 #endif
227 static int		ahc_loadseq(struct ahc_softc *ahc);
228 static int		ahc_check_patch(struct ahc_softc *ahc,
229 					struct patch **start_patch,
230 					u_int start_instr, u_int *skip_addr);
231 static void		ahc_download_instr(struct ahc_softc *ahc,
232 					   u_int instrptr, uint8_t *dconsts);
233 static int		ahc_other_scb_timeout(struct ahc_softc *ahc,
234 					      struct scb *scb,
235 					      struct scb *other_scb);
236 #ifdef AHC_TARGET_MODE
237 static 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);
242 static void		ahc_update_scsiid(struct ahc_softc *ahc,
243 					  u_int targid_mask);
244 static 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  */
251 void
252 ahc_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 ********************************/
312 void
313 ahc_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 
359 void
360 ahc_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 
368 void
369 ahc_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 *********************************/
388 void
389 ahc_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 
417 void
418 ahc_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 	}
963 unpause:
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 
972 void
973 ahc_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  */
1409 static void
1410 ahc_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
1425 void
1426 ahc_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  */
1516 void
1517 ahc_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
1532 uint32_t ahc_debug = AHC_DEBUG_OPTS;
1533 #endif
1534 
1535 void
1536 ahc_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  */
1573 static struct ahc_tmode_tstate *
1574 ahc_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  */
1621 static void
1622 ahc_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  */
1650 struct ahc_syncrate *
1651 ahc_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  */
1705 struct ahc_syncrate *
1706 ahc_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  */
1772 u_int
1773 ahc_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  */
1802 void
1803 ahc_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  */
1834 void
1835 ahc_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  */
1864 int
1865 ahc_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  */
1907 void
1908 ahc_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  */
2034 void
2035 ahc_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  */
2090 void
2091 ahc_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  */
2104 static void
2105 ahc_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 *****************************/
2182 static void
2183 ahc_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 
2214 struct ahc_phase_table_entry*
2215 ahc_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 
2232 void
2233 ahc_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 
2247 void
2248 ahc_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 
2254 static void
2255 ahc_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 ****************************/
2271 static void
2272 ahc_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  */
2288 static void
2289 ahc_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  */
2374 static void
2375 ahc_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  */
2472 static void
2473 ahc_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  */
2495 static void
2496 ahc_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  */
2515 static void
2516 ahc_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  */
2542 static void
2543 ahc_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 
2560 static void
2561 ahc_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) {
2619 proto_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  */
2657 static void
2658 ahc_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 
2668 reswitch:
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  */
3032 static int
3033 ahc_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  */
3079 static int
3080 ahc_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  */
3501 static int
3502 ahc_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  */
3652 static void
3653 ahc_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  */
3761 static void
3762 ahc_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  */
3817 static void
3818 ahc_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
3872 static void
3873 ahc_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  */
3899 struct ahc_softc *
3900 ahc_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 
3954 int
3955 ahc_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 
3976 void
3977 ahc_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 
4032 void
4033 ahc_set_unit(struct ahc_softc *ahc, int unit)
4034 {
4035 	ahc->unit = unit;
4036 }
4037 
4038 void
4039 ahc_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 
4046 void
4047 ahc_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 		/* FALLTHROUGH */
4065 	case 2:
4066 		aic_dma_tag_destroy(ahc, ahc->shared_data_dmat);
4067 	case 1:
4068 #ifndef __linux__
4069 		aic_dma_tag_destroy(ahc, ahc->buffer_dmat);
4070 #endif
4071 		break;
4072 	case 0:
4073 		break;
4074 	}
4075 
4076 #ifndef __linux__
4077 	aic_dma_tag_destroy(ahc, ahc->parent_dmat);
4078 #endif
4079 	ahc_platform_free(ahc);
4080 	ahc_fini_scbdata(ahc);
4081 	for (i = 0; i < AHC_NUM_TARGETS; i++) {
4082 		struct ahc_tmode_tstate *tstate;
4083 
4084 		tstate = ahc->enabled_targets[i];
4085 		if (tstate != NULL) {
4086 #ifdef AHC_TARGET_MODE
4087 			int j;
4088 
4089 			for (j = 0; j < AHC_NUM_LUNS; j++) {
4090 				struct ahc_tmode_lstate *lstate;
4091 
4092 				lstate = tstate->enabled_luns[j];
4093 				if (lstate != NULL) {
4094 					xpt_free_path(lstate->path);
4095 					free(lstate, M_DEVBUF);
4096 				}
4097 			}
4098 #endif
4099 			free(tstate, M_DEVBUF);
4100 		}
4101 	}
4102 #ifdef AHC_TARGET_MODE
4103 	if (ahc->black_hole != NULL) {
4104 		xpt_free_path(ahc->black_hole->path);
4105 		free(ahc->black_hole, M_DEVBUF);
4106 	}
4107 #endif
4108 	if (ahc->name != NULL)
4109 		free(ahc->name, M_DEVBUF);
4110 	if (ahc->seep_config != NULL)
4111 		free(ahc->seep_config, M_DEVBUF);
4112 #ifndef __FreeBSD__
4113 	free(ahc, M_DEVBUF);
4114 #endif
4115 	return;
4116 }
4117 
4118 void
4119 ahc_shutdown(void *arg)
4120 {
4121 	struct	ahc_softc *ahc;
4122 	int	i;
4123 
4124 	ahc = (struct ahc_softc *)arg;
4125 
4126 	/* This will reset most registers to 0, but not all */
4127 	ahc_reset(ahc, /*reinit*/FALSE);
4128 	ahc_outb(ahc, SCSISEQ, 0);
4129 	ahc_outb(ahc, SXFRCTL0, 0);
4130 	ahc_outb(ahc, DSPCISTATUS, 0);
4131 
4132 	for (i = TARG_SCSIRATE; i < SCSICONF; i++)
4133 		ahc_outb(ahc, i, 0);
4134 }
4135 
4136 /*
4137  * Reset the controller and record some information about it
4138  * that is only available just after a reset.  If "reinit" is
4139  * non-zero, this reset occured after initial configuration
4140  * and the caller requests that the chip be fully reinitialized
4141  * to a runable state.  Chip interrupts are *not* enabled after
4142  * a reinitialization.  The caller must enable interrupts via
4143  * ahc_intr_enable().
4144  */
4145 int
4146 ahc_reset(struct ahc_softc *ahc, int reinit)
4147 {
4148 	u_int	sblkctl;
4149 	u_int	sxfrctl1_a, sxfrctl1_b;
4150 	int	error;
4151 	int	wait;
4152 
4153 	/*
4154 	 * Preserve the value of the SXFRCTL1 register for all channels.
4155 	 * It contains settings that affect termination and we don't want
4156 	 * to disturb the integrity of the bus.
4157 	 */
4158 	ahc_pause(ahc);
4159 	sxfrctl1_b = 0;
4160 	if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7770) {
4161 		u_int sblkctl;
4162 
4163 		/*
4164 		 * Save channel B's settings in case this chip
4165 		 * is setup for TWIN channel operation.
4166 		 */
4167 		sblkctl = ahc_inb(ahc, SBLKCTL);
4168 		ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4169 		sxfrctl1_b = ahc_inb(ahc, SXFRCTL1);
4170 		ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4171 	}
4172 	sxfrctl1_a = ahc_inb(ahc, SXFRCTL1);
4173 
4174 	ahc_outb(ahc, HCNTRL, CHIPRST | ahc->pause);
4175 
4176 	/*
4177 	 * Ensure that the reset has finished.  We delay 1000us
4178 	 * prior to reading the register to make sure the chip
4179 	 * has sufficiently completed its reset to handle register
4180 	 * accesses.
4181 	 */
4182 	wait = 1000;
4183 	do {
4184 		aic_delay(1000);
4185 	} while (--wait && !(ahc_inb(ahc, HCNTRL) & CHIPRSTACK));
4186 
4187 	if (wait == 0) {
4188 		printf("%s: WARNING - Failed chip reset!  "
4189 		       "Trying to initialize anyway.\n", ahc_name(ahc));
4190 	}
4191 	ahc_outb(ahc, HCNTRL, ahc->pause);
4192 
4193 	/* Determine channel configuration */
4194 	sblkctl = ahc_inb(ahc, SBLKCTL) & (SELBUSB|SELWIDE);
4195 	/* No Twin Channel PCI cards */
4196 	if ((ahc->chip & AHC_PCI) != 0)
4197 		sblkctl &= ~SELBUSB;
4198 	switch (sblkctl) {
4199 	case 0:
4200 		/* Single Narrow Channel */
4201 		break;
4202 	case 2:
4203 		/* Wide Channel */
4204 		ahc->features |= AHC_WIDE;
4205 		break;
4206 	case 8:
4207 		/* Twin Channel */
4208 		ahc->features |= AHC_TWIN;
4209 		break;
4210 	default:
4211 		printf(" Unsupported adapter type.  Ignoring\n");
4212 		return(-1);
4213 	}
4214 
4215 	/*
4216 	 * Reload sxfrctl1.
4217 	 *
4218 	 * We must always initialize STPWEN to 1 before we
4219 	 * restore the saved values.  STPWEN is initialized
4220 	 * to a tri-state condition which can only be cleared
4221 	 * by turning it on.
4222 	 */
4223 	if ((ahc->features & AHC_TWIN) != 0) {
4224 		u_int sblkctl;
4225 
4226 		sblkctl = ahc_inb(ahc, SBLKCTL);
4227 		ahc_outb(ahc, SBLKCTL, sblkctl | SELBUSB);
4228 		ahc_outb(ahc, SXFRCTL1, sxfrctl1_b);
4229 		ahc_outb(ahc, SBLKCTL, sblkctl & ~SELBUSB);
4230 	}
4231 	ahc_outb(ahc, SXFRCTL1, sxfrctl1_a);
4232 
4233 	error = 0;
4234 	if (reinit != 0)
4235 		/*
4236 		 * If a recovery action has forced a chip reset,
4237 		 * re-initialize the chip to our liking.
4238 		 */
4239 		error = ahc->bus_chip_init(ahc);
4240 #ifdef AHC_DUMP_SEQ
4241 	else
4242 		ahc_dumpseq(ahc);
4243 #endif
4244 
4245 	return (error);
4246 }
4247 
4248 /*
4249  * Determine the number of SCBs available on the controller
4250  */
4251 int
4252 ahc_probe_scbs(struct ahc_softc *ahc) {
4253 	int i;
4254 
4255 	for (i = 0; i < AHC_SCB_MAX; i++) {
4256 
4257 		ahc_outb(ahc, SCBPTR, i);
4258 		ahc_outb(ahc, SCB_BASE, i);
4259 		if (ahc_inb(ahc, SCB_BASE) != i)
4260 			break;
4261 		ahc_outb(ahc, SCBPTR, 0);
4262 		if (ahc_inb(ahc, SCB_BASE) != 0)
4263 			break;
4264 	}
4265 	return (i);
4266 }
4267 
4268 static void
4269 ahc_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
4270 {
4271 	bus_addr_t *baddr;
4272 
4273 	baddr = (bus_addr_t *)arg;
4274 	*baddr = segs->ds_addr;
4275 }
4276 
4277 static void
4278 ahc_build_free_scb_list(struct ahc_softc *ahc)
4279 {
4280 	int scbsize;
4281 	int i;
4282 
4283 	scbsize = 32;
4284 	if ((ahc->flags & AHC_LSCBS_ENABLED) != 0)
4285 		scbsize = 64;
4286 
4287 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
4288 		int j;
4289 
4290 		ahc_outb(ahc, SCBPTR, i);
4291 
4292 		/*
4293 		 * Touch all SCB bytes to avoid parity errors
4294 		 * should one of our debugging routines read
4295 		 * an otherwise uninitiatlized byte.
4296 		 */
4297 		for (j = 0; j < scbsize; j++)
4298 			ahc_outb(ahc, SCB_BASE+j, 0xFF);
4299 
4300 		/* Clear the control byte. */
4301 		ahc_outb(ahc, SCB_CONTROL, 0);
4302 
4303 		/* Set the next pointer */
4304 		if ((ahc->flags & AHC_PAGESCBS) != 0)
4305 			ahc_outb(ahc, SCB_NEXT, i+1);
4306 		else
4307 			ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4308 
4309 		/* Make the tag number, SCSIID, and lun invalid */
4310 		ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
4311 		ahc_outb(ahc, SCB_SCSIID, 0xFF);
4312 		ahc_outb(ahc, SCB_LUN, 0xFF);
4313 	}
4314 
4315 	if ((ahc->flags & AHC_PAGESCBS) != 0) {
4316 		/* SCB 0 heads the free list. */
4317 		ahc_outb(ahc, FREE_SCBH, 0);
4318 	} else {
4319 		/* No free list. */
4320 		ahc_outb(ahc, FREE_SCBH, SCB_LIST_NULL);
4321 	}
4322 
4323 	/* Make sure that the last SCB terminates the free list */
4324 	ahc_outb(ahc, SCBPTR, i-1);
4325 	ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
4326 }
4327 
4328 static int
4329 ahc_init_scbdata(struct ahc_softc *ahc)
4330 {
4331 	struct scb_data *scb_data;
4332 
4333 	scb_data = ahc->scb_data;
4334 	SLIST_INIT(&scb_data->free_scbs);
4335 	SLIST_INIT(&scb_data->sg_maps);
4336 
4337 	/* Allocate SCB resources */
4338 	scb_data->scbarray =
4339 	    (struct scb *)malloc(sizeof(struct scb) * AHC_SCB_MAX_ALLOC,
4340 				 M_DEVBUF, M_NOWAIT);
4341 	if (scb_data->scbarray == NULL)
4342 		return (ENOMEM);
4343 	memset(scb_data->scbarray, 0, sizeof(struct scb) * AHC_SCB_MAX_ALLOC);
4344 
4345 	/* Determine the number of hardware SCBs and initialize them */
4346 
4347 	scb_data->maxhscbs = ahc_probe_scbs(ahc);
4348 	if (ahc->scb_data->maxhscbs == 0) {
4349 		printf("%s: No SCB space found\n", ahc_name(ahc));
4350 		return (ENXIO);
4351 	}
4352 
4353 	/*
4354 	 * Create our DMA tags.  These tags define the kinds of device
4355 	 * accessible memory allocations and memory mappings we will
4356 	 * need to perform during normal operation.
4357 	 *
4358 	 * Unless we need to further restrict the allocation, we rely
4359 	 * on the restrictions of the parent dmat, hence the common
4360 	 * use of MAXADDR and MAXSIZE.
4361 	 */
4362 
4363 	/* DMA tag for our hardware scb structures */
4364 	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4365 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4366 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4367 			       /*highaddr*/BUS_SPACE_MAXADDR,
4368 			       /*filter*/NULL, /*filterarg*/NULL,
4369 			       AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4370 			       /*nsegments*/1,
4371 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4372 			       /*flags*/0, &scb_data->hscb_dmat) != 0) {
4373 		goto error_exit;
4374 	}
4375 
4376 	scb_data->init_level++;
4377 
4378 	/* Allocation for our hscbs */
4379 	if (aic_dmamem_alloc(ahc, scb_data->hscb_dmat,
4380 			     (void **)&scb_data->hscbs,
4381 			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4382 			     &scb_data->hscb_dmamap) != 0) {
4383 		goto error_exit;
4384 	}
4385 
4386 	scb_data->init_level++;
4387 
4388 	/* And permanently map them */
4389 	aic_dmamap_load(ahc, scb_data->hscb_dmat, scb_data->hscb_dmamap,
4390 			scb_data->hscbs,
4391 			AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb),
4392 			ahc_dmamap_cb, &scb_data->hscb_busaddr, /*flags*/0);
4393 
4394 	scb_data->init_level++;
4395 
4396 	/* DMA tag for our sense buffers */
4397 	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4398 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4399 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4400 			       /*highaddr*/BUS_SPACE_MAXADDR,
4401 			       /*filter*/NULL, /*filterarg*/NULL,
4402 			       AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4403 			       /*nsegments*/1,
4404 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4405 			       /*flags*/0, &scb_data->sense_dmat) != 0) {
4406 		goto error_exit;
4407 	}
4408 
4409 	scb_data->init_level++;
4410 
4411 	/* Allocate them */
4412 	if (aic_dmamem_alloc(ahc, scb_data->sense_dmat,
4413 			     (void **)&scb_data->sense,
4414 			     BUS_DMA_NOWAIT, &scb_data->sense_dmamap) != 0) {
4415 		goto error_exit;
4416 	}
4417 
4418 	scb_data->init_level++;
4419 
4420 	/* And permanently map them */
4421 	aic_dmamap_load(ahc, scb_data->sense_dmat, scb_data->sense_dmamap,
4422 			scb_data->sense,
4423 			AHC_SCB_MAX_ALLOC * sizeof(struct scsi_sense_data),
4424 			ahc_dmamap_cb, &scb_data->sense_busaddr, /*flags*/0);
4425 
4426 	scb_data->init_level++;
4427 
4428 	/* DMA tag for our S/G structures.  We allocate in page sized chunks */
4429 	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/8,
4430 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4431 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4432 			       /*highaddr*/BUS_SPACE_MAXADDR,
4433 			       /*filter*/NULL, /*filterarg*/NULL,
4434 			       PAGE_SIZE, /*nsegments*/1,
4435 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4436 			       /*flags*/0, &scb_data->sg_dmat) != 0) {
4437 		goto error_exit;
4438 	}
4439 
4440 	scb_data->init_level++;
4441 
4442 	/* Perform initial CCB allocation */
4443 	memset(scb_data->hscbs, 0,
4444 	       AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb));
4445 	while (ahc_alloc_scbs(ahc) != 0)
4446 		;
4447 
4448 	if (scb_data->numscbs == 0) {
4449 		printf("%s: ahc_init_scbdata - "
4450 		       "Unable to allocate initial scbs\n",
4451 		       ahc_name(ahc));
4452 		goto error_exit;
4453 	}
4454 
4455 	/*
4456 	 * Reserve the next queued SCB.
4457 	 */
4458 	ahc->next_queued_scb = ahc_get_scb(ahc);
4459 
4460 	/*
4461 	 * Note that we were successfull
4462 	 */
4463 	return (0);
4464 
4465 error_exit:
4466 
4467 	return (ENOMEM);
4468 }
4469 
4470 static void
4471 ahc_fini_scbdata(struct ahc_softc *ahc)
4472 {
4473 	struct scb_data *scb_data;
4474 
4475 	scb_data = ahc->scb_data;
4476 	if (scb_data == NULL)
4477 		return;
4478 
4479 	switch (scb_data->init_level) {
4480 	default:
4481 	case 7:
4482 	{
4483 		struct sg_map_node *sg_map;
4484 
4485 		while ((sg_map = SLIST_FIRST(&scb_data->sg_maps))!= NULL) {
4486 			SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
4487 			aic_dmamap_unload(ahc, scb_data->sg_dmat,
4488 					  sg_map->sg_dmamap);
4489 			aic_dmamem_free(ahc, scb_data->sg_dmat,
4490 					sg_map->sg_vaddr,
4491 					sg_map->sg_dmamap);
4492 			free(sg_map, M_DEVBUF);
4493 		}
4494 		aic_dma_tag_destroy(ahc, scb_data->sg_dmat);
4495 	}
4496 	case 6:
4497 		aic_dmamap_unload(ahc, scb_data->sense_dmat,
4498 				  scb_data->sense_dmamap);
4499 	case 5:
4500 		aic_dmamem_free(ahc, scb_data->sense_dmat, scb_data->sense,
4501 				scb_data->sense_dmamap);
4502 	case 4:
4503 		aic_dma_tag_destroy(ahc, scb_data->sense_dmat);
4504 	case 3:
4505 		aic_dmamap_unload(ahc, scb_data->hscb_dmat,
4506 				  scb_data->hscb_dmamap);
4507 	case 2:
4508 		aic_dmamem_free(ahc, scb_data->hscb_dmat, scb_data->hscbs,
4509 				scb_data->hscb_dmamap);
4510 	case 1:
4511 		aic_dma_tag_destroy(ahc, scb_data->hscb_dmat);
4512 		break;
4513 	case 0:
4514 		break;
4515 	}
4516 	if (scb_data->scbarray != NULL)
4517 		free(scb_data->scbarray, M_DEVBUF);
4518 }
4519 
4520 int
4521 ahc_alloc_scbs(struct ahc_softc *ahc)
4522 {
4523 	struct scb_data *scb_data;
4524 	struct scb *next_scb;
4525 	struct sg_map_node *sg_map;
4526 	bus_addr_t physaddr;
4527 	struct ahc_dma_seg *segs;
4528 	int newcount;
4529 	int i;
4530 
4531 	scb_data = ahc->scb_data;
4532 	if (scb_data->numscbs >= AHC_SCB_MAX_ALLOC)
4533 		/* Can't allocate any more */
4534 		return (0);
4535 
4536 	next_scb = &scb_data->scbarray[scb_data->numscbs];
4537 
4538 	sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
4539 
4540 	if (sg_map == NULL)
4541 		return (0);
4542 
4543 	/* Allocate S/G space for the next batch of SCBS */
4544 	if (aic_dmamem_alloc(ahc, scb_data->sg_dmat,
4545 			     (void **)&sg_map->sg_vaddr,
4546 			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4547 			     &sg_map->sg_dmamap) != 0) {
4548 		free(sg_map, M_DEVBUF);
4549 		return (0);
4550 	}
4551 
4552 	SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
4553 
4554 	aic_dmamap_load(ahc, scb_data->sg_dmat, sg_map->sg_dmamap,
4555 			sg_map->sg_vaddr, PAGE_SIZE, ahc_dmamap_cb,
4556 			&sg_map->sg_physaddr, /*flags*/0);
4557 
4558 	segs = sg_map->sg_vaddr;
4559 	physaddr = sg_map->sg_physaddr;
4560 
4561 	newcount = (PAGE_SIZE / (AHC_NSEG * sizeof(struct ahc_dma_seg)));
4562 	newcount = MIN(newcount, (AHC_SCB_MAX_ALLOC - scb_data->numscbs));
4563 	for (i = 0; i < newcount; i++) {
4564 		struct scb_platform_data *pdata;
4565 #ifndef __linux__
4566 		int error;
4567 #endif
4568 		pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
4569 							   M_DEVBUF, M_NOWAIT);
4570 		if (pdata == NULL)
4571 			break;
4572 		next_scb->platform_data = pdata;
4573 		next_scb->sg_map = sg_map;
4574 		next_scb->sg_list = segs;
4575 		/*
4576 		 * The sequencer always starts with the second entry.
4577 		 * The first entry is embedded in the scb.
4578 		 */
4579 		next_scb->sg_list_phys = physaddr + sizeof(struct ahc_dma_seg);
4580 		next_scb->ahc_softc = ahc;
4581 		next_scb->flags = SCB_FLAG_NONE;
4582 #ifndef __linux__
4583 		error = aic_dmamap_create(ahc, ahc->buffer_dmat, /*flags*/0,
4584 					  &next_scb->dmamap);
4585 		if (error != 0)
4586 			break;
4587 #endif
4588 		next_scb->hscb = &scb_data->hscbs[scb_data->numscbs];
4589 		next_scb->hscb->tag = ahc->scb_data->numscbs;
4590 		aic_timer_init(&next_scb->io_timer);
4591 		SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs,
4592 				  next_scb, links.sle);
4593 		segs += AHC_NSEG;
4594 		physaddr += (AHC_NSEG * sizeof(struct ahc_dma_seg));
4595 		next_scb++;
4596 		ahc->scb_data->numscbs++;
4597 	}
4598 	return (i);
4599 }
4600 
4601 void
4602 ahc_controller_info(struct ahc_softc *ahc, char *buf)
4603 {
4604 	int len;
4605 
4606 	len = sprintf(buf, "%s: ", ahc_chip_names[ahc->chip & AHC_CHIPID_MASK]);
4607 	buf += len;
4608 	if ((ahc->features & AHC_TWIN) != 0)
4609  		len = sprintf(buf, "Twin Channel, A SCSI Id=%d, "
4610 			      "B SCSI Id=%d, primary %c, ",
4611 			      ahc->our_id, ahc->our_id_b,
4612 			      (ahc->flags & AHC_PRIMARY_CHANNEL) + 'A');
4613 	else {
4614 		const char *speed;
4615 		const char *type;
4616 
4617 		speed = "";
4618 		if ((ahc->features & AHC_ULTRA) != 0) {
4619 			speed = "Ultra ";
4620 		} else if ((ahc->features & AHC_DT) != 0) {
4621 			speed = "Ultra160 ";
4622 		} else if ((ahc->features & AHC_ULTRA2) != 0) {
4623 			speed = "Ultra2 ";
4624 		}
4625 		if ((ahc->features & AHC_WIDE) != 0) {
4626 			type = "Wide";
4627 		} else {
4628 			type = "Single";
4629 		}
4630 		len = sprintf(buf, "%s%s Channel %c, SCSI Id=%d, ",
4631 			      speed, type, ahc->channel, ahc->our_id);
4632 	}
4633 	buf += len;
4634 
4635 	if ((ahc->flags & AHC_PAGESCBS) != 0)
4636 		sprintf(buf, "%d/%d SCBs",
4637 			ahc->scb_data->maxhscbs, AHC_MAX_QUEUE);
4638 	else
4639 		sprintf(buf, "%d SCBs", ahc->scb_data->maxhscbs);
4640 }
4641 
4642 int
4643 ahc_chip_init(struct ahc_softc *ahc)
4644 {
4645 	int	 term;
4646 	int	 error;
4647 	u_int	 i;
4648 	u_int	 scsi_conf;
4649 	u_int	 scsiseq_template;
4650 	uint32_t physaddr;
4651 
4652 	ahc_outb(ahc, SEQ_FLAGS, 0);
4653 	ahc_outb(ahc, SEQ_FLAGS2, 0);
4654 
4655 	/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
4656 	if (ahc->features & AHC_TWIN) {
4657 
4658 		/*
4659 		 * Setup Channel B first.
4660 		 */
4661 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
4662 		term = (ahc->flags & AHC_TERM_ENB_B) != 0 ? STPWEN : 0;
4663 		ahc_outb(ahc, SCSIID, ahc->our_id_b);
4664 		scsi_conf = ahc_inb(ahc, SCSICONF + 1);
4665 		ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4666 					|term|ahc->seltime_b|ENSTIMER|ACTNEGEN);
4667 		if ((ahc->features & AHC_ULTRA2) != 0)
4668 			ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4669 		ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4670 		ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4671 
4672 		/* Select Channel A */
4673 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
4674 	}
4675 	term = (ahc->flags & AHC_TERM_ENB_A) != 0 ? STPWEN : 0;
4676 	if ((ahc->features & AHC_ULTRA2) != 0)
4677 		ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
4678 	else
4679 		ahc_outb(ahc, SCSIID, ahc->our_id);
4680 	scsi_conf = ahc_inb(ahc, SCSICONF);
4681 	ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
4682 				|term|ahc->seltime
4683 				|ENSTIMER|ACTNEGEN);
4684 	if ((ahc->features & AHC_ULTRA2) != 0)
4685 		ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
4686 	ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
4687 	ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
4688 
4689 	/* There are no untagged SCBs active yet. */
4690 	for (i = 0; i < 16; i++) {
4691 		ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, 0));
4692 		if ((ahc->flags & AHC_SCB_BTT) != 0) {
4693 			int lun;
4694 
4695 			/*
4696 			 * The SCB based BTT allows an entry per
4697 			 * target and lun pair.
4698 			 */
4699 			for (lun = 1; lun < AHC_NUM_LUNS; lun++)
4700 				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, lun));
4701 		}
4702 	}
4703 
4704 	/* All of our queues are empty */
4705 	for (i = 0; i < 256; i++)
4706 		ahc->qoutfifo[i] = SCB_LIST_NULL;
4707 	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_PREREAD);
4708 
4709 	for (i = 0; i < 256; i++)
4710 		ahc->qinfifo[i] = SCB_LIST_NULL;
4711 
4712 	if ((ahc->features & AHC_MULTI_TID) != 0) {
4713 		ahc_outb(ahc, TARGID, 0);
4714 		ahc_outb(ahc, TARGID + 1, 0);
4715 	}
4716 
4717 	/*
4718 	 * Tell the sequencer where it can find our arrays in memory.
4719 	 */
4720 	physaddr = ahc->scb_data->hscb_busaddr;
4721 	ahc_outb(ahc, HSCB_ADDR, physaddr & 0xFF);
4722 	ahc_outb(ahc, HSCB_ADDR + 1, (physaddr >> 8) & 0xFF);
4723 	ahc_outb(ahc, HSCB_ADDR + 2, (physaddr >> 16) & 0xFF);
4724 	ahc_outb(ahc, HSCB_ADDR + 3, (physaddr >> 24) & 0xFF);
4725 
4726 	physaddr = ahc->shared_data_busaddr;
4727 	ahc_outb(ahc, SHARED_DATA_ADDR, physaddr & 0xFF);
4728 	ahc_outb(ahc, SHARED_DATA_ADDR + 1, (physaddr >> 8) & 0xFF);
4729 	ahc_outb(ahc, SHARED_DATA_ADDR + 2, (physaddr >> 16) & 0xFF);
4730 	ahc_outb(ahc, SHARED_DATA_ADDR + 3, (physaddr >> 24) & 0xFF);
4731 
4732 	/*
4733 	 * Initialize the group code to command length table.
4734 	 * This overrides the values in TARG_SCSIRATE, so only
4735 	 * setup the table after we have processed that information.
4736 	 */
4737 	ahc_outb(ahc, CMDSIZE_TABLE, 5);
4738 	ahc_outb(ahc, CMDSIZE_TABLE + 1, 9);
4739 	ahc_outb(ahc, CMDSIZE_TABLE + 2, 9);
4740 	ahc_outb(ahc, CMDSIZE_TABLE + 3, 0);
4741 	ahc_outb(ahc, CMDSIZE_TABLE + 4, 15);
4742 	ahc_outb(ahc, CMDSIZE_TABLE + 5, 11);
4743 	ahc_outb(ahc, CMDSIZE_TABLE + 6, 0);
4744 	ahc_outb(ahc, CMDSIZE_TABLE + 7, 0);
4745 
4746 	if ((ahc->features & AHC_HS_MAILBOX) != 0)
4747 		ahc_outb(ahc, HS_MAILBOX, 0);
4748 
4749 	/* Tell the sequencer of our initial queue positions */
4750 	if ((ahc->features & AHC_TARGETMODE) != 0) {
4751 		ahc->tqinfifonext = 1;
4752 		ahc_outb(ahc, KERNEL_TQINPOS, ahc->tqinfifonext - 1);
4753 		ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
4754 	}
4755 	ahc->qinfifonext = 0;
4756 	ahc->qoutfifonext = 0;
4757 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
4758 		ahc_outb(ahc, QOFF_CTLSTA, SCB_QSIZE_256);
4759 		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
4760 		ahc_outb(ahc, SNSCB_QOFF, ahc->qinfifonext);
4761 		ahc_outb(ahc, SDSCB_QOFF, 0);
4762 	} else {
4763 		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
4764 		ahc_outb(ahc, QINPOS, ahc->qinfifonext);
4765 		ahc_outb(ahc, QOUTPOS, ahc->qoutfifonext);
4766 	}
4767 
4768 	/* We don't have any waiting selections */
4769 	ahc_outb(ahc, WAITING_SCBH, SCB_LIST_NULL);
4770 
4771 	/* Our disconnection list is empty too */
4772 	ahc_outb(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
4773 
4774 	/* Message out buffer starts empty */
4775 	ahc_outb(ahc, MSG_OUT, MSG_NOOP);
4776 
4777 	/*
4778 	 * Setup the allowed SCSI Sequences based on operational mode.
4779 	 * If we are a target, we'll enalbe select in operations once
4780 	 * we've had a lun enabled.
4781 	 */
4782 	scsiseq_template = ENSELO|ENAUTOATNO|ENAUTOATNP;
4783 	if ((ahc->flags & AHC_INITIATORROLE) != 0)
4784 		scsiseq_template |= ENRSELI;
4785 	ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq_template);
4786 
4787 	/* Initialize our list of free SCBs. */
4788 	ahc_build_free_scb_list(ahc);
4789 
4790 	/*
4791 	 * Tell the sequencer which SCB will be the next one it receives.
4792 	 */
4793 	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
4794 
4795 	/*
4796 	 * Load the Sequencer program and Enable the adapter
4797 	 * in "fast" mode.
4798 	 */
4799 	if (bootverbose)
4800 		printf("%s: Downloading Sequencer Program...",
4801 		       ahc_name(ahc));
4802 
4803 	error = ahc_loadseq(ahc);
4804 	if (error != 0)
4805 		return (error);
4806 
4807 	if ((ahc->features & AHC_ULTRA2) != 0) {
4808 		int wait;
4809 
4810 		/*
4811 		 * Wait for up to 500ms for our transceivers
4812 		 * to settle.  If the adapter does not have
4813 		 * a cable attached, the transceivers may
4814 		 * never settle, so don't complain if we
4815 		 * fail here.
4816 		 */
4817 		for (wait = 5000;
4818 		     (ahc_inb(ahc, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
4819 		     wait--)
4820 			aic_delay(100);
4821 	}
4822 	ahc_restart(ahc);
4823 	return (0);
4824 }
4825 
4826 /*
4827  * Start the board, ready for normal operation
4828  */
4829 int
4830 ahc_init(struct ahc_softc *ahc)
4831 {
4832 	int	 max_targ;
4833 	int	 error;
4834 	u_int	 i;
4835 	u_int	 scsi_conf;
4836 	u_int	 ultraenb;
4837 	u_int	 discenable;
4838 	u_int	 tagenable;
4839 	size_t	 driver_data_size;
4840 
4841 #ifdef AHC_DEBUG
4842 	if ((ahc_debug & AHC_DEBUG_SEQUENCER) != 0)
4843 		ahc->flags |= AHC_SEQUENCER_DEBUG;
4844 #endif
4845 
4846 #ifdef AHC_PRINT_SRAM
4847 	printf("Scratch Ram:");
4848 	for (i = 0x20; i < 0x5f; i++) {
4849 		if (((i % 8) == 0) && (i != 0)) {
4850 			printf ("\n              ");
4851 		}
4852 		printf (" 0x%x", ahc_inb(ahc, i));
4853 	}
4854 	if ((ahc->features & AHC_MORE_SRAM) != 0) {
4855 		for (i = 0x70; i < 0x7f; i++) {
4856 			if (((i % 8) == 0) && (i != 0)) {
4857 				printf ("\n              ");
4858 			}
4859 			printf (" 0x%x", ahc_inb(ahc, i));
4860 		}
4861 	}
4862 	printf ("\n");
4863 	/*
4864 	 * Reading uninitialized scratch ram may
4865 	 * generate parity errors.
4866 	 */
4867 	ahc_outb(ahc, CLRINT, CLRPARERR);
4868 	ahc_outb(ahc, CLRINT, CLRBRKADRINT);
4869 #endif
4870 	max_targ = 15;
4871 
4872 	/*
4873 	 * Assume we have a board at this stage and it has been reset.
4874 	 */
4875 	if ((ahc->flags & AHC_USEDEFAULTS) != 0)
4876 		ahc->our_id = ahc->our_id_b = 7;
4877 
4878 	/*
4879 	 * Default to allowing initiator operations.
4880 	 */
4881 	ahc->flags |= AHC_INITIATORROLE;
4882 
4883 	/*
4884 	 * Only allow target mode features if this unit has them enabled.
4885 	 */
4886 	if ((AHC_TMODE_ENABLE & (0x1 << ahc->unit)) == 0)
4887 		ahc->features &= ~AHC_TARGETMODE;
4888 
4889 #ifndef __linux__
4890 	/* DMA tag for mapping buffers into device visible space. */
4891 	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4892 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4893 			       /*lowaddr*/ahc->flags & AHC_39BIT_ADDRESSING
4894 					? (bus_addr_t)0x7FFFFFFFFFULL
4895 					: BUS_SPACE_MAXADDR_32BIT,
4896 			       /*highaddr*/BUS_SPACE_MAXADDR,
4897 			       /*filter*/NULL, /*filterarg*/NULL,
4898 			       /*maxsize*/(AHC_NSEG - 1) * PAGE_SIZE,
4899 			       /*nsegments*/AHC_NSEG,
4900 			       /*maxsegsz*/AHC_MAXTRANSFER_SIZE,
4901 			       /*flags*/BUS_DMA_ALLOCNOW,
4902 			       &ahc->buffer_dmat) != 0) {
4903 		return (ENOMEM);
4904 	}
4905 #endif
4906 
4907 	ahc->init_level++;
4908 
4909 	/*
4910 	 * DMA tag for our command fifos and other data in system memory
4911 	 * the card's sequencer must be able to access.  For initiator
4912 	 * roles, we need to allocate space for the qinfifo and qoutfifo.
4913 	 * The qinfifo and qoutfifo are composed of 256 1 byte elements.
4914 	 * When providing for the target mode role, we must additionally
4915 	 * provide space for the incoming target command fifo and an extra
4916 	 * byte to deal with a dma bug in some chip versions.
4917 	 */
4918 	driver_data_size = 2 * 256 * sizeof(uint8_t);
4919 	if ((ahc->features & AHC_TARGETMODE) != 0)
4920 		driver_data_size += AHC_TMODE_CMDS * sizeof(struct target_cmd)
4921 				 + /*DMA WideOdd Bug Buffer*/1;
4922 	if (aic_dma_tag_create(ahc, ahc->parent_dmat, /*alignment*/1,
4923 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
4924 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
4925 			       /*highaddr*/BUS_SPACE_MAXADDR,
4926 			       /*filter*/NULL, /*filterarg*/NULL,
4927 			       driver_data_size,
4928 			       /*nsegments*/1,
4929 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
4930 			       /*flags*/0, &ahc->shared_data_dmat) != 0) {
4931 		return (ENOMEM);
4932 	}
4933 
4934 	ahc->init_level++;
4935 
4936 	/* Allocation of driver data */
4937 	if (aic_dmamem_alloc(ahc, ahc->shared_data_dmat,
4938 			     (void **)&ahc->qoutfifo,
4939 			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
4940 			     &ahc->shared_data_dmamap) != 0) {
4941 		return (ENOMEM);
4942 	}
4943 
4944 	ahc->init_level++;
4945 
4946 	/* And permanently map it in */
4947 	aic_dmamap_load(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
4948 			ahc->qoutfifo, driver_data_size, ahc_dmamap_cb,
4949 			&ahc->shared_data_busaddr, /*flags*/0);
4950 
4951 	if ((ahc->features & AHC_TARGETMODE) != 0) {
4952 		ahc->targetcmds = (struct target_cmd *)ahc->qoutfifo;
4953 		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[AHC_TMODE_CMDS];
4954 		ahc->dma_bug_buf = ahc->shared_data_busaddr
4955 				 + driver_data_size - 1;
4956 		/* All target command blocks start out invalid. */
4957 		for (i = 0; i < AHC_TMODE_CMDS; i++)
4958 			ahc->targetcmds[i].cmd_valid = 0;
4959 		ahc_sync_tqinfifo(ahc, BUS_DMASYNC_PREREAD);
4960 		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[256];
4961 	}
4962 	ahc->qinfifo = &ahc->qoutfifo[256];
4963 
4964 	ahc->init_level++;
4965 
4966 	/* Allocate SCB data now that buffer_dmat is initialized */
4967 	if (ahc->scb_data->maxhscbs == 0)
4968 		if (ahc_init_scbdata(ahc) != 0)
4969 			return (ENOMEM);
4970 
4971 	/*
4972 	 * Allocate a tstate to house information for our
4973 	 * initiator presence on the bus as well as the user
4974 	 * data for any target mode initiator.
4975 	 */
4976 	if (ahc_alloc_tstate(ahc, ahc->our_id, 'A') == NULL) {
4977 		printf("%s: unable to allocate ahc_tmode_tstate.  "
4978 		       "Failing attach\n", ahc_name(ahc));
4979 		return (ENOMEM);
4980 	}
4981 
4982 	if ((ahc->features & AHC_TWIN) != 0) {
4983 		if (ahc_alloc_tstate(ahc, ahc->our_id_b, 'B') == NULL) {
4984 			printf("%s: unable to allocate ahc_tmode_tstate.  "
4985 			       "Failing attach\n", ahc_name(ahc));
4986 			return (ENOMEM);
4987 		}
4988 	}
4989 
4990 	/*
4991 	 * Fire up a recovery thread for this controller.
4992 	 */
4993 	error = ahc_spawn_recovery_thread(ahc);
4994 	if (error != 0)
4995 		return (error);
4996 
4997 	if (ahc->scb_data->maxhscbs < AHC_SCB_MAX_ALLOC) {
4998 		ahc->flags |= AHC_PAGESCBS;
4999 	} else {
5000 		ahc->flags &= ~AHC_PAGESCBS;
5001 	}
5002 
5003 #ifdef AHC_DEBUG
5004 	if (ahc_debug & AHC_SHOW_MISC) {
5005 		printf("%s: hardware scb %u bytes; kernel scb %u bytes; "
5006 		       "ahc_dma %u bytes\n",
5007 			ahc_name(ahc),
5008 			(u_int)sizeof(struct hardware_scb),
5009 			(u_int)sizeof(struct scb),
5010 			(u_int)sizeof(struct ahc_dma_seg));
5011 	}
5012 #endif /* AHC_DEBUG */
5013 
5014 	/*
5015 	 * Look at the information that board initialization or
5016 	 * the board bios has left us.
5017 	 */
5018 	if (ahc->features & AHC_TWIN) {
5019 		scsi_conf = ahc_inb(ahc, SCSICONF + 1);
5020 		if ((scsi_conf & RESET_SCSI) != 0
5021 		 && (ahc->flags & AHC_INITIATORROLE) != 0)
5022 			ahc->flags |= AHC_RESET_BUS_B;
5023 	}
5024 
5025 	scsi_conf = ahc_inb(ahc, SCSICONF);
5026 	if ((scsi_conf & RESET_SCSI) != 0
5027 	 && (ahc->flags & AHC_INITIATORROLE) != 0)
5028 		ahc->flags |= AHC_RESET_BUS_A;
5029 
5030 	ultraenb = 0;
5031 	tagenable = ALL_TARGETS_MASK;
5032 
5033 	/* Grab the disconnection disable table and invert it for our needs */
5034 	if ((ahc->flags & AHC_USEDEFAULTS) != 0) {
5035 		printf("%s: Host Adapter Bios disabled.  Using default SCSI "
5036 			"device parameters\n", ahc_name(ahc));
5037 		ahc->flags |= AHC_EXTENDED_TRANS_A|AHC_EXTENDED_TRANS_B|
5038 			      AHC_TERM_ENB_A|AHC_TERM_ENB_B;
5039 		discenable = ALL_TARGETS_MASK;
5040 		if ((ahc->features & AHC_ULTRA) != 0)
5041 			ultraenb = ALL_TARGETS_MASK;
5042 	} else {
5043 		discenable = ~((ahc_inb(ahc, DISC_DSB + 1) << 8)
5044 			   | ahc_inb(ahc, DISC_DSB));
5045 		if ((ahc->features & (AHC_ULTRA|AHC_ULTRA2)) != 0)
5046 			ultraenb = (ahc_inb(ahc, ULTRA_ENB + 1) << 8)
5047 				      | ahc_inb(ahc, ULTRA_ENB);
5048 	}
5049 
5050 	if ((ahc->features & (AHC_WIDE|AHC_TWIN)) == 0)
5051 		max_targ = 7;
5052 
5053 	for (i = 0; i <= max_targ; i++) {
5054 		struct ahc_initiator_tinfo *tinfo;
5055 		struct ahc_tmode_tstate *tstate;
5056 		u_int our_id;
5057 		u_int target_id;
5058 		char channel;
5059 
5060 		channel = 'A';
5061 		our_id = ahc->our_id;
5062 		target_id = i;
5063 		if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
5064 			channel = 'B';
5065 			our_id = ahc->our_id_b;
5066 			target_id = i % 8;
5067 		}
5068 		tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
5069 					    target_id, &tstate);
5070 		/* Default to async narrow across the board */
5071 		memset(tinfo, 0, sizeof(*tinfo));
5072 		if (ahc->flags & AHC_USEDEFAULTS) {
5073 			if ((ahc->features & AHC_WIDE) != 0)
5074 				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
5075 
5076 			/*
5077 			 * These will be truncated when we determine the
5078 			 * connection type we have with the target.
5079 			 */
5080 			tinfo->user.period = ahc_syncrates->period;
5081 			tinfo->user.offset = MAX_OFFSET;
5082 		} else {
5083 			u_int scsirate;
5084 			uint16_t mask;
5085 
5086 			/* Take the settings leftover in scratch RAM. */
5087 			scsirate = ahc_inb(ahc, TARG_SCSIRATE + i);
5088 			mask = (0x01 << i);
5089 			if ((ahc->features & AHC_ULTRA2) != 0) {
5090 				u_int offset;
5091 				u_int maxsync;
5092 
5093 				if ((scsirate & SOFS) == 0x0F) {
5094 					/*
5095 					 * Haven't negotiated yet,
5096 					 * so the format is different.
5097 					 */
5098 					scsirate = (scsirate & SXFR) >> 4
5099 						 | (ultraenb & mask)
5100 						  ? 0x08 : 0x0
5101 						 | (scsirate & WIDEXFER);
5102 					offset = MAX_OFFSET_ULTRA2;
5103 				} else
5104 					offset = ahc_inb(ahc, TARG_OFFSET + i);
5105 				if ((scsirate & ~WIDEXFER) == 0 && offset != 0)
5106 					/* Set to the lowest sync rate, 5MHz */
5107 					scsirate |= 0x1c;
5108 				maxsync = AHC_SYNCRATE_ULTRA2;
5109 				if ((ahc->features & AHC_DT) != 0)
5110 					maxsync = AHC_SYNCRATE_DT;
5111 				tinfo->user.period =
5112 				    ahc_find_period(ahc, scsirate, maxsync);
5113 				if (offset == 0)
5114 					tinfo->user.period = 0;
5115 				else
5116 					tinfo->user.offset = MAX_OFFSET;
5117 				if ((scsirate & SXFR_ULTRA2) <= 8/*10MHz*/
5118 				 && (ahc->features & AHC_DT) != 0)
5119 					tinfo->user.ppr_options =
5120 					    MSG_EXT_PPR_DT_REQ;
5121 			} else if ((scsirate & SOFS) != 0) {
5122 				if ((scsirate & SXFR) == 0x40
5123 				 && (ultraenb & mask) != 0) {
5124 					/* Treat 10MHz as a non-ultra speed */
5125 					scsirate &= ~SXFR;
5126 				 	ultraenb &= ~mask;
5127 				}
5128 				tinfo->user.period =
5129 				    ahc_find_period(ahc, scsirate,
5130 						    (ultraenb & mask)
5131 						   ? AHC_SYNCRATE_ULTRA
5132 						   : AHC_SYNCRATE_FAST);
5133 				if (tinfo->user.period != 0)
5134 					tinfo->user.offset = MAX_OFFSET;
5135 			}
5136 			if (tinfo->user.period == 0)
5137 				tinfo->user.offset = 0;
5138 			if ((scsirate & WIDEXFER) != 0
5139 			 && (ahc->features & AHC_WIDE) != 0)
5140 				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
5141 			tinfo->user.protocol_version = 4;
5142 			if ((ahc->features & AHC_DT) != 0)
5143 				tinfo->user.transport_version = 3;
5144 			else
5145 				tinfo->user.transport_version = 2;
5146 			tinfo->goal.protocol_version = 2;
5147 			tinfo->goal.transport_version = 2;
5148 			tinfo->curr.protocol_version = 2;
5149 			tinfo->curr.transport_version = 2;
5150 		}
5151 		tstate->ultraenb = 0;
5152 	}
5153 	ahc->user_discenable = discenable;
5154 	ahc->user_tagenable = tagenable;
5155 
5156 	return (ahc->bus_chip_init(ahc));
5157 }
5158 
5159 void
5160 ahc_intr_enable(struct ahc_softc *ahc, int enable)
5161 {
5162 	u_int hcntrl;
5163 
5164 	hcntrl = ahc_inb(ahc, HCNTRL);
5165 	hcntrl &= ~INTEN;
5166 	ahc->pause &= ~INTEN;
5167 	ahc->unpause &= ~INTEN;
5168 	if (enable) {
5169 		hcntrl |= INTEN;
5170 		ahc->pause |= INTEN;
5171 		ahc->unpause |= INTEN;
5172 	}
5173 	ahc_outb(ahc, HCNTRL, hcntrl);
5174 }
5175 
5176 /*
5177  * Ensure that the card is paused in a location
5178  * outside of all critical sections and that all
5179  * pending work is completed prior to returning.
5180  * This routine should only be called from outside
5181  * an interrupt context.
5182  */
5183 void
5184 ahc_pause_and_flushwork(struct ahc_softc *ahc)
5185 {
5186 	int intstat;
5187 	int maxloops;
5188 	int paused;
5189 
5190 	maxloops = 1000;
5191 	ahc->flags |= AHC_ALL_INTERRUPTS;
5192 	paused = FALSE;
5193 	do {
5194 		if (paused) {
5195 			ahc_unpause(ahc);
5196 			/*
5197 			 * Give the sequencer some time to service
5198 			 * any active selections.
5199 			 */
5200 			aic_delay(500);
5201 		}
5202 		ahc_intr(ahc);
5203 		ahc_pause(ahc);
5204 		paused = TRUE;
5205 		ahc_outb(ahc, SCSISEQ, ahc_inb(ahc, SCSISEQ) & ~ENSELO);
5206 		intstat = ahc_inb(ahc, INTSTAT);
5207 		if ((intstat & INT_PEND) == 0) {
5208 			ahc_clear_critical_section(ahc);
5209 			intstat = ahc_inb(ahc, INTSTAT);
5210 		}
5211 	} while (--maxloops
5212 	      && (intstat != 0xFF || (ahc->features & AHC_REMOVABLE) == 0)
5213 	      && ((intstat & INT_PEND) != 0
5214 	       || (ahc_inb(ahc, SSTAT0) & (SELDO|SELINGO)) != 0));
5215 	if (maxloops == 0) {
5216 		printf("Infinite interrupt loop, INTSTAT = %x",
5217 		       ahc_inb(ahc, INTSTAT));
5218 	}
5219 	ahc_platform_flushwork(ahc);
5220 	ahc->flags &= ~AHC_ALL_INTERRUPTS;
5221 }
5222 
5223 int
5224 ahc_suspend(struct ahc_softc *ahc)
5225 {
5226 
5227 	ahc_pause_and_flushwork(ahc);
5228 
5229 	if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
5230 		ahc_unpause(ahc);
5231 		return (EBUSY);
5232 	}
5233 
5234 #ifdef AHC_TARGET_MODE
5235 	/*
5236 	 * XXX What about ATIOs that have not yet been serviced?
5237 	 * Perhaps we should just refuse to be suspended if we
5238 	 * are acting in a target role.
5239 	 */
5240 	if (ahc->pending_device != NULL) {
5241 		ahc_unpause(ahc);
5242 		return (EBUSY);
5243 	}
5244 #endif
5245 	ahc_shutdown(ahc);
5246 	return (0);
5247 }
5248 
5249 int
5250 ahc_resume(struct ahc_softc *ahc)
5251 {
5252 
5253 	ahc_reset(ahc, /*reinit*/TRUE);
5254 	ahc_intr_enable(ahc, TRUE);
5255 	ahc_restart(ahc);
5256 	return (0);
5257 }
5258 
5259 /************************** Busy Target Table *********************************/
5260 /*
5261  * Return the untagged transaction id for a given target/channel lun.
5262  * Optionally, clear the entry.
5263  */
5264 u_int
5265 ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl)
5266 {
5267 	u_int scbid;
5268 	u_int target_offset;
5269 
5270 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5271 		u_int saved_scbptr;
5272 
5273 		saved_scbptr = ahc_inb(ahc, SCBPTR);
5274 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5275 		scbid = ahc_inb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl));
5276 		ahc_outb(ahc, SCBPTR, saved_scbptr);
5277 	} else {
5278 		target_offset = TCL_TARGET_OFFSET(tcl);
5279 		scbid = ahc_inb(ahc, BUSY_TARGETS + target_offset);
5280 	}
5281 
5282 	return (scbid);
5283 }
5284 
5285 void
5286 ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl)
5287 {
5288 	u_int target_offset;
5289 
5290 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5291 		u_int saved_scbptr;
5292 
5293 		saved_scbptr = ahc_inb(ahc, SCBPTR);
5294 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5295 		ahc_outb(ahc, SCB_64_BTT+TCL_TARGET_OFFSET(tcl), SCB_LIST_NULL);
5296 		ahc_outb(ahc, SCBPTR, saved_scbptr);
5297 	} else {
5298 		target_offset = TCL_TARGET_OFFSET(tcl);
5299 		ahc_outb(ahc, BUSY_TARGETS + target_offset, SCB_LIST_NULL);
5300 	}
5301 }
5302 
5303 void
5304 ahc_busy_tcl(struct ahc_softc *ahc, u_int tcl, u_int scbid)
5305 {
5306 	u_int target_offset;
5307 
5308 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
5309 		u_int saved_scbptr;
5310 
5311 		saved_scbptr = ahc_inb(ahc, SCBPTR);
5312 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
5313 		ahc_outb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl), scbid);
5314 		ahc_outb(ahc, SCBPTR, saved_scbptr);
5315 	} else {
5316 		target_offset = TCL_TARGET_OFFSET(tcl);
5317 		ahc_outb(ahc, BUSY_TARGETS + target_offset, scbid);
5318 	}
5319 }
5320 
5321 /************************** SCB and SCB queue management **********************/
5322 int
5323 ahc_match_scb(struct ahc_softc *ahc, struct scb *scb, int target,
5324 	      char channel, int lun, u_int tag, role_t role)
5325 {
5326 	int targ = SCB_GET_TARGET(ahc, scb);
5327 	char chan = SCB_GET_CHANNEL(ahc, scb);
5328 	int slun = SCB_GET_LUN(scb);
5329 	int match;
5330 
5331 	match = ((chan == channel) || (channel == ALL_CHANNELS));
5332 	if (match != 0)
5333 		match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
5334 	if (match != 0)
5335 		match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
5336 	if (match != 0) {
5337 #ifdef AHC_TARGET_MODE
5338 		int group;
5339 
5340 		group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
5341 		if (role == ROLE_INITIATOR) {
5342 			match = (group != XPT_FC_GROUP_TMODE)
5343 			      && ((tag == scb->hscb->tag)
5344 			       || (tag == SCB_LIST_NULL));
5345 		} else if (role == ROLE_TARGET) {
5346 			match = (group == XPT_FC_GROUP_TMODE)
5347 			      && ((tag == scb->io_ctx->csio.tag_id)
5348 			       || (tag == SCB_LIST_NULL));
5349 		}
5350 #else /* !AHC_TARGET_MODE */
5351 		match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
5352 #endif /* AHC_TARGET_MODE */
5353 	}
5354 
5355 	return match;
5356 }
5357 
5358 void
5359 ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
5360 {
5361 	int	target;
5362 	char	channel;
5363 	int	lun;
5364 
5365 	target = SCB_GET_TARGET(ahc, scb);
5366 	lun = SCB_GET_LUN(scb);
5367 	channel = SCB_GET_CHANNEL(ahc, scb);
5368 
5369 	ahc_search_qinfifo(ahc, target, channel, lun,
5370 			   /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
5371 			   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5372 
5373 	ahc_platform_freeze_devq(ahc, scb);
5374 }
5375 
5376 void
5377 ahc_qinfifo_requeue_tail(struct ahc_softc *ahc, struct scb *scb)
5378 {
5379 	struct scb *prev_scb;
5380 
5381 	prev_scb = NULL;
5382 	if (ahc_qinfifo_count(ahc) != 0) {
5383 		u_int prev_tag;
5384 		uint8_t prev_pos;
5385 
5386 		prev_pos = ahc->qinfifonext - 1;
5387 		prev_tag = ahc->qinfifo[prev_pos];
5388 		prev_scb = ahc_lookup_scb(ahc, prev_tag);
5389 	}
5390 	ahc_qinfifo_requeue(ahc, prev_scb, scb);
5391 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5392 		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5393 	} else {
5394 		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5395 	}
5396 }
5397 
5398 static void
5399 ahc_qinfifo_requeue(struct ahc_softc *ahc, struct scb *prev_scb,
5400 		    struct scb *scb)
5401 {
5402 	if (prev_scb == NULL) {
5403 		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5404 	} else {
5405 		prev_scb->hscb->next = scb->hscb->tag;
5406 		ahc_sync_scb(ahc, prev_scb,
5407 			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5408 	}
5409 	ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
5410 	scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5411 	ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
5412 }
5413 
5414 static int
5415 ahc_qinfifo_count(struct ahc_softc *ahc)
5416 {
5417 	uint8_t qinpos;
5418 	uint8_t diff;
5419 
5420 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5421 		qinpos = ahc_inb(ahc, SNSCB_QOFF);
5422 		ahc_outb(ahc, SNSCB_QOFF, qinpos);
5423 	} else
5424 		qinpos = ahc_inb(ahc, QINPOS);
5425 	diff = ahc->qinfifonext - qinpos;
5426 	return (diff);
5427 }
5428 
5429 int
5430 ahc_search_qinfifo(struct ahc_softc *ahc, int target, char channel,
5431 		   int lun, u_int tag, role_t role, uint32_t status,
5432 		   ahc_search_action action)
5433 {
5434 	struct	scb *scb;
5435 	struct	scb *prev_scb;
5436 	uint8_t qinstart;
5437 	uint8_t qinpos;
5438 	uint8_t qintail;
5439 	uint8_t next;
5440 	uint8_t prev;
5441 	uint8_t curscbptr;
5442 	int	found;
5443 	int	have_qregs;
5444 
5445 	qintail = ahc->qinfifonext;
5446 	have_qregs = (ahc->features & AHC_QUEUE_REGS) != 0;
5447 	if (have_qregs) {
5448 		qinstart = ahc_inb(ahc, SNSCB_QOFF);
5449 		ahc_outb(ahc, SNSCB_QOFF, qinstart);
5450 	} else
5451 		qinstart = ahc_inb(ahc, QINPOS);
5452 	qinpos = qinstart;
5453 	found = 0;
5454 	prev_scb = NULL;
5455 
5456 	if (action == SEARCH_COMPLETE) {
5457 		/*
5458 		 * Don't attempt to run any queued untagged transactions
5459 		 * until we are done with the abort process.
5460 		 */
5461 		ahc_freeze_untagged_queues(ahc);
5462 	}
5463 
5464 	/*
5465 	 * Start with an empty queue.  Entries that are not chosen
5466 	 * for removal will be re-added to the queue as we go.
5467 	 */
5468 	ahc->qinfifonext = qinpos;
5469 	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
5470 
5471 	while (qinpos != qintail) {
5472 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinpos]);
5473 		if (scb == NULL) {
5474 			printf("qinpos = %d, SCB index = %d\n",
5475 				qinpos, ahc->qinfifo[qinpos]);
5476 			panic("Loop 1\n");
5477 		}
5478 
5479 		if (ahc_match_scb(ahc, scb, target, channel, lun, tag, role)) {
5480 			/*
5481 			 * We found an scb that needs to be acted on.
5482 			 */
5483 			found++;
5484 			switch (action) {
5485 			case SEARCH_COMPLETE:
5486 			{
5487 				cam_status ostat;
5488 				cam_status cstat;
5489 
5490 				ostat = aic_get_transaction_status(scb);
5491 				if (ostat == CAM_REQ_INPROG)
5492 					aic_set_transaction_status(scb, status);
5493 				cstat = aic_get_transaction_status(scb);
5494 				if (cstat != CAM_REQ_CMP)
5495 					aic_freeze_scb(scb);
5496 				if ((scb->flags & SCB_ACTIVE) == 0)
5497 					printf("Inactive SCB in qinfifo\n");
5498 				ahc_done(ahc, scb);
5499 
5500 				/* FALLTHROUGH */
5501 			}
5502 			case SEARCH_REMOVE:
5503 				break;
5504 			case SEARCH_COUNT:
5505 				ahc_qinfifo_requeue(ahc, prev_scb, scb);
5506 				prev_scb = scb;
5507 				break;
5508 			}
5509 		} else {
5510 			ahc_qinfifo_requeue(ahc, prev_scb, scb);
5511 			prev_scb = scb;
5512 		}
5513 		qinpos++;
5514 	}
5515 
5516 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
5517 		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
5518 	} else {
5519 		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
5520 	}
5521 
5522 	if (action != SEARCH_COUNT
5523 	 && (found != 0)
5524 	 && (qinstart != ahc->qinfifonext)) {
5525 		/*
5526 		 * The sequencer may be in the process of dmaing
5527 		 * down the SCB at the beginning of the queue.
5528 		 * This could be problematic if either the first,
5529 		 * or the second SCB is removed from the queue
5530 		 * (the first SCB includes a pointer to the "next"
5531 		 * SCB to dma). If we have removed any entries, swap
5532 		 * the first element in the queue with the next HSCB
5533 		 * so the sequencer will notice that NEXT_QUEUED_SCB
5534 		 * has changed during its dma attempt and will retry
5535 		 * the DMA.
5536 		 */
5537 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinstart]);
5538 
5539 		if (scb == NULL) {
5540 			printf("found = %d, qinstart = %d, qinfifionext = %d\n",
5541 				found, qinstart, ahc->qinfifonext);
5542 			panic("First/Second Qinfifo fixup\n");
5543 		}
5544 		/*
5545 		 * ahc_swap_with_next_hscb forces our next pointer to
5546 		 * point to the reserved SCB for future commands.  Save
5547 		 * and restore our original next pointer to maintain
5548 		 * queue integrity.
5549 		 */
5550 		next = scb->hscb->next;
5551 		ahc->scb_data->scbindex[scb->hscb->tag] = NULL;
5552 		ahc_swap_with_next_hscb(ahc, scb);
5553 		scb->hscb->next = next;
5554 		ahc->qinfifo[qinstart] = scb->hscb->tag;
5555 
5556 		/* Tell the card about the new head of the qinfifo. */
5557 		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
5558 
5559 		/* Fixup the tail "next" pointer. */
5560 		qintail = ahc->qinfifonext - 1;
5561 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qintail]);
5562 		scb->hscb->next = ahc->next_queued_scb->hscb->tag;
5563 	}
5564 
5565 	/*
5566 	 * Search waiting for selection list.
5567 	 */
5568 	curscbptr = ahc_inb(ahc, SCBPTR);
5569 	next = ahc_inb(ahc, WAITING_SCBH);  /* Start at head of list. */
5570 	prev = SCB_LIST_NULL;
5571 
5572 	while (next != SCB_LIST_NULL) {
5573 		uint8_t scb_index;
5574 
5575 		ahc_outb(ahc, SCBPTR, next);
5576 		scb_index = ahc_inb(ahc, SCB_TAG);
5577 		if (scb_index >= ahc->scb_data->numscbs) {
5578 			printf("Waiting List inconsistency. "
5579 			       "SCB index == %d, yet numscbs == %d.",
5580 			       scb_index, ahc->scb_data->numscbs);
5581 			ahc_dump_card_state(ahc);
5582 			panic("for safety");
5583 		}
5584 		scb = ahc_lookup_scb(ahc, scb_index);
5585 		if (scb == NULL) {
5586 			printf("scb_index = %d, next = %d\n",
5587 				scb_index, next);
5588 			panic("Waiting List traversal\n");
5589 		}
5590 		if (ahc_match_scb(ahc, scb, target, channel,
5591 				  lun, SCB_LIST_NULL, role)) {
5592 			/*
5593 			 * We found an scb that needs to be acted on.
5594 			 */
5595 			found++;
5596 			switch (action) {
5597 			case SEARCH_COMPLETE:
5598 			{
5599 				cam_status ostat;
5600 				cam_status cstat;
5601 
5602 				ostat = aic_get_transaction_status(scb);
5603 				if (ostat == CAM_REQ_INPROG)
5604 					aic_set_transaction_status(scb,
5605 								   status);
5606 				cstat = aic_get_transaction_status(scb);
5607 				if (cstat != CAM_REQ_CMP)
5608 					aic_freeze_scb(scb);
5609 				if ((scb->flags & SCB_ACTIVE) == 0)
5610 					printf("Inactive SCB in Wait List\n");
5611 				ahc_done(ahc, scb);
5612 				/* FALLTHROUGH */
5613 			}
5614 			case SEARCH_REMOVE:
5615 				next = ahc_rem_wscb(ahc, next, prev);
5616 				break;
5617 			case SEARCH_COUNT:
5618 				prev = next;
5619 				next = ahc_inb(ahc, SCB_NEXT);
5620 				break;
5621 			}
5622 		} else {
5623 
5624 			prev = next;
5625 			next = ahc_inb(ahc, SCB_NEXT);
5626 		}
5627 	}
5628 	ahc_outb(ahc, SCBPTR, curscbptr);
5629 
5630 	found += ahc_search_untagged_queues(ahc, /*aic_io_ctx_t*/NULL, target,
5631 					    channel, lun, status, action);
5632 
5633 	if (action == SEARCH_COMPLETE)
5634 		ahc_release_untagged_queues(ahc);
5635 	return (found);
5636 }
5637 
5638 int
5639 ahc_search_untagged_queues(struct ahc_softc *ahc, aic_io_ctx_t ctx,
5640 			   int target, char channel, int lun, uint32_t status,
5641 			   ahc_search_action action)
5642 {
5643 	struct	scb *scb;
5644 	int	maxtarget;
5645 	int	found;
5646 	int	i;
5647 
5648 	if (action == SEARCH_COMPLETE) {
5649 		/*
5650 		 * Don't attempt to run any queued untagged transactions
5651 		 * until we are done with the abort process.
5652 		 */
5653 		ahc_freeze_untagged_queues(ahc);
5654 	}
5655 
5656 	found = 0;
5657 	i = 0;
5658 	if ((ahc->flags & AHC_SCB_BTT) == 0) {
5659 
5660 		maxtarget = 16;
5661 		if (target != CAM_TARGET_WILDCARD) {
5662 
5663 			i = target;
5664 			if (channel == 'B')
5665 				i += 8;
5666 			maxtarget = i + 1;
5667 		}
5668 	} else {
5669 		maxtarget = 0;
5670 	}
5671 
5672 	for (; i < maxtarget; i++) {
5673 		struct scb_tailq *untagged_q;
5674 		struct scb *next_scb;
5675 
5676 		untagged_q = &(ahc->untagged_queues[i]);
5677 		next_scb = TAILQ_FIRST(untagged_q);
5678 		while (next_scb != NULL) {
5679 
5680 			scb = next_scb;
5681 			next_scb = TAILQ_NEXT(scb, links.tqe);
5682 
5683 			/*
5684 			 * The head of the list may be the currently
5685 			 * active untagged command for a device.
5686 			 * We're only searching for commands that
5687 			 * have not been started.  A transaction
5688 			 * marked active but still in the qinfifo
5689 			 * is removed by the qinfifo scanning code
5690 			 * above.
5691 			 */
5692 			if ((scb->flags & SCB_ACTIVE) != 0)
5693 				continue;
5694 
5695 			if (ahc_match_scb(ahc, scb, target, channel, lun,
5696 					  SCB_LIST_NULL, ROLE_INITIATOR) == 0
5697 			 || (ctx != NULL && ctx != scb->io_ctx))
5698 				continue;
5699 
5700 			/*
5701 			 * We found an scb that needs to be acted on.
5702 			 */
5703 			found++;
5704 			switch (action) {
5705 			case SEARCH_COMPLETE:
5706 			{
5707 				cam_status ostat;
5708 				cam_status cstat;
5709 
5710 				ostat = aic_get_transaction_status(scb);
5711 				if (ostat == CAM_REQ_INPROG)
5712 					aic_set_transaction_status(scb, status);
5713 				cstat = aic_get_transaction_status(scb);
5714 				if (cstat != CAM_REQ_CMP)
5715 					aic_freeze_scb(scb);
5716 				ahc_done(ahc, scb);
5717 				break;
5718 			}
5719 			case SEARCH_REMOVE:
5720 				scb->flags &= ~SCB_UNTAGGEDQ;
5721 				TAILQ_REMOVE(untagged_q, scb, links.tqe);
5722 				break;
5723 			case SEARCH_COUNT:
5724 				break;
5725 			}
5726 		}
5727 	}
5728 
5729 	if (action == SEARCH_COMPLETE)
5730 		ahc_release_untagged_queues(ahc);
5731 	return (found);
5732 }
5733 
5734 int
5735 ahc_search_disc_list(struct ahc_softc *ahc, int target, char channel,
5736 		     int lun, u_int tag, int stop_on_first, int remove,
5737 		     int save_state)
5738 {
5739 	struct	scb *scbp;
5740 	u_int	next;
5741 	u_int	prev;
5742 	u_int	count;
5743 	u_int	active_scb;
5744 
5745 	count = 0;
5746 	next = ahc_inb(ahc, DISCONNECTED_SCBH);
5747 	prev = SCB_LIST_NULL;
5748 
5749 	if (save_state) {
5750 		/* restore this when we're done */
5751 		active_scb = ahc_inb(ahc, SCBPTR);
5752 	} else
5753 		/* Silence compiler */
5754 		active_scb = SCB_LIST_NULL;
5755 
5756 	while (next != SCB_LIST_NULL) {
5757 		u_int scb_index;
5758 
5759 		ahc_outb(ahc, SCBPTR, next);
5760 		scb_index = ahc_inb(ahc, SCB_TAG);
5761 		if (scb_index >= ahc->scb_data->numscbs) {
5762 			printf("Disconnected List inconsistency. "
5763 			       "SCB index == %d, yet numscbs == %d.",
5764 			       scb_index, ahc->scb_data->numscbs);
5765 			ahc_dump_card_state(ahc);
5766 			panic("for safety");
5767 		}
5768 
5769 		if (next == prev) {
5770 			panic("Disconnected List Loop. "
5771 			      "cur SCBPTR == %x, prev SCBPTR == %x.",
5772 			      next, prev);
5773 		}
5774 		scbp = ahc_lookup_scb(ahc, scb_index);
5775 		if (ahc_match_scb(ahc, scbp, target, channel, lun,
5776 				  tag, ROLE_INITIATOR)) {
5777 			count++;
5778 			if (remove) {
5779 				next =
5780 				    ahc_rem_scb_from_disc_list(ahc, prev, next);
5781 			} else {
5782 				prev = next;
5783 				next = ahc_inb(ahc, SCB_NEXT);
5784 			}
5785 			if (stop_on_first)
5786 				break;
5787 		} else {
5788 			prev = next;
5789 			next = ahc_inb(ahc, SCB_NEXT);
5790 		}
5791 	}
5792 	if (save_state)
5793 		ahc_outb(ahc, SCBPTR, active_scb);
5794 	return (count);
5795 }
5796 
5797 /*
5798  * Remove an SCB from the on chip list of disconnected transactions.
5799  * This is empty/unused if we are not performing SCB paging.
5800  */
5801 static u_int
5802 ahc_rem_scb_from_disc_list(struct ahc_softc *ahc, u_int prev, u_int scbptr)
5803 {
5804 	u_int next;
5805 
5806 	ahc_outb(ahc, SCBPTR, scbptr);
5807 	next = ahc_inb(ahc, SCB_NEXT);
5808 
5809 	ahc_outb(ahc, SCB_CONTROL, 0);
5810 
5811 	ahc_add_curscb_to_free_list(ahc);
5812 
5813 	if (prev != SCB_LIST_NULL) {
5814 		ahc_outb(ahc, SCBPTR, prev);
5815 		ahc_outb(ahc, SCB_NEXT, next);
5816 	} else
5817 		ahc_outb(ahc, DISCONNECTED_SCBH, next);
5818 
5819 	return (next);
5820 }
5821 
5822 /*
5823  * Add the SCB as selected by SCBPTR onto the on chip list of
5824  * free hardware SCBs.  This list is empty/unused if we are not
5825  * performing SCB paging.
5826  */
5827 static void
5828 ahc_add_curscb_to_free_list(struct ahc_softc *ahc)
5829 {
5830 	/*
5831 	 * Invalidate the tag so that our abort
5832 	 * routines don't think it's active.
5833 	 */
5834 	ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
5835 
5836 	if ((ahc->flags & AHC_PAGESCBS) != 0) {
5837 		ahc_outb(ahc, SCB_NEXT, ahc_inb(ahc, FREE_SCBH));
5838 		ahc_outb(ahc, FREE_SCBH, ahc_inb(ahc, SCBPTR));
5839 	}
5840 }
5841 
5842 /*
5843  * Manipulate the waiting for selection list and return the
5844  * scb that follows the one that we remove.
5845  */
5846 static u_int
5847 ahc_rem_wscb(struct ahc_softc *ahc, u_int scbpos, u_int prev)
5848 {
5849 	u_int curscb, next;
5850 
5851 	/*
5852 	 * Select the SCB we want to abort and
5853 	 * pull the next pointer out of it.
5854 	 */
5855 	curscb = ahc_inb(ahc, SCBPTR);
5856 	ahc_outb(ahc, SCBPTR, scbpos);
5857 	next = ahc_inb(ahc, SCB_NEXT);
5858 
5859 	/* Clear the necessary fields */
5860 	ahc_outb(ahc, SCB_CONTROL, 0);
5861 
5862 	ahc_add_curscb_to_free_list(ahc);
5863 
5864 	/* update the waiting list */
5865 	if (prev == SCB_LIST_NULL) {
5866 		/* First in the list */
5867 		ahc_outb(ahc, WAITING_SCBH, next);
5868 
5869 		/*
5870 		 * Ensure we aren't attempting to perform
5871 		 * selection for this entry.
5872 		 */
5873 		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
5874 	} else {
5875 		/*
5876 		 * Select the scb that pointed to us
5877 		 * and update its next pointer.
5878 		 */
5879 		ahc_outb(ahc, SCBPTR, prev);
5880 		ahc_outb(ahc, SCB_NEXT, next);
5881 	}
5882 
5883 	/*
5884 	 * Point us back at the original scb position.
5885 	 */
5886 	ahc_outb(ahc, SCBPTR, curscb);
5887 	return next;
5888 }
5889 
5890 /******************************** Error Handling ******************************/
5891 /*
5892  * Abort all SCBs that match the given description (target/channel/lun/tag),
5893  * setting their status to the passed in status if the status has not already
5894  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
5895  * is paused before it is called.
5896  */
5897 int
5898 ahc_abort_scbs(struct ahc_softc *ahc, int target, char channel,
5899 	       int lun, u_int tag, role_t role, uint32_t status)
5900 {
5901 	struct	scb *scbp;
5902 	struct	scb *scbp_next;
5903 	u_int	active_scb;
5904 	int	i, j;
5905 	int	maxtarget;
5906 	int	minlun;
5907 	int	maxlun;
5908 
5909 	int	found;
5910 
5911 	/*
5912 	 * Don't attempt to run any queued untagged transactions
5913 	 * until we are done with the abort process.
5914 	 */
5915 	ahc_freeze_untagged_queues(ahc);
5916 
5917 	/* restore this when we're done */
5918 	active_scb = ahc_inb(ahc, SCBPTR);
5919 
5920 	found = ahc_search_qinfifo(ahc, target, channel, lun, SCB_LIST_NULL,
5921 				   role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
5922 
5923 	/*
5924 	 * Clean out the busy target table for any untagged commands.
5925 	 */
5926 	i = 0;
5927 	maxtarget = 16;
5928 	if (target != CAM_TARGET_WILDCARD) {
5929 		i = target;
5930 		if (channel == 'B')
5931 			i += 8;
5932 		maxtarget = i + 1;
5933 	}
5934 
5935 	if (lun == CAM_LUN_WILDCARD) {
5936 
5937 		/*
5938 		 * Unless we are using an SCB based
5939 		 * busy targets table, there is only
5940 		 * one table entry for all luns of
5941 		 * a target.
5942 		 */
5943 		minlun = 0;
5944 		maxlun = 1;
5945 		if ((ahc->flags & AHC_SCB_BTT) != 0)
5946 			maxlun = AHC_NUM_LUNS;
5947 	} else {
5948 		minlun = lun;
5949 		maxlun = lun + 1;
5950 	}
5951 
5952 	if (role != ROLE_TARGET) {
5953 		for (;i < maxtarget; i++) {
5954 			for (j = minlun;j < maxlun; j++) {
5955 				u_int scbid;
5956 				u_int tcl;
5957 
5958 				tcl = BUILD_TCL(i << 4, j);
5959 				scbid = ahc_index_busy_tcl(ahc, tcl);
5960 				scbp = ahc_lookup_scb(ahc, scbid);
5961 				if (scbp == NULL
5962 				 || ahc_match_scb(ahc, scbp, target, channel,
5963 						  lun, tag, role) == 0)
5964 					continue;
5965 				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, j));
5966 			}
5967 		}
5968 
5969 		/*
5970 		 * Go through the disconnected list and remove any entries we
5971 		 * have queued for completion, 0'ing their control byte too.
5972 		 * We save the active SCB and restore it ourselves, so there
5973 		 * is no reason for this search to restore it too.
5974 		 */
5975 		ahc_search_disc_list(ahc, target, channel, lun, tag,
5976 				     /*stop_on_first*/FALSE, /*remove*/TRUE,
5977 				     /*save_state*/FALSE);
5978 	}
5979 
5980 	/*
5981 	 * Go through the hardware SCB array looking for commands that
5982 	 * were active but not on any list.  In some cases, these remnants
5983 	 * might not still have mappings in the scbindex array (e.g. unexpected
5984 	 * bus free with the same scb queued for an abort).  Don't hold this
5985 	 * against them.
5986 	 */
5987 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
5988 		u_int scbid;
5989 
5990 		ahc_outb(ahc, SCBPTR, i);
5991 		scbid = ahc_inb(ahc, SCB_TAG);
5992 		scbp = ahc_lookup_scb(ahc, scbid);
5993 		if ((scbp == NULL && scbid != SCB_LIST_NULL)
5994 		 || (scbp != NULL
5995 		  && ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)))
5996 			ahc_add_curscb_to_free_list(ahc);
5997 	}
5998 
5999 	/*
6000 	 * Go through the pending CCB list and look for
6001 	 * commands for this target that are still active.
6002 	 * These are other tagged commands that were
6003 	 * disconnected when the reset occurred.
6004 	 */
6005 	scbp_next = LIST_FIRST(&ahc->pending_scbs);
6006 	while (scbp_next != NULL) {
6007 		scbp = scbp_next;
6008 		scbp_next = LIST_NEXT(scbp, pending_links);
6009 		if (ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)) {
6010 			cam_status ostat;
6011 
6012 			ostat = aic_get_transaction_status(scbp);
6013 			if (ostat == CAM_REQ_INPROG)
6014 				aic_set_transaction_status(scbp, status);
6015 			if (aic_get_transaction_status(scbp) != CAM_REQ_CMP)
6016 				aic_freeze_scb(scbp);
6017 			if ((scbp->flags & SCB_ACTIVE) == 0)
6018 				printf("Inactive SCB on pending list\n");
6019 			ahc_done(ahc, scbp);
6020 			found++;
6021 		}
6022 	}
6023 	ahc_outb(ahc, SCBPTR, active_scb);
6024 	ahc_platform_abort_scbs(ahc, target, channel, lun, tag, role, status);
6025 	ahc_release_untagged_queues(ahc);
6026 	return found;
6027 }
6028 
6029 static void
6030 ahc_reset_current_bus(struct ahc_softc *ahc)
6031 {
6032 	uint8_t scsiseq;
6033 
6034 	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENSCSIRST);
6035 	scsiseq = ahc_inb(ahc, SCSISEQ);
6036 	ahc_outb(ahc, SCSISEQ, scsiseq | SCSIRSTO);
6037 	ahc_flush_device_writes(ahc);
6038 	aic_delay(AHC_BUSRESET_DELAY);
6039 	/* Turn off the bus reset */
6040 	ahc_outb(ahc, SCSISEQ, scsiseq & ~SCSIRSTO);
6041 
6042 	ahc_clear_intstat(ahc);
6043 
6044 	/* Re-enable reset interrupts */
6045 	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) | ENSCSIRST);
6046 }
6047 
6048 int
6049 ahc_reset_channel(struct ahc_softc *ahc, char channel, int initiate_reset)
6050 {
6051 	struct	ahc_devinfo devinfo;
6052 	u_int	initiator, target, max_scsiid;
6053 	u_int	sblkctl;
6054 	u_int	scsiseq;
6055 	u_int	simode1;
6056 	int	found;
6057 	int	restart_needed;
6058 	char	cur_channel;
6059 
6060 	ahc->pending_device = NULL;
6061 
6062 	ahc_compile_devinfo(&devinfo,
6063 			    CAM_TARGET_WILDCARD,
6064 			    CAM_TARGET_WILDCARD,
6065 			    CAM_LUN_WILDCARD,
6066 			    channel, ROLE_UNKNOWN);
6067 	ahc_pause(ahc);
6068 
6069 	/* Make sure the sequencer is in a safe location. */
6070 	ahc_clear_critical_section(ahc);
6071 
6072 	/*
6073 	 * Run our command complete fifos to ensure that we perform
6074 	 * completion processing on any commands that 'completed'
6075 	 * before the reset occurred.
6076 	 */
6077 	ahc_run_qoutfifo(ahc);
6078 #ifdef AHC_TARGET_MODE
6079 	/*
6080 	 * XXX - In Twin mode, the tqinfifo may have commands
6081 	 *	 for an unaffected channel in it.  However, if
6082 	 *	 we have run out of ATIO resources to drain that
6083 	 *	 queue, we may not get them all out here.  Further,
6084 	 *	 the blocked transactions for the reset channel
6085 	 *	 should just be killed off, irrespecitve of whether
6086 	 *	 we are blocked on ATIO resources.  Write a routine
6087 	 *	 to compact the tqinfifo appropriately.
6088 	 */
6089 	if ((ahc->flags & AHC_TARGETROLE) != 0) {
6090 		ahc_run_tqinfifo(ahc, /*paused*/TRUE);
6091 	}
6092 #endif
6093 
6094 	/*
6095 	 * Reset the bus if we are initiating this reset
6096 	 */
6097 	sblkctl = ahc_inb(ahc, SBLKCTL);
6098 	cur_channel = 'A';
6099 	if ((ahc->features & AHC_TWIN) != 0
6100 	 && ((sblkctl & SELBUSB) != 0))
6101 	    cur_channel = 'B';
6102 	scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
6103 	if (cur_channel != channel) {
6104 		/* Case 1: Command for another bus is active
6105 		 * Stealthily reset the other bus without
6106 		 * upsetting the current bus.
6107 		 */
6108 		ahc_outb(ahc, SBLKCTL, sblkctl ^ SELBUSB);
6109 		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
6110 #ifdef AHC_TARGET_MODE
6111 		/*
6112 		 * Bus resets clear ENSELI, so we cannot
6113 		 * defer re-enabling bus reset interrupts
6114 		 * if we are in target mode.
6115 		 */
6116 		if ((ahc->flags & AHC_TARGETROLE) != 0)
6117 			simode1 |= ENSCSIRST;
6118 #endif
6119 		ahc_outb(ahc, SIMODE1, simode1);
6120 		if (initiate_reset)
6121 			ahc_reset_current_bus(ahc);
6122 		ahc_clear_intstat(ahc);
6123 		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
6124 		ahc_outb(ahc, SBLKCTL, sblkctl);
6125 		restart_needed = FALSE;
6126 	} else {
6127 		/* Case 2: A command from this bus is active or we're idle */
6128 		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
6129 #ifdef AHC_TARGET_MODE
6130 		/*
6131 		 * Bus resets clear ENSELI, so we cannot
6132 		 * defer re-enabling bus reset interrupts
6133 		 * if we are in target mode.
6134 		 */
6135 		if ((ahc->flags & AHC_TARGETROLE) != 0)
6136 			simode1 |= ENSCSIRST;
6137 #endif
6138 		ahc_outb(ahc, SIMODE1, simode1);
6139 		if (initiate_reset)
6140 			ahc_reset_current_bus(ahc);
6141 		ahc_clear_intstat(ahc);
6142 		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
6143 		restart_needed = TRUE;
6144 	}
6145 
6146 	/*
6147 	 * Clean up all the state information for the
6148 	 * pending transactions on this bus.
6149 	 */
6150 	found = ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, channel,
6151 			       CAM_LUN_WILDCARD, SCB_LIST_NULL,
6152 			       ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
6153 
6154 	max_scsiid = (ahc->features & AHC_WIDE) ? 15 : 7;
6155 
6156 #ifdef AHC_TARGET_MODE
6157 	/*
6158 	 * Send an immediate notify ccb to all target more peripheral
6159 	 * drivers affected by this action.
6160 	 */
6161 	for (target = 0; target <= max_scsiid; target++) {
6162 		struct ahc_tmode_tstate* tstate;
6163 		u_int lun;
6164 
6165 		tstate = ahc->enabled_targets[target];
6166 		if (tstate == NULL)
6167 			continue;
6168 		for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
6169 			struct ahc_tmode_lstate* lstate;
6170 
6171 			lstate = tstate->enabled_luns[lun];
6172 			if (lstate == NULL)
6173 				continue;
6174 
6175 			ahc_queue_lstate_event(ahc, lstate, CAM_TARGET_WILDCARD,
6176 					       EVENT_TYPE_BUS_RESET, /*arg*/0);
6177 			ahc_send_lstate_events(ahc, lstate);
6178 		}
6179 	}
6180 #endif
6181 	/* Notify the XPT that a bus reset occurred */
6182 	ahc_send_async(ahc, devinfo.channel, CAM_TARGET_WILDCARD,
6183 		       CAM_LUN_WILDCARD, AC_BUS_RESET, NULL);
6184 
6185 	/*
6186 	 * Revert to async/narrow transfers until we renegotiate.
6187 	 */
6188 	for (target = 0; target <= max_scsiid; target++) {
6189 
6190 		if (ahc->enabled_targets[target] == NULL)
6191 			continue;
6192 		for (initiator = 0; initiator <= max_scsiid; initiator++) {
6193 			struct ahc_devinfo devinfo;
6194 
6195 			ahc_compile_devinfo(&devinfo, target, initiator,
6196 					    CAM_LUN_WILDCARD,
6197 					    channel, ROLE_UNKNOWN);
6198 			ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6199 				      AHC_TRANS_CUR, /*paused*/TRUE);
6200 			ahc_set_syncrate(ahc, &devinfo, /*syncrate*/NULL,
6201 					 /*period*/0, /*offset*/0,
6202 					 /*ppr_options*/0, AHC_TRANS_CUR,
6203 					 /*paused*/TRUE);
6204 		}
6205 	}
6206 
6207 	if (restart_needed)
6208 		ahc_restart(ahc);
6209 	else
6210 		ahc_unpause(ahc);
6211 	return found;
6212 }
6213 
6214 
6215 /***************************** Residual Processing ****************************/
6216 /*
6217  * Calculate the residual for a just completed SCB.
6218  */
6219 void
6220 ahc_calc_residual(struct ahc_softc *ahc, struct scb *scb)
6221 {
6222 	struct hardware_scb *hscb;
6223 	struct status_pkt *spkt;
6224 	uint32_t sgptr;
6225 	uint32_t resid_sgptr;
6226 	uint32_t resid;
6227 
6228 	/*
6229 	 * 5 cases.
6230 	 * 1) No residual.
6231 	 *    SG_RESID_VALID clear in sgptr.
6232 	 * 2) Transferless command
6233 	 * 3) Never performed any transfers.
6234 	 *    sgptr has SG_FULL_RESID set.
6235 	 * 4) No residual but target did not
6236 	 *    save data pointers after the
6237 	 *    last transfer, so sgptr was
6238 	 *    never updated.
6239 	 * 5) We have a partial residual.
6240 	 *    Use residual_sgptr to determine
6241 	 *    where we are.
6242 	 */
6243 
6244 	hscb = scb->hscb;
6245 	sgptr = aic_le32toh(hscb->sgptr);
6246 	if ((sgptr & SG_RESID_VALID) == 0)
6247 		/* Case 1 */
6248 		return;
6249 	sgptr &= ~SG_RESID_VALID;
6250 
6251 	if ((sgptr & SG_LIST_NULL) != 0)
6252 		/* Case 2 */
6253 		return;
6254 
6255 	spkt = &hscb->shared_data.status;
6256 	resid_sgptr = aic_le32toh(spkt->residual_sg_ptr);
6257 	if ((sgptr & SG_FULL_RESID) != 0) {
6258 		/* Case 3 */
6259 		resid = aic_get_transfer_length(scb);
6260 	} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
6261 		/* Case 4 */
6262 		return;
6263 	} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
6264 		panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
6265 		/* NOTREACHED */
6266 		return;
6267 	} else {
6268 		struct ahc_dma_seg *sg;
6269 
6270 		/*
6271 		 * Remainder of the SG where the transfer
6272 		 * stopped.
6273 		 */
6274 		resid = aic_le32toh(spkt->residual_datacnt) & AHC_SG_LEN_MASK;
6275 		sg = ahc_sg_bus_to_virt(scb, resid_sgptr & SG_PTR_MASK);
6276 
6277 		/* The residual sg_ptr always points to the next sg */
6278 		sg--;
6279 
6280 		/*
6281 		 * Add up the contents of all residual
6282 		 * SG segments that are after the SG where
6283 		 * the transfer stopped.
6284 		 */
6285 		while ((aic_le32toh(sg->len) & AHC_DMA_LAST_SEG) == 0) {
6286 			sg++;
6287 			resid += aic_le32toh(sg->len) & AHC_SG_LEN_MASK;
6288 		}
6289 	}
6290 	if ((scb->flags & SCB_SENSE) == 0)
6291 		aic_set_residual(scb, resid);
6292 	else
6293 		aic_set_sense_residual(scb, resid);
6294 
6295 #ifdef AHC_DEBUG
6296 	if ((ahc_debug & AHC_SHOW_MISC) != 0) {
6297 		ahc_print_path(ahc, scb);
6298 		printf("Handled %sResidual of %d bytes\n",
6299 		       (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
6300 	}
6301 #endif
6302 }
6303 
6304 /******************************* Target Mode **********************************/
6305 #ifdef AHC_TARGET_MODE
6306 /*
6307  * Add a target mode event to this lun's queue
6308  */
6309 static void
6310 ahc_queue_lstate_event(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate,
6311 		       u_int initiator_id, u_int event_type, u_int event_arg)
6312 {
6313 	struct ahc_tmode_event *event;
6314 	int pending;
6315 
6316 	xpt_freeze_devq(lstate->path, /*count*/1);
6317 	if (lstate->event_w_idx >= lstate->event_r_idx)
6318 		pending = lstate->event_w_idx - lstate->event_r_idx;
6319 	else
6320 		pending = AHC_TMODE_EVENT_BUFFER_SIZE + 1
6321 			- (lstate->event_r_idx - lstate->event_w_idx);
6322 
6323 	if (event_type == EVENT_TYPE_BUS_RESET
6324 	 || event_type == MSG_BUS_DEV_RESET) {
6325 		/*
6326 		 * Any earlier events are irrelevant, so reset our buffer.
6327 		 * This has the effect of allowing us to deal with reset
6328 		 * floods (an external device holding down the reset line)
6329 		 * without losing the event that is really interesting.
6330 		 */
6331 		lstate->event_r_idx = 0;
6332 		lstate->event_w_idx = 0;
6333 		xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
6334 	}
6335 
6336 	if (pending == AHC_TMODE_EVENT_BUFFER_SIZE) {
6337 		xpt_print_path(lstate->path);
6338 		printf("immediate event %x:%x lost\n",
6339 		       lstate->event_buffer[lstate->event_r_idx].event_type,
6340 		       lstate->event_buffer[lstate->event_r_idx].event_arg);
6341 		lstate->event_r_idx++;
6342 		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6343 			lstate->event_r_idx = 0;
6344 		xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
6345 	}
6346 
6347 	event = &lstate->event_buffer[lstate->event_w_idx];
6348 	event->initiator_id = initiator_id;
6349 	event->event_type = event_type;
6350 	event->event_arg = event_arg;
6351 	lstate->event_w_idx++;
6352 	if (lstate->event_w_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6353 		lstate->event_w_idx = 0;
6354 }
6355 
6356 /*
6357  * Send any target mode events queued up waiting
6358  * for immediate notify resources.
6359  */
6360 void
6361 ahc_send_lstate_events(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate)
6362 {
6363 	struct ccb_hdr *ccbh;
6364 	struct ccb_immediate_notify *inot;
6365 
6366 	while (lstate->event_r_idx != lstate->event_w_idx
6367 	    && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
6368 		struct ahc_tmode_event *event;
6369 
6370 		event = &lstate->event_buffer[lstate->event_r_idx];
6371 		SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
6372 		inot = (struct ccb_immediate_notify *)ccbh;
6373 		switch (event->event_type) {
6374 		case EVENT_TYPE_BUS_RESET:
6375 			ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
6376 			break;
6377 		default:
6378 			ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
6379 			inot->arg = event->event_type;
6380 			inot->seq_id = event->event_arg;
6381 			break;
6382 		}
6383 		inot->initiator_id = event->initiator_id;
6384 		xpt_done((union ccb *)inot);
6385 		lstate->event_r_idx++;
6386 		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
6387 			lstate->event_r_idx = 0;
6388 	}
6389 }
6390 #endif
6391 
6392 /******************** Sequencer Program Patching/Download *********************/
6393 
6394 #ifdef AHC_DUMP_SEQ
6395 void
6396 ahc_dumpseq(struct ahc_softc* ahc)
6397 {
6398 	int i;
6399 
6400 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6401 	ahc_outb(ahc, SEQADDR0, 0);
6402 	ahc_outb(ahc, SEQADDR1, 0);
6403 	for (i = 0; i < ahc->instruction_ram_size; i++) {
6404 		uint8_t ins_bytes[4];
6405 
6406 		ahc_insb(ahc, SEQRAM, ins_bytes, 4);
6407 		printf("0x%08x\n", ins_bytes[0] << 24
6408 				 | ins_bytes[1] << 16
6409 				 | ins_bytes[2] << 8
6410 				 | ins_bytes[3]);
6411 	}
6412 }
6413 #endif
6414 
6415 static int
6416 ahc_loadseq(struct ahc_softc *ahc)
6417 {
6418 	struct	cs cs_table[num_critical_sections];
6419 	u_int	begin_set[num_critical_sections];
6420 	u_int	end_set[num_critical_sections];
6421 	struct	patch *cur_patch;
6422 	u_int	cs_count;
6423 	u_int	cur_cs;
6424 	u_int	i;
6425 	u_int	skip_addr;
6426 	u_int	sg_prefetch_cnt;
6427 	int	downloaded;
6428 	uint8_t	download_consts[7];
6429 
6430 	/*
6431 	 * Start out with 0 critical sections
6432 	 * that apply to this firmware load.
6433 	 */
6434 	cs_count = 0;
6435 	cur_cs = 0;
6436 	memset(begin_set, 0, sizeof(begin_set));
6437 	memset(end_set, 0, sizeof(end_set));
6438 
6439 	/* Setup downloadable constant table */
6440 	download_consts[QOUTFIFO_OFFSET] = 0;
6441 	if (ahc->targetcmds != NULL)
6442 		download_consts[QOUTFIFO_OFFSET] += 32;
6443 	download_consts[QINFIFO_OFFSET] = download_consts[QOUTFIFO_OFFSET] + 1;
6444 	download_consts[CACHESIZE_MASK] = ahc->pci_cachesize - 1;
6445 	download_consts[INVERTED_CACHESIZE_MASK] = ~(ahc->pci_cachesize - 1);
6446 	sg_prefetch_cnt = ahc->pci_cachesize;
6447 	if (sg_prefetch_cnt < (2 * sizeof(struct ahc_dma_seg)))
6448 		sg_prefetch_cnt = 2 * sizeof(struct ahc_dma_seg);
6449 	download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
6450 	download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_cnt - 1);
6451 	download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_cnt - 1);
6452 
6453 	cur_patch = patches;
6454 	downloaded = 0;
6455 	skip_addr = 0;
6456 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
6457 	ahc_outb(ahc, SEQADDR0, 0);
6458 	ahc_outb(ahc, SEQADDR1, 0);
6459 
6460 	for (i = 0; i < sizeof(seqprog)/4; i++) {
6461 		if (ahc_check_patch(ahc, &cur_patch, i, &skip_addr) == 0) {
6462 			/*
6463 			 * Don't download this instruction as it
6464 			 * is in a patch that was removed.
6465 			 */
6466 			continue;
6467 		}
6468 
6469 		if (downloaded == ahc->instruction_ram_size) {
6470 			/*
6471 			 * We're about to exceed the instruction
6472 			 * storage capacity for this chip.  Fail
6473 			 * the load.
6474 			 */
6475 			printf("\n%s: Program too large for instruction memory "
6476 			       "size of %d!\n", ahc_name(ahc),
6477 			       ahc->instruction_ram_size);
6478 			return (ENOMEM);
6479 		}
6480 
6481 		/*
6482 		 * Move through the CS table until we find a CS
6483 		 * that might apply to this instruction.
6484 		 */
6485 		for (; cur_cs < num_critical_sections; cur_cs++) {
6486 			if (critical_sections[cur_cs].end <= i) {
6487 				if (begin_set[cs_count] == TRUE
6488 				 && end_set[cs_count] == FALSE) {
6489 					cs_table[cs_count].end = downloaded;
6490 				 	end_set[cs_count] = TRUE;
6491 					cs_count++;
6492 				}
6493 				continue;
6494 			}
6495 			if (critical_sections[cur_cs].begin <= i
6496 			 && begin_set[cs_count] == FALSE) {
6497 				cs_table[cs_count].begin = downloaded;
6498 				begin_set[cs_count] = TRUE;
6499 			}
6500 			break;
6501 		}
6502 		ahc_download_instr(ahc, i, download_consts);
6503 		downloaded++;
6504 	}
6505 
6506 	ahc->num_critical_sections = cs_count;
6507 	if (cs_count != 0) {
6508 
6509 		cs_count *= sizeof(struct cs);
6510 		ahc->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
6511 		if (ahc->critical_sections == NULL)
6512 			panic("ahc_loadseq: Could not malloc");
6513 		memcpy(ahc->critical_sections, cs_table, cs_count);
6514 	}
6515 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE);
6516 
6517 	if (bootverbose) {
6518 		printf(" %d instructions downloaded\n", downloaded);
6519 		printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
6520 		       ahc_name(ahc), ahc->features, ahc->bugs, ahc->flags);
6521 	}
6522 	return (0);
6523 }
6524 
6525 static int
6526 ahc_check_patch(struct ahc_softc *ahc, struct patch **start_patch,
6527 		u_int start_instr, u_int *skip_addr)
6528 {
6529 	struct	patch *cur_patch;
6530 	struct	patch *last_patch;
6531 	u_int	num_patches;
6532 
6533 	num_patches = sizeof(patches)/sizeof(struct patch);
6534 	last_patch = &patches[num_patches];
6535 	cur_patch = *start_patch;
6536 
6537 	while (cur_patch < last_patch && start_instr == cur_patch->begin) {
6538 
6539 		if (cur_patch->patch_func(ahc) == 0) {
6540 
6541 			/* Start rejecting code */
6542 			*skip_addr = start_instr + cur_patch->skip_instr;
6543 			cur_patch += cur_patch->skip_patch;
6544 		} else {
6545 			/* Accepted this patch.  Advance to the next
6546 			 * one and wait for our intruction pointer to
6547 			 * hit this point.
6548 			 */
6549 			cur_patch++;
6550 		}
6551 	}
6552 
6553 	*start_patch = cur_patch;
6554 	if (start_instr < *skip_addr)
6555 		/* Still skipping */
6556 		return (0);
6557 
6558 	return (1);
6559 }
6560 
6561 static void
6562 ahc_download_instr(struct ahc_softc *ahc, u_int instrptr, uint8_t *dconsts)
6563 {
6564 	union	ins_formats instr;
6565 	struct	ins_format1 *fmt1_ins;
6566 	struct	ins_format3 *fmt3_ins;
6567 	u_int	opcode;
6568 
6569 	/*
6570 	 * The firmware is always compiled into a little endian format.
6571 	 */
6572 	instr.integer = aic_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
6573 
6574 	fmt1_ins = &instr.format1;
6575 	fmt3_ins = NULL;
6576 
6577 	/* Pull the opcode */
6578 	opcode = instr.format1.opcode;
6579 	switch (opcode) {
6580 	case AIC_OP_JMP:
6581 	case AIC_OP_JC:
6582 	case AIC_OP_JNC:
6583 	case AIC_OP_CALL:
6584 	case AIC_OP_JNE:
6585 	case AIC_OP_JNZ:
6586 	case AIC_OP_JE:
6587 	case AIC_OP_JZ:
6588 	{
6589 		struct patch *cur_patch;
6590 		int address_offset;
6591 		u_int address;
6592 		u_int skip_addr;
6593 		u_int i;
6594 
6595 		fmt3_ins = &instr.format3;
6596 		address_offset = 0;
6597 		address = fmt3_ins->address;
6598 		cur_patch = patches;
6599 		skip_addr = 0;
6600 
6601 		for (i = 0; i < address;) {
6602 
6603 			ahc_check_patch(ahc, &cur_patch, i, &skip_addr);
6604 
6605 			if (skip_addr > i) {
6606 				int end_addr;
6607 
6608 				end_addr = MIN(address, skip_addr);
6609 				address_offset += end_addr - i;
6610 				i = skip_addr;
6611 			} else {
6612 				i++;
6613 			}
6614 		}
6615 		address -= address_offset;
6616 		fmt3_ins->address = address;
6617 		/* FALLTHROUGH */
6618 	}
6619 	case AIC_OP_OR:
6620 	case AIC_OP_AND:
6621 	case AIC_OP_XOR:
6622 	case AIC_OP_ADD:
6623 	case AIC_OP_ADC:
6624 	case AIC_OP_BMOV:
6625 		if (fmt1_ins->parity != 0) {
6626 			fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
6627 		}
6628 		fmt1_ins->parity = 0;
6629 		if ((ahc->features & AHC_CMD_CHAN) == 0
6630 		 && opcode == AIC_OP_BMOV) {
6631 			/*
6632 			 * Block move was added at the same time
6633 			 * as the command channel.  Verify that
6634 			 * this is only a move of a single element
6635 			 * and convert the BMOV to a MOV
6636 			 * (AND with an immediate of FF).
6637 			 */
6638 			if (fmt1_ins->immediate != 1)
6639 				panic("%s: BMOV not supported\n",
6640 				      ahc_name(ahc));
6641 			fmt1_ins->opcode = AIC_OP_AND;
6642 			fmt1_ins->immediate = 0xff;
6643 		}
6644 		/* FALLTHROUGH */
6645 	case AIC_OP_ROL:
6646 		if ((ahc->features & AHC_ULTRA2) != 0) {
6647 			int i, count;
6648 
6649 			/* Calculate odd parity for the instruction */
6650 			for (i = 0, count = 0; i < 31; i++) {
6651 				uint32_t mask;
6652 
6653 				mask = 0x01 << i;
6654 				if ((instr.integer & mask) != 0)
6655 					count++;
6656 			}
6657 			if ((count & 0x01) == 0)
6658 				instr.format1.parity = 1;
6659 		} else {
6660 			/* Compress the instruction for older sequencers */
6661 			if (fmt3_ins != NULL) {
6662 				instr.integer =
6663 					fmt3_ins->immediate
6664 				      | (fmt3_ins->source << 8)
6665 				      | (fmt3_ins->address << 16)
6666 				      |	(fmt3_ins->opcode << 25);
6667 			} else {
6668 				instr.integer =
6669 					fmt1_ins->immediate
6670 				      | (fmt1_ins->source << 8)
6671 				      | (fmt1_ins->destination << 16)
6672 				      |	(fmt1_ins->ret << 24)
6673 				      |	(fmt1_ins->opcode << 25);
6674 			}
6675 		}
6676 		/* The sequencer is a little endian cpu */
6677 		instr.integer = aic_htole32(instr.integer);
6678 		ahc_outsb(ahc, SEQRAM, instr.bytes, 4);
6679 		break;
6680 	default:
6681 		panic("Unknown opcode encountered in seq program");
6682 		break;
6683 	}
6684 }
6685 
6686 int
6687 ahc_print_register(ahc_reg_parse_entry_t *table, u_int num_entries,
6688 		   const char *name, u_int address, u_int value,
6689 		   u_int *cur_column, u_int wrap_point)
6690 {
6691 	int	printed;
6692 	u_int	printed_mask;
6693 	u_int	dummy_column;
6694 
6695 	if (cur_column == NULL) {
6696 		dummy_column = 0;
6697 		cur_column = &dummy_column;
6698 	}
6699 
6700 	if (*cur_column >= wrap_point) {
6701 		printf("\n");
6702 		*cur_column = 0;
6703 	}
6704 	printed = printf("%s[0x%x]", name, value);
6705 	if (table == NULL) {
6706 		printed += printf(" ");
6707 		*cur_column += printed;
6708 		return (printed);
6709 	}
6710 	printed_mask = 0;
6711 	while (printed_mask != 0xFF) {
6712 		int entry;
6713 
6714 		for (entry = 0; entry < num_entries; entry++) {
6715 			if (((value & table[entry].mask)
6716 			  != table[entry].value)
6717 			 || ((printed_mask & table[entry].mask)
6718 			  == table[entry].mask))
6719 				continue;
6720 
6721 			printed += printf("%s%s",
6722 					  printed_mask == 0 ? ":(" : "|",
6723 					  table[entry].name);
6724 			printed_mask |= table[entry].mask;
6725 
6726 			break;
6727 		}
6728 		if (entry >= num_entries)
6729 			break;
6730 	}
6731 	if (printed_mask != 0)
6732 		printed += printf(") ");
6733 	else
6734 		printed += printf(" ");
6735 	if (cur_column != NULL)
6736 		*cur_column += printed;
6737 	return (printed);
6738 }
6739 
6740 void
6741 ahc_dump_card_state(struct ahc_softc *ahc)
6742 {
6743 	struct	scb *scb;
6744 	struct	scb_tailq *untagged_q;
6745 	u_int	cur_col;
6746 	int	paused;
6747 	int	target;
6748 	int	maxtarget;
6749 	int	i;
6750 	uint8_t last_phase;
6751 	uint8_t qinpos;
6752 	uint8_t qintail;
6753 	uint8_t qoutpos;
6754 	uint8_t scb_index;
6755 	uint8_t saved_scbptr;
6756 
6757 	if (ahc_is_paused(ahc)) {
6758 		paused = 1;
6759 	} else {
6760 		paused = 0;
6761 		ahc_pause(ahc);
6762 	}
6763 
6764 	saved_scbptr = ahc_inb(ahc, SCBPTR);
6765 	last_phase = ahc_inb(ahc, LASTPHASE);
6766 	printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
6767 	       "%s: Dumping Card State %s, at SEQADDR 0x%x\n",
6768 	       ahc_name(ahc), ahc_lookup_phase_entry(last_phase)->phasemsg,
6769 	       ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
6770 	if (paused)
6771 		printf("Card was paused\n");
6772 	printf("ACCUM = 0x%x, SINDEX = 0x%x, DINDEX = 0x%x, ARG_2 = 0x%x\n",
6773 	       ahc_inb(ahc, ACCUM), ahc_inb(ahc, SINDEX), ahc_inb(ahc, DINDEX),
6774 	       ahc_inb(ahc, ARG_2));
6775 	printf("HCNT = 0x%x SCBPTR = 0x%x\n", ahc_inb(ahc, HCNT),
6776 	       ahc_inb(ahc, SCBPTR));
6777 	cur_col = 0;
6778 	if ((ahc->features & AHC_DT) != 0)
6779 		ahc_scsiphase_print(ahc_inb(ahc, SCSIPHASE), &cur_col, 50);
6780 	ahc_scsisigi_print(ahc_inb(ahc, SCSISIGI), &cur_col, 50);
6781 	ahc_error_print(ahc_inb(ahc, ERROR), &cur_col, 50);
6782 	ahc_scsibusl_print(ahc_inb(ahc, SCSIBUSL), &cur_col, 50);
6783 	ahc_lastphase_print(ahc_inb(ahc, LASTPHASE), &cur_col, 50);
6784 	ahc_scsiseq_print(ahc_inb(ahc, SCSISEQ), &cur_col, 50);
6785 	ahc_sblkctl_print(ahc_inb(ahc, SBLKCTL), &cur_col, 50);
6786 	ahc_scsirate_print(ahc_inb(ahc, SCSIRATE), &cur_col, 50);
6787 	ahc_seqctl_print(ahc_inb(ahc, SEQCTL), &cur_col, 50);
6788 	ahc_seq_flags_print(ahc_inb(ahc, SEQ_FLAGS), &cur_col, 50);
6789 	ahc_sstat0_print(ahc_inb(ahc, SSTAT0), &cur_col, 50);
6790 	ahc_sstat1_print(ahc_inb(ahc, SSTAT1), &cur_col, 50);
6791 	ahc_sstat2_print(ahc_inb(ahc, SSTAT2), &cur_col, 50);
6792 	ahc_sstat3_print(ahc_inb(ahc, SSTAT3), &cur_col, 50);
6793 	ahc_simode0_print(ahc_inb(ahc, SIMODE0), &cur_col, 50);
6794 	ahc_simode1_print(ahc_inb(ahc, SIMODE1), &cur_col, 50);
6795 	ahc_sxfrctl0_print(ahc_inb(ahc, SXFRCTL0), &cur_col, 50);
6796 	ahc_dfcntrl_print(ahc_inb(ahc, DFCNTRL), &cur_col, 50);
6797 	ahc_dfstatus_print(ahc_inb(ahc, DFSTATUS), &cur_col, 50);
6798 	if (cur_col != 0)
6799 		printf("\n");
6800 	printf("STACK:");
6801 	for (i = 0; i < STACK_SIZE; i++)
6802 	       printf(" 0x%x", ahc_inb(ahc, STACK)|(ahc_inb(ahc, STACK) << 8));
6803 	printf("\nSCB count = %d\n", ahc->scb_data->numscbs);
6804 	printf("Kernel NEXTQSCB = %d\n", ahc->next_queued_scb->hscb->tag);
6805 	printf("Card NEXTQSCB = %d\n", ahc_inb(ahc, NEXT_QUEUED_SCB));
6806 	/* QINFIFO */
6807 	printf("QINFIFO entries: ");
6808 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
6809 		qinpos = ahc_inb(ahc, SNSCB_QOFF);
6810 		ahc_outb(ahc, SNSCB_QOFF, qinpos);
6811 	} else
6812 		qinpos = ahc_inb(ahc, QINPOS);
6813 	qintail = ahc->qinfifonext;
6814 	while (qinpos != qintail) {
6815 		printf("%d ", ahc->qinfifo[qinpos]);
6816 		qinpos++;
6817 	}
6818 	printf("\n");
6819 
6820 	printf("Waiting Queue entries: ");
6821 	scb_index = ahc_inb(ahc, WAITING_SCBH);
6822 	i = 0;
6823 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6824 		ahc_outb(ahc, SCBPTR, scb_index);
6825 		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6826 		scb_index = ahc_inb(ahc, SCB_NEXT);
6827 	}
6828 	printf("\n");
6829 
6830 	printf("Disconnected Queue entries: ");
6831 	scb_index = ahc_inb(ahc, DISCONNECTED_SCBH);
6832 	i = 0;
6833 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6834 		ahc_outb(ahc, SCBPTR, scb_index);
6835 		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
6836 		scb_index = ahc_inb(ahc, SCB_NEXT);
6837 	}
6838 	printf("\n");
6839 
6840 	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
6841 	printf("QOUTFIFO entries: ");
6842 	qoutpos = ahc->qoutfifonext;
6843 	i = 0;
6844 	while (ahc->qoutfifo[qoutpos] != SCB_LIST_NULL && i++ < 256) {
6845 		printf("%d ", ahc->qoutfifo[qoutpos]);
6846 		qoutpos++;
6847 	}
6848 	printf("\n");
6849 
6850 	printf("Sequencer Free SCB List: ");
6851 	scb_index = ahc_inb(ahc, FREE_SCBH);
6852 	i = 0;
6853 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
6854 		ahc_outb(ahc, SCBPTR, scb_index);
6855 		printf("%d ", scb_index);
6856 		scb_index = ahc_inb(ahc, SCB_NEXT);
6857 	}
6858 	printf("\n");
6859 
6860 	printf("Sequencer SCB Info: ");
6861 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
6862 		ahc_outb(ahc, SCBPTR, i);
6863 		cur_col = printf("\n%3d ", i);
6864 
6865 		ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL), &cur_col, 60);
6866 		ahc_scb_scsiid_print(ahc_inb(ahc, SCB_SCSIID), &cur_col, 60);
6867 		ahc_scb_lun_print(ahc_inb(ahc, SCB_LUN), &cur_col, 60);
6868 		ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6869 	}
6870 	printf("\n");
6871 
6872 	printf("Pending list: ");
6873 	i = 0;
6874 	LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
6875 		if (i++ > 256)
6876 			break;
6877 		cur_col = printf("\n%3d ", scb->hscb->tag);
6878 		ahc_scb_control_print(scb->hscb->control, &cur_col, 60);
6879 		ahc_scb_scsiid_print(scb->hscb->scsiid, &cur_col, 60);
6880 		ahc_scb_lun_print(scb->hscb->lun, &cur_col, 60);
6881 		if ((ahc->flags & AHC_PAGESCBS) == 0) {
6882 			ahc_outb(ahc, SCBPTR, scb->hscb->tag);
6883 			printf("(");
6884 			ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL),
6885 					      &cur_col, 60);
6886 			ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
6887 			printf(")");
6888 		}
6889 	}
6890 	printf("\n");
6891 
6892 	printf("Kernel Free SCB list: ");
6893 	i = 0;
6894 	SLIST_FOREACH(scb, &ahc->scb_data->free_scbs, links.sle) {
6895 		if (i++ > 256)
6896 			break;
6897 		printf("%d ", scb->hscb->tag);
6898 	}
6899 	printf("\n");
6900 
6901 	maxtarget = (ahc->features & (AHC_WIDE|AHC_TWIN)) ? 15 : 7;
6902 	for (target = 0; target <= maxtarget; target++) {
6903 		untagged_q = &ahc->untagged_queues[target];
6904 		if (TAILQ_FIRST(untagged_q) == NULL)
6905 			continue;
6906 		printf("Untagged Q(%d): ", target);
6907 		i = 0;
6908 		TAILQ_FOREACH(scb, untagged_q, links.tqe) {
6909 			if (i++ > 256)
6910 				break;
6911 			printf("%d ", scb->hscb->tag);
6912 		}
6913 		printf("\n");
6914 	}
6915 
6916 	ahc_platform_dump_card_state(ahc);
6917 	printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
6918 	ahc_outb(ahc, SCBPTR, saved_scbptr);
6919 	if (paused == 0)
6920 		ahc_unpause(ahc);
6921 }
6922 
6923 /*************************** Timeout Handling *********************************/
6924 void
6925 ahc_timeout(struct scb *scb)
6926 {
6927 	struct ahc_softc *ahc;
6928 
6929 	ahc = scb->ahc_softc;
6930 	if ((scb->flags & SCB_ACTIVE) != 0) {
6931 		if ((scb->flags & SCB_TIMEDOUT) == 0) {
6932 			LIST_INSERT_HEAD(&ahc->timedout_scbs, scb,
6933 					 timedout_links);
6934 			scb->flags |= SCB_TIMEDOUT;
6935 		}
6936 		ahc_wakeup_recovery_thread(ahc);
6937 	}
6938 }
6939 
6940 /*
6941  * Re-schedule a timeout for the passed in SCB if we determine that some
6942  * other SCB is in the process of recovery or an SCB with a longer
6943  * timeout is still pending.  Limit our search to just "other_scb"
6944  * if it is non-NULL.
6945  */
6946 static int
6947 ahc_other_scb_timeout(struct ahc_softc *ahc, struct scb *scb,
6948 		      struct scb *other_scb)
6949 {
6950 	u_int	newtimeout;
6951 	int	found;
6952 
6953 	ahc_print_path(ahc, scb);
6954 	printf("Other SCB Timeout%s",
6955  	       (scb->flags & SCB_OTHERTCL_TIMEOUT) != 0
6956 	       ? " again\n" : "\n");
6957 
6958 	newtimeout = aic_get_timeout(scb);
6959 	scb->flags |= SCB_OTHERTCL_TIMEOUT;
6960 	found = 0;
6961 	if (other_scb != NULL) {
6962 		if ((other_scb->flags
6963 		   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
6964 		 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
6965 			found++;
6966 			newtimeout = MAX(aic_get_timeout(other_scb),
6967 					 newtimeout);
6968 		}
6969 	} else {
6970 		LIST_FOREACH(other_scb, &ahc->pending_scbs, pending_links) {
6971 			if ((other_scb->flags
6972 			   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
6973 			 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
6974 				found++;
6975 				newtimeout =
6976 				    MAX(aic_get_timeout(other_scb),
6977 					newtimeout);
6978 			}
6979 		}
6980 	}
6981 
6982 	if (found != 0)
6983 		aic_scb_timer_reset(scb, newtimeout);
6984 	else {
6985 		ahc_print_path(ahc, scb);
6986 		printf("No other SCB worth waiting for...\n");
6987 	}
6988 
6989 	return (found != 0);
6990 }
6991 
6992 /*
6993  * ahc_recover_commands determines if any of the commands that have currently
6994  * timedout are the root cause for this timeout.  Innocent commands are given
6995  * a new timeout while we wait for the command executing on the bus to timeout.
6996  * This routine is invoked from a thread context so we are allowed to sleep.
6997  * Our lock is not held on entry.
6998  */
6999 void
7000 ahc_recover_commands(struct ahc_softc *ahc)
7001 {
7002 	struct	scb *scb;
7003 	int	found;
7004 	int	restart_needed;
7005 	u_int	last_phase;
7006 
7007 	/*
7008 	 * Pause the controller and manually flush any
7009 	 * commands that have just completed but that our
7010 	 * interrupt handler has yet to see.
7011 	 */
7012 	ahc_pause_and_flushwork(ahc);
7013 
7014 	if (LIST_EMPTY(&ahc->timedout_scbs) != 0) {
7015 		/*
7016 		 * The timedout commands have already
7017 		 * completed.  This typically means
7018 		 * that either the timeout value was on
7019 		 * the hairy edge of what the device
7020 		 * requires or - more likely - interrupts
7021 		 * are not happening.
7022 		 */
7023 		printf("%s: Timedout SCBs already complete. "
7024 		       "Interrupts may not be functioning.\n", ahc_name(ahc));
7025 		ahc_unpause(ahc);
7026 		return;
7027 	}
7028 
7029 	restart_needed = 0;
7030 	printf("%s: Recovery Initiated\n", ahc_name(ahc));
7031 	ahc_dump_card_state(ahc);
7032 
7033 	last_phase = ahc_inb(ahc, LASTPHASE);
7034 	while ((scb = LIST_FIRST(&ahc->timedout_scbs)) != NULL) {
7035 		u_int	active_scb_index;
7036 		u_int	saved_scbptr;
7037 		int	target;
7038 		int	lun;
7039 		int	i;
7040 		char	channel;
7041 
7042 		target = SCB_GET_TARGET(ahc, scb);
7043 		channel = SCB_GET_CHANNEL(ahc, scb);
7044 		lun = SCB_GET_LUN(scb);
7045 
7046 		ahc_print_path(ahc, scb);
7047 		printf("SCB 0x%x - timed out\n", scb->hscb->tag);
7048 		if (scb->sg_count > 0) {
7049 			for (i = 0; i < scb->sg_count; i++) {
7050 				printf("sg[%d] - Addr 0x%x : Length %d\n",
7051 				       i,
7052 				       scb->sg_list[i].addr,
7053 				       scb->sg_list[i].len & AHC_SG_LEN_MASK);
7054 			}
7055 		}
7056 		if (scb->flags & (SCB_DEVICE_RESET|SCB_ABORT)) {
7057 			/*
7058 			 * Been down this road before.
7059 			 * Do a full bus reset.
7060 			 */
7061 			aic_set_transaction_status(scb, CAM_CMD_TIMEOUT);
7062 bus_reset:
7063 			found = ahc_reset_channel(ahc, channel,
7064 						  /*Initiate Reset*/TRUE);
7065 			printf("%s: Issued Channel %c Bus Reset. "
7066 			       "%d SCBs aborted\n", ahc_name(ahc), channel,
7067 			       found);
7068 			continue;
7069 		}
7070 
7071 		/*
7072 		 * Remove the command from the timedout list in
7073 		 * preparation for requeing it.
7074 		 */
7075 		LIST_REMOVE(scb, timedout_links);
7076 		scb->flags &= ~SCB_TIMEDOUT;
7077 
7078 		/*
7079 		 * If we are a target, transition to bus free and report
7080 		 * the timeout.
7081 		 *
7082 		 * The target/initiator that is holding up the bus may not
7083 		 * be the same as the one that triggered this timeout
7084 		 * (different commands have different timeout lengths).
7085 		 * If the bus is idle and we are actiing as the initiator
7086 		 * for this request, queue a BDR message to the timed out
7087 		 * target.  Otherwise, if the timed out transaction is
7088 		 * active:
7089 		 *   Initiator transaction:
7090 		 *	Stuff the message buffer with a BDR message and assert
7091 		 *	ATN in the hopes that the target will let go of the bus
7092 		 *	and go to the mesgout phase.  If this fails, we'll
7093 		 *	get another timeout 2 seconds later which will attempt
7094 		 *	a bus reset.
7095 		 *
7096 		 *   Target transaction:
7097 		 *	Transition to BUS FREE and report the error.
7098 		 *	It's good to be the target!
7099 		 */
7100 		saved_scbptr = ahc_inb(ahc, SCBPTR);
7101 		active_scb_index = ahc_inb(ahc, SCB_TAG);
7102 
7103 		if ((ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) == 0
7104 		  && (active_scb_index < ahc->scb_data->numscbs)) {
7105 			struct scb *active_scb;
7106 
7107 			/*
7108 			 * If the active SCB is not us, assume that
7109 			 * the active SCB has a longer timeout than
7110 			 * the timedout SCB, and wait for the active
7111 			 * SCB to timeout.
7112 			 */
7113 			active_scb = ahc_lookup_scb(ahc, active_scb_index);
7114 			if (active_scb != scb) {
7115 				if (ahc_other_scb_timeout(ahc, scb,
7116 							  active_scb) == 0)
7117 					goto bus_reset;
7118 				continue;
7119 			}
7120 
7121 			/* It's us */
7122 			if ((scb->flags & SCB_TARGET_SCB) != 0) {
7123 
7124 				/*
7125 				 * Send back any queued up transactions
7126 				 * and properly record the error condition.
7127 				 */
7128 				ahc_abort_scbs(ahc, SCB_GET_TARGET(ahc, scb),
7129 					       SCB_GET_CHANNEL(ahc, scb),
7130 					       SCB_GET_LUN(scb),
7131 					       scb->hscb->tag,
7132 					       ROLE_TARGET,
7133 					       CAM_CMD_TIMEOUT);
7134 
7135 				/* Will clear us from the bus */
7136 				restart_needed = 1;
7137 				break;
7138 			}
7139 
7140 			ahc_set_recoveryscb(ahc, active_scb);
7141 			ahc_outb(ahc, MSG_OUT, HOST_MSG);
7142 			ahc_outb(ahc, SCSISIGO, last_phase|ATNO);
7143 			ahc_print_path(ahc, active_scb);
7144 			printf("BDR message in message buffer\n");
7145 			active_scb->flags |= SCB_DEVICE_RESET;
7146 			aic_scb_timer_reset(scb, 2 * 1000);
7147 		} else if (last_phase != P_BUSFREE
7148 			&& (ahc_inb(ahc, SSTAT1) & REQINIT) == 0) {
7149 			/*
7150 			 * SCB is not identified, there
7151 			 * is no pending REQ, and the sequencer
7152 			 * has not seen a busfree.  Looks like
7153 			 * a stuck connection waiting to
7154 			 * go busfree.  Reset the bus.
7155 			 */
7156 			printf("%s: Connection stuck awaiting busfree or "
7157 			       "Identify Msg.\n", ahc_name(ahc));
7158 			goto bus_reset;
7159 		} else {
7160 			int	 disconnected;
7161 
7162 			if (last_phase != P_BUSFREE
7163 			 && (ahc_inb(ahc, SSTAT0) & TARGET) != 0) {
7164 				/* Hung target selection.  Goto busfree */
7165 				printf("%s: Hung target selection\n",
7166 				       ahc_name(ahc));
7167 				restart_needed = 1;
7168 				break;
7169 			}
7170 
7171 			/* XXX Shouldn't panic.  Just punt instead? */
7172 			if ((scb->flags & SCB_TARGET_SCB) != 0)
7173 				panic("Timed-out target SCB but bus idle");
7174 
7175 			if (ahc_search_qinfifo(ahc, target, channel, lun,
7176 					       scb->hscb->tag, ROLE_INITIATOR,
7177 					       /*status*/0, SEARCH_COUNT) > 0) {
7178 				disconnected = FALSE;
7179 			} else {
7180 				disconnected = TRUE;
7181 			}
7182 
7183 			if (disconnected) {
7184 
7185 				ahc_set_recoveryscb(ahc, scb);
7186 				/*
7187 				 * Actually re-queue this SCB in an attempt
7188 				 * to select the device before it reconnects.
7189 				 * In either case (selection or reselection),
7190 				 * we will now issue a target reset to the
7191 				 * timed-out device.
7192 				 *
7193 				 * Set the MK_MESSAGE control bit indicating
7194 				 * that we desire to send a message.  We
7195 				 * also set the disconnected flag since
7196 				 * in the paging case there is no guarantee
7197 				 * that our SCB control byte matches the
7198 				 * version on the card.  We don't want the
7199 				 * sequencer to abort the command thinking
7200 				 * an unsolicited reselection occurred.
7201 				 */
7202 				scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
7203 				scb->flags |= SCB_DEVICE_RESET;
7204 
7205 				/*
7206 				 * Remove any cached copy of this SCB in the
7207 				 * disconnected list in preparation for the
7208 				 * queuing of our abort SCB.  We use the
7209 				 * same element in the SCB, SCB_NEXT, for
7210 				 * both the qinfifo and the disconnected list.
7211 				 */
7212 				ahc_search_disc_list(ahc, target, channel,
7213 						     lun, scb->hscb->tag,
7214 						     /*stop_on_first*/TRUE,
7215 						     /*remove*/TRUE,
7216 						     /*save_state*/FALSE);
7217 
7218 				/*
7219 				 * In the non-paging case, the sequencer will
7220 				 * never re-reference the in-core SCB.
7221 				 * To make sure we are notified during
7222 				 * reslection, set the MK_MESSAGE flag in
7223 				 * the card's copy of the SCB.
7224 				 */
7225 				if ((ahc->flags & AHC_PAGESCBS) == 0) {
7226 					ahc_outb(ahc, SCBPTR, scb->hscb->tag);
7227 					ahc_outb(ahc, SCB_CONTROL,
7228 						 ahc_inb(ahc, SCB_CONTROL)
7229 						| MK_MESSAGE);
7230 				}
7231 
7232 				/*
7233 				 * Clear out any entries in the QINFIFO first
7234 				 * so we are the next SCB for this target
7235 				 * to run.
7236 				 */
7237 				ahc_search_qinfifo(ahc,
7238 						   SCB_GET_TARGET(ahc, scb),
7239 						   channel, SCB_GET_LUN(scb),
7240 						   SCB_LIST_NULL,
7241 						   ROLE_INITIATOR,
7242 						   CAM_REQUEUE_REQ,
7243 						   SEARCH_COMPLETE);
7244 				ahc_print_path(ahc, scb);
7245 				printf("Queuing a BDR SCB\n");
7246 				ahc_qinfifo_requeue_tail(ahc, scb);
7247 				ahc_outb(ahc, SCBPTR, saved_scbptr);
7248 				aic_scb_timer_reset(scb, 2 * 1000);
7249 			} else {
7250 				/* Go "immediatly" to the bus reset */
7251 				/* This shouldn't happen */
7252 				ahc_set_recoveryscb(ahc, scb);
7253 				ahc_print_path(ahc, scb);
7254 				printf("SCB %d: Immediate reset.  "
7255 					"Flags = 0x%x\n", scb->hscb->tag,
7256 					scb->flags);
7257 				goto bus_reset;
7258 			}
7259 		}
7260 		break;
7261 	}
7262 
7263 	/*
7264 	 * Any remaining SCBs were not the "culprit", so remove
7265 	 * them from the timeout list.  The timer for these commands
7266 	 * will be reset once the recovery SCB completes.
7267 	 */
7268 	while ((scb = LIST_FIRST(&ahc->timedout_scbs)) != NULL) {
7269 
7270 		LIST_REMOVE(scb, timedout_links);
7271 		scb->flags &= ~SCB_TIMEDOUT;
7272 	}
7273 
7274 	if (restart_needed)
7275 		ahc_restart(ahc);
7276 	else
7277 		ahc_unpause(ahc);
7278 }
7279 
7280 /************************* Target Mode ****************************************/
7281 #ifdef AHC_TARGET_MODE
7282 cam_status
7283 ahc_find_tmode_devs(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb,
7284 		    struct ahc_tmode_tstate **tstate,
7285 		    struct ahc_tmode_lstate **lstate,
7286 		    int notfound_failure)
7287 {
7288 
7289 	if ((ahc->features & AHC_TARGETMODE) == 0)
7290 		return (CAM_REQ_INVALID);
7291 
7292 	/*
7293 	 * Handle the 'black hole' device that sucks up
7294 	 * requests to unattached luns on enabled targets.
7295 	 */
7296 	if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
7297 	 && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
7298 		*tstate = NULL;
7299 		*lstate = ahc->black_hole;
7300 	} else {
7301 		u_int max_id;
7302 
7303 		max_id = (ahc->features & AHC_WIDE) ? 15 : 7;
7304 		if (ccb->ccb_h.target_id > max_id)
7305 			return (CAM_TID_INVALID);
7306 
7307 		if (ccb->ccb_h.target_lun >= AHC_NUM_LUNS)
7308 			return (CAM_LUN_INVALID);
7309 
7310 		*tstate = ahc->enabled_targets[ccb->ccb_h.target_id];
7311 		*lstate = NULL;
7312 		if (*tstate != NULL)
7313 			*lstate =
7314 			    (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
7315 	}
7316 
7317 	if (notfound_failure != 0 && *lstate == NULL)
7318 		return (CAM_PATH_INVALID);
7319 
7320 	return (CAM_REQ_CMP);
7321 }
7322 
7323 void
7324 ahc_handle_en_lun(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb)
7325 {
7326 	struct	   ahc_tmode_tstate *tstate;
7327 	struct	   ahc_tmode_lstate *lstate;
7328 	struct	   ccb_en_lun *cel;
7329 	cam_status status;
7330 	u_int	   target;
7331 	u_int	   lun;
7332 	u_int	   target_mask;
7333 	u_int	   our_id;
7334 	int	   error;
7335 	char	   channel;
7336 
7337 	status = ahc_find_tmode_devs(ahc, sim, ccb, &tstate, &lstate,
7338 				     /*notfound_failure*/FALSE);
7339 
7340 	if (status != CAM_REQ_CMP) {
7341 		ccb->ccb_h.status = status;
7342 		return;
7343 	}
7344 
7345 	if (cam_sim_bus(sim) == 0)
7346 		our_id = ahc->our_id;
7347 	else
7348 		our_id = ahc->our_id_b;
7349 
7350 	if (ccb->ccb_h.target_id != our_id) {
7351 		/*
7352 		 * our_id represents our initiator ID, or
7353 		 * the ID of the first target to have an
7354 		 * enabled lun in target mode.  There are
7355 		 * two cases that may preclude enabling a
7356 		 * target id other than our_id.
7357 		 *
7358 		 *   o our_id is for an active initiator role.
7359 		 *     Since the hardware does not support
7360 		 *     reselections to the initiator role at
7361 		 *     anything other than our_id, and our_id
7362 		 *     is used by the hardware to indicate the
7363 		 *     ID to use for both select-out and
7364 		 *     reselect-out operations, the only target
7365 		 *     ID we can support in this mode is our_id.
7366 		 *
7367 		 *   o The MULTARGID feature is not available and
7368 		 *     a previous target mode ID has been enabled.
7369 		 */
7370 		if ((ahc->features & AHC_MULTIROLE) != 0) {
7371 
7372 			if ((ahc->features & AHC_MULTI_TID) != 0
7373 		   	 && (ahc->flags & AHC_INITIATORROLE) != 0) {
7374 				/*
7375 				 * Only allow additional targets if
7376 				 * the initiator role is disabled.
7377 				 * The hardware cannot handle a re-select-in
7378 				 * on the initiator id during a re-select-out
7379 				 * on a different target id.
7380 				 */
7381 				status = CAM_TID_INVALID;
7382 			} else if ((ahc->flags & AHC_INITIATORROLE) != 0
7383 				|| ahc->enabled_luns > 0) {
7384 				/*
7385 				 * Only allow our target id to change
7386 				 * if the initiator role is not configured
7387 				 * and there are no enabled luns which
7388 				 * are attached to the currently registered
7389 				 * scsi id.
7390 				 */
7391 				status = CAM_TID_INVALID;
7392 			}
7393 		} else if ((ahc->features & AHC_MULTI_TID) == 0
7394 			&& ahc->enabled_luns > 0) {
7395 
7396 			status = CAM_TID_INVALID;
7397 		}
7398 	}
7399 
7400 	if (status != CAM_REQ_CMP) {
7401 		ccb->ccb_h.status = status;
7402 		return;
7403 	}
7404 
7405 	/*
7406 	 * We now have an id that is valid.
7407 	 * If we aren't in target mode, switch modes.
7408 	 */
7409 	if ((ahc->flags & AHC_TARGETROLE) == 0
7410 	 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
7411 		ahc_flag saved_flags;
7412 
7413 		printf("Configuring Target Mode\n");
7414 		if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
7415 			ccb->ccb_h.status = CAM_BUSY;
7416 			return;
7417 		}
7418 		saved_flags = ahc->flags;
7419 		ahc->flags |= AHC_TARGETROLE;
7420 		if ((ahc->features & AHC_MULTIROLE) == 0)
7421 			ahc->flags &= ~AHC_INITIATORROLE;
7422 		ahc_pause(ahc);
7423 		error = ahc_loadseq(ahc);
7424 		if (error != 0) {
7425 			/*
7426 			 * Restore original configuration and notify
7427 			 * the caller that we cannot support target mode.
7428 			 * Since the adapter started out in this
7429 			 * configuration, the firmware load will succeed,
7430 			 * so there is no point in checking ahc_loadseq's
7431 			 * return value.
7432 			 */
7433 			ahc->flags = saved_flags;
7434 			(void)ahc_loadseq(ahc);
7435 			ahc_restart(ahc);
7436 			ccb->ccb_h.status = CAM_FUNC_NOTAVAIL;
7437 			return;
7438 		}
7439 		ahc_restart(ahc);
7440 	}
7441 	cel = &ccb->cel;
7442 	target = ccb->ccb_h.target_id;
7443 	lun = ccb->ccb_h.target_lun;
7444 	channel = SIM_CHANNEL(ahc, sim);
7445 	target_mask = 0x01 << target;
7446 	if (channel == 'B')
7447 		target_mask <<= 8;
7448 
7449 	if (cel->enable != 0) {
7450 		u_int scsiseq;
7451 
7452 		/* Are we already enabled?? */
7453 		if (lstate != NULL) {
7454 			xpt_print_path(ccb->ccb_h.path);
7455 			printf("Lun already enabled\n");
7456 			ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
7457 			return;
7458 		}
7459 
7460 		if (cel->grp6_len != 0
7461 		 || cel->grp7_len != 0) {
7462 			/*
7463 			 * Don't (yet?) support vendor
7464 			 * specific commands.
7465 			 */
7466 			ccb->ccb_h.status = CAM_REQ_INVALID;
7467 			printf("Non-zero Group Codes\n");
7468 			return;
7469 		}
7470 
7471 		/*
7472 		 * Seems to be okay.
7473 		 * Setup our data structures.
7474 		 */
7475 		if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
7476 			tstate = ahc_alloc_tstate(ahc, target, channel);
7477 			if (tstate == NULL) {
7478 				xpt_print_path(ccb->ccb_h.path);
7479 				printf("Couldn't allocate tstate\n");
7480 				ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7481 				return;
7482 			}
7483 		}
7484 		lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
7485 		if (lstate == NULL) {
7486 			xpt_print_path(ccb->ccb_h.path);
7487 			printf("Couldn't allocate lstate\n");
7488 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7489 			return;
7490 		}
7491 		memset(lstate, 0, sizeof(*lstate));
7492 		status = xpt_create_path(&lstate->path, /*periph*/NULL,
7493 					 xpt_path_path_id(ccb->ccb_h.path),
7494 					 xpt_path_target_id(ccb->ccb_h.path),
7495 					 xpt_path_lun_id(ccb->ccb_h.path));
7496 		if (status != CAM_REQ_CMP) {
7497 			free(lstate, M_DEVBUF);
7498 			xpt_print_path(ccb->ccb_h.path);
7499 			printf("Couldn't allocate path\n");
7500 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
7501 			return;
7502 		}
7503 		SLIST_INIT(&lstate->accept_tios);
7504 		SLIST_INIT(&lstate->immed_notifies);
7505 		ahc_pause(ahc);
7506 		if (target != CAM_TARGET_WILDCARD) {
7507 			tstate->enabled_luns[lun] = lstate;
7508 			ahc->enabled_luns++;
7509 
7510 			if ((ahc->features & AHC_MULTI_TID) != 0) {
7511 				u_int targid_mask;
7512 
7513 				targid_mask = ahc_inb(ahc, TARGID)
7514 					    | (ahc_inb(ahc, TARGID + 1) << 8);
7515 
7516 				targid_mask |= target_mask;
7517 				ahc_outb(ahc, TARGID, targid_mask);
7518 				ahc_outb(ahc, TARGID+1, (targid_mask >> 8));
7519 
7520 				ahc_update_scsiid(ahc, targid_mask);
7521 			} else {
7522 				u_int our_id;
7523 				char  channel;
7524 
7525 				channel = SIM_CHANNEL(ahc, sim);
7526 				our_id = SIM_SCSI_ID(ahc, sim);
7527 
7528 				/*
7529 				 * This can only happen if selections
7530 				 * are not enabled
7531 				 */
7532 				if (target != our_id) {
7533 					u_int sblkctl;
7534 					char  cur_channel;
7535 					int   swap;
7536 
7537 					sblkctl = ahc_inb(ahc, SBLKCTL);
7538 					cur_channel = (sblkctl & SELBUSB)
7539 						    ? 'B' : 'A';
7540 					if ((ahc->features & AHC_TWIN) == 0)
7541 						cur_channel = 'A';
7542 					swap = cur_channel != channel;
7543 					if (channel == 'A')
7544 						ahc->our_id = target;
7545 					else
7546 						ahc->our_id_b = target;
7547 
7548 					if (swap)
7549 						ahc_outb(ahc, SBLKCTL,
7550 							 sblkctl ^ SELBUSB);
7551 
7552 					ahc_outb(ahc, SCSIID, target);
7553 
7554 					if (swap)
7555 						ahc_outb(ahc, SBLKCTL, sblkctl);
7556 				}
7557 			}
7558 		} else
7559 			ahc->black_hole = lstate;
7560 		/* Allow select-in operations */
7561 		if (ahc->black_hole != NULL && ahc->enabled_luns > 0) {
7562 			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7563 			scsiseq |= ENSELI;
7564 			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7565 			scsiseq = ahc_inb(ahc, SCSISEQ);
7566 			scsiseq |= ENSELI;
7567 			ahc_outb(ahc, SCSISEQ, scsiseq);
7568 		}
7569 		ahc_unpause(ahc);
7570 		ccb->ccb_h.status = CAM_REQ_CMP;
7571 		xpt_print_path(ccb->ccb_h.path);
7572 		printf("Lun now enabled for target mode\n");
7573 	} else {
7574 		struct scb *scb;
7575 		int i, empty;
7576 
7577 		if (lstate == NULL) {
7578 			ccb->ccb_h.status = CAM_LUN_INVALID;
7579 			return;
7580 		}
7581 
7582 		ccb->ccb_h.status = CAM_REQ_CMP;
7583 		LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
7584 			struct ccb_hdr *ccbh;
7585 
7586 			ccbh = &scb->io_ctx->ccb_h;
7587 			if (ccbh->func_code == XPT_CONT_TARGET_IO
7588 			 && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
7589 				printf("CTIO pending\n");
7590 				ccb->ccb_h.status = CAM_REQ_INVALID;
7591 				return;
7592 			}
7593 		}
7594 
7595 		if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
7596 			printf("ATIOs pending\n");
7597 			ccb->ccb_h.status = CAM_REQ_INVALID;
7598 		}
7599 
7600 		if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
7601 			printf("INOTs pending\n");
7602 			ccb->ccb_h.status = CAM_REQ_INVALID;
7603 		}
7604 
7605 		if (ccb->ccb_h.status != CAM_REQ_CMP) {
7606 			return;
7607 		}
7608 
7609 		xpt_print_path(ccb->ccb_h.path);
7610 		printf("Target mode disabled\n");
7611 		xpt_free_path(lstate->path);
7612 		free(lstate, M_DEVBUF);
7613 
7614 		ahc_pause(ahc);
7615 		/* Can we clean up the target too? */
7616 		if (target != CAM_TARGET_WILDCARD) {
7617 			tstate->enabled_luns[lun] = NULL;
7618 			ahc->enabled_luns--;
7619 			for (empty = 1, i = 0; i < 8; i++)
7620 				if (tstate->enabled_luns[i] != NULL) {
7621 					empty = 0;
7622 					break;
7623 				}
7624 
7625 			if (empty) {
7626 				ahc_free_tstate(ahc, target, channel,
7627 						/*force*/FALSE);
7628 				if (ahc->features & AHC_MULTI_TID) {
7629 					u_int targid_mask;
7630 
7631 					targid_mask = ahc_inb(ahc, TARGID)
7632 						    | (ahc_inb(ahc, TARGID + 1)
7633 						       << 8);
7634 
7635 					targid_mask &= ~target_mask;
7636 					ahc_outb(ahc, TARGID, targid_mask);
7637 					ahc_outb(ahc, TARGID+1,
7638 					 	 (targid_mask >> 8));
7639 					ahc_update_scsiid(ahc, targid_mask);
7640 				}
7641 			}
7642 		} else {
7643 
7644 			ahc->black_hole = NULL;
7645 
7646 			/*
7647 			 * We can't allow selections without
7648 			 * our black hole device.
7649 			 */
7650 			empty = TRUE;
7651 		}
7652 		if (ahc->enabled_luns == 0) {
7653 			/* Disallow select-in */
7654 			u_int scsiseq;
7655 
7656 			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
7657 			scsiseq &= ~ENSELI;
7658 			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
7659 			scsiseq = ahc_inb(ahc, SCSISEQ);
7660 			scsiseq &= ~ENSELI;
7661 			ahc_outb(ahc, SCSISEQ, scsiseq);
7662 
7663 			if ((ahc->features & AHC_MULTIROLE) == 0) {
7664 				printf("Configuring Initiator Mode\n");
7665 				ahc->flags &= ~AHC_TARGETROLE;
7666 				ahc->flags |= AHC_INITIATORROLE;
7667 				/*
7668 				 * Returning to a configuration that
7669 				 * fit previously will always succeed.
7670 				 */
7671 				(void)ahc_loadseq(ahc);
7672 				ahc_restart(ahc);
7673 				/*
7674 				 * Unpaused.  The extra unpause
7675 				 * that follows is harmless.
7676 				 */
7677 			}
7678 		}
7679 		ahc_unpause(ahc);
7680 	}
7681 }
7682 
7683 static void
7684 ahc_update_scsiid(struct ahc_softc *ahc, u_int targid_mask)
7685 {
7686 	u_int scsiid_mask;
7687 	u_int scsiid;
7688 
7689 	if ((ahc->features & AHC_MULTI_TID) == 0)
7690 		panic("ahc_update_scsiid called on non-multitid unit\n");
7691 
7692 	/*
7693 	 * Since we will rely on the TARGID mask
7694 	 * for selection enables, ensure that OID
7695 	 * in SCSIID is not set to some other ID
7696 	 * that we don't want to allow selections on.
7697 	 */
7698 	if ((ahc->features & AHC_ULTRA2) != 0)
7699 		scsiid = ahc_inb(ahc, SCSIID_ULTRA2);
7700 	else
7701 		scsiid = ahc_inb(ahc, SCSIID);
7702 	scsiid_mask = 0x1 << (scsiid & OID);
7703 	if ((targid_mask & scsiid_mask) == 0) {
7704 		u_int our_id;
7705 
7706 		/* ffs counts from 1 */
7707 		our_id = ffs(targid_mask);
7708 		if (our_id == 0)
7709 			our_id = ahc->our_id;
7710 		else
7711 			our_id--;
7712 		scsiid &= TID;
7713 		scsiid |= our_id;
7714 	}
7715 	if ((ahc->features & AHC_ULTRA2) != 0)
7716 		ahc_outb(ahc, SCSIID_ULTRA2, scsiid);
7717 	else
7718 		ahc_outb(ahc, SCSIID, scsiid);
7719 }
7720 
7721 void
7722 ahc_run_tqinfifo(struct ahc_softc *ahc, int paused)
7723 {
7724 	struct target_cmd *cmd;
7725 
7726 	/*
7727 	 * If the card supports auto-access pause,
7728 	 * we can access the card directly regardless
7729 	 * of whether it is paused or not.
7730 	 */
7731 	if ((ahc->features & AHC_AUTOPAUSE) != 0)
7732 		paused = TRUE;
7733 
7734 	ahc_sync_tqinfifo(ahc, BUS_DMASYNC_POSTREAD);
7735 	while ((cmd = &ahc->targetcmds[ahc->tqinfifonext])->cmd_valid != 0) {
7736 
7737 		/*
7738 		 * Only advance through the queue if we
7739 		 * have the resources to process the command.
7740 		 */
7741 		if (ahc_handle_target_cmd(ahc, cmd) != 0)
7742 			break;
7743 
7744 		cmd->cmd_valid = 0;
7745 		aic_dmamap_sync(ahc, ahc->shared_data_dmat,
7746 				ahc->shared_data_dmamap,
7747 				ahc_targetcmd_offset(ahc, ahc->tqinfifonext),
7748 				sizeof(struct target_cmd),
7749 				BUS_DMASYNC_PREREAD);
7750 		ahc->tqinfifonext++;
7751 
7752 		/*
7753 		 * Lazily update our position in the target mode incoming
7754 		 * command queue as seen by the sequencer.
7755 		 */
7756 		if ((ahc->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
7757 			if ((ahc->features & AHC_HS_MAILBOX) != 0) {
7758 				u_int hs_mailbox;
7759 
7760 				hs_mailbox = ahc_inb(ahc, HS_MAILBOX);
7761 				hs_mailbox &= ~HOST_TQINPOS;
7762 				hs_mailbox |= ahc->tqinfifonext & HOST_TQINPOS;
7763 				ahc_outb(ahc, HS_MAILBOX, hs_mailbox);
7764 			} else {
7765 				if (!paused)
7766 					ahc_pause(ahc);
7767 				ahc_outb(ahc, KERNEL_TQINPOS,
7768 					 ahc->tqinfifonext & HOST_TQINPOS);
7769 				if (!paused)
7770 					ahc_unpause(ahc);
7771 			}
7772 		}
7773 	}
7774 }
7775 
7776 static int
7777 ahc_handle_target_cmd(struct ahc_softc *ahc, struct target_cmd *cmd)
7778 {
7779 	struct	  ahc_tmode_tstate *tstate;
7780 	struct	  ahc_tmode_lstate *lstate;
7781 	struct	  ccb_accept_tio *atio;
7782 	uint8_t *byte;
7783 	int	  initiator;
7784 	int	  target;
7785 	int	  lun;
7786 
7787 	initiator = SCSIID_TARGET(ahc, cmd->scsiid);
7788 	target = SCSIID_OUR_ID(cmd->scsiid);
7789 	lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
7790 
7791 	byte = cmd->bytes;
7792 	tstate = ahc->enabled_targets[target];
7793 	lstate = NULL;
7794 	if (tstate != NULL)
7795 		lstate = tstate->enabled_luns[lun];
7796 
7797 	/*
7798 	 * Commands for disabled luns go to the black hole driver.
7799 	 */
7800 	if (lstate == NULL)
7801 		lstate = ahc->black_hole;
7802 
7803 	atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
7804 	if (atio == NULL) {
7805 		ahc->flags |= AHC_TQINFIFO_BLOCKED;
7806 		/*
7807 		 * Wait for more ATIOs from the peripheral driver for this lun.
7808 		 */
7809 		if (bootverbose)
7810 			printf("%s: ATIOs exhausted\n", ahc_name(ahc));
7811 		return (1);
7812 	} else
7813 		ahc->flags &= ~AHC_TQINFIFO_BLOCKED;
7814 #ifdef AHC_DEBUG
7815 	if (ahc_debug & AHC_SHOW_TQIN) {
7816 		printf("Incoming command from %d for %d:%d%s\n",
7817 		       initiator, target, lun,
7818 		       lstate == ahc->black_hole ? "(Black Holed)" : "");
7819 	}
7820 #endif
7821 	SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
7822 
7823 	if (lstate == ahc->black_hole) {
7824 		/* Fill in the wildcards */
7825 		atio->ccb_h.target_id = target;
7826 		atio->ccb_h.target_lun = lun;
7827 	}
7828 
7829 	/*
7830 	 * Package it up and send it off to
7831 	 * whomever has this lun enabled.
7832 	 */
7833 	atio->sense_len = 0;
7834 	atio->init_id = initiator;
7835 	if (byte[0] != 0xFF) {
7836 		/* Tag was included */
7837 		atio->tag_action = *byte++;
7838 		atio->tag_id = *byte++;
7839 		atio->ccb_h.flags |= CAM_TAG_ACTION_VALID;
7840 	} else {
7841 		atio->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
7842 	}
7843 	byte++;
7844 
7845 	/* Okay.  Now determine the cdb size based on the command code */
7846 	switch (*byte >> CMD_GROUP_CODE_SHIFT) {
7847 	case 0:
7848 		atio->cdb_len = 6;
7849 		break;
7850 	case 1:
7851 	case 2:
7852 		atio->cdb_len = 10;
7853 		break;
7854 	case 4:
7855 		atio->cdb_len = 16;
7856 		break;
7857 	case 5:
7858 		atio->cdb_len = 12;
7859 		break;
7860 	case 3:
7861 	default:
7862 		/* Only copy the opcode. */
7863 		atio->cdb_len = 1;
7864 		printf("Reserved or VU command code type encountered\n");
7865 		break;
7866 	}
7867 
7868 	memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
7869 
7870 	atio->ccb_h.status |= CAM_CDB_RECVD;
7871 
7872 	if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
7873 		/*
7874 		 * We weren't allowed to disconnect.
7875 		 * We're hanging on the bus until a
7876 		 * continue target I/O comes in response
7877 		 * to this accept tio.
7878 		 */
7879 #ifdef AHC_DEBUG
7880 		if (ahc_debug & AHC_SHOW_TQIN) {
7881 			printf("Received Immediate Command %d:%d:%d - %p\n",
7882 			       initiator, target, lun, ahc->pending_device);
7883 		}
7884 #endif
7885 		ahc->pending_device = lstate;
7886 		aic_freeze_ccb((union ccb *)atio);
7887 		atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
7888 	}
7889 	xpt_done((union ccb*)atio);
7890 	return (0);
7891 }
7892 
7893 #endif
7894