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