xref: /freebsd/sys/dev/aic7xxx/aic79xx.c (revision 38a52bd3)
1 /*-
2  * Core routines and tables shareable across OS platforms.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  *
6  * Copyright (c) 1994-2002, 2004 Justin T. Gibbs.
7  * Copyright (c) 2000-2003 Adaptec Inc.
8  * All rights reserved.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions, and the following disclaimer,
15  *    without modification.
16  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
17  *    substantially similar to the "NO WARRANTY" disclaimer below
18  *    ("Disclaimer") and any redistribution must be conditioned upon
19  *    including a substantially similar Disclaimer requirement for further
20  *    binary redistribution.
21  * 3. Neither the names of the above-listed copyright holders nor the names
22  *    of any contributors may be used to endorse or promote products derived
23  *    from this software without specific prior written permission.
24  *
25  * Alternatively, this software may be distributed under the terms of the
26  * GNU General Public License ("GPL") version 2 as published by the Free
27  * Software Foundation.
28  *
29  * NO WARRANTY
30  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
31  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
32  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
33  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
34  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
35  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
36  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
37  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
38  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
39  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
40  * POSSIBILITY OF SUCH DAMAGES.
41  *
42  * $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#246 $
43  */
44 
45 #ifdef __linux__
46 #include "aic79xx_osm.h"
47 #include "aic79xx_inline.h"
48 #include "aicasm/aicasm_insformat.h"
49 #else
50 #include <sys/cdefs.h>
51 __FBSDID("$FreeBSD$");
52 #include <dev/aic7xxx/aic79xx_osm.h>
53 #include <dev/aic7xxx/aic79xx_inline.h>
54 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
55 #endif
56 
57 /******************************** Globals *************************************/
58 struct ahd_softc_tailq ahd_tailq = TAILQ_HEAD_INITIALIZER(ahd_tailq);
59 uint32_t ahd_attach_to_HostRAID_controllers = 1;
60 
61 /***************************** Lookup Tables **********************************/
62 char *ahd_chip_names[] =
63 {
64 	"NONE",
65 	"aic7901",
66 	"aic7902",
67 	"aic7901A"
68 };
69 
70 /*
71  * Hardware error codes.
72  */
73 struct ahd_hard_error_entry {
74         uint8_t errno;
75 	char *errmesg;
76 };
77 
78 static struct ahd_hard_error_entry ahd_hard_errors[] = {
79 	{ DSCTMOUT,	"Discard Timer has timed out" },
80 	{ ILLOPCODE,	"Illegal Opcode in sequencer program" },
81 	{ SQPARERR,	"Sequencer Parity Error" },
82 	{ DPARERR,	"Data-path Parity Error" },
83 	{ MPARERR,	"Scratch or SCB Memory Parity Error" },
84 	{ CIOPARERR,	"CIOBUS Parity Error" },
85 };
86 static const u_int num_errors = NUM_ELEMENTS(ahd_hard_errors);
87 
88 static struct ahd_phase_table_entry ahd_phase_table[] =
89 {
90 	{ P_DATAOUT,	MSG_NOOP,		"in Data-out phase"	},
91 	{ P_DATAIN,	MSG_INITIATOR_DET_ERR,	"in Data-in phase"	},
92 	{ P_DATAOUT_DT,	MSG_NOOP,		"in DT Data-out phase"	},
93 	{ P_DATAIN_DT,	MSG_INITIATOR_DET_ERR,	"in DT Data-in phase"	},
94 	{ P_COMMAND,	MSG_NOOP,		"in Command phase"	},
95 	{ P_MESGOUT,	MSG_NOOP,		"in Message-out phase"	},
96 	{ P_STATUS,	MSG_INITIATOR_DET_ERR,	"in Status phase"	},
97 	{ P_MESGIN,	MSG_PARITY_ERROR,	"in Message-in phase"	},
98 	{ P_BUSFREE,	MSG_NOOP,		"while idle"		},
99 	{ 0,		MSG_NOOP,		"in unknown phase"	}
100 };
101 
102 /*
103  * In most cases we only wish to itterate over real phases, so
104  * exclude the last element from the count.
105  */
106 static const u_int num_phases = NUM_ELEMENTS(ahd_phase_table) - 1;
107 
108 /* Our Sequencer Program */
109 #include "aic79xx_seq.h"
110 
111 /**************************** Function Declarations ***************************/
112 static void		ahd_handle_transmission_error(struct ahd_softc *ahd);
113 static void		ahd_handle_lqiphase_error(struct ahd_softc *ahd,
114 						  u_int lqistat1);
115 static int		ahd_handle_pkt_busfree(struct ahd_softc *ahd,
116 					       u_int busfreetime);
117 static int		ahd_handle_nonpkt_busfree(struct ahd_softc *ahd);
118 static void		ahd_handle_proto_violation(struct ahd_softc *ahd);
119 static void		ahd_force_renegotiation(struct ahd_softc *ahd,
120 						struct ahd_devinfo *devinfo);
121 
122 static struct ahd_tmode_tstate*
123 			ahd_alloc_tstate(struct ahd_softc *ahd,
124 					 u_int scsi_id, char channel);
125 #ifdef AHD_TARGET_MODE
126 static void		ahd_free_tstate(struct ahd_softc *ahd,
127 					u_int scsi_id, char channel, int force);
128 #endif
129 static void		ahd_devlimited_syncrate(struct ahd_softc *ahd,
130 					        struct ahd_initiator_tinfo *,
131 						u_int *period,
132 						u_int *ppr_options,
133 						role_t role);
134 static void		ahd_update_neg_table(struct ahd_softc *ahd,
135 					     struct ahd_devinfo *devinfo,
136 					     struct ahd_transinfo *tinfo);
137 static void		ahd_update_pending_scbs(struct ahd_softc *ahd);
138 static void		ahd_fetch_devinfo(struct ahd_softc *ahd,
139 					  struct ahd_devinfo *devinfo);
140 static void		ahd_scb_devinfo(struct ahd_softc *ahd,
141 					struct ahd_devinfo *devinfo,
142 					struct scb *scb);
143 static void		ahd_setup_initiator_msgout(struct ahd_softc *ahd,
144 						   struct ahd_devinfo *devinfo,
145 						   struct scb *scb);
146 static void		ahd_build_transfer_msg(struct ahd_softc *ahd,
147 					       struct ahd_devinfo *devinfo);
148 static void		ahd_construct_sdtr(struct ahd_softc *ahd,
149 					   struct ahd_devinfo *devinfo,
150 					   u_int period, u_int offset);
151 static void		ahd_construct_wdtr(struct ahd_softc *ahd,
152 					   struct ahd_devinfo *devinfo,
153 					   u_int bus_width);
154 static void		ahd_construct_ppr(struct ahd_softc *ahd,
155 					  struct ahd_devinfo *devinfo,
156 					  u_int period, u_int offset,
157 					  u_int bus_width, u_int ppr_options);
158 static void		ahd_clear_msg_state(struct ahd_softc *ahd);
159 static void		ahd_handle_message_phase(struct ahd_softc *ahd);
160 typedef enum {
161 	AHDMSG_1B,
162 	AHDMSG_2B,
163 	AHDMSG_EXT
164 } ahd_msgtype;
165 static int		ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type,
166 				     u_int msgval, int full);
167 static int		ahd_parse_msg(struct ahd_softc *ahd,
168 				      struct ahd_devinfo *devinfo);
169 static int		ahd_handle_msg_reject(struct ahd_softc *ahd,
170 					      struct ahd_devinfo *devinfo);
171 static void		ahd_handle_ign_wide_residue(struct ahd_softc *ahd,
172 						struct ahd_devinfo *devinfo);
173 static void		ahd_reinitialize_dataptrs(struct ahd_softc *ahd);
174 static void		ahd_handle_devreset(struct ahd_softc *ahd,
175 					    struct ahd_devinfo *devinfo,
176 					    u_int lun, cam_status status,
177 					    char *message, int verbose_level);
178 #ifdef AHD_TARGET_MODE
179 static void		ahd_setup_target_msgin(struct ahd_softc *ahd,
180 					       struct ahd_devinfo *devinfo,
181 					       struct scb *scb);
182 #endif
183 
184 static u_int		ahd_sglist_size(struct ahd_softc *ahd);
185 static u_int		ahd_sglist_allocsize(struct ahd_softc *ahd);
186 static bus_dmamap_callback_t
187 			ahd_dmamap_cb;
188 static void		ahd_initialize_hscbs(struct ahd_softc *ahd);
189 static int		ahd_init_scbdata(struct ahd_softc *ahd);
190 static void		ahd_fini_scbdata(struct ahd_softc *ahd);
191 static void		ahd_setup_iocell_workaround(struct ahd_softc *ahd);
192 static void		ahd_iocell_first_selection(struct ahd_softc *ahd);
193 static void		ahd_add_col_list(struct ahd_softc *ahd,
194 					 struct scb *scb, u_int col_idx);
195 static void		ahd_rem_col_list(struct ahd_softc *ahd,
196 					 struct scb *scb);
197 static void		ahd_chip_init(struct ahd_softc *ahd);
198 static void		ahd_qinfifo_requeue(struct ahd_softc *ahd,
199 					    struct scb *prev_scb,
200 					    struct scb *scb);
201 static int		ahd_qinfifo_count(struct ahd_softc *ahd);
202 static int		ahd_search_scb_list(struct ahd_softc *ahd, int target,
203 					    char channel, int lun, u_int tag,
204 					    role_t role, uint32_t status,
205 					    ahd_search_action action,
206 					    u_int *list_head, u_int *list_tail,
207 					    u_int tid);
208 static void		ahd_stitch_tid_list(struct ahd_softc *ahd,
209 					    u_int tid_prev, u_int tid_cur,
210 					    u_int tid_next);
211 static void		ahd_add_scb_to_free_list(struct ahd_softc *ahd,
212 						 u_int scbid);
213 static u_int		ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
214 				     u_int prev, u_int next, u_int tid);
215 static void		ahd_reset_current_bus(struct ahd_softc *ahd);
216 static ahd_callback_t	ahd_reset_poll;
217 static ahd_callback_t	ahd_stat_timer;
218 #ifdef AHD_DUMP_SEQ
219 static void		ahd_dumpseq(struct ahd_softc *ahd);
220 #endif
221 static void		ahd_loadseq(struct ahd_softc *ahd);
222 static int		ahd_check_patch(struct ahd_softc *ahd,
223 					struct patch **start_patch,
224 					u_int start_instr, u_int *skip_addr);
225 static u_int		ahd_resolve_seqaddr(struct ahd_softc *ahd,
226 					    u_int address);
227 static void		ahd_download_instr(struct ahd_softc *ahd,
228 					   u_int instrptr, uint8_t *dconsts);
229 static int		ahd_probe_stack_size(struct ahd_softc *ahd);
230 static int		ahd_other_scb_timeout(struct ahd_softc *ahd,
231 					      struct scb *scb,
232 					      struct scb *other_scb);
233 static int		ahd_scb_active_in_fifo(struct ahd_softc *ahd,
234 					       struct scb *scb);
235 static void		ahd_run_data_fifo(struct ahd_softc *ahd,
236 					  struct scb *scb);
237 
238 #ifdef AHD_TARGET_MODE
239 static void		ahd_queue_lstate_event(struct ahd_softc *ahd,
240 					       struct ahd_tmode_lstate *lstate,
241 					       u_int initiator_id,
242 					       u_int event_type,
243 					       u_int event_arg);
244 static void		ahd_update_scsiid(struct ahd_softc *ahd,
245 					  u_int targid_mask);
246 static int		ahd_handle_target_cmd(struct ahd_softc *ahd,
247 					      struct target_cmd *cmd);
248 #endif
249 
250 /******************************** Private Inlines *****************************/
251 static __inline void	ahd_assert_atn(struct ahd_softc *ahd);
252 static __inline int	ahd_currently_packetized(struct ahd_softc *ahd);
253 static __inline int	ahd_set_active_fifo(struct ahd_softc *ahd);
254 
255 static __inline void
256 ahd_assert_atn(struct ahd_softc *ahd)
257 {
258 	ahd_outb(ahd, SCSISIGO, ATNO);
259 }
260 
261 /*
262  * Determine if the current connection has a packetized
263  * agreement.  This does not necessarily mean that we
264  * are currently in a packetized transfer.  We could
265  * just as easily be sending or receiving a message.
266  */
267 static __inline int
268 ahd_currently_packetized(struct ahd_softc *ahd)
269 {
270 	ahd_mode_state	 saved_modes;
271 	int		 packetized;
272 
273 	saved_modes = ahd_save_modes(ahd);
274 	if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) {
275 		/*
276 		 * The packetized bit refers to the last
277 		 * connection, not the current one.  Check
278 		 * for non-zero LQISTATE instead.
279 		 */
280 		ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
281 		packetized = ahd_inb(ahd, LQISTATE) != 0;
282 	} else {
283 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
284 		packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED;
285 	}
286 	ahd_restore_modes(ahd, saved_modes);
287 	return (packetized);
288 }
289 
290 static __inline int
291 ahd_set_active_fifo(struct ahd_softc *ahd)
292 {
293 	u_int active_fifo;
294 
295 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
296 	active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
297 	switch (active_fifo) {
298 	case 0:
299 	case 1:
300 		ahd_set_modes(ahd, active_fifo, active_fifo);
301 		return (1);
302 	default:
303 		return (0);
304 	}
305 }
306 
307 /************************* Sequencer Execution Control ************************/
308 /*
309  * Restart the sequencer program from address zero
310  */
311 void
312 ahd_restart(struct ahd_softc *ahd)
313 {
314 
315 	ahd_pause(ahd);
316 
317 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
318 
319 	/* No more pending messages */
320 	ahd_clear_msg_state(ahd);
321 	ahd_outb(ahd, SCSISIGO, 0);		/* De-assert BSY */
322 	ahd_outb(ahd, MSG_OUT, MSG_NOOP);	/* No message to send */
323 	ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET);
324 	ahd_outb(ahd, SEQINTCTL, 0);
325 	ahd_outb(ahd, LASTPHASE, P_BUSFREE);
326 	ahd_outb(ahd, SEQ_FLAGS, 0);
327 	ahd_outb(ahd, SAVED_SCSIID, 0xFF);
328 	ahd_outb(ahd, SAVED_LUN, 0xFF);
329 
330 	/*
331 	 * Ensure that the sequencer's idea of TQINPOS
332 	 * matches our own.  The sequencer increments TQINPOS
333 	 * only after it sees a DMA complete and a reset could
334 	 * occur before the increment leaving the kernel to believe
335 	 * the command arrived but the sequencer to not.
336 	 */
337 	ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
338 
339 	/* Always allow reselection */
340 	ahd_outb(ahd, SCSISEQ1,
341 		 ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
342 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
343 
344 	/*
345 	 * Clear any pending sequencer interrupt.  It is no
346 	 * longer relevant since we're resetting the Program
347 	 * Counter.
348 	 */
349 	ahd_outb(ahd, CLRINT, CLRSEQINT);
350 
351 	ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
352 	ahd_unpause(ahd);
353 }
354 
355 void
356 ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo)
357 {
358 	ahd_mode_state	 saved_modes;
359 
360 #ifdef AHD_DEBUG
361 	if ((ahd_debug & AHD_SHOW_FIFOS) != 0)
362 		printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo);
363 #endif
364 	saved_modes = ahd_save_modes(ahd);
365 	ahd_set_modes(ahd, fifo, fifo);
366 	ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
367 	if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
368 		ahd_outb(ahd, CCSGCTL, CCSGRESET);
369 	ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
370 	ahd_outb(ahd, SG_STATE, 0);
371 	ahd_restore_modes(ahd, saved_modes);
372 }
373 
374 /************************* Input/Output Queues ********************************/
375 /*
376  * Flush and completed commands that are sitting in the command
377  * complete queues down on the chip but have yet to be dma'ed back up.
378  */
379 void
380 ahd_flush_qoutfifo(struct ahd_softc *ahd)
381 {
382 	struct		scb *scb;
383 	ahd_mode_state	saved_modes;
384 	u_int		saved_scbptr;
385 	u_int		ccscbctl;
386 	u_int		scbid;
387 	u_int		next_scbid;
388 
389 	saved_modes = ahd_save_modes(ahd);
390 
391 	/*
392 	 * Flush the good status FIFO for completed packetized commands.
393 	 */
394 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
395 	saved_scbptr = ahd_get_scbptr(ahd);
396 	while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) {
397 		u_int fifo_mode;
398 		u_int i;
399 
400 		scbid = ahd_inw(ahd, GSFIFO);
401 		scb = ahd_lookup_scb(ahd, scbid);
402 		if (scb == NULL) {
403 			printf("%s: Warning - GSFIFO SCB %d invalid\n",
404 			       ahd_name(ahd), scbid);
405 			AHD_CORRECTABLE_ERROR(ahd);
406 			continue;
407 		}
408 		/*
409 		 * Determine if this transaction is still active in
410 		 * any FIFO.  If it is, we must flush that FIFO to
411 		 * the host before completing the  command.
412 		 */
413 		fifo_mode = 0;
414 rescan_fifos:
415 		for (i = 0; i < 2; i++) {
416 			/* Toggle to the other mode. */
417 			fifo_mode ^= 1;
418 			ahd_set_modes(ahd, fifo_mode, fifo_mode);
419 
420 			if (ahd_scb_active_in_fifo(ahd, scb) == 0)
421 				continue;
422 
423 			ahd_run_data_fifo(ahd, scb);
424 
425 			/*
426 			 * Running this FIFO may cause a CFG4DATA for
427 			 * this same transaction to assert in the other
428 			 * FIFO or a new snapshot SAVEPTRS interrupt
429 			 * in this FIFO.  Even running a FIFO may not
430 			 * clear the transaction if we are still waiting
431 			 * for data to drain to the host. We must loop
432 			 * until the transaction is not active in either
433 			 * FIFO just to be sure.  Reset our loop counter
434 			 * so we will visit both FIFOs again before
435 			 * declaring this transaction finished.  We
436 			 * also delay a bit so that status has a chance
437 			 * to change before we look at this FIFO again.
438 			 */
439 			aic_delay(200);
440 			goto rescan_fifos;
441 		}
442 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
443 		ahd_set_scbptr(ahd, scbid);
444 		if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0
445 		 && ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0
446 		  || (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR)
447 		      & SG_LIST_NULL) != 0)) {
448 			u_int comp_head;
449 
450 			/*
451 			 * The transfer completed with a residual.
452 			 * Place this SCB on the complete DMA list
453 			 * so that we update our in-core copy of the
454 			 * SCB before completing the command.
455 			 */
456 			ahd_outb(ahd, SCB_SCSI_STATUS, 0);
457 			ahd_outb(ahd, SCB_SGPTR,
458 				 ahd_inb_scbram(ahd, SCB_SGPTR)
459 				 | SG_STATUS_VALID);
460 			ahd_outw(ahd, SCB_TAG, scbid);
461 			ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL);
462 			comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
463 			if (SCBID_IS_NULL(comp_head)) {
464 				ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid);
465 				ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
466 			} else {
467 				u_int tail;
468 
469 				tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL);
470 				ahd_set_scbptr(ahd, tail);
471 				ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid);
472 				ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
473 				ahd_set_scbptr(ahd, scbid);
474 			}
475 		} else
476 			ahd_complete_scb(ahd, scb);
477 	}
478 	ahd_set_scbptr(ahd, saved_scbptr);
479 
480 	/*
481 	 * Setup for command channel portion of flush.
482 	 */
483 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
484 
485 	/*
486 	 * Wait for any inprogress DMA to complete and clear DMA state
487 	 * if this if for an SCB in the qinfifo.
488 	 */
489 	while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) {
490 		if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) {
491 			if ((ccscbctl & ARRDONE) != 0)
492 				break;
493 		} else if ((ccscbctl & CCSCBDONE) != 0)
494 			break;
495 		aic_delay(200);
496 	}
497 	/*
498 	 * We leave the sequencer to cleanup in the case of DMA's to
499 	 * update the qoutfifo.  In all other cases (DMA's to the
500 	 * chip or a push of an SCB from the COMPLETE_DMA_SCB list),
501 	 * we disable the DMA engine so that the sequencer will not
502 	 * attempt to handle the DMA completion.
503 	 */
504 	if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0)
505 		ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN));
506 
507 	/*
508 	 * Complete any SCBs that just finished
509 	 * being DMA'ed into the qoutfifo.
510 	 */
511 	ahd_run_qoutfifo(ahd);
512 
513 	saved_scbptr = ahd_get_scbptr(ahd);
514 	/*
515 	 * Manually update/complete any completed SCBs that are waiting to be
516 	 * DMA'ed back up to the host.
517 	 */
518 	scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
519 	while (!SCBID_IS_NULL(scbid)) {
520 		uint8_t *hscb_ptr;
521 		u_int	 i;
522 
523 		ahd_set_scbptr(ahd, scbid);
524 		next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
525 		scb = ahd_lookup_scb(ahd, scbid);
526 		if (scb == NULL) {
527 			printf("%s: Warning - DMA-up and complete "
528 			       "SCB %d invalid\n", ahd_name(ahd), scbid);
529 			AHD_CORRECTABLE_ERROR(ahd);
530 			continue;
531 		}
532 		hscb_ptr = (uint8_t *)scb->hscb;
533 		for (i = 0; i < sizeof(struct hardware_scb); i++)
534 			*hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i);
535 
536 		ahd_complete_scb(ahd, scb);
537 		scbid = next_scbid;
538 	}
539 	ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
540 	ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
541 
542 	scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
543 	while (!SCBID_IS_NULL(scbid)) {
544 		ahd_set_scbptr(ahd, scbid);
545 		next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
546 		scb = ahd_lookup_scb(ahd, scbid);
547 		if (scb == NULL) {
548 			printf("%s: Warning - Complete Qfrz SCB %d invalid\n",
549 			       ahd_name(ahd), scbid);
550 			AHD_CORRECTABLE_ERROR(ahd);
551 			continue;
552 		}
553 
554 		ahd_complete_scb(ahd, scb);
555 		scbid = next_scbid;
556 	}
557 	ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
558 
559 	scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD);
560 	while (!SCBID_IS_NULL(scbid)) {
561 		ahd_set_scbptr(ahd, scbid);
562 		next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
563 		scb = ahd_lookup_scb(ahd, scbid);
564 		if (scb == NULL) {
565 			printf("%s: Warning - Complete SCB %d invalid\n",
566 			       ahd_name(ahd), scbid);
567 			AHD_CORRECTABLE_ERROR(ahd);
568 			continue;
569 		}
570 
571 		ahd_complete_scb(ahd, scb);
572 		scbid = next_scbid;
573 	}
574 	ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
575 
576 	/*
577 	 * Restore state.
578 	 */
579 	ahd_set_scbptr(ahd, saved_scbptr);
580 	ahd_restore_modes(ahd, saved_modes);
581 	ahd->flags |= AHD_UPDATE_PEND_CMDS;
582 }
583 
584 /*
585  * Determine if an SCB for a packetized transaction
586  * is active in a FIFO.
587  */
588 static int
589 ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb)
590 {
591 
592 	/*
593 	 * The FIFO is only active for our transaction if
594 	 * the SCBPTR matches the SCB's ID and the firmware
595 	 * has installed a handler for the FIFO or we have
596 	 * a pending SAVEPTRS or CFG4DATA interrupt.
597 	 */
598 	if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb)
599 	 || ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0
600 	  && (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0))
601 		return (0);
602 
603 	return (1);
604 }
605 
606 /*
607  * Run a data fifo to completion for a transaction we know
608  * has completed across the SCSI bus (good status has been
609  * received).  We are already set to the correct FIFO mode
610  * on entry to this routine.
611  *
612  * This function attempts to operate exactly as the firmware
613  * would when running this FIFO.  Care must be taken to update
614  * this routine any time the firmware's FIFO algorithm is
615  * changed.
616  */
617 static void
618 ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb)
619 {
620 	u_int seqintsrc;
621 
622 	seqintsrc = ahd_inb(ahd, SEQINTSRC);
623 	if ((seqintsrc & CFG4DATA) != 0) {
624 		uint32_t datacnt;
625 		uint32_t sgptr;
626 
627 		/*
628 		 * Clear full residual flag.
629 		 */
630 		sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID;
631 		ahd_outb(ahd, SCB_SGPTR, sgptr);
632 
633 		/*
634 		 * Load datacnt and address.
635 		 */
636 		datacnt = ahd_inl_scbram(ahd, SCB_DATACNT);
637 		if ((datacnt & AHD_DMA_LAST_SEG) != 0) {
638 			sgptr |= LAST_SEG;
639 			ahd_outb(ahd, SG_STATE, 0);
640 		} else
641 			ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
642 		ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR));
643 		ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK);
644 		ahd_outb(ahd, SG_CACHE_PRE, sgptr);
645 		ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
646 
647 		/*
648 		 * Initialize Residual Fields.
649 		 */
650 		ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24);
651 		ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK);
652 
653 		/*
654 		 * Mark the SCB as having a FIFO in use.
655 		 */
656 		ahd_outb(ahd, SCB_FIFO_USE_COUNT,
657 			 ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1);
658 
659 		/*
660 		 * Install a "fake" handler for this FIFO.
661 		 */
662 		ahd_outw(ahd, LONGJMP_ADDR, 0);
663 
664 		/*
665 		 * Notify the hardware that we have satisfied
666 		 * this sequencer interrupt.
667 		 */
668 		ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA);
669 	} else if ((seqintsrc & SAVEPTRS) != 0) {
670 		uint32_t sgptr;
671 		uint32_t resid;
672 
673 		if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) {
674 			/*
675 			 * Snapshot Save Pointers.  All that
676 			 * is necessary to clear the snapshot
677 			 * is a CLRCHN.
678 			 */
679 			goto clrchn;
680 		}
681 
682 		/*
683 		 * Disable S/G fetch so the DMA engine
684 		 * is available to future users.
685 		 */
686 		if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
687 			ahd_outb(ahd, CCSGCTL, 0);
688 		ahd_outb(ahd, SG_STATE, 0);
689 
690 		/*
691 		 * Flush the data FIFO.  Strickly only
692 		 * necessary for Rev A parts.
693 		 */
694 		ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH);
695 
696 		/*
697 		 * Calculate residual.
698 		 */
699 		sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
700 		resid = ahd_inl(ahd, SHCNT);
701 		resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24;
702 		ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid);
703 		if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) {
704 			/*
705 			 * Must back up to the correct S/G element.
706 			 * Typically this just means resetting our
707 			 * low byte to the offset in the SG_CACHE,
708 			 * but if we wrapped, we have to correct
709 			 * the other bytes of the sgptr too.
710 			 */
711 			if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0
712 			 && (sgptr & 0x80) == 0)
713 				sgptr -= 0x100;
714 			sgptr &= ~0xFF;
715 			sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW)
716 			       & SG_ADDR_MASK;
717 			ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
718 			ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0);
719 		} else if ((resid & AHD_SG_LEN_MASK) == 0) {
720 			ahd_outb(ahd, SCB_RESIDUAL_SGPTR,
721 				 sgptr | SG_LIST_NULL);
722 		}
723 		/*
724 		 * Save Pointers.
725 		 */
726 		ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR));
727 		ahd_outl(ahd, SCB_DATACNT, resid);
728 		ahd_outl(ahd, SCB_SGPTR, sgptr);
729 		ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS);
730 		ahd_outb(ahd, SEQIMODE,
731 			 ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS);
732 		/*
733 		 * If the data is to the SCSI bus, we are
734 		 * done, otherwise wait for FIFOEMP.
735 		 */
736 		if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0)
737 			goto clrchn;
738 	} else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) {
739 		uint32_t sgptr;
740 		uint64_t data_addr;
741 		uint32_t data_len;
742 		u_int	 dfcntrl;
743 
744 		/*
745 		 * Disable S/G fetch so the DMA engine
746 		 * is available to future users.  We won't
747 		 * be using the DMA engine to load segments.
748 		 */
749 		if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) {
750 			ahd_outb(ahd, CCSGCTL, 0);
751 			ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
752 		}
753 
754 		/*
755 		 * Wait for the DMA engine to notice that the
756 		 * host transfer is enabled and that there is
757 		 * space in the S/G FIFO for new segments before
758 		 * loading more segments.
759 		 */
760 		if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0
761 		 && (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) {
762 			/*
763 			 * Determine the offset of the next S/G
764 			 * element to load.
765 			 */
766 			sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
767 			sgptr &= SG_PTR_MASK;
768 			if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
769 				struct ahd_dma64_seg *sg;
770 
771 				sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
772 				data_addr = sg->addr;
773 				data_len = sg->len;
774 				sgptr += sizeof(*sg);
775 			} else {
776 				struct	ahd_dma_seg *sg;
777 
778 				sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
779 				data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK;
780 				data_addr <<= 8;
781 				data_addr |= sg->addr;
782 				data_len = sg->len;
783 				sgptr += sizeof(*sg);
784 			}
785 
786 			/*
787 			 * Update residual information.
788 			 */
789 			ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24);
790 			ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
791 
792 			/*
793 			 * Load the S/G.
794 			 */
795 			if (data_len & AHD_DMA_LAST_SEG) {
796 				sgptr |= LAST_SEG;
797 				ahd_outb(ahd, SG_STATE, 0);
798 			}
799 			ahd_outq(ahd, HADDR, data_addr);
800 			ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK);
801 			ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF);
802 
803 			/*
804 			 * Advertise the segment to the hardware.
805 			 */
806 			dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN;
807 			if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) {
808 				/*
809 				 * Use SCSIENWRDIS so that SCSIEN
810 				 * is never modified by this
811 				 * operation.
812 				 */
813 				dfcntrl |= SCSIENWRDIS;
814 			}
815 			ahd_outb(ahd, DFCNTRL, dfcntrl);
816 		}
817 	} else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) {
818 		/*
819 		 * Transfer completed to the end of SG list
820 		 * and has flushed to the host.
821 		 */
822 		ahd_outb(ahd, SCB_SGPTR,
823 			 ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL);
824 		goto clrchn;
825 	} else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) {
826 clrchn:
827 		/*
828 		 * Clear any handler for this FIFO, decrement
829 		 * the FIFO use count for the SCB, and release
830 		 * the FIFO.
831 		 */
832 		ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
833 		ahd_outb(ahd, SCB_FIFO_USE_COUNT,
834 			 ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1);
835 		ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
836 	}
837 }
838 
839 /*
840  * Look for entries in the QoutFIFO that have completed.
841  * The valid_tag completion field indicates the validity
842  * of the entry - the valid value toggles each time through
843  * the queue. We use the sg_status field in the completion
844  * entry to avoid referencing the hscb if the completion
845  * occurred with no errors and no residual.  sg_status is
846  * a copy of the first byte (little endian) of the sgptr
847  * hscb field.
848  */
849 void
850 ahd_run_qoutfifo(struct ahd_softc *ahd)
851 {
852 	struct ahd_completion *completion;
853 	struct scb *scb;
854 	u_int  scb_index;
855 
856 	if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0)
857 		panic("ahd_run_qoutfifo recursion");
858 	ahd->flags |= AHD_RUNNING_QOUTFIFO;
859 	ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD);
860 	for (;;) {
861 		completion = &ahd->qoutfifo[ahd->qoutfifonext];
862 
863 		if (completion->valid_tag != ahd->qoutfifonext_valid_tag)
864 			break;
865 
866 		scb_index = aic_le16toh(completion->tag);
867 		scb = ahd_lookup_scb(ahd, scb_index);
868 		if (scb == NULL) {
869 			printf("%s: WARNING no command for scb %d "
870 			       "(cmdcmplt)\nQOUTPOS = %d\n",
871 			       ahd_name(ahd), scb_index,
872 			       ahd->qoutfifonext);
873 			AHD_CORRECTABLE_ERROR(ahd);
874 			ahd_dump_card_state(ahd);
875 		} else if ((completion->sg_status & SG_STATUS_VALID) != 0) {
876 			ahd_handle_scb_status(ahd, scb);
877 		} else {
878 			ahd_done(ahd, scb);
879 		}
880 
881 		ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1);
882 		if (ahd->qoutfifonext == 0)
883 			ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID;
884 	}
885 	ahd->flags &= ~AHD_RUNNING_QOUTFIFO;
886 }
887 
888 /************************* Interrupt Handling *********************************/
889 void
890 ahd_handle_hwerrint(struct ahd_softc *ahd)
891 {
892 	/*
893 	 * Some catastrophic hardware error has occurred.
894 	 * Print it for the user and disable the controller.
895 	 */
896 	int i;
897 	int error;
898 
899 	error = ahd_inb(ahd, ERROR);
900 	for (i = 0; i < num_errors; i++) {
901 		if ((error & ahd_hard_errors[i].errno) != 0) {
902 			printf("%s: hwerrint, %s\n",
903 			       ahd_name(ahd), ahd_hard_errors[i].errmesg);
904 			AHD_UNCORRECTABLE_ERROR(ahd);
905 		}
906 	}
907 
908 	ahd_dump_card_state(ahd);
909 	panic("BRKADRINT");
910 
911 	/* Tell everyone that this HBA is no longer available */
912 	ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
913 		       CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
914 		       CAM_NO_HBA);
915 
916 	/* Tell the system that this controller has gone away. */
917 	ahd_free(ahd);
918 }
919 
920 void
921 ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat)
922 {
923 	u_int seqintcode;
924 
925 	/*
926 	 * Save the sequencer interrupt code and clear the SEQINT
927 	 * bit. We will unpause the sequencer, if appropriate,
928 	 * after servicing the request.
929 	 */
930 	seqintcode = ahd_inb(ahd, SEQINTCODE);
931 	ahd_outb(ahd, CLRINT, CLRSEQINT);
932 	if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
933 		/*
934 		 * Unpause the sequencer and let it clear
935 		 * SEQINT by writing NO_SEQINT to it.  This
936 		 * will cause the sequencer to be paused again,
937 		 * which is the expected state of this routine.
938 		 */
939 		ahd_unpause(ahd);
940 		while (!ahd_is_paused(ahd))
941 			;
942 		ahd_outb(ahd, CLRINT, CLRSEQINT);
943 	}
944 	ahd_update_modes(ahd);
945 #ifdef AHD_DEBUG
946 	if ((ahd_debug & AHD_SHOW_MISC) != 0)
947 		printf("%s: Handle Seqint Called for code %d\n",
948 		       ahd_name(ahd), seqintcode);
949 #endif
950 	switch (seqintcode) {
951 	case ENTERING_NONPACK:
952 	{
953 		struct	scb *scb;
954 		u_int	scbid;
955 
956 		AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
957 				 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
958 		scbid = ahd_get_scbptr(ahd);
959 		scb = ahd_lookup_scb(ahd, scbid);
960 		if (scb == NULL) {
961 			/*
962 			 * Somehow need to know if this
963 			 * is from a selection or reselection.
964 			 * From that, we can determine target
965 			 * ID so we at least have an I_T nexus.
966 			 */
967 		} else {
968 			ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
969 			ahd_outb(ahd, SAVED_LUN, scb->hscb->lun);
970 			ahd_outb(ahd, SEQ_FLAGS, 0x0);
971 		}
972 		if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0
973 		 && (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
974 			/*
975 			 * Phase change after read stream with
976 			 * CRC error with P0 asserted on last
977 			 * packet.
978 			 */
979 #ifdef AHD_DEBUG
980 			if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
981 				printf("%s: Assuming LQIPHASE_NLQ with "
982 				       "P0 assertion\n", ahd_name(ahd));
983 #endif
984 		}
985 #ifdef AHD_DEBUG
986 		if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
987 			printf("%s: Entering NONPACK\n", ahd_name(ahd));
988 #endif
989 		break;
990 	}
991 	case INVALID_SEQINT:
992 		printf("%s: Invalid Sequencer interrupt occurred.\n",
993 		       ahd_name(ahd));
994 		ahd_dump_card_state(ahd);
995 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
996 		AHD_UNCORRECTABLE_ERROR(ahd);
997 		break;
998 	case STATUS_OVERRUN:
999 	{
1000 		struct	scb *scb;
1001 		u_int	scbid;
1002 
1003 		scbid = ahd_get_scbptr(ahd);
1004 		scb = ahd_lookup_scb(ahd, scbid);
1005 		if (scb != NULL)
1006 			ahd_print_path(ahd, scb);
1007 		else
1008 			printf("%s: ", ahd_name(ahd));
1009 		printf("SCB %d Packetized Status Overrun", scbid);
1010 		ahd_dump_card_state(ahd);
1011 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1012 		AHD_UNCORRECTABLE_ERROR(ahd);
1013 		break;
1014 	}
1015 	case CFG4ISTAT_INTR:
1016 	{
1017 		struct	scb *scb;
1018 		u_int	scbid;
1019 
1020 		scbid = ahd_get_scbptr(ahd);
1021 		scb = ahd_lookup_scb(ahd, scbid);
1022 		if (scb == NULL) {
1023 			ahd_dump_card_state(ahd);
1024 			printf("CFG4ISTAT: Free SCB %d referenced", scbid);
1025 			AHD_FATAL_ERROR(ahd);
1026 			panic("For safety");
1027 		}
1028 		ahd_outq(ahd, HADDR, scb->sense_busaddr);
1029 		ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE);
1030 		ahd_outb(ahd, HCNT + 2, 0);
1031 		ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG);
1032 		ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
1033 		break;
1034 	}
1035 	case ILLEGAL_PHASE:
1036 	{
1037 		u_int bus_phase;
1038 
1039 		bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1040 		printf("%s: ILLEGAL_PHASE 0x%x\n",
1041 		       ahd_name(ahd), bus_phase);
1042 
1043 		switch (bus_phase) {
1044 		case P_DATAOUT:
1045 		case P_DATAIN:
1046 		case P_DATAOUT_DT:
1047 		case P_DATAIN_DT:
1048 		case P_MESGOUT:
1049 		case P_STATUS:
1050 		case P_MESGIN:
1051 			ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1052 			printf("%s: Issued Bus Reset.\n", ahd_name(ahd));
1053 			AHD_UNCORRECTABLE_ERROR(ahd);
1054 			break;
1055 		case P_COMMAND:
1056 		{
1057 			struct	ahd_devinfo devinfo;
1058 			struct	scb *scb;
1059 			struct	ahd_tmode_tstate *tstate;
1060 			u_int	scbid;
1061 
1062 			/*
1063 			 * If a target takes us into the command phase
1064 			 * assume that it has been externally reset and
1065 			 * has thus lost our previous packetized negotiation
1066 			 * agreement.  Since we have not sent an identify
1067 			 * message and may not have fully qualified the
1068 			 * connection, we change our command to TUR, assert
1069 			 * ATN and ABORT the task when we go to message in
1070 			 * phase.  The OSM will see the REQUEUE_REQUEST
1071 			 * status and retry the command.
1072 			 */
1073 			scbid = ahd_get_scbptr(ahd);
1074 			scb = ahd_lookup_scb(ahd, scbid);
1075 			if (scb == NULL) {
1076 				AHD_CORRECTABLE_ERROR(ahd);
1077 				printf("Invalid phase with no valid SCB.  "
1078 				       "Resetting bus.\n");
1079 				ahd_reset_channel(ahd, 'A',
1080 						  /*Initiate Reset*/TRUE);
1081 				break;
1082 			}
1083 			ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
1084 					    SCB_GET_TARGET(ahd, scb),
1085 					    SCB_GET_LUN(scb),
1086 					    SCB_GET_CHANNEL(ahd, scb),
1087 					    ROLE_INITIATOR);
1088 			ahd_fetch_transinfo(ahd,
1089 					    devinfo.channel,
1090 					    devinfo.our_scsiid,
1091 					    devinfo.target,
1092 					    &tstate);
1093 			ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
1094 				      AHD_TRANS_ACTIVE, /*paused*/TRUE);
1095 			ahd_set_syncrate(ahd, &devinfo, /*period*/0,
1096 					 /*offset*/0, /*ppr_options*/0,
1097 					 AHD_TRANS_ACTIVE, /*paused*/TRUE);
1098 			ahd_outb(ahd, SCB_CDB_STORE, 0);
1099 			ahd_outb(ahd, SCB_CDB_STORE+1, 0);
1100 			ahd_outb(ahd, SCB_CDB_STORE+2, 0);
1101 			ahd_outb(ahd, SCB_CDB_STORE+3, 0);
1102 			ahd_outb(ahd, SCB_CDB_STORE+4, 0);
1103 			ahd_outb(ahd, SCB_CDB_STORE+5, 0);
1104 			ahd_outb(ahd, SCB_CDB_LEN, 6);
1105 			scb->hscb->control &= ~(TAG_ENB|SCB_TAG_TYPE);
1106 			scb->hscb->control |= MK_MESSAGE;
1107 			ahd_outb(ahd, SCB_CONTROL, scb->hscb->control);
1108 			ahd_outb(ahd, MSG_OUT, HOST_MSG);
1109 			ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
1110 			/*
1111 			 * The lun is 0, regardless of the SCB's lun
1112 			 * as we have not sent an identify message.
1113 			 */
1114 			ahd_outb(ahd, SAVED_LUN, 0);
1115 			ahd_outb(ahd, SEQ_FLAGS, 0);
1116 			ahd_assert_atn(ahd);
1117 			scb->flags &= ~SCB_PACKETIZED;
1118 			scb->flags |= SCB_ABORT|SCB_CMDPHASE_ABORT;
1119 			ahd_freeze_devq(ahd, scb);
1120 			aic_set_transaction_status(scb, CAM_REQUEUE_REQ);
1121 			aic_freeze_scb(scb);
1122 
1123 			/*
1124 			 * Allow the sequencer to continue with
1125 			 * non-pack processing.
1126 			 */
1127 			ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1128 			ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT);
1129 			if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
1130 				ahd_outb(ahd, CLRLQOINT1, 0);
1131 			}
1132 #ifdef AHD_DEBUG
1133 			if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1134 				ahd_print_path(ahd, scb);
1135 				AHD_CORRECTABLE_ERROR(ahd);
1136 				printf("Unexpected command phase from "
1137 				       "packetized target\n");
1138 			}
1139 #endif
1140 			break;
1141 		}
1142 		}
1143 		break;
1144 	}
1145 	case CFG4OVERRUN:
1146 	{
1147 		struct	scb *scb;
1148 		u_int	scb_index;
1149 
1150 #ifdef AHD_DEBUG
1151 		if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1152 			printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd),
1153 			       ahd_inb(ahd, MODE_PTR));
1154 		}
1155 #endif
1156 		scb_index = ahd_get_scbptr(ahd);
1157 		scb = ahd_lookup_scb(ahd, scb_index);
1158 		if (scb == NULL) {
1159 			/*
1160 			 * Attempt to transfer to an SCB that is
1161 			 * not outstanding.
1162 			 */
1163 			ahd_assert_atn(ahd);
1164 			ahd_outb(ahd, MSG_OUT, HOST_MSG);
1165 			ahd->msgout_buf[0] = MSG_ABORT_TASK;
1166 			ahd->msgout_len = 1;
1167 			ahd->msgout_index = 0;
1168 			ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1169 			/*
1170 			 * Clear status received flag to prevent any
1171 			 * attempt to complete this bogus SCB.
1172 			 */
1173 			ahd_outb(ahd, SCB_CONTROL,
1174 				 ahd_inb_scbram(ahd, SCB_CONTROL)
1175 				 & ~STATUS_RCVD);
1176 		}
1177 		break;
1178 	}
1179 	case DUMP_CARD_STATE:
1180 	{
1181 		ahd_dump_card_state(ahd);
1182 		break;
1183 	}
1184 	case PDATA_REINIT:
1185 	{
1186 #ifdef AHD_DEBUG
1187 		if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1188 			printf("%s: PDATA_REINIT - DFCNTRL = 0x%x "
1189 			       "SG_CACHE_SHADOW = 0x%x\n",
1190 			       ahd_name(ahd), ahd_inb(ahd, DFCNTRL),
1191 			       ahd_inb(ahd, SG_CACHE_SHADOW));
1192 		}
1193 #endif
1194 		ahd_reinitialize_dataptrs(ahd);
1195 		break;
1196 	}
1197 	case HOST_MSG_LOOP:
1198 	{
1199 		struct ahd_devinfo devinfo;
1200 
1201 		/*
1202 		 * The sequencer has encountered a message phase
1203 		 * that requires host assistance for completion.
1204 		 * While handling the message phase(s), we will be
1205 		 * notified by the sequencer after each byte is
1206 		 * transferred so we can track bus phase changes.
1207 		 *
1208 		 * If this is the first time we've seen a HOST_MSG_LOOP
1209 		 * interrupt, initialize the state of the host message
1210 		 * loop.
1211 		 */
1212 		ahd_fetch_devinfo(ahd, &devinfo);
1213 		if (ahd->msg_type == MSG_TYPE_NONE) {
1214 			struct scb *scb;
1215 			u_int scb_index;
1216 			u_int bus_phase;
1217 
1218 			bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1219 			if (bus_phase != P_MESGIN
1220 			 && bus_phase != P_MESGOUT) {
1221 				printf("ahd_intr: HOST_MSG_LOOP bad "
1222 				       "phase 0x%x\n", bus_phase);
1223 				AHD_CORRECTABLE_ERROR(ahd);
1224 				/*
1225 				 * Probably transitioned to bus free before
1226 				 * we got here.  Just punt the message.
1227 				 */
1228 				ahd_dump_card_state(ahd);
1229 				ahd_clear_intstat(ahd);
1230 				ahd_restart(ahd);
1231 				return;
1232 			}
1233 
1234 			scb_index = ahd_get_scbptr(ahd);
1235 			scb = ahd_lookup_scb(ahd, scb_index);
1236 			if (devinfo.role == ROLE_INITIATOR) {
1237 				if (bus_phase == P_MESGOUT)
1238 					ahd_setup_initiator_msgout(ahd,
1239 								   &devinfo,
1240 								   scb);
1241 				else {
1242 					ahd->msg_type =
1243 					    MSG_TYPE_INITIATOR_MSGIN;
1244 					ahd->msgin_index = 0;
1245 				}
1246 			}
1247 #ifdef AHD_TARGET_MODE
1248 			else {
1249 				if (bus_phase == P_MESGOUT) {
1250 					ahd->msg_type =
1251 					    MSG_TYPE_TARGET_MSGOUT;
1252 					ahd->msgin_index = 0;
1253 				}
1254 				else
1255 					ahd_setup_target_msgin(ahd,
1256 							       &devinfo,
1257 							       scb);
1258 			}
1259 #endif
1260 		}
1261 
1262 		ahd_handle_message_phase(ahd);
1263 		break;
1264 	}
1265 	case NO_MATCH:
1266 	{
1267 		/* Ensure we don't leave the selection hardware on */
1268 		AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
1269 		ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
1270 
1271 		printf("%s:%c:%d: no active SCB for reconnecting "
1272 		       "target - issuing BUS DEVICE RESET\n",
1273 		       ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4);
1274 		printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
1275 		       "REG0 == 0x%x ACCUM = 0x%x\n",
1276 		       ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN),
1277 		       ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM));
1278 		printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
1279 		       "SINDEX == 0x%x\n",
1280 		       ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd),
1281 		       ahd_find_busy_tcl(ahd,
1282 					 BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID),
1283 						   ahd_inb(ahd, SAVED_LUN))),
1284 		       ahd_inw(ahd, SINDEX));
1285 		printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
1286 		       "SCB_CONTROL == 0x%x\n",
1287 		       ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID),
1288 		       ahd_inb_scbram(ahd, SCB_LUN),
1289 		       ahd_inb_scbram(ahd, SCB_CONTROL));
1290 		printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n",
1291 		       ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI));
1292 		printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0));
1293 		printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0));
1294 		ahd_dump_card_state(ahd);
1295 		ahd->msgout_buf[0] = MSG_BUS_DEV_RESET;
1296 		ahd->msgout_len = 1;
1297 		ahd->msgout_index = 0;
1298 		ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1299 		ahd_outb(ahd, MSG_OUT, HOST_MSG);
1300 		ahd_assert_atn(ahd);
1301 		break;
1302 	}
1303 	case PROTO_VIOLATION:
1304 	{
1305 		ahd_handle_proto_violation(ahd);
1306 		break;
1307 	}
1308 	case IGN_WIDE_RES:
1309 	{
1310 		struct ahd_devinfo devinfo;
1311 
1312 		ahd_fetch_devinfo(ahd, &devinfo);
1313 		ahd_handle_ign_wide_residue(ahd, &devinfo);
1314 		break;
1315 	}
1316 	case BAD_PHASE:
1317 	{
1318 		u_int lastphase;
1319 
1320 		lastphase = ahd_inb(ahd, LASTPHASE);
1321 		printf("%s:%c:%d: unknown scsi bus phase %x, "
1322 		       "lastphase = 0x%x.  Attempting to continue\n",
1323 		       ahd_name(ahd), 'A',
1324 		       SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1325 		       lastphase, ahd_inb(ahd, SCSISIGI));
1326 		AHD_CORRECTABLE_ERROR(ahd);
1327 		break;
1328 	}
1329 	case MISSED_BUSFREE:
1330 	{
1331 		u_int lastphase;
1332 
1333 		lastphase = ahd_inb(ahd, LASTPHASE);
1334 		printf("%s:%c:%d: Missed busfree. "
1335 		       "Lastphase = 0x%x, Curphase = 0x%x\n",
1336 		       ahd_name(ahd), 'A',
1337 		       SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1338 		       lastphase, ahd_inb(ahd, SCSISIGI));
1339 		AHD_CORRECTABLE_ERROR(ahd);
1340 		ahd_restart(ahd);
1341 		return;
1342 	}
1343 	case DATA_OVERRUN:
1344 	{
1345 		/*
1346 		 * When the sequencer detects an overrun, it
1347 		 * places the controller in "BITBUCKET" mode
1348 		 * and allows the target to complete its transfer.
1349 		 * Unfortunately, none of the counters get updated
1350 		 * when the controller is in this mode, so we have
1351 		 * no way of knowing how large the overrun was.
1352 		 */
1353 		struct	scb *scb;
1354 		u_int	scbindex;
1355 #ifdef AHD_DEBUG
1356 		u_int	lastphase;
1357 #endif
1358 
1359 		scbindex = ahd_get_scbptr(ahd);
1360 		scb = ahd_lookup_scb(ahd, scbindex);
1361 #ifdef AHD_DEBUG
1362 		lastphase = ahd_inb(ahd, LASTPHASE);
1363 		if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1364 			ahd_print_path(ahd, scb);
1365 			printf("data overrun detected %s.  Tag == 0x%x.\n",
1366 			       ahd_lookup_phase_entry(lastphase)->phasemsg,
1367 			       SCB_GET_TAG(scb));
1368 			ahd_print_path(ahd, scb);
1369 			printf("%s seen Data Phase.  Length = %ld.  "
1370 			       "NumSGs = %d.\n",
1371 			       ahd_inb(ahd, SEQ_FLAGS) & DPHASE
1372 			       ? "Have" : "Haven't",
1373 			       aic_get_transfer_length(scb), scb->sg_count);
1374 			ahd_dump_sglist(scb);
1375 		}
1376 #endif
1377 
1378 		/*
1379 		 * Set this and it will take effect when the
1380 		 * target does a command complete.
1381 		 */
1382 		ahd_freeze_devq(ahd, scb);
1383 		aic_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1384 		aic_freeze_scb(scb);
1385 		break;
1386 	}
1387 	case MKMSG_FAILED:
1388 	{
1389 		struct ahd_devinfo devinfo;
1390 		struct scb *scb;
1391 		u_int scbid;
1392 
1393 		ahd_fetch_devinfo(ahd, &devinfo);
1394 		printf("%s:%c:%d:%d: Attempt to issue message failed\n",
1395 		       ahd_name(ahd), devinfo.channel, devinfo.target,
1396 		       devinfo.lun);
1397 		scbid = ahd_get_scbptr(ahd);
1398 		scb = ahd_lookup_scb(ahd, scbid);
1399 		AHD_CORRECTABLE_ERROR(ahd);
1400 		if (scb != NULL
1401 		 && (scb->flags & SCB_RECOVERY_SCB) != 0)
1402 			/*
1403 			 * Ensure that we didn't put a second instance of this
1404 			 * SCB into the QINFIFO.
1405 			 */
1406 			ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1407 					   SCB_GET_CHANNEL(ahd, scb),
1408 					   SCB_GET_LUN(scb), SCB_GET_TAG(scb),
1409 					   ROLE_INITIATOR, /*status*/0,
1410 					   SEARCH_REMOVE);
1411 		ahd_outb(ahd, SCB_CONTROL,
1412 			 ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
1413 		break;
1414 	}
1415 	case TASKMGMT_FUNC_COMPLETE:
1416 	{
1417 		u_int	scbid;
1418 		struct	scb *scb;
1419 
1420 		scbid = ahd_get_scbptr(ahd);
1421 		scb = ahd_lookup_scb(ahd, scbid);
1422 		if (scb != NULL) {
1423 			u_int	   lun;
1424 			u_int	   tag;
1425 			cam_status error;
1426 
1427 			ahd_print_path(ahd, scb);
1428 			printf("Task Management Func 0x%x Complete\n",
1429 			       scb->hscb->task_management);
1430 			lun = CAM_LUN_WILDCARD;
1431 			tag = SCB_LIST_NULL;
1432 
1433 			switch (scb->hscb->task_management) {
1434 			case SIU_TASKMGMT_ABORT_TASK:
1435 				tag = SCB_GET_TAG(scb);
1436 			case SIU_TASKMGMT_ABORT_TASK_SET:
1437 			case SIU_TASKMGMT_CLEAR_TASK_SET:
1438 				lun = scb->hscb->lun;
1439 				error = CAM_REQ_ABORTED;
1440 				ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
1441 					       'A', lun, tag, ROLE_INITIATOR,
1442 					       error);
1443 				break;
1444 			case SIU_TASKMGMT_LUN_RESET:
1445 				lun = scb->hscb->lun;
1446 			case SIU_TASKMGMT_TARGET_RESET:
1447 			{
1448 				struct ahd_devinfo devinfo;
1449 
1450 				ahd_scb_devinfo(ahd, &devinfo, scb);
1451 				error = CAM_BDR_SENT;
1452 				ahd_handle_devreset(ahd, &devinfo, lun,
1453 						    CAM_BDR_SENT,
1454 						    lun != CAM_LUN_WILDCARD
1455 						    ? "Lun Reset"
1456 						    : "Target Reset",
1457 						    /*verbose_level*/0);
1458 				break;
1459 			}
1460 			default:
1461 				panic("Unexpected TaskMgmt Func\n");
1462 				break;
1463 			}
1464 		}
1465 		break;
1466 	}
1467 	case TASKMGMT_CMD_CMPLT_OKAY:
1468 	{
1469 		u_int	scbid;
1470 		struct	scb *scb;
1471 
1472 		/*
1473 		 * An ABORT TASK TMF failed to be delivered before
1474 		 * the targeted command completed normally.
1475 		 */
1476 		scbid = ahd_get_scbptr(ahd);
1477 		scb = ahd_lookup_scb(ahd, scbid);
1478 		if (scb != NULL) {
1479 			/*
1480 			 * Remove the second instance of this SCB from
1481 			 * the QINFIFO if it is still there.
1482                          */
1483 			ahd_print_path(ahd, scb);
1484 			printf("SCB completes before TMF\n");
1485 			/*
1486 			 * Handle losing the race.  Wait until any
1487 			 * current selection completes.  We will then
1488 			 * set the TMF back to zero in this SCB so that
1489 			 * the sequencer doesn't bother to issue another
1490 			 * sequencer interrupt for its completion.
1491 			 */
1492 			while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
1493 			    && (ahd_inb(ahd, SSTAT0) & SELDO) == 0
1494 			    && (ahd_inb(ahd, SSTAT1) & SELTO) == 0)
1495 				;
1496 			ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0);
1497 			ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1498 					   SCB_GET_CHANNEL(ahd, scb),
1499 					   SCB_GET_LUN(scb), SCB_GET_TAG(scb),
1500 					   ROLE_INITIATOR, /*status*/0,
1501 					   SEARCH_REMOVE);
1502 		}
1503 		break;
1504 	}
1505 	case TRACEPOINT0:
1506 	case TRACEPOINT1:
1507 	case TRACEPOINT2:
1508 	case TRACEPOINT3:
1509 		printf("%s: Tracepoint %d\n", ahd_name(ahd),
1510 		       seqintcode - TRACEPOINT0);
1511 		break;
1512 	case NO_SEQINT:
1513 		break;
1514 	case SAW_HWERR:
1515 		ahd_handle_hwerrint(ahd);
1516 		break;
1517 	default:
1518 		printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd),
1519 		       seqintcode);
1520 		break;
1521 	}
1522 	/*
1523 	 *  The sequencer is paused immediately on
1524 	 *  a SEQINT, so we should restart it when
1525 	 *  we're done.
1526 	 */
1527 	ahd_unpause(ahd);
1528 }
1529 
1530 void
1531 ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat)
1532 {
1533 	struct scb	*scb;
1534 	u_int		 status0;
1535 	u_int		 status3;
1536 	u_int		 status;
1537 	u_int		 lqistat1;
1538 	u_int		 lqostat0;
1539 	u_int		 scbid;
1540 	u_int		 busfreetime;
1541 
1542 	ahd_update_modes(ahd);
1543 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1544 
1545 	status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR);
1546 	status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO);
1547 	status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1548 	lqistat1 = ahd_inb(ahd, LQISTAT1);
1549 	lqostat0 = ahd_inb(ahd, LQOSTAT0);
1550 	busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1551 	if ((status0 & (SELDI|SELDO)) != 0) {
1552 		u_int simode0;
1553 
1554 		ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1555 		simode0 = ahd_inb(ahd, SIMODE0);
1556 		status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO);
1557 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1558 	}
1559 	scbid = ahd_get_scbptr(ahd);
1560 	scb = ahd_lookup_scb(ahd, scbid);
1561 	if (scb != NULL
1562 	 && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1563 		scb = NULL;
1564 
1565 	if ((status0 & IOERR) != 0) {
1566 		u_int now_lvd;
1567 
1568 		now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40;
1569 		printf("%s: Transceiver State Has Changed to %s mode\n",
1570 		       ahd_name(ahd), now_lvd ? "LVD" : "SE");
1571 		ahd_outb(ahd, CLRSINT0, CLRIOERR);
1572 		/*
1573 		 * A change in I/O mode is equivalent to a bus reset.
1574 		 */
1575 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1576 		ahd_pause(ahd);
1577 		ahd_setup_iocell_workaround(ahd);
1578 		ahd_unpause(ahd);
1579 	} else if ((status0 & OVERRUN) != 0) {
1580 		printf("%s: SCSI offset overrun detected.  Resetting bus.\n",
1581 		       ahd_name(ahd));
1582 		AHD_CORRECTABLE_ERROR(ahd);
1583 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1584 	} else if ((status & SCSIRSTI) != 0) {
1585 		printf("%s: Someone reset channel A\n", ahd_name(ahd));
1586 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE);
1587 		AHD_UNCORRECTABLE_ERROR(ahd);
1588 	} else if ((status & SCSIPERR) != 0) {
1589 		/* Make sure the sequencer is in a safe location. */
1590 		ahd_clear_critical_section(ahd);
1591 
1592 		ahd_handle_transmission_error(ahd);
1593 	} else if (lqostat0 != 0) {
1594 		printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0);
1595 		ahd_outb(ahd, CLRLQOINT0, lqostat0);
1596 		if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
1597 			ahd_outb(ahd, CLRLQOINT1, 0);
1598 	} else if ((status & SELTO) != 0) {
1599 		u_int  scbid;
1600 
1601 		/* Stop the selection */
1602 		ahd_outb(ahd, SCSISEQ0, 0);
1603 
1604 		/* Make sure the sequencer is in a safe location. */
1605 		ahd_clear_critical_section(ahd);
1606 
1607 		/* No more pending messages */
1608 		ahd_clear_msg_state(ahd);
1609 
1610 		/* Clear interrupt state */
1611 		ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1612 
1613 		/*
1614 		 * Although the driver does not care about the
1615 		 * 'Selection in Progress' status bit, the busy
1616 		 * LED does.  SELINGO is only cleared by a successful
1617 		 * selection, so we must manually clear it to insure
1618 		 * the LED turns off just incase no future successful
1619 		 * selections occur (e.g. no devices on the bus).
1620 		 */
1621 		ahd_outb(ahd, CLRSINT0, CLRSELINGO);
1622 
1623 		scbid = ahd_inw(ahd, WAITING_TID_HEAD);
1624 		scb = ahd_lookup_scb(ahd, scbid);
1625 		if (scb == NULL) {
1626 			printf("%s: ahd_intr - referenced scb not "
1627 			       "valid during SELTO scb(0x%x)\n",
1628 			       ahd_name(ahd), scbid);
1629 			ahd_dump_card_state(ahd);
1630 			AHD_UNCORRECTABLE_ERROR(ahd);
1631 		} else {
1632 			struct ahd_devinfo devinfo;
1633 #ifdef AHD_DEBUG
1634 			if ((ahd_debug & AHD_SHOW_SELTO) != 0) {
1635 				ahd_print_path(ahd, scb);
1636 				printf("Saw Selection Timeout for SCB 0x%x\n",
1637 				       scbid);
1638 			}
1639 #endif
1640 			ahd_scb_devinfo(ahd, &devinfo, scb);
1641 			aic_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1642 			ahd_freeze_devq(ahd, scb);
1643 
1644 			/*
1645 			 * Cancel any pending transactions on the device
1646 			 * now that it seems to be missing.  This will
1647 			 * also revert us to async/narrow transfers until
1648 			 * we can renegotiate with the device.
1649 			 */
1650 			ahd_handle_devreset(ahd, &devinfo,
1651 					    CAM_LUN_WILDCARD,
1652 					    CAM_SEL_TIMEOUT,
1653 					    "Selection Timeout",
1654 					    /*verbose_level*/1);
1655 		}
1656 		ahd_outb(ahd, CLRINT, CLRSCSIINT);
1657 		ahd_iocell_first_selection(ahd);
1658 		ahd_unpause(ahd);
1659 	} else if ((status0 & (SELDI|SELDO)) != 0) {
1660 		ahd_iocell_first_selection(ahd);
1661 		ahd_unpause(ahd);
1662 	} else if (status3 != 0) {
1663 		printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n",
1664 		       ahd_name(ahd), status3);
1665 		AHD_CORRECTABLE_ERROR(ahd);
1666 		ahd_outb(ahd, CLRSINT3, status3);
1667 	} else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) {
1668 		/* Make sure the sequencer is in a safe location. */
1669 		ahd_clear_critical_section(ahd);
1670 
1671 		ahd_handle_lqiphase_error(ahd, lqistat1);
1672 	} else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1673 		/*
1674 		 * This status can be delayed during some
1675 		 * streaming operations.  The SCSIPHASE
1676 		 * handler has already dealt with this case
1677 		 * so just clear the error.
1678 		 */
1679 		ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ);
1680 	} else if ((status & BUSFREE) != 0
1681 		|| (lqistat1 & LQOBUSFREE) != 0) {
1682 		u_int lqostat1;
1683 		int   restart;
1684 		int   clear_fifo;
1685 		int   packetized;
1686 		u_int mode;
1687 
1688 		/*
1689 		 * Clear our selection hardware as soon as possible.
1690 		 * We may have an entry in the waiting Q for this target,
1691 		 * that is affected by this busfree and we don't want to
1692 		 * go about selecting the target while we handle the event.
1693 		 */
1694 		ahd_outb(ahd, SCSISEQ0, 0);
1695 
1696 		/* Make sure the sequencer is in a safe location. */
1697 		ahd_clear_critical_section(ahd);
1698 
1699 		/*
1700 		 * Determine what we were up to at the time of
1701 		 * the busfree.
1702 		 */
1703 		mode = AHD_MODE_SCSI;
1704 		busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1705 		lqostat1 = ahd_inb(ahd, LQOSTAT1);
1706 		switch (busfreetime) {
1707 		case BUSFREE_DFF0:
1708 		case BUSFREE_DFF1:
1709 		{
1710 			u_int	scbid;
1711 			struct	scb *scb;
1712 
1713 			mode = busfreetime == BUSFREE_DFF0
1714 			     ? AHD_MODE_DFF0 : AHD_MODE_DFF1;
1715 			ahd_set_modes(ahd, mode, mode);
1716 			scbid = ahd_get_scbptr(ahd);
1717 			scb = ahd_lookup_scb(ahd, scbid);
1718 			if (scb == NULL) {
1719 				printf("%s: Invalid SCB %d in DFF%d "
1720 				       "during unexpected busfree\n",
1721 				       ahd_name(ahd), scbid, mode);
1722 				packetized = 0;
1723 				AHD_CORRECTABLE_ERROR(ahd);
1724 			} else
1725 				packetized = (scb->flags & SCB_PACKETIZED) != 0;
1726 			clear_fifo = 1;
1727 			break;
1728 		}
1729 		case BUSFREE_LQO:
1730 			clear_fifo = 0;
1731 			packetized = 1;
1732 			break;
1733 		default:
1734 			clear_fifo = 0;
1735 			packetized =  (lqostat1 & LQOBUSFREE) != 0;
1736 			if (!packetized
1737 			 && ahd_inb(ahd, LASTPHASE) == P_BUSFREE
1738 			 && (ahd_inb(ahd, SSTAT0) & SELDI) == 0
1739 			 && ((ahd_inb(ahd, SSTAT0) & SELDO) == 0
1740 			  || (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0))
1741 				/*
1742 				 * Assume packetized if we are not
1743 				 * on the bus in a non-packetized
1744 				 * capacity and any pending selection
1745 				 * was a packetized selection.
1746 				 */
1747 				packetized = 1;
1748 			break;
1749 		}
1750 
1751 #ifdef AHD_DEBUG
1752 		if ((ahd_debug & AHD_SHOW_MISC) != 0)
1753 			printf("Saw Busfree.  Busfreetime = 0x%x.\n",
1754 			       busfreetime);
1755 #endif
1756 		/*
1757 		 * Busfrees that occur in non-packetized phases are
1758 		 * handled by the nonpkt_busfree handler.
1759 		 */
1760 		if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) {
1761 			restart = ahd_handle_pkt_busfree(ahd, busfreetime);
1762 		} else {
1763 			packetized = 0;
1764 			restart = ahd_handle_nonpkt_busfree(ahd);
1765 		}
1766 		/*
1767 		 * Clear the busfree interrupt status.  The setting of
1768 		 * the interrupt is a pulse, so in a perfect world, we
1769 		 * would not need to muck with the ENBUSFREE logic.  This
1770 		 * would ensure that if the bus moves on to another
1771 		 * connection, busfree protection is still in force.  If
1772 		 * BUSFREEREV is broken, however, we must manually clear
1773 		 * the ENBUSFREE if the busfree occurred during a non-pack
1774 		 * connection so that we don't get false positives during
1775 		 * future, packetized, connections.
1776 		 */
1777 		ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
1778 		if (packetized == 0
1779 		 && (ahd->bugs & AHD_BUSFREEREV_BUG) != 0)
1780 			ahd_outb(ahd, SIMODE1,
1781 				 ahd_inb(ahd, SIMODE1) & ~ENBUSFREE);
1782 
1783 		if (clear_fifo)
1784 			ahd_clear_fifo(ahd, mode);
1785 
1786 		ahd_clear_msg_state(ahd);
1787 		ahd_outb(ahd, CLRINT, CLRSCSIINT);
1788 		if (restart) {
1789 			ahd_restart(ahd);
1790 		} else {
1791 			ahd_unpause(ahd);
1792 		}
1793 	} else {
1794 		printf("%s: Missing case in ahd_handle_scsiint. status = %x\n",
1795 		       ahd_name(ahd), status);
1796 		ahd_dump_card_state(ahd);
1797 		ahd_clear_intstat(ahd);
1798 		ahd_unpause(ahd);
1799 	}
1800 }
1801 
1802 static void
1803 ahd_handle_transmission_error(struct ahd_softc *ahd)
1804 {
1805 	struct	scb *scb;
1806 	u_int	scbid;
1807 	u_int	lqistat1;
1808 	u_int	msg_out;
1809 	u_int	curphase;
1810 	u_int	lastphase;
1811 	u_int	perrdiag;
1812 	u_int	cur_col;
1813 	int	silent;
1814 
1815 	scb = NULL;
1816 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1817 	lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ);
1818 	ahd_inb(ahd, LQISTAT2);
1819 	if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0
1820 	 && (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) {
1821 		u_int lqistate;
1822 
1823 		ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1824 		lqistate = ahd_inb(ahd, LQISTATE);
1825 		if ((lqistate >= 0x1E && lqistate <= 0x24)
1826 		 || (lqistate == 0x29)) {
1827 #ifdef AHD_DEBUG
1828 			if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1829 				printf("%s: NLQCRC found via LQISTATE\n",
1830 				       ahd_name(ahd));
1831 			}
1832 #endif
1833 			lqistat1 |= LQICRCI_NLQ;
1834 		}
1835 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1836 	}
1837 
1838 	ahd_outb(ahd, CLRLQIINT1, lqistat1);
1839 	lastphase = ahd_inb(ahd, LASTPHASE);
1840 	curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1841 	perrdiag = ahd_inb(ahd, PERRDIAG);
1842 	msg_out = MSG_INITIATOR_DET_ERR;
1843 	ahd_outb(ahd, CLRSINT1, CLRSCSIPERR);
1844 
1845 	/*
1846 	 * Try to find the SCB associated with this error.
1847 	 */
1848 	silent = FALSE;
1849 	if (lqistat1 == 0
1850 	 || (lqistat1 & LQICRCI_NLQ) != 0) {
1851 	 	if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0)
1852 			ahd_set_active_fifo(ahd);
1853 		scbid = ahd_get_scbptr(ahd);
1854 		scb = ahd_lookup_scb(ahd, scbid);
1855 		if (scb != NULL && SCB_IS_SILENT(scb))
1856 			silent = TRUE;
1857 	}
1858 
1859 	cur_col = 0;
1860 	if (silent == FALSE) {
1861 		printf("%s: Transmission error detected\n", ahd_name(ahd));
1862 		ahd_lqistat1_print(lqistat1, &cur_col, 50);
1863 		ahd_lastphase_print(lastphase, &cur_col, 50);
1864 		ahd_scsisigi_print(curphase, &cur_col, 50);
1865 		ahd_perrdiag_print(perrdiag, &cur_col, 50);
1866 		printf("\n");
1867 		AHD_CORRECTABLE_ERROR(ahd);
1868 		ahd_dump_card_state(ahd);
1869 	}
1870 
1871 	if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) {
1872 		if (silent == FALSE) {
1873 			printf("%s: Gross protocol error during incoming "
1874 			       "packet.  lqistat1 == 0x%x.  Resetting bus.\n",
1875 			       ahd_name(ahd), lqistat1);
1876 			AHD_UNCORRECTABLE_ERROR(ahd);
1877 		}
1878 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1879 		return;
1880 	} else if ((lqistat1 & LQICRCI_LQ) != 0) {
1881 		/*
1882 		 * A CRC error has been detected on an incoming LQ.
1883 		 * The bus is currently hung on the last ACK.
1884 		 * Hit LQIRETRY to release the last ack, and
1885 		 * wait for the sequencer to determine that ATNO
1886 		 * is asserted while in message out to take us
1887 		 * to our host message loop.  No NONPACKREQ or
1888 		 * LQIPHASE type errors will occur in this
1889 		 * scenario.  After this first LQIRETRY, the LQI
1890 		 * manager will be in ISELO where it will
1891 		 * happily sit until another packet phase begins.
1892 		 * Unexpected bus free detection is enabled
1893 		 * through any phases that occur after we release
1894 		 * this last ack until the LQI manager sees a
1895 		 * packet phase.  This implies we may have to
1896 		 * ignore a perfectly valid "unexected busfree"
1897 		 * after our "initiator detected error" message is
1898 		 * sent.  A busfree is the expected response after
1899 		 * we tell the target that it's L_Q was corrupted.
1900 		 * (SPI4R09 10.7.3.3.3)
1901 		 */
1902 		ahd_outb(ahd, LQCTL2, LQIRETRY);
1903 		printf("LQIRetry for LQICRCI_LQ to release ACK\n");
1904 		AHD_CORRECTABLE_ERROR(ahd);
1905 	} else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1906 		/*
1907 		 * We detected a CRC error in a NON-LQ packet.
1908 		 * The hardware has varying behavior in this situation
1909 		 * depending on whether this packet was part of a
1910 		 * stream or not.
1911 		 *
1912 		 * PKT by PKT mode:
1913 		 * The hardware has already acked the complete packet.
1914 		 * If the target honors our outstanding ATN condition,
1915 		 * we should be (or soon will be) in MSGOUT phase.
1916 		 * This will trigger the LQIPHASE_LQ status bit as the
1917 		 * hardware was expecting another LQ.  Unexpected
1918 		 * busfree detection is enabled.  Once LQIPHASE_LQ is
1919 		 * true (first entry into host message loop is much
1920 		 * the same), we must clear LQIPHASE_LQ and hit
1921 		 * LQIRETRY so the hardware is ready to handle
1922 		 * a future LQ.  NONPACKREQ will not be asserted again
1923 		 * once we hit LQIRETRY until another packet is
1924 		 * processed.  The target may either go busfree
1925 		 * or start another packet in response to our message.
1926 		 *
1927 		 * Read Streaming P0 asserted:
1928 		 * If we raise ATN and the target completes the entire
1929 		 * stream (P0 asserted during the last packet), the
1930 		 * hardware will ack all data and return to the ISTART
1931 		 * state.  When the target reponds to our ATN condition,
1932 		 * LQIPHASE_LQ will be asserted.  We should respond to
1933 		 * this with an LQIRETRY to prepare for any future
1934 		 * packets.  NONPACKREQ will not be asserted again
1935 		 * once we hit LQIRETRY until another packet is
1936 		 * processed.  The target may either go busfree or
1937 		 * start another packet in response to our message.
1938 		 * Busfree detection is enabled.
1939 		 *
1940 		 * Read Streaming P0 not asserted:
1941 		 * If we raise ATN and the target transitions to
1942 		 * MSGOUT in or after a packet where P0 is not
1943 		 * asserted, the hardware will assert LQIPHASE_NLQ.
1944 		 * We should respond to the LQIPHASE_NLQ with an
1945 		 * LQIRETRY.  Should the target stay in a non-pkt
1946 		 * phase after we send our message, the hardware
1947 		 * will assert LQIPHASE_LQ.  Recovery is then just as
1948 		 * listed above for the read streaming with P0 asserted.
1949 		 * Busfree detection is enabled.
1950 		 */
1951 		if (silent == FALSE)
1952 			printf("LQICRC_NLQ\n");
1953 		if (scb == NULL) {
1954 			printf("%s: No SCB valid for LQICRC_NLQ.  "
1955 			       "Resetting bus\n", ahd_name(ahd));
1956 			AHD_UNCORRECTABLE_ERROR(ahd);
1957 			ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1958 			return;
1959 		}
1960 	} else if ((lqistat1 & LQIBADLQI) != 0) {
1961 		printf("Need to handle BADLQI!\n");
1962 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1963 		return;
1964 	} else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) {
1965 		if ((curphase & ~P_DATAIN_DT) != 0) {
1966 			/* Ack the byte.  So we can continue. */
1967 			if (silent == FALSE)
1968 				printf("Acking %s to clear perror\n",
1969 				    ahd_lookup_phase_entry(curphase)->phasemsg);
1970 			ahd_inb(ahd, SCSIDAT);
1971 		}
1972 
1973 		if (curphase == P_MESGIN)
1974 			msg_out = MSG_PARITY_ERROR;
1975 	}
1976 
1977 	/*
1978 	 * We've set the hardware to assert ATN if we
1979 	 * get a parity error on "in" phases, so all we
1980 	 * need to do is stuff the message buffer with
1981 	 * the appropriate message.  "In" phases have set
1982 	 * mesg_out to something other than MSG_NOP.
1983 	 */
1984 	ahd->send_msg_perror = msg_out;
1985 	if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR)
1986 		scb->flags |= SCB_TRANSMISSION_ERROR;
1987 	ahd_outb(ahd, MSG_OUT, HOST_MSG);
1988 	ahd_outb(ahd, CLRINT, CLRSCSIINT);
1989 	ahd_unpause(ahd);
1990 }
1991 
1992 static void
1993 ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1)
1994 {
1995 	/*
1996 	 * Clear the sources of the interrupts.
1997 	 */
1998 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1999 	ahd_outb(ahd, CLRLQIINT1, lqistat1);
2000 
2001 	/*
2002 	 * If the "illegal" phase changes were in response
2003 	 * to our ATN to flag a CRC error, AND we ended up
2004 	 * on packet boundaries, clear the error, restart the
2005 	 * LQI manager as appropriate, and go on our merry
2006 	 * way toward sending the message.  Otherwise, reset
2007 	 * the bus to clear the error.
2008 	 */
2009 	ahd_set_active_fifo(ahd);
2010 	if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0
2011 	 && (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) {
2012 		if ((lqistat1 & LQIPHASE_LQ) != 0) {
2013 			printf("LQIRETRY for LQIPHASE_LQ\n");
2014 			AHD_CORRECTABLE_ERROR(ahd);
2015 			ahd_outb(ahd, LQCTL2, LQIRETRY);
2016 		} else if ((lqistat1 & LQIPHASE_NLQ) != 0) {
2017 			printf("LQIRETRY for LQIPHASE_NLQ\n");
2018 			AHD_CORRECTABLE_ERROR(ahd);
2019 			ahd_outb(ahd, LQCTL2, LQIRETRY);
2020 		} else
2021 			panic("ahd_handle_lqiphase_error: No phase errors\n");
2022 		ahd_dump_card_state(ahd);
2023 		ahd_outb(ahd, CLRINT, CLRSCSIINT);
2024 		ahd_unpause(ahd);
2025 	} else {
2026 		printf("Reseting Channel for LQI Phase error\n");
2027 		AHD_CORRECTABLE_ERROR(ahd);
2028 		ahd_dump_card_state(ahd);
2029 		ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2030 	}
2031 }
2032 
2033 /*
2034  * Packetized unexpected or expected busfree.
2035  * Entered in mode based on busfreetime.
2036  */
2037 static int
2038 ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime)
2039 {
2040 	u_int lqostat1;
2041 
2042 	AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2043 			 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2044 	lqostat1 = ahd_inb(ahd, LQOSTAT1);
2045 	if ((lqostat1 & LQOBUSFREE) != 0) {
2046 		struct scb *scb;
2047 		u_int scbid;
2048 		u_int saved_scbptr;
2049 		u_int waiting_h;
2050 		u_int waiting_t;
2051 		u_int next;
2052 
2053 		/*
2054 		 * The LQO manager detected an unexpected busfree
2055 		 * either:
2056 		 *
2057 		 * 1) During an outgoing LQ.
2058 		 * 2) After an outgoing LQ but before the first
2059 		 *    REQ of the command packet.
2060 		 * 3) During an outgoing command packet.
2061 		 *
2062 		 * In all cases, CURRSCB is pointing to the
2063 		 * SCB that encountered the failure.  Clean
2064 		 * up the queue, clear SELDO and LQOBUSFREE,
2065 		 * and allow the sequencer to restart the select
2066 		 * out at its lesure.
2067 		 */
2068 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2069 		scbid = ahd_inw(ahd, CURRSCB);
2070 		scb = ahd_lookup_scb(ahd, scbid);
2071 		if (scb == NULL)
2072 		       panic("SCB not valid during LQOBUSFREE");
2073 		/*
2074 		 * Clear the status.
2075 		 */
2076 		ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE);
2077 		if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
2078 			ahd_outb(ahd, CLRLQOINT1, 0);
2079 		ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2080 		ahd_flush_device_writes(ahd);
2081 		ahd_outb(ahd, CLRSINT0, CLRSELDO);
2082 
2083 		/*
2084 		 * Return the LQO manager to its idle loop.  It will
2085 		 * not do this automatically if the busfree occurs
2086 		 * after the first REQ of either the LQ or command
2087 		 * packet or between the LQ and command packet.
2088 		 */
2089 		ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE);
2090 
2091 		/*
2092 		 * Update the waiting for selection queue so
2093 		 * we restart on the correct SCB.
2094 		 */
2095 		waiting_h = ahd_inw(ahd, WAITING_TID_HEAD);
2096 		saved_scbptr = ahd_get_scbptr(ahd);
2097 		if (waiting_h != scbid) {
2098 			ahd_outw(ahd, WAITING_TID_HEAD, scbid);
2099 			waiting_t = ahd_inw(ahd, WAITING_TID_TAIL);
2100 			if (waiting_t == waiting_h) {
2101 				ahd_outw(ahd, WAITING_TID_TAIL, scbid);
2102 				next = SCB_LIST_NULL;
2103 			} else {
2104 				ahd_set_scbptr(ahd, waiting_h);
2105 				next = ahd_inw_scbram(ahd, SCB_NEXT2);
2106 			}
2107 			ahd_set_scbptr(ahd, scbid);
2108 			ahd_outw(ahd, SCB_NEXT2, next);
2109 		}
2110 		ahd_set_scbptr(ahd, saved_scbptr);
2111 		if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) {
2112 			if (SCB_IS_SILENT(scb) == FALSE) {
2113 				ahd_print_path(ahd, scb);
2114 				printf("Probable outgoing LQ CRC error.  "
2115 				       "Retrying command\n");
2116 				AHD_CORRECTABLE_ERROR(ahd);
2117 			}
2118 			scb->crc_retry_count++;
2119 		} else {
2120 			aic_set_transaction_status(scb, CAM_UNCOR_PARITY);
2121 			aic_freeze_scb(scb);
2122 			ahd_freeze_devq(ahd, scb);
2123 		}
2124 		/* Return unpausing the sequencer. */
2125 		return (0);
2126 	} else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) {
2127 		/*
2128 		 * Ignore what are really parity errors that
2129 		 * occur on the last REQ of a free running
2130 		 * clock prior to going busfree.  Some drives
2131 		 * do not properly active negate just before
2132 		 * going busfree resulting in a parity glitch.
2133 		 */
2134 		ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE);
2135 #ifdef AHD_DEBUG
2136 		if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0)
2137 			printf("%s: Parity on last REQ detected "
2138 			       "during busfree phase.\n",
2139 			       ahd_name(ahd));
2140 #endif
2141 		/* Return unpausing the sequencer. */
2142 		return (0);
2143 	}
2144 	if (ahd->src_mode != AHD_MODE_SCSI) {
2145 		u_int	scbid;
2146 		struct	scb *scb;
2147 
2148 		scbid = ahd_get_scbptr(ahd);
2149 		scb = ahd_lookup_scb(ahd, scbid);
2150 		ahd_print_path(ahd, scb);
2151 		printf("Unexpected PKT busfree condition\n");
2152 		AHD_UNCORRECTABLE_ERROR(ahd);
2153 		ahd_dump_card_state(ahd);
2154 		ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A',
2155 			       SCB_GET_LUN(scb), SCB_GET_TAG(scb),
2156 			       ROLE_INITIATOR, CAM_UNEXP_BUSFREE);
2157 
2158 		/* Return restarting the sequencer. */
2159 		return (1);
2160 	}
2161 	printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd));
2162 	AHD_UNCORRECTABLE_ERROR(ahd);
2163 	ahd_dump_card_state(ahd);
2164 	/* Restart the sequencer. */
2165 	return (1);
2166 }
2167 
2168 /*
2169  * Non-packetized unexpected or expected busfree.
2170  */
2171 static int
2172 ahd_handle_nonpkt_busfree(struct ahd_softc *ahd)
2173 {
2174 	struct	ahd_devinfo devinfo;
2175 	struct	scb *scb;
2176 	u_int	lastphase;
2177 	u_int	saved_scsiid;
2178 	u_int	saved_lun;
2179 	u_int	target;
2180 	u_int	initiator_role_id;
2181 	u_int	scbid;
2182 	u_int	ppr_busfree;
2183 	int	printerror;
2184 
2185 	/*
2186 	 * Look at what phase we were last in.  If its message out,
2187 	 * chances are pretty good that the busfree was in response
2188 	 * to one of our abort requests.
2189 	 */
2190 	lastphase = ahd_inb(ahd, LASTPHASE);
2191 	saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
2192 	saved_lun = ahd_inb(ahd, SAVED_LUN);
2193 	target = SCSIID_TARGET(ahd, saved_scsiid);
2194 	initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
2195 	ahd_compile_devinfo(&devinfo, initiator_role_id,
2196 			    target, saved_lun, 'A', ROLE_INITIATOR);
2197 	printerror = 1;
2198 
2199 	scbid = ahd_get_scbptr(ahd);
2200 	scb = ahd_lookup_scb(ahd, scbid);
2201 	if (scb != NULL
2202 	 && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
2203 		scb = NULL;
2204 
2205 	ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0;
2206 	if (lastphase == P_MESGOUT) {
2207 		u_int tag;
2208 
2209 		tag = SCB_LIST_NULL;
2210 		if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE)
2211 		 || ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) {
2212 			int found;
2213 			int sent_msg;
2214 
2215 			if (scb == NULL) {
2216 				ahd_print_devinfo(ahd, &devinfo);
2217 				printf("Abort for unidentified "
2218 				       "connection completed.\n");
2219 				/* restart the sequencer. */
2220 				return (1);
2221 			}
2222 			sent_msg = ahd->msgout_buf[ahd->msgout_index - 1];
2223 			ahd_print_path(ahd, scb);
2224 			printf("SCB %d - Abort%s Completed.\n",
2225 			       SCB_GET_TAG(scb),
2226 			       sent_msg == MSG_ABORT_TAG ? "" : " Tag");
2227 
2228 			if (sent_msg == MSG_ABORT_TAG)
2229 				tag = SCB_GET_TAG(scb);
2230 
2231 			if ((scb->flags & SCB_CMDPHASE_ABORT) != 0) {
2232 				/*
2233 				 * This abort is in response to an
2234 				 * unexpected switch to command phase
2235 				 * for a packetized connection.  Since
2236 				 * the identify message was never sent,
2237 				 * "saved lun" is 0.  We really want to
2238 				 * abort only the SCB that encountered
2239 				 * this error, which could have a different
2240 				 * lun.  The SCB will be retried so the OS
2241 				 * will see the UA after renegotiating to
2242 				 * packetized.
2243 				 */
2244 				tag = SCB_GET_TAG(scb);
2245 				saved_lun = scb->hscb->lun;
2246 			}
2247 			found = ahd_abort_scbs(ahd, target, 'A', saved_lun,
2248 					       tag, ROLE_INITIATOR,
2249 					       CAM_REQ_ABORTED);
2250 			printf("found == 0x%x\n", found);
2251 			printerror = 0;
2252 		} else if (ahd_sent_msg(ahd, AHDMSG_1B,
2253 					MSG_BUS_DEV_RESET, TRUE)) {
2254 #ifdef __FreeBSD__
2255 			/*
2256 			 * Don't mark the user's request for this BDR
2257 			 * as completing with CAM_BDR_SENT.  CAM3
2258 			 * specifies CAM_REQ_CMP.
2259 			 */
2260 			if (scb != NULL
2261 			 && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
2262 			 && ahd_match_scb(ahd, scb, target, 'A',
2263 					  CAM_LUN_WILDCARD, SCB_LIST_NULL,
2264 					  ROLE_INITIATOR))
2265 				aic_set_transaction_status(scb, CAM_REQ_CMP);
2266 #endif
2267 			ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD,
2268 					    CAM_BDR_SENT, "Bus Device Reset",
2269 					    /*verbose_level*/0);
2270 			printerror = 0;
2271 		} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE)
2272 			&& ppr_busfree == 0) {
2273 			struct ahd_initiator_tinfo *tinfo;
2274 			struct ahd_tmode_tstate *tstate;
2275 
2276 			/*
2277 			 * PPR Rejected.
2278 			 *
2279 			 * If the previous negotiation was packetized,
2280 			 * this could be because the device has been
2281 			 * reset without our knowledge.  Force our
2282 			 * current negotiation to async and retry the
2283 			 * negotiation.  Otherwise retry the command
2284 			 * with non-ppr negotiation.
2285 			 */
2286 #ifdef AHD_DEBUG
2287 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2288 				printf("PPR negotiation rejected busfree.\n");
2289 #endif
2290 			tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
2291 						    devinfo.our_scsiid,
2292 						    devinfo.target, &tstate);
2293 			if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) {
2294 				ahd_set_width(ahd, &devinfo,
2295 					      MSG_EXT_WDTR_BUS_8_BIT,
2296 					      AHD_TRANS_CUR,
2297 					      /*paused*/TRUE);
2298 				ahd_set_syncrate(ahd, &devinfo,
2299 						/*period*/0, /*offset*/0,
2300 						/*ppr_options*/0,
2301 						AHD_TRANS_CUR,
2302 						/*paused*/TRUE);
2303 				/*
2304 				 * The expect PPR busfree handler below
2305 				 * will effect the retry and necessary
2306 				 * abort.
2307 				 */
2308 			} else {
2309 				tinfo->curr.transport_version = 2;
2310 				tinfo->goal.transport_version = 2;
2311 				tinfo->goal.ppr_options = 0;
2312 				/*
2313 				 * Remove any SCBs in the waiting for selection
2314 				 * queue that may also be for this target so
2315 				 * that command ordering is preserved.
2316 				 */
2317 				ahd_freeze_devq(ahd, scb);
2318 				ahd_qinfifo_requeue_tail(ahd, scb);
2319 				printerror = 0;
2320 			}
2321 		} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE)
2322 			&& ppr_busfree == 0) {
2323 			/*
2324 			 * Negotiation Rejected.  Go-narrow and
2325 			 * retry command.
2326 			 */
2327 #ifdef AHD_DEBUG
2328 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2329 				printf("WDTR negotiation rejected busfree.\n");
2330 #endif
2331 			ahd_set_width(ahd, &devinfo,
2332 				      MSG_EXT_WDTR_BUS_8_BIT,
2333 				      AHD_TRANS_CUR|AHD_TRANS_GOAL,
2334 				      /*paused*/TRUE);
2335 			/*
2336 			 * Remove any SCBs in the waiting for selection
2337 			 * queue that may also be for this target so that
2338 			 * command ordering is preserved.
2339 			 */
2340 			ahd_freeze_devq(ahd, scb);
2341 			ahd_qinfifo_requeue_tail(ahd, scb);
2342 			printerror = 0;
2343 		} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE)
2344 			&& ppr_busfree == 0) {
2345 			/*
2346 			 * Negotiation Rejected.  Go-async and
2347 			 * retry command.
2348 			 */
2349 #ifdef AHD_DEBUG
2350 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2351 				printf("SDTR negotiation rejected busfree.\n");
2352 #endif
2353 			ahd_set_syncrate(ahd, &devinfo,
2354 					/*period*/0, /*offset*/0,
2355 					/*ppr_options*/0,
2356 					AHD_TRANS_CUR|AHD_TRANS_GOAL,
2357 					/*paused*/TRUE);
2358 			/*
2359 			 * Remove any SCBs in the waiting for selection
2360 			 * queue that may also be for this target so that
2361 			 * command ordering is preserved.
2362 			 */
2363 			ahd_freeze_devq(ahd, scb);
2364 			ahd_qinfifo_requeue_tail(ahd, scb);
2365 			printerror = 0;
2366 		} else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0
2367 			&& ahd_sent_msg(ahd, AHDMSG_1B,
2368 					 MSG_INITIATOR_DET_ERR, TRUE)) {
2369 #ifdef AHD_DEBUG
2370 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2371 				printf("Expected IDE Busfree\n");
2372 #endif
2373 			printerror = 0;
2374 		} else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE)
2375 			&& ahd_sent_msg(ahd, AHDMSG_1B,
2376 					MSG_MESSAGE_REJECT, TRUE)) {
2377 #ifdef AHD_DEBUG
2378 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2379 				printf("Expected QAS Reject Busfree\n");
2380 #endif
2381 			printerror = 0;
2382 		}
2383 	}
2384 
2385 	/*
2386 	 * The busfree required flag is honored at the end of
2387 	 * the message phases.  We check it last in case we
2388 	 * had to send some other message that caused a busfree.
2389 	 */
2390 	if (printerror != 0
2391 	 && (lastphase == P_MESGIN || lastphase == P_MESGOUT)
2392 	 && ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) {
2393 		ahd_freeze_devq(ahd, scb);
2394 		aic_set_transaction_status(scb, CAM_REQUEUE_REQ);
2395 		aic_freeze_scb(scb);
2396 		if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) {
2397 			ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
2398 				       SCB_GET_CHANNEL(ahd, scb),
2399 				       SCB_GET_LUN(scb), SCB_LIST_NULL,
2400 				       ROLE_INITIATOR, CAM_REQ_ABORTED);
2401 		} else {
2402 #ifdef AHD_DEBUG
2403 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2404 				printf("PPR Negotiation Busfree.\n");
2405 #endif
2406 			ahd_done(ahd, scb);
2407 		}
2408 		printerror = 0;
2409 	}
2410 	if (printerror != 0) {
2411 		int aborted;
2412 
2413 		aborted = 0;
2414 		if (scb != NULL) {
2415 			u_int tag;
2416 
2417 			if ((scb->hscb->control & TAG_ENB) != 0)
2418 				tag = SCB_GET_TAG(scb);
2419 			else
2420 				tag = SCB_LIST_NULL;
2421 			ahd_print_path(ahd, scb);
2422 			aborted = ahd_abort_scbs(ahd, target, 'A',
2423 				       SCB_GET_LUN(scb), tag,
2424 				       ROLE_INITIATOR,
2425 				       CAM_UNEXP_BUSFREE);
2426 		} else {
2427 			/*
2428 			 * We had not fully identified this connection,
2429 			 * so we cannot abort anything.
2430 			 */
2431 			printf("%s: ", ahd_name(ahd));
2432 		}
2433 		printf("Unexpected busfree %s, %d SCBs aborted, "
2434 		       "PRGMCNT == 0x%x\n",
2435 		       ahd_lookup_phase_entry(lastphase)->phasemsg,
2436 		       aborted,
2437 		       ahd_inw(ahd, PRGMCNT));
2438 		AHD_UNCORRECTABLE_ERROR(ahd);
2439 		ahd_dump_card_state(ahd);
2440 		if (lastphase != P_BUSFREE)
2441 			ahd_force_renegotiation(ahd, &devinfo);
2442 	}
2443 	/* Always restart the sequencer. */
2444 	return (1);
2445 }
2446 
2447 static void
2448 ahd_handle_proto_violation(struct ahd_softc *ahd)
2449 {
2450 	struct	ahd_devinfo devinfo;
2451 	struct	scb *scb;
2452 	u_int	scbid;
2453 	u_int	seq_flags;
2454 	u_int	curphase;
2455 	u_int	lastphase;
2456 	int	found;
2457 
2458 	ahd_fetch_devinfo(ahd, &devinfo);
2459 	scbid = ahd_get_scbptr(ahd);
2460 	scb = ahd_lookup_scb(ahd, scbid);
2461 	seq_flags = ahd_inb(ahd, SEQ_FLAGS);
2462 	curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
2463 	lastphase = ahd_inb(ahd, LASTPHASE);
2464 	if ((seq_flags & NOT_IDENTIFIED) != 0) {
2465 		/*
2466 		 * The reconnecting target either did not send an
2467 		 * identify message, or did, but we didn't find an SCB
2468 		 * to match.
2469 		 */
2470 		ahd_print_devinfo(ahd, &devinfo);
2471 		printf("Target did not send an IDENTIFY message. "
2472 		       "LASTPHASE = 0x%x.\n", lastphase);
2473 		AHD_UNCORRECTABLE_ERROR(ahd);
2474 		scb = NULL;
2475 	} else if (scb == NULL) {
2476 		/*
2477 		 * We don't seem to have an SCB active for this
2478 		 * transaction.  Print an error and reset the bus.
2479 		 */
2480 		ahd_print_devinfo(ahd, &devinfo);
2481 		printf("No SCB found during protocol violation\n");
2482 		AHD_UNCORRECTABLE_ERROR(ahd);
2483 		goto proto_violation_reset;
2484 	} else {
2485 		aic_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2486 		if ((seq_flags & NO_CDB_SENT) != 0) {
2487 			ahd_print_path(ahd, scb);
2488 			printf("No or incomplete CDB sent to device.\n");
2489 			AHD_UNCORRECTABLE_ERROR(ahd);
2490 		} else if ((ahd_inb_scbram(ahd, SCB_CONTROL)
2491 			  & STATUS_RCVD) == 0) {
2492 			/*
2493 			 * The target never bothered to provide status to
2494 			 * us prior to completing the command.  Since we don't
2495 			 * know the disposition of this command, we must attempt
2496 			 * to abort it.  Assert ATN and prepare to send an abort
2497 			 * message.
2498 			 */
2499 			ahd_print_path(ahd, scb);
2500 			printf("Completed command without status.\n");
2501 		} else {
2502 			ahd_print_path(ahd, scb);
2503 			printf("Unknown protocol violation.\n");
2504 			AHD_UNCORRECTABLE_ERROR(ahd);
2505 			ahd_dump_card_state(ahd);
2506 		}
2507 	}
2508 	if ((lastphase & ~P_DATAIN_DT) == 0
2509 	 || lastphase == P_COMMAND) {
2510 proto_violation_reset:
2511 		/*
2512 		 * Target either went directly to data
2513 		 * phase or didn't respond to our ATN.
2514 		 * The only safe thing to do is to blow
2515 		 * it away with a bus reset.
2516 		 */
2517 		found = ahd_reset_channel(ahd, 'A', TRUE);
2518 		printf("%s: Issued Channel %c Bus Reset. "
2519 		       "%d SCBs aborted\n", ahd_name(ahd), 'A', found);
2520 		AHD_UNCORRECTABLE_ERROR(ahd);
2521 	} else {
2522 		/*
2523 		 * Leave the selection hardware off in case
2524 		 * this abort attempt will affect yet to
2525 		 * be sent commands.
2526 		 */
2527 		ahd_outb(ahd, SCSISEQ0,
2528 			 ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2529 		ahd_assert_atn(ahd);
2530 		ahd_outb(ahd, MSG_OUT, HOST_MSG);
2531 		if (scb == NULL) {
2532 			ahd_print_devinfo(ahd, &devinfo);
2533 			ahd->msgout_buf[0] = MSG_ABORT_TASK;
2534 			ahd->msgout_len = 1;
2535 			ahd->msgout_index = 0;
2536 			ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2537 		} else {
2538 			ahd_print_path(ahd, scb);
2539 			scb->flags |= SCB_ABORT;
2540 		}
2541 		printf("Protocol violation %s.  Attempting to abort.\n",
2542 		       ahd_lookup_phase_entry(curphase)->phasemsg);
2543 		AHD_UNCORRECTABLE_ERROR(ahd);
2544 	}
2545 }
2546 
2547 /*
2548  * Force renegotiation to occur the next time we initiate
2549  * a command to the current device.
2550  */
2551 static void
2552 ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
2553 {
2554 	struct	ahd_initiator_tinfo *targ_info;
2555 	struct	ahd_tmode_tstate *tstate;
2556 
2557 #ifdef AHD_DEBUG
2558 	if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
2559 		ahd_print_devinfo(ahd, devinfo);
2560 		printf("Forcing renegotiation\n");
2561 	}
2562 #endif
2563 	targ_info = ahd_fetch_transinfo(ahd,
2564 					devinfo->channel,
2565 					devinfo->our_scsiid,
2566 					devinfo->target,
2567 					&tstate);
2568 	ahd_update_neg_request(ahd, devinfo, tstate,
2569 			       targ_info, AHD_NEG_IF_NON_ASYNC);
2570 }
2571 
2572 #define AHD_MAX_STEPS 2000
2573 void
2574 ahd_clear_critical_section(struct ahd_softc *ahd)
2575 {
2576 	ahd_mode_state	saved_modes;
2577 	int		stepping;
2578 	int		steps;
2579 	int		first_instr;
2580 	u_int		simode0;
2581 	u_int		simode1;
2582 	u_int		simode3;
2583 	u_int		lqimode0;
2584 	u_int		lqimode1;
2585 	u_int		lqomode0;
2586 	u_int		lqomode1;
2587 
2588 	if (ahd->num_critical_sections == 0)
2589 		return;
2590 
2591 	stepping = FALSE;
2592 	steps = 0;
2593 	first_instr = 0;
2594 	simode0 = 0;
2595 	simode1 = 0;
2596 	simode3 = 0;
2597 	lqimode0 = 0;
2598 	lqimode1 = 0;
2599 	lqomode0 = 0;
2600 	lqomode1 = 0;
2601 	saved_modes = ahd_save_modes(ahd);
2602 	for (;;) {
2603 		struct	cs *cs;
2604 		u_int	seqaddr;
2605 		u_int	i;
2606 
2607 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2608 		seqaddr = ahd_inw(ahd, CURADDR);
2609 
2610 		cs = ahd->critical_sections;
2611 		for (i = 0; i < ahd->num_critical_sections; i++, cs++) {
2612 
2613 			if (cs->begin < seqaddr && cs->end >= seqaddr)
2614 				break;
2615 		}
2616 
2617 		if (i == ahd->num_critical_sections)
2618 			break;
2619 
2620 		if (steps > AHD_MAX_STEPS) {
2621 			printf("%s: Infinite loop in critical section\n"
2622 			       "%s: First Instruction 0x%x now 0x%x\n",
2623 			       ahd_name(ahd), ahd_name(ahd), first_instr,
2624 			       seqaddr);
2625 			AHD_FATAL_ERROR(ahd);
2626 			ahd_dump_card_state(ahd);
2627 			panic("critical section loop");
2628 		}
2629 
2630 		steps++;
2631 #ifdef AHD_DEBUG
2632 		if ((ahd_debug & AHD_SHOW_MISC) != 0)
2633 			printf("%s: Single stepping at 0x%x\n", ahd_name(ahd),
2634 			       seqaddr);
2635 #endif
2636 		if (stepping == FALSE) {
2637 			first_instr = seqaddr;
2638   			ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2639   			simode0 = ahd_inb(ahd, SIMODE0);
2640 			simode3 = ahd_inb(ahd, SIMODE3);
2641 			lqimode0 = ahd_inb(ahd, LQIMODE0);
2642 			lqimode1 = ahd_inb(ahd, LQIMODE1);
2643 			lqomode0 = ahd_inb(ahd, LQOMODE0);
2644 			lqomode1 = ahd_inb(ahd, LQOMODE1);
2645 			ahd_outb(ahd, SIMODE0, 0);
2646 			ahd_outb(ahd, SIMODE3, 0);
2647 			ahd_outb(ahd, LQIMODE0, 0);
2648 			ahd_outb(ahd, LQIMODE1, 0);
2649 			ahd_outb(ahd, LQOMODE0, 0);
2650 			ahd_outb(ahd, LQOMODE1, 0);
2651 			ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2652 			simode1 = ahd_inb(ahd, SIMODE1);
2653 			/*
2654 			 * We don't clear ENBUSFREE.  Unfortunately
2655 			 * we cannot re-enable busfree detection within
2656 			 * the current connection, so we must leave it
2657 			 * on while single stepping.
2658 			 */
2659 			ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE);
2660 			ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP);
2661 			stepping = TRUE;
2662 		}
2663 		ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
2664 		ahd_outb(ahd, CLRINT, CLRSCSIINT);
2665 		ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
2666 		ahd_outb(ahd, HCNTRL, ahd->unpause);
2667 		while (!ahd_is_paused(ahd))
2668 			aic_delay(200);
2669 		ahd_update_modes(ahd);
2670 	}
2671 	if (stepping) {
2672 		ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2673 		ahd_outb(ahd, SIMODE0, simode0);
2674 		ahd_outb(ahd, SIMODE3, simode3);
2675 		ahd_outb(ahd, LQIMODE0, lqimode0);
2676 		ahd_outb(ahd, LQIMODE1, lqimode1);
2677 		ahd_outb(ahd, LQOMODE0, lqomode0);
2678 		ahd_outb(ahd, LQOMODE1, lqomode1);
2679 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2680 		ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP);
2681   		ahd_outb(ahd, SIMODE1, simode1);
2682 		/*
2683 		 * SCSIINT seems to glitch occasionally when
2684 		 * the interrupt masks are restored.  Clear SCSIINT
2685 		 * one more time so that only persistent errors
2686 		 * are seen as a real interrupt.
2687 		 */
2688 		ahd_outb(ahd, CLRINT, CLRSCSIINT);
2689 	}
2690 	ahd_restore_modes(ahd, saved_modes);
2691 }
2692 
2693 /*
2694  * Clear any pending interrupt status.
2695  */
2696 void
2697 ahd_clear_intstat(struct ahd_softc *ahd)
2698 {
2699 	AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2700 			 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2701 	/* Clear any interrupt conditions this may have caused */
2702 	ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2
2703 				 |CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD);
2704 	ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT
2705 				 |CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI
2706 				 |CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ);
2707 	ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ
2708 				 |CLRLQOATNPKT|CLRLQOTCRC);
2709 	ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS
2710 				 |CLRLQOBUSFREE|CLRLQOPHACHGINPKT);
2711 	if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
2712 		ahd_outb(ahd, CLRLQOINT0, 0);
2713 		ahd_outb(ahd, CLRLQOINT1, 0);
2714 	}
2715 	ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR);
2716 	ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
2717 				|CLRBUSFREE|CLRSCSIPERR|CLRREQINIT);
2718 	ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO
2719 			        |CLRIOERR|CLROVERRUN);
2720 	ahd_outb(ahd, CLRINT, CLRSCSIINT);
2721 }
2722 
2723 /**************************** Debugging Routines ******************************/
2724 #ifdef AHD_DEBUG
2725 uint32_t ahd_debug = AHD_DEBUG_OPTS;
2726 #endif
2727 void
2728 ahd_print_scb(struct scb *scb)
2729 {
2730 	struct hardware_scb *hscb;
2731 	int i;
2732 
2733 	hscb = scb->hscb;
2734 	printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
2735 	       (void *)scb,
2736 	       hscb->control,
2737 	       hscb->scsiid,
2738 	       hscb->lun,
2739 	       hscb->cdb_len);
2740 	printf("Shared Data: ");
2741 	for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++)
2742 		printf("%#02x", hscb->shared_data.idata.cdb[i]);
2743 	printf("        dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n",
2744 	       (uint32_t)((aic_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF),
2745 	       (uint32_t)(aic_le64toh(hscb->dataptr) & 0xFFFFFFFF),
2746 	       aic_le32toh(hscb->datacnt),
2747 	       aic_le32toh(hscb->sgptr),
2748 	       SCB_GET_TAG(scb));
2749 	ahd_dump_sglist(scb);
2750 }
2751 
2752 void
2753 ahd_dump_sglist(struct scb *scb)
2754 {
2755 	int i;
2756 
2757 	if (scb->sg_count > 0) {
2758 		if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) {
2759 			struct ahd_dma64_seg *sg_list;
2760 
2761 			sg_list = (struct ahd_dma64_seg*)scb->sg_list;
2762 			for (i = 0; i < scb->sg_count; i++) {
2763 				uint64_t addr;
2764 
2765 				addr = aic_le64toh(sg_list[i].addr);
2766 				printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
2767 				       i,
2768 				       (uint32_t)((addr >> 32) & 0xFFFFFFFF),
2769 				       (uint32_t)(addr & 0xFFFFFFFF),
2770 				       sg_list[i].len & AHD_SG_LEN_MASK,
2771 				       (sg_list[i].len & AHD_DMA_LAST_SEG)
2772 				     ? " Last" : "");
2773 			}
2774 		} else {
2775 			struct ahd_dma_seg *sg_list;
2776 
2777 			sg_list = (struct ahd_dma_seg*)scb->sg_list;
2778 			for (i = 0; i < scb->sg_count; i++) {
2779 				uint32_t len;
2780 
2781 				len = aic_le32toh(sg_list[i].len);
2782 				printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
2783 				       i,
2784 				       (len & AHD_SG_HIGH_ADDR_MASK) >> 24,
2785 				       aic_le32toh(sg_list[i].addr),
2786 				       len & AHD_SG_LEN_MASK,
2787 				       len & AHD_DMA_LAST_SEG ? " Last" : "");
2788 			}
2789 		}
2790 	}
2791 }
2792 
2793 /************************* Transfer Negotiation *******************************/
2794 /*
2795  * Allocate per target mode instance (ID we respond to as a target)
2796  * transfer negotiation data structures.
2797  */
2798 static struct ahd_tmode_tstate *
2799 ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel)
2800 {
2801 	struct ahd_tmode_tstate *master_tstate;
2802 	struct ahd_tmode_tstate *tstate;
2803 	int i;
2804 
2805 	master_tstate = ahd->enabled_targets[ahd->our_id];
2806 	if (ahd->enabled_targets[scsi_id] != NULL
2807 	 && ahd->enabled_targets[scsi_id] != master_tstate)
2808 		panic("%s: ahd_alloc_tstate - Target already allocated",
2809 		      ahd_name(ahd));
2810 	tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT);
2811 	if (tstate == NULL)
2812 		return (NULL);
2813 
2814 	/*
2815 	 * If we have allocated a master tstate, copy user settings from
2816 	 * the master tstate (taken from SRAM or the EEPROM) for this
2817 	 * channel, but reset our current and goal settings to async/narrow
2818 	 * until an initiator talks to us.
2819 	 */
2820 	if (master_tstate != NULL) {
2821 		memcpy(tstate, master_tstate, sizeof(*tstate));
2822 		memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
2823 		for (i = 0; i < 16; i++) {
2824 			memset(&tstate->transinfo[i].curr, 0,
2825 			      sizeof(tstate->transinfo[i].curr));
2826 			memset(&tstate->transinfo[i].goal, 0,
2827 			      sizeof(tstate->transinfo[i].goal));
2828 		}
2829 	} else
2830 		memset(tstate, 0, sizeof(*tstate));
2831 	ahd->enabled_targets[scsi_id] = tstate;
2832 	return (tstate);
2833 }
2834 
2835 #ifdef AHD_TARGET_MODE
2836 /*
2837  * Free per target mode instance (ID we respond to as a target)
2838  * transfer negotiation data structures.
2839  */
2840 static void
2841 ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force)
2842 {
2843 	struct ahd_tmode_tstate *tstate;
2844 
2845 	/*
2846 	 * Don't clean up our "master" tstate.
2847 	 * It has our default user settings.
2848 	 */
2849 	if (scsi_id == ahd->our_id
2850 	 && force == FALSE)
2851 		return;
2852 
2853 	tstate = ahd->enabled_targets[scsi_id];
2854 	if (tstate != NULL)
2855 		free(tstate, M_DEVBUF);
2856 	ahd->enabled_targets[scsi_id] = NULL;
2857 }
2858 #endif
2859 
2860 /*
2861  * Called when we have an active connection to a target on the bus,
2862  * this function finds the nearest period to the input period limited
2863  * by the capabilities of the bus connectivity of and sync settings for
2864  * the target.
2865  */
2866 void
2867 ahd_devlimited_syncrate(struct ahd_softc *ahd,
2868 			struct ahd_initiator_tinfo *tinfo,
2869 			u_int *period, u_int *ppr_options, role_t role)
2870 {
2871 	struct	ahd_transinfo *transinfo;
2872 	u_int	maxsync;
2873 
2874 	if ((ahd_inb(ahd, SBLKCTL) & ENAB40) != 0
2875 	 && (ahd_inb(ahd, SSTAT2) & EXP_ACTIVE) == 0) {
2876 		maxsync = AHD_SYNCRATE_PACED;
2877 	} else {
2878 		maxsync = AHD_SYNCRATE_ULTRA;
2879 		/* Can't do DT related options on an SE bus */
2880 		*ppr_options &= MSG_EXT_PPR_QAS_REQ;
2881 	}
2882 	/*
2883 	 * Never allow a value higher than our current goal
2884 	 * period otherwise we may allow a target initiated
2885 	 * negotiation to go above the limit as set by the
2886 	 * user.  In the case of an initiator initiated
2887 	 * sync negotiation, we limit based on the user
2888 	 * setting.  This allows the system to still accept
2889 	 * incoming negotiations even if target initiated
2890 	 * negotiation is not performed.
2891 	 */
2892 	if (role == ROLE_TARGET)
2893 		transinfo = &tinfo->user;
2894 	else
2895 		transinfo = &tinfo->goal;
2896 	*ppr_options &= (transinfo->ppr_options|MSG_EXT_PPR_PCOMP_EN);
2897 	if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
2898 		maxsync = MAX(maxsync, AHD_SYNCRATE_ULTRA2);
2899 		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2900 	}
2901 	if (transinfo->period == 0) {
2902 		*period = 0;
2903 		*ppr_options = 0;
2904 	} else {
2905 		*period = MAX(*period, transinfo->period);
2906 		ahd_find_syncrate(ahd, period, ppr_options, maxsync);
2907 	}
2908 }
2909 
2910 /*
2911  * Look up the valid period to SCSIRATE conversion in our table.
2912  * Return the period and offset that should be sent to the target
2913  * if this was the beginning of an SDTR.
2914  */
2915 void
2916 ahd_find_syncrate(struct ahd_softc *ahd, u_int *period,
2917 		  u_int *ppr_options, u_int maxsync)
2918 {
2919 	if (*period < maxsync)
2920 		*period = maxsync;
2921 
2922 	if ((*ppr_options & MSG_EXT_PPR_DT_REQ) != 0
2923 	 && *period > AHD_SYNCRATE_MIN_DT)
2924 		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2925 
2926 	if (*period > AHD_SYNCRATE_MIN)
2927 		*period = 0;
2928 
2929 	/* Honor PPR option conformance rules. */
2930 	if (*period > AHD_SYNCRATE_PACED)
2931 		*ppr_options &= ~MSG_EXT_PPR_RTI;
2932 
2933 	if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
2934 		*ppr_options &= (MSG_EXT_PPR_DT_REQ|MSG_EXT_PPR_QAS_REQ);
2935 
2936 	if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0)
2937 		*ppr_options &= MSG_EXT_PPR_QAS_REQ;
2938 
2939 	/* Skip all PACED only entries if IU is not available */
2940 	if ((*ppr_options & MSG_EXT_PPR_IU_REQ) == 0
2941 	 && *period < AHD_SYNCRATE_DT)
2942 		*period = AHD_SYNCRATE_DT;
2943 
2944 	/* Skip all DT only entries if DT is not available */
2945 	if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
2946 	 && *period < AHD_SYNCRATE_ULTRA2)
2947 		*period = AHD_SYNCRATE_ULTRA2;
2948 }
2949 
2950 /*
2951  * Truncate the given synchronous offset to a value the
2952  * current adapter type and syncrate are capable of.
2953  */
2954 void
2955 ahd_validate_offset(struct ahd_softc *ahd,
2956 		    struct ahd_initiator_tinfo *tinfo,
2957 		    u_int period, u_int *offset, int wide,
2958 		    role_t role)
2959 {
2960 	u_int maxoffset;
2961 
2962 	/* Limit offset to what we can do */
2963 	if (period == 0)
2964 		maxoffset = 0;
2965 	else if (period <= AHD_SYNCRATE_PACED) {
2966 		if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0)
2967 			maxoffset = MAX_OFFSET_PACED_BUG;
2968 		else
2969 			maxoffset = MAX_OFFSET_PACED;
2970 	} else
2971 		maxoffset = MAX_OFFSET_NON_PACED;
2972 	*offset = MIN(*offset, maxoffset);
2973 	if (tinfo != NULL) {
2974 		if (role == ROLE_TARGET)
2975 			*offset = MIN(*offset, tinfo->user.offset);
2976 		else
2977 			*offset = MIN(*offset, tinfo->goal.offset);
2978 	}
2979 }
2980 
2981 /*
2982  * Truncate the given transfer width parameter to a value the
2983  * current adapter type is capable of.
2984  */
2985 void
2986 ahd_validate_width(struct ahd_softc *ahd, struct ahd_initiator_tinfo *tinfo,
2987 		   u_int *bus_width, role_t role)
2988 {
2989 	switch (*bus_width) {
2990 	default:
2991 		if (ahd->features & AHD_WIDE) {
2992 			/* Respond Wide */
2993 			*bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2994 			break;
2995 		}
2996 		/* FALLTHROUGH */
2997 	case MSG_EXT_WDTR_BUS_8_BIT:
2998 		*bus_width = MSG_EXT_WDTR_BUS_8_BIT;
2999 		break;
3000 	}
3001 	if (tinfo != NULL) {
3002 		if (role == ROLE_TARGET)
3003 			*bus_width = MIN(tinfo->user.width, *bus_width);
3004 		else
3005 			*bus_width = MIN(tinfo->goal.width, *bus_width);
3006 	}
3007 }
3008 
3009 /*
3010  * Update the bitmask of targets for which the controller should
3011  * negotiate with at the next convenient opportunity.  This currently
3012  * means the next time we send the initial identify messages for
3013  * a new transaction.
3014  */
3015 int
3016 ahd_update_neg_request(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3017 		       struct ahd_tmode_tstate *tstate,
3018 		       struct ahd_initiator_tinfo *tinfo, ahd_neg_type neg_type)
3019 {
3020 	u_int auto_negotiate_orig;
3021 
3022 	auto_negotiate_orig = tstate->auto_negotiate;
3023 	if (neg_type == AHD_NEG_ALWAYS) {
3024 		/*
3025 		 * Force our "current" settings to be
3026 		 * unknown so that unless a bus reset
3027 		 * occurs the need to renegotiate is
3028 		 * recorded persistently.
3029 		 */
3030 		if ((ahd->features & AHD_WIDE) != 0)
3031 			tinfo->curr.width = AHD_WIDTH_UNKNOWN;
3032 		tinfo->curr.period = AHD_PERIOD_UNKNOWN;
3033 		tinfo->curr.offset = AHD_OFFSET_UNKNOWN;
3034 	}
3035 	if (tinfo->curr.period != tinfo->goal.period
3036 	 || tinfo->curr.width != tinfo->goal.width
3037 	 || tinfo->curr.offset != tinfo->goal.offset
3038 	 || tinfo->curr.ppr_options != tinfo->goal.ppr_options
3039 	 || (neg_type == AHD_NEG_IF_NON_ASYNC
3040 	  && (tinfo->goal.offset != 0
3041 	   || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
3042 	   || tinfo->goal.ppr_options != 0)))
3043 		tstate->auto_negotiate |= devinfo->target_mask;
3044 	else
3045 		tstate->auto_negotiate &= ~devinfo->target_mask;
3046 
3047 	return (auto_negotiate_orig != tstate->auto_negotiate);
3048 }
3049 
3050 /*
3051  * Update the user/goal/curr tables of synchronous negotiation
3052  * parameters as well as, in the case of a current or active update,
3053  * any data structures on the host controller.  In the case of an
3054  * active update, the specified target is currently talking to us on
3055  * the bus, so the transfer parameter update must take effect
3056  * immediately.
3057  */
3058 void
3059 ahd_set_syncrate(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3060 		 u_int period, u_int offset, u_int ppr_options,
3061 		 u_int type, int paused)
3062 {
3063 	struct	ahd_initiator_tinfo *tinfo;
3064 	struct	ahd_tmode_tstate *tstate;
3065 	u_int	old_period;
3066 	u_int	old_offset;
3067 	u_int	old_ppr;
3068 	int	active;
3069 	int	update_needed;
3070 
3071 	active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
3072 	update_needed = 0;
3073 
3074 	if (period == 0 || offset == 0) {
3075 		period = 0;
3076 		offset = 0;
3077 	}
3078 
3079 	tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3080 				    devinfo->target, &tstate);
3081 
3082 	if ((type & AHD_TRANS_USER) != 0) {
3083 		tinfo->user.period = period;
3084 		tinfo->user.offset = offset;
3085 		tinfo->user.ppr_options = ppr_options;
3086 	}
3087 
3088 	if ((type & AHD_TRANS_GOAL) != 0) {
3089 		tinfo->goal.period = period;
3090 		tinfo->goal.offset = offset;
3091 		tinfo->goal.ppr_options = ppr_options;
3092 	}
3093 
3094 	old_period = tinfo->curr.period;
3095 	old_offset = tinfo->curr.offset;
3096 	old_ppr	   = tinfo->curr.ppr_options;
3097 
3098 	if ((type & AHD_TRANS_CUR) != 0
3099 	 && (old_period != period
3100 	  || old_offset != offset
3101 	  || old_ppr != ppr_options)) {
3102 		update_needed++;
3103 
3104 		tinfo->curr.period = period;
3105 		tinfo->curr.offset = offset;
3106 		tinfo->curr.ppr_options = ppr_options;
3107 
3108 		ahd_send_async(ahd, devinfo->channel, devinfo->target,
3109 			       CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
3110 		if (bootverbose) {
3111 			if (offset != 0) {
3112 				int options;
3113 
3114 				printf("%s: target %d synchronous with "
3115 				       "period = 0x%x, offset = 0x%x",
3116 				       ahd_name(ahd), devinfo->target,
3117 				       period, offset);
3118 				options = 0;
3119 				if ((ppr_options & MSG_EXT_PPR_RD_STRM) != 0) {
3120 					printf("(RDSTRM");
3121 					options++;
3122 				}
3123 				if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0) {
3124 					printf("%s", options ? "|DT" : "(DT");
3125 					options++;
3126 				}
3127 				if ((ppr_options & MSG_EXT_PPR_IU_REQ) != 0) {
3128 					printf("%s", options ? "|IU" : "(IU");
3129 					options++;
3130 				}
3131 				if ((ppr_options & MSG_EXT_PPR_RTI) != 0) {
3132 					printf("%s", options ? "|RTI" : "(RTI");
3133 					options++;
3134 				}
3135 				if ((ppr_options & MSG_EXT_PPR_QAS_REQ) != 0) {
3136 					printf("%s", options ? "|QAS" : "(QAS");
3137 					options++;
3138 				}
3139 				if (options != 0)
3140 					printf(")\n");
3141 				else
3142 					printf("\n");
3143 			} else {
3144 				printf("%s: target %d using "
3145 				       "asynchronous transfers%s\n",
3146 				       ahd_name(ahd), devinfo->target,
3147 				       (ppr_options & MSG_EXT_PPR_QAS_REQ) != 0
3148 				     ?  "(QAS)" : "");
3149 			}
3150 		}
3151 	}
3152 	/*
3153 	 * Always refresh the neg-table to handle the case of the
3154 	 * sequencer setting the ENATNO bit for a MK_MESSAGE request.
3155 	 * We will always renegotiate in that case if this is a
3156 	 * packetized request.  Also manage the busfree expected flag
3157 	 * from this common routine so that we catch changes due to
3158 	 * WDTR or SDTR messages.
3159 	 */
3160 	if ((type & AHD_TRANS_CUR) != 0) {
3161 		if (!paused)
3162 			ahd_pause(ahd);
3163 		ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
3164 		if (!paused)
3165 			ahd_unpause(ahd);
3166 		if (ahd->msg_type != MSG_TYPE_NONE) {
3167 			if ((old_ppr & MSG_EXT_PPR_IU_REQ)
3168 			 != (ppr_options & MSG_EXT_PPR_IU_REQ)) {
3169 #ifdef AHD_DEBUG
3170 				if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3171 					ahd_print_devinfo(ahd, devinfo);
3172 					printf("Expecting IU Change busfree\n");
3173 				}
3174 #endif
3175 				ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
3176 					       |  MSG_FLAG_IU_REQ_CHANGED;
3177 			}
3178 			if ((old_ppr & MSG_EXT_PPR_IU_REQ) != 0) {
3179 #ifdef AHD_DEBUG
3180 				if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3181 					printf("PPR with IU_REQ outstanding\n");
3182 #endif
3183 				ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE;
3184 			}
3185 		}
3186 	}
3187 
3188 	update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
3189 						tinfo, AHD_NEG_TO_GOAL);
3190 
3191 	if (update_needed && active)
3192 		ahd_update_pending_scbs(ahd);
3193 }
3194 
3195 /*
3196  * Update the user/goal/curr tables of wide negotiation
3197  * parameters as well as, in the case of a current or active update,
3198  * any data structures on the host controller.  In the case of an
3199  * active update, the specified target is currently talking to us on
3200  * the bus, so the transfer parameter update must take effect
3201  * immediately.
3202  */
3203 void
3204 ahd_set_width(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3205 	      u_int width, u_int type, int paused)
3206 {
3207 	struct	ahd_initiator_tinfo *tinfo;
3208 	struct	ahd_tmode_tstate *tstate;
3209 	u_int	oldwidth;
3210 	int	active;
3211 	int	update_needed;
3212 
3213 	active = (type & AHD_TRANS_ACTIVE) == AHD_TRANS_ACTIVE;
3214 	update_needed = 0;
3215 	tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3216 				    devinfo->target, &tstate);
3217 
3218 	if ((type & AHD_TRANS_USER) != 0)
3219 		tinfo->user.width = width;
3220 
3221 	if ((type & AHD_TRANS_GOAL) != 0)
3222 		tinfo->goal.width = width;
3223 
3224 	oldwidth = tinfo->curr.width;
3225 	if ((type & AHD_TRANS_CUR) != 0 && oldwidth != width) {
3226 		update_needed++;
3227 
3228 		tinfo->curr.width = width;
3229 		ahd_send_async(ahd, devinfo->channel, devinfo->target,
3230 			       CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
3231 		if (bootverbose) {
3232 			printf("%s: target %d using %dbit transfers\n",
3233 			       ahd_name(ahd), devinfo->target,
3234 			       8 * (0x01 << width));
3235 		}
3236 	}
3237 
3238 	if ((type & AHD_TRANS_CUR) != 0) {
3239 		if (!paused)
3240 			ahd_pause(ahd);
3241 		ahd_update_neg_table(ahd, devinfo, &tinfo->curr);
3242 		if (!paused)
3243 			ahd_unpause(ahd);
3244 	}
3245 
3246 	update_needed += ahd_update_neg_request(ahd, devinfo, tstate,
3247 						tinfo, AHD_NEG_TO_GOAL);
3248 	if (update_needed && active)
3249 		ahd_update_pending_scbs(ahd);
3250 
3251 }
3252 
3253 /*
3254  * Update the current state of tagged queuing for a given target.
3255  */
3256 void
3257 ahd_set_tags(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3258 	     ahd_queue_alg alg)
3259 {
3260 	ahd_platform_set_tags(ahd, devinfo, alg);
3261 	ahd_send_async(ahd, devinfo->channel, devinfo->target,
3262 		       devinfo->lun, AC_TRANSFER_NEG, &alg);
3263 }
3264 
3265 static void
3266 ahd_update_neg_table(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3267 		     struct ahd_transinfo *tinfo)
3268 {
3269 	ahd_mode_state	saved_modes;
3270 	u_int		period;
3271 	u_int		ppr_opts;
3272 	u_int		con_opts;
3273 	u_int		offset;
3274 	u_int		saved_negoaddr;
3275 	uint8_t		iocell_opts[sizeof(ahd->iocell_opts)];
3276 
3277 	saved_modes = ahd_save_modes(ahd);
3278 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3279 
3280 	saved_negoaddr = ahd_inb(ahd, NEGOADDR);
3281 	ahd_outb(ahd, NEGOADDR, devinfo->target);
3282 	period = tinfo->period;
3283 	offset = tinfo->offset;
3284 	memcpy(iocell_opts, ahd->iocell_opts, sizeof(ahd->iocell_opts));
3285 	ppr_opts = tinfo->ppr_options & (MSG_EXT_PPR_QAS_REQ|MSG_EXT_PPR_DT_REQ
3286 					|MSG_EXT_PPR_IU_REQ|MSG_EXT_PPR_RTI);
3287 	con_opts = 0;
3288 	if (period == 0)
3289 		period = AHD_SYNCRATE_ASYNC;
3290 	if (period == AHD_SYNCRATE_160) {
3291 		if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
3292 			/*
3293 			 * When the SPI4 spec was finalized, PACE transfers
3294 			 * was not made a configurable option in the PPR
3295 			 * message.  Instead it is assumed to be enabled for
3296 			 * any syncrate faster than 80MHz.  Nevertheless,
3297 			 * Harpoon2A4 allows this to be configurable.
3298 			 *
3299 			 * Harpoon2A4 also assumes at most 2 data bytes per
3300 			 * negotiated REQ/ACK offset.  Paced transfers take
3301 			 * 4, so we must adjust our offset.
3302 			 */
3303 			ppr_opts |= PPROPT_PACE;
3304 			offset *= 2;
3305 
3306 			/*
3307 			 * Harpoon2A assumed that there would be a
3308 			 * fallback rate between 160MHz and 80Mhz,
3309 			 * so 7 is used as the period factor rather
3310 			 * than 8 for 160MHz.
3311 			 */
3312 			period = AHD_SYNCRATE_REVA_160;
3313 		}
3314 		if ((tinfo->ppr_options & MSG_EXT_PPR_PCOMP_EN) == 0)
3315 			iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
3316 			    ~AHD_PRECOMP_MASK;
3317 	} else {
3318 		/*
3319 		 * Precomp should be disabled for non-paced transfers.
3320 		 */
3321 		iocell_opts[AHD_PRECOMP_SLEW_INDEX] &= ~AHD_PRECOMP_MASK;
3322 
3323 		if ((ahd->features & AHD_NEW_IOCELL_OPTS) != 0
3324 		 && (ppr_opts & MSG_EXT_PPR_DT_REQ) != 0
3325 		 && (ppr_opts & MSG_EXT_PPR_IU_REQ) == 0) {
3326 			/*
3327 			 * Slow down our CRC interval to be
3328 			 * compatible with non-packetized
3329 			 * U160 devices that can't handle a
3330 			 * CRC at full speed.
3331 			 */
3332 			con_opts |= ENSLOWCRC;
3333 		}
3334 
3335 		if ((ahd->bugs & AHD_PACED_NEGTABLE_BUG) != 0) {
3336 			/*
3337 			 * On H2A4, revert to a slower slewrate
3338 			 * on non-paced transfers.
3339 			 */
3340 			iocell_opts[AHD_PRECOMP_SLEW_INDEX] &=
3341 			    ~AHD_SLEWRATE_MASK;
3342 		}
3343 	}
3344 
3345 	ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PRECOMP_SLEW);
3346 	ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_PRECOMP_SLEW_INDEX]);
3347 	ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_AMPLITUDE);
3348 	ahd_outb(ahd, ANNEXDAT, iocell_opts[AHD_AMPLITUDE_INDEX]);
3349 
3350 	ahd_outb(ahd, NEGPERIOD, period);
3351 	ahd_outb(ahd, NEGPPROPTS, ppr_opts);
3352 	ahd_outb(ahd, NEGOFFSET, offset);
3353 
3354 	if (tinfo->width == MSG_EXT_WDTR_BUS_16_BIT)
3355 		con_opts |= WIDEXFER;
3356 
3357 	/*
3358 	 * During packetized transfers, the target will
3359 	 * give us the opportunity to send command packets
3360 	 * without us asserting attention.
3361 	 */
3362 	if ((tinfo->ppr_options & MSG_EXT_PPR_IU_REQ) == 0)
3363 		con_opts |= ENAUTOATNO;
3364 	ahd_outb(ahd, NEGCONOPTS, con_opts);
3365 	ahd_outb(ahd, NEGOADDR, saved_negoaddr);
3366 	ahd_restore_modes(ahd, saved_modes);
3367 }
3368 
3369 /*
3370  * When the transfer settings for a connection change, setup for
3371  * negotiation in pending SCBs to effect the change as quickly as
3372  * possible.  We also cancel any negotiations that are scheduled
3373  * for inflight SCBs that have not been started yet.
3374  */
3375 static void
3376 ahd_update_pending_scbs(struct ahd_softc *ahd)
3377 {
3378 	struct		scb *pending_scb;
3379 	int		pending_scb_count;
3380 	int		paused;
3381 	u_int		saved_scbptr;
3382 	ahd_mode_state	saved_modes;
3383 
3384 	/*
3385 	 * Traverse the pending SCB list and ensure that all of the
3386 	 * SCBs there have the proper settings.  We can only safely
3387 	 * clear the negotiation required flag (setting requires the
3388 	 * execution queue to be modified) and this is only possible
3389 	 * if we are not already attempting to select out for this
3390 	 * SCB.  For this reason, all callers only call this routine
3391 	 * if we are changing the negotiation settings for the currently
3392 	 * active transaction on the bus.
3393 	 */
3394 	pending_scb_count = 0;
3395 	LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
3396 		struct ahd_devinfo devinfo;
3397 		struct ahd_tmode_tstate *tstate;
3398 
3399 		ahd_scb_devinfo(ahd, &devinfo, pending_scb);
3400 		ahd_fetch_transinfo(ahd, devinfo.channel,
3401 				    devinfo.our_scsiid,
3402 				    devinfo.target, &tstate);
3403 		if ((tstate->auto_negotiate & devinfo.target_mask) == 0
3404 		 && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
3405 			pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
3406 			pending_scb->hscb->control &= ~MK_MESSAGE;
3407 		}
3408 		ahd_sync_scb(ahd, pending_scb,
3409 			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
3410 		pending_scb_count++;
3411 	}
3412 
3413 	if (pending_scb_count == 0)
3414 		return;
3415 
3416 	if (ahd_is_paused(ahd)) {
3417 		paused = 1;
3418 	} else {
3419 		paused = 0;
3420 		ahd_pause(ahd);
3421 	}
3422 
3423 	/*
3424 	 * Force the sequencer to reinitialize the selection for
3425 	 * the command at the head of the execution queue if it
3426 	 * has already been setup.  The negotiation changes may
3427 	 * effect whether we select-out with ATN.  It is only
3428 	 * safe to clear ENSELO when the bus is not free and no
3429 	 * selection is in progres or completed.
3430 	 */
3431 	saved_modes = ahd_save_modes(ahd);
3432 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3433 	if ((ahd_inb(ahd, SCSISIGI) & BSYI) != 0
3434 	 && (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) == 0)
3435 		ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
3436 	saved_scbptr = ahd_get_scbptr(ahd);
3437 	/* Ensure that the hscbs down on the card match the new information */
3438 	LIST_FOREACH(pending_scb, &ahd->pending_scbs, pending_links) {
3439 		u_int	scb_tag;
3440 		u_int	control;
3441 
3442 		scb_tag = SCB_GET_TAG(pending_scb);
3443 		ahd_set_scbptr(ahd, scb_tag);
3444 		control = ahd_inb_scbram(ahd, SCB_CONTROL);
3445 		control &= ~MK_MESSAGE;
3446 		control |= pending_scb->hscb->control & MK_MESSAGE;
3447 		ahd_outb(ahd, SCB_CONTROL, control);
3448 	}
3449 	ahd_set_scbptr(ahd, saved_scbptr);
3450 	ahd_restore_modes(ahd, saved_modes);
3451 
3452 	if (paused == 0)
3453 		ahd_unpause(ahd);
3454 }
3455 
3456 /**************************** Pathing Information *****************************/
3457 static void
3458 ahd_fetch_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3459 {
3460 	ahd_mode_state	saved_modes;
3461 	u_int		saved_scsiid;
3462 	role_t		role;
3463 	int		our_id;
3464 
3465 	saved_modes = ahd_save_modes(ahd);
3466 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3467 
3468 	if (ahd_inb(ahd, SSTAT0) & TARGET)
3469 		role = ROLE_TARGET;
3470 	else
3471 		role = ROLE_INITIATOR;
3472 
3473 	if (role == ROLE_TARGET
3474 	 && (ahd_inb(ahd, SEQ_FLAGS) & CMDPHASE_PENDING) != 0) {
3475 		/* We were selected, so pull our id from TARGIDIN */
3476 		our_id = ahd_inb(ahd, TARGIDIN) & OID;
3477 	} else if (role == ROLE_TARGET)
3478 		our_id = ahd_inb(ahd, TOWNID);
3479 	else
3480 		our_id = ahd_inb(ahd, IOWNID);
3481 
3482 	saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
3483 	ahd_compile_devinfo(devinfo,
3484 			    our_id,
3485 			    SCSIID_TARGET(ahd, saved_scsiid),
3486 			    ahd_inb(ahd, SAVED_LUN),
3487 			    SCSIID_CHANNEL(ahd, saved_scsiid),
3488 			    role);
3489 	ahd_restore_modes(ahd, saved_modes);
3490 }
3491 
3492 void
3493 ahd_print_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3494 {
3495 	printf("%s:%c:%d:%d: ", ahd_name(ahd), 'A',
3496 	       devinfo->target, devinfo->lun);
3497 }
3498 
3499 struct ahd_phase_table_entry*
3500 ahd_lookup_phase_entry(int phase)
3501 {
3502 	struct ahd_phase_table_entry *entry;
3503 	struct ahd_phase_table_entry *last_entry;
3504 
3505 	/*
3506 	 * num_phases doesn't include the default entry which
3507 	 * will be returned if the phase doesn't match.
3508 	 */
3509 	last_entry = &ahd_phase_table[num_phases];
3510 	for (entry = ahd_phase_table; entry < last_entry; entry++) {
3511 		if (phase == entry->phase)
3512 			break;
3513 	}
3514 	return (entry);
3515 }
3516 
3517 void
3518 ahd_compile_devinfo(struct ahd_devinfo *devinfo, u_int our_id, u_int target,
3519 		    u_int lun, char channel, role_t role)
3520 {
3521 	devinfo->our_scsiid = our_id;
3522 	devinfo->target = target;
3523 	devinfo->lun = lun;
3524 	devinfo->target_offset = target;
3525 	devinfo->channel = channel;
3526 	devinfo->role = role;
3527 	if (channel == 'B')
3528 		devinfo->target_offset += 8;
3529 	devinfo->target_mask = (0x01 << devinfo->target_offset);
3530 }
3531 
3532 static void
3533 ahd_scb_devinfo(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3534 		struct scb *scb)
3535 {
3536 	role_t	role;
3537 	int	our_id;
3538 
3539 	our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
3540 	role = ROLE_INITIATOR;
3541 	if ((scb->hscb->control & TARGET_SCB) != 0)
3542 		role = ROLE_TARGET;
3543 	ahd_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahd, scb),
3544 			    SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahd, scb), role);
3545 }
3546 
3547 /************************ Message Phase Processing ****************************/
3548 /*
3549  * When an initiator transaction with the MK_MESSAGE flag either reconnects
3550  * or enters the initial message out phase, we are interrupted.  Fill our
3551  * outgoing message buffer with the appropriate message and beging handing
3552  * the message phase(s) manually.
3553  */
3554 static void
3555 ahd_setup_initiator_msgout(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3556 			   struct scb *scb)
3557 {
3558 	/*
3559 	 * To facilitate adding multiple messages together,
3560 	 * each routine should increment the index and len
3561 	 * variables instead of setting them explicitly.
3562 	 */
3563 	ahd->msgout_index = 0;
3564 	ahd->msgout_len = 0;
3565 
3566 	if (ahd_currently_packetized(ahd))
3567 		ahd->msg_flags |= MSG_FLAG_PACKETIZED;
3568 
3569 	if (ahd->send_msg_perror
3570 	 && ahd_inb(ahd, MSG_OUT) == HOST_MSG) {
3571 		ahd->msgout_buf[ahd->msgout_index++] = ahd->send_msg_perror;
3572 		ahd->msgout_len++;
3573 		ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3574 #ifdef AHD_DEBUG
3575 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3576 			printf("Setting up for Parity Error delivery\n");
3577 #endif
3578 		return;
3579 	} else if (scb == NULL) {
3580 		printf("%s: WARNING. No pending message for "
3581 		       "I_T msgin.  Issuing NO-OP\n", ahd_name(ahd));
3582 		AHD_CORRECTABLE_ERROR(ahd);
3583 		ahd->msgout_buf[ahd->msgout_index++] = MSG_NOOP;
3584 		ahd->msgout_len++;
3585 		ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3586 		return;
3587 	}
3588 
3589 	if ((scb->flags & SCB_DEVICE_RESET) == 0
3590 	 && (scb->flags & SCB_PACKETIZED) == 0
3591 	 && ahd_inb(ahd, MSG_OUT) == MSG_IDENTIFYFLAG) {
3592 		u_int identify_msg;
3593 
3594 		identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
3595 		if ((scb->hscb->control & DISCENB) != 0)
3596 			identify_msg |= MSG_IDENTIFY_DISCFLAG;
3597 		ahd->msgout_buf[ahd->msgout_index++] = identify_msg;
3598 		ahd->msgout_len++;
3599 
3600 		if ((scb->hscb->control & TAG_ENB) != 0) {
3601 			ahd->msgout_buf[ahd->msgout_index++] =
3602 			    scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
3603 			ahd->msgout_buf[ahd->msgout_index++] = SCB_GET_TAG(scb);
3604 			ahd->msgout_len += 2;
3605 		}
3606 	}
3607 
3608 	if (scb->flags & SCB_DEVICE_RESET) {
3609 		ahd->msgout_buf[ahd->msgout_index++] = MSG_BUS_DEV_RESET;
3610 		ahd->msgout_len++;
3611 		ahd_print_path(ahd, scb);
3612 		printf("Bus Device Reset Message Sent\n");
3613 		AHD_CORRECTABLE_ERROR(ahd);
3614 		/*
3615 		 * Clear our selection hardware in advance of
3616 		 * the busfree.  We may have an entry in the waiting
3617 		 * Q for this target, and we don't want to go about
3618 		 * selecting while we handle the busfree and blow it
3619 		 * away.
3620 		 */
3621 		ahd_outb(ahd, SCSISEQ0, 0);
3622 	} else if ((scb->flags & SCB_ABORT) != 0) {
3623 		if ((scb->hscb->control & TAG_ENB) != 0) {
3624 			ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT_TAG;
3625 		} else {
3626 			ahd->msgout_buf[ahd->msgout_index++] = MSG_ABORT;
3627 		}
3628 		ahd->msgout_len++;
3629 		ahd_print_path(ahd, scb);
3630 		printf("Abort%s Message Sent\n",
3631 		       (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
3632 		AHD_CORRECTABLE_ERROR(ahd);
3633 		/*
3634 		 * Clear our selection hardware in advance of
3635 		 * the busfree.  We may have an entry in the waiting
3636 		 * Q for this target, and we don't want to go about
3637 		 * selecting while we handle the busfree and blow it
3638 		 * away.
3639 		 */
3640 		ahd_outb(ahd, SCSISEQ0, 0);
3641 	} else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
3642 		ahd_build_transfer_msg(ahd, devinfo);
3643 		/*
3644 		 * Clear our selection hardware in advance of potential
3645 		 * PPR IU status change busfree.  We may have an entry in
3646 		 * the waiting Q for this target, and we don't want to go
3647 		 * about selecting while we handle the busfree and blow
3648 		 * it away.
3649 		 */
3650 		ahd_outb(ahd, SCSISEQ0, 0);
3651 	} else {
3652 		printf("ahd_intr: AWAITING_MSG for an SCB that "
3653 		       "does not have a waiting message\n");
3654 		printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
3655 		       devinfo->target_mask);
3656 		AHD_FATAL_ERROR(ahd);
3657 		panic("SCB = %d, SCB Control = %x:%x, MSG_OUT = %x "
3658 		      "SCB flags = %x", SCB_GET_TAG(scb), scb->hscb->control,
3659 		      ahd_inb_scbram(ahd, SCB_CONTROL), ahd_inb(ahd, MSG_OUT),
3660 		      scb->flags);
3661 	}
3662 
3663 	/*
3664 	 * Clear the MK_MESSAGE flag from the SCB so we aren't
3665 	 * asked to send this message again.
3666 	 */
3667 	ahd_outb(ahd, SCB_CONTROL,
3668 		 ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
3669 	scb->hscb->control &= ~MK_MESSAGE;
3670 	ahd->msgout_index = 0;
3671 	ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3672 }
3673 
3674 /*
3675  * Build an appropriate transfer negotiation message for the
3676  * currently active target.
3677  */
3678 static void
3679 ahd_build_transfer_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
3680 {
3681 	/*
3682 	 * We need to initiate transfer negotiations.
3683 	 * If our current and goal settings are identical,
3684 	 * we want to renegotiate due to a check condition.
3685 	 */
3686 	struct	ahd_initiator_tinfo *tinfo;
3687 	struct	ahd_tmode_tstate *tstate;
3688 	int	dowide;
3689 	int	dosync;
3690 	int	doppr;
3691 	u_int	period;
3692 	u_int	ppr_options;
3693 	u_int	offset;
3694 
3695 	tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
3696 				    devinfo->target, &tstate);
3697 	/*
3698 	 * Filter our period based on the current connection.
3699 	 * If we can't perform DT transfers on this segment (not in LVD
3700 	 * mode for instance), then our decision to issue a PPR message
3701 	 * may change.
3702 	 */
3703 	period = tinfo->goal.period;
3704 	offset = tinfo->goal.offset;
3705 	ppr_options = tinfo->goal.ppr_options;
3706 	/* Target initiated PPR is not allowed in the SCSI spec */
3707 	if (devinfo->role == ROLE_TARGET)
3708 		ppr_options = 0;
3709 	ahd_devlimited_syncrate(ahd, tinfo, &period,
3710 				&ppr_options, devinfo->role);
3711 	dowide = tinfo->curr.width != tinfo->goal.width;
3712 	dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
3713 	/*
3714 	 * Only use PPR if we have options that need it, even if the device
3715 	 * claims to support it.  There might be an expander in the way
3716 	 * that doesn't.
3717 	 */
3718 	doppr = ppr_options != 0;
3719 
3720 	if (!dowide && !dosync && !doppr) {
3721 		dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
3722 		dosync = tinfo->goal.offset != 0;
3723 	}
3724 
3725 	if (!dowide && !dosync && !doppr) {
3726 		/*
3727 		 * Force async with a WDTR message if we have a wide bus,
3728 		 * or just issue an SDTR with a 0 offset.
3729 		 */
3730 		if ((ahd->features & AHD_WIDE) != 0)
3731 			dowide = 1;
3732 		else
3733 			dosync = 1;
3734 
3735 		if (bootverbose) {
3736 			ahd_print_devinfo(ahd, devinfo);
3737 			printf("Ensuring async\n");
3738 		}
3739 	}
3740 	/* Target initiated PPR is not allowed in the SCSI spec */
3741 	if (devinfo->role == ROLE_TARGET)
3742 		doppr = 0;
3743 
3744 	/*
3745 	 * Both the PPR message and SDTR message require the
3746 	 * goal syncrate to be limited to what the target device
3747 	 * is capable of handling (based on whether an LVD->SE
3748 	 * expander is on the bus), so combine these two cases.
3749 	 * Regardless, guarantee that if we are using WDTR and SDTR
3750 	 * messages that WDTR comes first.
3751 	 */
3752 	if (doppr || (dosync && !dowide)) {
3753 		offset = tinfo->goal.offset;
3754 		ahd_validate_offset(ahd, tinfo, period, &offset,
3755 				    doppr ? tinfo->goal.width
3756 					  : tinfo->curr.width,
3757 				    devinfo->role);
3758 		if (doppr) {
3759 			ahd_construct_ppr(ahd, devinfo, period, offset,
3760 					  tinfo->goal.width, ppr_options);
3761 		} else {
3762 			ahd_construct_sdtr(ahd, devinfo, period, offset);
3763 		}
3764 	} else {
3765 		ahd_construct_wdtr(ahd, devinfo, tinfo->goal.width);
3766 	}
3767 }
3768 
3769 /*
3770  * Build a synchronous negotiation message in our message
3771  * buffer based on the input parameters.
3772  */
3773 static void
3774 ahd_construct_sdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3775 		   u_int period, u_int offset)
3776 {
3777 	if (offset == 0)
3778 		period = AHD_ASYNC_XFER_PERIOD;
3779 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXTENDED;
3780 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_SDTR_LEN;
3781 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_SDTR;
3782 	ahd->msgout_buf[ahd->msgout_index++] = period;
3783 	ahd->msgout_buf[ahd->msgout_index++] = offset;
3784 	ahd->msgout_len += 5;
3785 	if (bootverbose) {
3786 		printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
3787 		       ahd_name(ahd), devinfo->channel, devinfo->target,
3788 		       devinfo->lun, period, offset);
3789 	}
3790 }
3791 
3792 /*
3793  * Build a wide negotiateion message in our message
3794  * buffer based on the input parameters.
3795  */
3796 static void
3797 ahd_construct_wdtr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3798 		   u_int bus_width)
3799 {
3800 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXTENDED;
3801 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_WDTR_LEN;
3802 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_WDTR;
3803 	ahd->msgout_buf[ahd->msgout_index++] = bus_width;
3804 	ahd->msgout_len += 4;
3805 	if (bootverbose) {
3806 		printf("(%s:%c:%d:%d): Sending WDTR %x\n",
3807 		       ahd_name(ahd), devinfo->channel, devinfo->target,
3808 		       devinfo->lun, bus_width);
3809 	}
3810 }
3811 
3812 /*
3813  * Build a parallel protocol request message in our message
3814  * buffer based on the input parameters.
3815  */
3816 static void
3817 ahd_construct_ppr(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
3818 		  u_int period, u_int offset, u_int bus_width,
3819 		  u_int ppr_options)
3820 {
3821 	/*
3822 	 * Always request precompensation from
3823 	 * the other target if we are running
3824 	 * at paced syncrates.
3825 	 */
3826 	if (period <= AHD_SYNCRATE_PACED)
3827 		ppr_options |= MSG_EXT_PPR_PCOMP_EN;
3828 	if (offset == 0)
3829 		period = AHD_ASYNC_XFER_PERIOD;
3830 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXTENDED;
3831 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_PPR_LEN;
3832 	ahd->msgout_buf[ahd->msgout_index++] = MSG_EXT_PPR;
3833 	ahd->msgout_buf[ahd->msgout_index++] = period;
3834 	ahd->msgout_buf[ahd->msgout_index++] = 0;
3835 	ahd->msgout_buf[ahd->msgout_index++] = offset;
3836 	ahd->msgout_buf[ahd->msgout_index++] = bus_width;
3837 	ahd->msgout_buf[ahd->msgout_index++] = ppr_options;
3838 	ahd->msgout_len += 8;
3839 	if (bootverbose) {
3840 		printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
3841 		       "offset %x, ppr_options %x\n", ahd_name(ahd),
3842 		       devinfo->channel, devinfo->target, devinfo->lun,
3843 		       bus_width, period, offset, ppr_options);
3844 	}
3845 }
3846 
3847 /*
3848  * Clear any active message state.
3849  */
3850 static void
3851 ahd_clear_msg_state(struct ahd_softc *ahd)
3852 {
3853 	ahd_mode_state saved_modes;
3854 
3855 	saved_modes = ahd_save_modes(ahd);
3856 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
3857 	ahd->send_msg_perror = 0;
3858 	ahd->msg_flags = MSG_FLAG_NONE;
3859 	ahd->msgout_len = 0;
3860 	ahd->msgin_index = 0;
3861 	ahd->msg_type = MSG_TYPE_NONE;
3862 	if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
3863 		/*
3864 		 * The target didn't care to respond to our
3865 		 * message request, so clear ATN.
3866 		 */
3867 		ahd_outb(ahd, CLRSINT1, CLRATNO);
3868 	}
3869 	ahd_outb(ahd, MSG_OUT, MSG_NOOP);
3870 	ahd_outb(ahd, SEQ_FLAGS2,
3871 		 ahd_inb(ahd, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
3872 	ahd_restore_modes(ahd, saved_modes);
3873 }
3874 
3875 /*
3876  * Manual message loop handler.
3877  */
3878 static void
3879 ahd_handle_message_phase(struct ahd_softc *ahd)
3880 {
3881 	struct	ahd_devinfo devinfo;
3882 	u_int	bus_phase;
3883 	int	end_session;
3884 
3885 	ahd_fetch_devinfo(ahd, &devinfo);
3886 	end_session = FALSE;
3887 	bus_phase = ahd_inb(ahd, LASTPHASE);
3888 
3889 	if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0) {
3890 		printf("LQIRETRY for LQIPHASE_OUTPKT\n");
3891 		ahd_outb(ahd, LQCTL2, LQIRETRY);
3892 	}
3893 reswitch:
3894 	switch (ahd->msg_type) {
3895 	case MSG_TYPE_INITIATOR_MSGOUT:
3896 	{
3897 		int lastbyte;
3898 		int phasemis;
3899 		int msgdone;
3900 
3901 		if (ahd->msgout_len == 0 && ahd->send_msg_perror == 0)
3902 			panic("HOST_MSG_LOOP interrupt with no active message");
3903 
3904 #ifdef AHD_DEBUG
3905 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3906 			ahd_print_devinfo(ahd, &devinfo);
3907 			printf("INITIATOR_MSG_OUT");
3908 		}
3909 #endif
3910 		phasemis = bus_phase != P_MESGOUT;
3911 		if (phasemis) {
3912 #ifdef AHD_DEBUG
3913 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3914 				printf(" PHASEMIS %s\n",
3915 				       ahd_lookup_phase_entry(bus_phase)
3916 							     ->phasemsg);
3917 			}
3918 #endif
3919 			if (bus_phase == P_MESGIN) {
3920 				/*
3921 				 * Change gears and see if
3922 				 * this messages is of interest to
3923 				 * us or should be passed back to
3924 				 * the sequencer.
3925 				 */
3926 				ahd_outb(ahd, CLRSINT1, CLRATNO);
3927 				ahd->send_msg_perror = 0;
3928 				ahd->msg_type = MSG_TYPE_INITIATOR_MSGIN;
3929 				ahd->msgin_index = 0;
3930 				goto reswitch;
3931 			}
3932 			end_session = TRUE;
3933 			break;
3934 		}
3935 
3936 		if (ahd->send_msg_perror) {
3937 			ahd_outb(ahd, CLRSINT1, CLRATNO);
3938 			ahd_outb(ahd, CLRSINT1, CLRREQINIT);
3939 #ifdef AHD_DEBUG
3940 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3941 				printf(" byte 0x%x\n", ahd->send_msg_perror);
3942 #endif
3943 			/*
3944 			 * If we are notifying the target of a CRC error
3945 			 * during packetized operations, the target is
3946 			 * within its rights to acknowledge our message
3947 			 * with a busfree.
3948 			 */
3949 			if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0
3950 			 && ahd->send_msg_perror == MSG_INITIATOR_DET_ERR)
3951 				ahd->msg_flags |= MSG_FLAG_EXPECT_IDE_BUSFREE;
3952 
3953 			ahd_outb(ahd, RETURN_2, ahd->send_msg_perror);
3954 			ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
3955 			break;
3956 		}
3957 
3958 		msgdone	= ahd->msgout_index == ahd->msgout_len;
3959 		if (msgdone) {
3960 			/*
3961 			 * The target has requested a retry.
3962 			 * Re-assert ATN, reset our message index to
3963 			 * 0, and try again.
3964 			 */
3965 			ahd->msgout_index = 0;
3966 			ahd_assert_atn(ahd);
3967 		}
3968 
3969 		lastbyte = ahd->msgout_index == (ahd->msgout_len - 1);
3970 		if (lastbyte) {
3971 			/* Last byte is signified by dropping ATN */
3972 			ahd_outb(ahd, CLRSINT1, CLRATNO);
3973 		}
3974 
3975 		/*
3976 		 * Clear our interrupt status and present
3977 		 * the next byte on the bus.
3978 		 */
3979 		ahd_outb(ahd, CLRSINT1, CLRREQINIT);
3980 #ifdef AHD_DEBUG
3981 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
3982 			printf(" byte 0x%x\n",
3983 			       ahd->msgout_buf[ahd->msgout_index]);
3984 #endif
3985 		ahd_outb(ahd, RETURN_2, ahd->msgout_buf[ahd->msgout_index++]);
3986 		ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_WRITE);
3987 		break;
3988 	}
3989 	case MSG_TYPE_INITIATOR_MSGIN:
3990 	{
3991 		int phasemis;
3992 		int message_done;
3993 
3994 #ifdef AHD_DEBUG
3995 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
3996 			ahd_print_devinfo(ahd, &devinfo);
3997 			printf("INITIATOR_MSG_IN");
3998 		}
3999 #endif
4000 		phasemis = bus_phase != P_MESGIN;
4001 		if (phasemis) {
4002 #ifdef AHD_DEBUG
4003 			if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4004 				printf(" PHASEMIS %s\n",
4005 				       ahd_lookup_phase_entry(bus_phase)
4006 							     ->phasemsg);
4007 			}
4008 #endif
4009 			ahd->msgin_index = 0;
4010 			if (bus_phase == P_MESGOUT
4011 			 && (ahd->send_msg_perror != 0
4012 			  || (ahd->msgout_len != 0
4013 			   && ahd->msgout_index == 0))) {
4014 				ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
4015 				goto reswitch;
4016 			}
4017 			end_session = TRUE;
4018 			break;
4019 		}
4020 
4021 		/* Pull the byte in without acking it */
4022 		ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIBUS);
4023 #ifdef AHD_DEBUG
4024 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4025 			printf(" byte 0x%x\n",
4026 			       ahd->msgin_buf[ahd->msgin_index]);
4027 #endif
4028 
4029 		message_done = ahd_parse_msg(ahd, &devinfo);
4030 
4031 		if (message_done) {
4032 			/*
4033 			 * Clear our incoming message buffer in case there
4034 			 * is another message following this one.
4035 			 */
4036 			ahd->msgin_index = 0;
4037 
4038 			/*
4039 			 * If this message illicited a response,
4040 			 * assert ATN so the target takes us to the
4041 			 * message out phase.
4042 			 */
4043 			if (ahd->msgout_len != 0) {
4044 #ifdef AHD_DEBUG
4045 				if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
4046 					ahd_print_devinfo(ahd, &devinfo);
4047 					printf("Asserting ATN for response\n");
4048 				}
4049 #endif
4050 				ahd_assert_atn(ahd);
4051 			}
4052 		} else
4053 			ahd->msgin_index++;
4054 
4055 		if (message_done == MSGLOOP_TERMINATED) {
4056 			end_session = TRUE;
4057 		} else {
4058 			/* Ack the byte */
4059 			ahd_outb(ahd, CLRSINT1, CLRREQINIT);
4060 			ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_READ);
4061 		}
4062 		break;
4063 	}
4064 	case MSG_TYPE_TARGET_MSGIN:
4065 	{
4066 		int msgdone;
4067 		int msgout_request;
4068 
4069 		/*
4070 		 * By default, the message loop will continue.
4071 		 */
4072 		ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4073 
4074 		if (ahd->msgout_len == 0)
4075 			panic("Target MSGIN with no active message");
4076 
4077 		/*
4078 		 * If we interrupted a mesgout session, the initiator
4079 		 * will not know this until our first REQ.  So, we
4080 		 * only honor mesgout requests after we've sent our
4081 		 * first byte.
4082 		 */
4083 		if ((ahd_inb(ahd, SCSISIGI) & ATNI) != 0
4084 		 && ahd->msgout_index > 0)
4085 			msgout_request = TRUE;
4086 		else
4087 			msgout_request = FALSE;
4088 
4089 		if (msgout_request) {
4090 			/*
4091 			 * Change gears and see if
4092 			 * this messages is of interest to
4093 			 * us or should be passed back to
4094 			 * the sequencer.
4095 			 */
4096 			ahd->msg_type = MSG_TYPE_TARGET_MSGOUT;
4097 			ahd_outb(ahd, SCSISIGO, P_MESGOUT | BSYO);
4098 			ahd->msgin_index = 0;
4099 			/* Dummy read to REQ for first byte */
4100 			ahd_inb(ahd, SCSIDAT);
4101 			ahd_outb(ahd, SXFRCTL0,
4102 				 ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4103 			break;
4104 		}
4105 
4106 		msgdone = ahd->msgout_index == ahd->msgout_len;
4107 		if (msgdone) {
4108 			ahd_outb(ahd, SXFRCTL0,
4109 				 ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4110 			end_session = TRUE;
4111 			break;
4112 		}
4113 
4114 		/*
4115 		 * Present the next byte on the bus.
4116 		 */
4117 		ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4118 		ahd_outb(ahd, SCSIDAT, ahd->msgout_buf[ahd->msgout_index++]);
4119 		break;
4120 	}
4121 	case MSG_TYPE_TARGET_MSGOUT:
4122 	{
4123 		int lastbyte;
4124 		int msgdone;
4125 
4126 		/*
4127 		 * By default, the message loop will continue.
4128 		 */
4129 		ahd_outb(ahd, RETURN_1, CONT_MSG_LOOP_TARG);
4130 
4131 		/*
4132 		 * The initiator signals that this is
4133 		 * the last byte by dropping ATN.
4134 		 */
4135 		lastbyte = (ahd_inb(ahd, SCSISIGI) & ATNI) == 0;
4136 
4137 		/*
4138 		 * Read the latched byte, but turn off SPIOEN first
4139 		 * so that we don't inadvertently cause a REQ for the
4140 		 * next byte.
4141 		 */
4142 		ahd_outb(ahd, SXFRCTL0, ahd_inb(ahd, SXFRCTL0) & ~SPIOEN);
4143 		ahd->msgin_buf[ahd->msgin_index] = ahd_inb(ahd, SCSIDAT);
4144 		msgdone = ahd_parse_msg(ahd, &devinfo);
4145 		if (msgdone == MSGLOOP_TERMINATED) {
4146 			/*
4147 			 * The message is *really* done in that it caused
4148 			 * us to go to bus free.  The sequencer has already
4149 			 * been reset at this point, so pull the ejection
4150 			 * handle.
4151 			 */
4152 			return;
4153 		}
4154 
4155 		ahd->msgin_index++;
4156 
4157 		/*
4158 		 * XXX Read spec about initiator dropping ATN too soon
4159 		 *     and use msgdone to detect it.
4160 		 */
4161 		if (msgdone == MSGLOOP_MSGCOMPLETE) {
4162 			ahd->msgin_index = 0;
4163 
4164 			/*
4165 			 * If this message illicited a response, transition
4166 			 * to the Message in phase and send it.
4167 			 */
4168 			if (ahd->msgout_len != 0) {
4169 				ahd_outb(ahd, SCSISIGO, P_MESGIN | BSYO);
4170 				ahd_outb(ahd, SXFRCTL0,
4171 					 ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4172 				ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
4173 				ahd->msgin_index = 0;
4174 				break;
4175 			}
4176 		}
4177 
4178 		if (lastbyte)
4179 			end_session = TRUE;
4180 		else {
4181 			/* Ask for the next byte. */
4182 			ahd_outb(ahd, SXFRCTL0,
4183 				 ahd_inb(ahd, SXFRCTL0) | SPIOEN);
4184 		}
4185 
4186 		break;
4187 	}
4188 	default:
4189 		panic("Unknown REQINIT message type");
4190 	}
4191 
4192 	if (end_session) {
4193 		if ((ahd->msg_flags & MSG_FLAG_PACKETIZED) != 0) {
4194 			printf("%s: Returning to Idle Loop\n",
4195 			       ahd_name(ahd));
4196 			ahd_clear_msg_state(ahd);
4197 
4198 			/*
4199 			 * Perform the equivalent of a clear_target_state.
4200 			 */
4201 			ahd_outb(ahd, LASTPHASE, P_BUSFREE);
4202 			ahd_outb(ahd, SEQ_FLAGS, NOT_IDENTIFIED|NO_CDB_SENT);
4203 			ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
4204 		} else {
4205 			ahd_clear_msg_state(ahd);
4206 			ahd_outb(ahd, RETURN_1, EXIT_MSG_LOOP);
4207 		}
4208 	}
4209 }
4210 
4211 /*
4212  * See if we sent a particular extended message to the target.
4213  * If "full" is true, return true only if the target saw the full
4214  * message.  If "full" is false, return true if the target saw at
4215  * least the first byte of the message.
4216  */
4217 static int
4218 ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type, u_int msgval, int full)
4219 {
4220 	int found;
4221 	u_int index;
4222 
4223 	found = FALSE;
4224 	index = 0;
4225 
4226 	while (index < ahd->msgout_len) {
4227 		if (ahd->msgout_buf[index] == MSG_EXTENDED) {
4228 			u_int end_index;
4229 
4230 			end_index = index + 1 + ahd->msgout_buf[index + 1];
4231 			if (ahd->msgout_buf[index+2] == msgval
4232 			 && type == AHDMSG_EXT) {
4233 				if (full) {
4234 					if (ahd->msgout_index > end_index)
4235 						found = TRUE;
4236 				} else if (ahd->msgout_index > index)
4237 					found = TRUE;
4238 			}
4239 			index = end_index;
4240 		} else if (ahd->msgout_buf[index] >= MSG_SIMPLE_TASK
4241 			&& ahd->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
4242 			/* Skip tag type and tag id or residue param*/
4243 			index += 2;
4244 		} else {
4245 			/* Single byte message */
4246 			if (type == AHDMSG_1B
4247 			 && ahd->msgout_index > index
4248 			 && (ahd->msgout_buf[index] == msgval
4249 			  || ((ahd->msgout_buf[index] & MSG_IDENTIFYFLAG) != 0
4250 			   && msgval == MSG_IDENTIFYFLAG)))
4251 				found = TRUE;
4252 			index++;
4253 		}
4254 
4255 		if (found)
4256 			break;
4257 	}
4258 	return (found);
4259 }
4260 
4261 /*
4262  * Wait for a complete incoming message, parse it, and respond accordingly.
4263  */
4264 static int
4265 ahd_parse_msg(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4266 {
4267 	struct	ahd_initiator_tinfo *tinfo;
4268 	struct	ahd_tmode_tstate *tstate;
4269 	int	reject;
4270 	int	done;
4271 	int	response;
4272 
4273 	done = MSGLOOP_IN_PROG;
4274 	response = FALSE;
4275 	reject = FALSE;
4276 	tinfo = ahd_fetch_transinfo(ahd, devinfo->channel, devinfo->our_scsiid,
4277 				    devinfo->target, &tstate);
4278 
4279 	/*
4280 	 * Parse as much of the message as is available,
4281 	 * rejecting it if we don't support it.  When
4282 	 * the entire message is available and has been
4283 	 * handled, return MSGLOOP_MSGCOMPLETE, indicating
4284 	 * that we have parsed an entire message.
4285 	 *
4286 	 * In the case of extended messages, we accept the length
4287 	 * byte outright and perform more checking once we know the
4288 	 * extended message type.
4289 	 */
4290 	switch (ahd->msgin_buf[0]) {
4291 	case MSG_DISCONNECT:
4292 	case MSG_SAVEDATAPOINTER:
4293 	case MSG_CMDCOMPLETE:
4294 	case MSG_RESTOREPOINTERS:
4295 	case MSG_IGN_WIDE_RESIDUE:
4296 		/*
4297 		 * End our message loop as these are messages
4298 		 * the sequencer handles on its own.
4299 		 */
4300 		done = MSGLOOP_TERMINATED;
4301 		break;
4302 	case MSG_MESSAGE_REJECT:
4303 		response = ahd_handle_msg_reject(ahd, devinfo);
4304 		/* FALLTHROUGH */
4305 	case MSG_NOOP:
4306 		done = MSGLOOP_MSGCOMPLETE;
4307 		break;
4308 	case MSG_EXTENDED:
4309 	{
4310 		/* Wait for enough of the message to begin validation */
4311 		if (ahd->msgin_index < 2)
4312 			break;
4313 		switch (ahd->msgin_buf[2]) {
4314 		case MSG_EXT_SDTR:
4315 		{
4316 			u_int	 period;
4317 			u_int	 ppr_options;
4318 			u_int	 offset;
4319 			u_int	 saved_offset;
4320 
4321 			if (ahd->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
4322 				reject = TRUE;
4323 				break;
4324 			}
4325 
4326 			/*
4327 			 * Wait until we have both args before validating
4328 			 * and acting on this message.
4329 			 *
4330 			 * Add one to MSG_EXT_SDTR_LEN to account for
4331 			 * the extended message preamble.
4332 			 */
4333 			if (ahd->msgin_index < (MSG_EXT_SDTR_LEN + 1))
4334 				break;
4335 
4336 			period = ahd->msgin_buf[3];
4337 			ppr_options = 0;
4338 			saved_offset = offset = ahd->msgin_buf[4];
4339 			ahd_devlimited_syncrate(ahd, tinfo, &period,
4340 						&ppr_options, devinfo->role);
4341 			ahd_validate_offset(ahd, tinfo, period, &offset,
4342 					    tinfo->curr.width, devinfo->role);
4343 			if (bootverbose) {
4344 				printf("(%s:%c:%d:%d): Received "
4345 				       "SDTR period %x, offset %x\n\t"
4346 				       "Filtered to period %x, offset %x\n",
4347 				       ahd_name(ahd), devinfo->channel,
4348 				       devinfo->target, devinfo->lun,
4349 				       ahd->msgin_buf[3], saved_offset,
4350 				       period, offset);
4351 			}
4352 			ahd_set_syncrate(ahd, devinfo, period,
4353 					 offset, ppr_options,
4354 					 AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4355 					 /*paused*/TRUE);
4356 
4357 			/*
4358 			 * See if we initiated Sync Negotiation
4359 			 * and didn't have to fall down to async
4360 			 * transfers.
4361 			 */
4362 			if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, TRUE)) {
4363 				/* We started it */
4364 				if (saved_offset != offset) {
4365 					/* Went too low - force async */
4366 					reject = TRUE;
4367 				}
4368 			} else {
4369 				/*
4370 				 * Send our own SDTR in reply
4371 				 */
4372 				if (bootverbose
4373 				 && devinfo->role == ROLE_INITIATOR) {
4374 					printf("(%s:%c:%d:%d): Target "
4375 					       "Initiated SDTR\n",
4376 					       ahd_name(ahd), devinfo->channel,
4377 					       devinfo->target, devinfo->lun);
4378 				}
4379 				ahd->msgout_index = 0;
4380 				ahd->msgout_len = 0;
4381 				ahd_construct_sdtr(ahd, devinfo,
4382 						   period, offset);
4383 				ahd->msgout_index = 0;
4384 				response = TRUE;
4385 			}
4386 			done = MSGLOOP_MSGCOMPLETE;
4387 			break;
4388 		}
4389 		case MSG_EXT_WDTR:
4390 		{
4391 			u_int bus_width;
4392 			u_int saved_width;
4393 			u_int sending_reply;
4394 
4395 			sending_reply = FALSE;
4396 			if (ahd->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
4397 				reject = TRUE;
4398 				break;
4399 			}
4400 
4401 			/*
4402 			 * Wait until we have our arg before validating
4403 			 * and acting on this message.
4404 			 *
4405 			 * Add one to MSG_EXT_WDTR_LEN to account for
4406 			 * the extended message preamble.
4407 			 */
4408 			if (ahd->msgin_index < (MSG_EXT_WDTR_LEN + 1))
4409 				break;
4410 
4411 			bus_width = ahd->msgin_buf[3];
4412 			saved_width = bus_width;
4413 			ahd_validate_width(ahd, tinfo, &bus_width,
4414 					   devinfo->role);
4415 			if (bootverbose) {
4416 				printf("(%s:%c:%d:%d): Received WDTR "
4417 				       "%x filtered to %x\n",
4418 				       ahd_name(ahd), devinfo->channel,
4419 				       devinfo->target, devinfo->lun,
4420 				       saved_width, bus_width);
4421 			}
4422 
4423 			if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, TRUE)) {
4424 				/*
4425 				 * Don't send a WDTR back to the
4426 				 * target, since we asked first.
4427 				 * If the width went higher than our
4428 				 * request, reject it.
4429 				 */
4430 				if (saved_width > bus_width) {
4431 					reject = TRUE;
4432 					printf("(%s:%c:%d:%d): requested %dBit "
4433 					       "transfers.  Rejecting...\n",
4434 					       ahd_name(ahd), devinfo->channel,
4435 					       devinfo->target, devinfo->lun,
4436 					       8 * (0x01 << bus_width));
4437 					bus_width = 0;
4438 				}
4439 			} else {
4440 				/*
4441 				 * Send our own WDTR in reply
4442 				 */
4443 				if (bootverbose
4444 				 && devinfo->role == ROLE_INITIATOR) {
4445 					printf("(%s:%c:%d:%d): Target "
4446 					       "Initiated WDTR\n",
4447 					       ahd_name(ahd), devinfo->channel,
4448 					       devinfo->target, devinfo->lun);
4449 				}
4450 				ahd->msgout_index = 0;
4451 				ahd->msgout_len = 0;
4452 				ahd_construct_wdtr(ahd, devinfo, bus_width);
4453 				ahd->msgout_index = 0;
4454 				response = TRUE;
4455 				sending_reply = TRUE;
4456 			}
4457 			/*
4458 			 * After a wide message, we are async, but
4459 			 * some devices don't seem to honor this portion
4460 			 * of the spec.  Force a renegotiation of the
4461 			 * sync component of our transfer agreement even
4462 			 * if our goal is async.  By updating our width
4463 			 * after forcing the negotiation, we avoid
4464 			 * renegotiating for width.
4465 			 */
4466 			ahd_update_neg_request(ahd, devinfo, tstate,
4467 					       tinfo, AHD_NEG_ALWAYS);
4468 			ahd_set_width(ahd, devinfo, bus_width,
4469 				      AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4470 				      /*paused*/TRUE);
4471 			if (sending_reply == FALSE && reject == FALSE) {
4472 				/*
4473 				 * We will always have an SDTR to send.
4474 				 */
4475 				ahd->msgout_index = 0;
4476 				ahd->msgout_len = 0;
4477 				ahd_build_transfer_msg(ahd, devinfo);
4478 				ahd->msgout_index = 0;
4479 				response = TRUE;
4480 			}
4481 			done = MSGLOOP_MSGCOMPLETE;
4482 			break;
4483 		}
4484 		case MSG_EXT_PPR:
4485 		{
4486 			u_int	period;
4487 			u_int	offset;
4488 			u_int	bus_width;
4489 			u_int	ppr_options;
4490 			u_int	saved_width;
4491 			u_int	saved_offset;
4492 			u_int	saved_ppr_options;
4493 
4494 			if (ahd->msgin_buf[1] != MSG_EXT_PPR_LEN) {
4495 				reject = TRUE;
4496 				break;
4497 			}
4498 
4499 			/*
4500 			 * Wait until we have all args before validating
4501 			 * and acting on this message.
4502 			 *
4503 			 * Add one to MSG_EXT_PPR_LEN to account for
4504 			 * the extended message preamble.
4505 			 */
4506 			if (ahd->msgin_index < (MSG_EXT_PPR_LEN + 1))
4507 				break;
4508 
4509 			period = ahd->msgin_buf[3];
4510 			offset = ahd->msgin_buf[5];
4511 			bus_width = ahd->msgin_buf[6];
4512 			saved_width = bus_width;
4513 			ppr_options = ahd->msgin_buf[7];
4514 			/*
4515 			 * According to the spec, a DT only
4516 			 * period factor with no DT option
4517 			 * set implies async.
4518 			 */
4519 			if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
4520 			 && period <= 9)
4521 				offset = 0;
4522 			saved_ppr_options = ppr_options;
4523 			saved_offset = offset;
4524 
4525 			/*
4526 			 * Transfer options are only available if we
4527 			 * are negotiating wide.
4528 			 */
4529 			if (bus_width == 0)
4530 				ppr_options &= MSG_EXT_PPR_QAS_REQ;
4531 
4532 			ahd_validate_width(ahd, tinfo, &bus_width,
4533 					   devinfo->role);
4534 			ahd_devlimited_syncrate(ahd, tinfo, &period,
4535 						&ppr_options, devinfo->role);
4536 			ahd_validate_offset(ahd, tinfo, period, &offset,
4537 					    bus_width, devinfo->role);
4538 
4539 			if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, TRUE)) {
4540 				/*
4541 				 * If we are unable to do any of the
4542 				 * requested options (we went too low),
4543 				 * then we'll have to reject the message.
4544 				 */
4545 				if (saved_width > bus_width
4546 				 || saved_offset != offset
4547 				 || saved_ppr_options != ppr_options) {
4548 					reject = TRUE;
4549 					period = 0;
4550 					offset = 0;
4551 					bus_width = 0;
4552 					ppr_options = 0;
4553 				}
4554 			} else {
4555 				if (devinfo->role != ROLE_TARGET)
4556 					printf("(%s:%c:%d:%d): Target "
4557 					       "Initiated PPR\n",
4558 					       ahd_name(ahd), devinfo->channel,
4559 					       devinfo->target, devinfo->lun);
4560 				else
4561 					printf("(%s:%c:%d:%d): Initiator "
4562 					       "Initiated PPR\n",
4563 					       ahd_name(ahd), devinfo->channel,
4564 					       devinfo->target, devinfo->lun);
4565 				ahd->msgout_index = 0;
4566 				ahd->msgout_len = 0;
4567 				ahd_construct_ppr(ahd, devinfo, period, offset,
4568 						  bus_width, ppr_options);
4569 				ahd->msgout_index = 0;
4570 				response = TRUE;
4571 			}
4572 			if (bootverbose) {
4573 				printf("(%s:%c:%d:%d): Received PPR width %x, "
4574 				       "period %x, offset %x,options %x\n"
4575 				       "\tFiltered to width %x, period %x, "
4576 				       "offset %x, options %x\n",
4577 				       ahd_name(ahd), devinfo->channel,
4578 				       devinfo->target, devinfo->lun,
4579 				       saved_width, ahd->msgin_buf[3],
4580 				       saved_offset, saved_ppr_options,
4581 				       bus_width, period, offset, ppr_options);
4582 			}
4583 			ahd_set_width(ahd, devinfo, bus_width,
4584 				      AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4585 				      /*paused*/TRUE);
4586 			ahd_set_syncrate(ahd, devinfo, period,
4587 					 offset, ppr_options,
4588 					 AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4589 					 /*paused*/TRUE);
4590 
4591 			done = MSGLOOP_MSGCOMPLETE;
4592 			break;
4593 		}
4594 		default:
4595 			/* Unknown extended message.  Reject it. */
4596 			reject = TRUE;
4597 			break;
4598 		}
4599 		break;
4600 	}
4601 #ifdef AHD_TARGET_MODE
4602 	case MSG_BUS_DEV_RESET:
4603 		ahd_handle_devreset(ahd, devinfo, CAM_LUN_WILDCARD,
4604 				    CAM_BDR_SENT,
4605 				    "Bus Device Reset Received",
4606 				    /*verbose_level*/0);
4607 		ahd_restart(ahd);
4608 		done = MSGLOOP_TERMINATED;
4609 		break;
4610 	case MSG_ABORT_TAG:
4611 	case MSG_ABORT:
4612 	case MSG_CLEAR_QUEUE:
4613 	{
4614 		int tag;
4615 
4616 		/* Target mode messages */
4617 		if (devinfo->role != ROLE_TARGET) {
4618 			reject = TRUE;
4619 			break;
4620 		}
4621 		tag = SCB_LIST_NULL;
4622 		if (ahd->msgin_buf[0] == MSG_ABORT_TAG)
4623 			tag = ahd_inb(ahd, INITIATOR_TAG);
4624 		ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
4625 			       devinfo->lun, tag, ROLE_TARGET,
4626 			       CAM_REQ_ABORTED);
4627 
4628 		tstate = ahd->enabled_targets[devinfo->our_scsiid];
4629 		if (tstate != NULL) {
4630 			struct ahd_tmode_lstate* lstate;
4631 
4632 			lstate = tstate->enabled_luns[devinfo->lun];
4633 			if (lstate != NULL) {
4634 				ahd_queue_lstate_event(ahd, lstate,
4635 						       devinfo->our_scsiid,
4636 						       ahd->msgin_buf[0],
4637 						       /*arg*/tag);
4638 				ahd_send_lstate_events(ahd, lstate);
4639 			}
4640 		}
4641 		ahd_restart(ahd);
4642 		done = MSGLOOP_TERMINATED;
4643 		break;
4644 	}
4645 #endif
4646 	case MSG_QAS_REQUEST:
4647 #ifdef AHD_DEBUG
4648 		if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
4649 			printf("%s: QAS request.  SCSISIGI == 0x%x\n",
4650 			       ahd_name(ahd), ahd_inb(ahd, SCSISIGI));
4651 #endif
4652 		ahd->msg_flags |= MSG_FLAG_EXPECT_QASREJ_BUSFREE;
4653 		/* FALLTHROUGH */
4654 	case MSG_TERM_IO_PROC:
4655 	default:
4656 		reject = TRUE;
4657 		break;
4658 	}
4659 
4660 	if (reject) {
4661 		/*
4662 		 * Setup to reject the message.
4663 		 */
4664 		ahd->msgout_index = 0;
4665 		ahd->msgout_len = 1;
4666 		ahd->msgout_buf[0] = MSG_MESSAGE_REJECT;
4667 		done = MSGLOOP_MSGCOMPLETE;
4668 		response = TRUE;
4669 	}
4670 
4671 	if (done != MSGLOOP_IN_PROG && !response)
4672 		/* Clear the outgoing message buffer */
4673 		ahd->msgout_len = 0;
4674 
4675 	return (done);
4676 }
4677 
4678 /*
4679  * Process a message reject message.
4680  */
4681 static int
4682 ahd_handle_msg_reject(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4683 {
4684 	/*
4685 	 * What we care about here is if we had an
4686 	 * outstanding SDTR or WDTR message for this
4687 	 * target.  If we did, this is a signal that
4688 	 * the target is refusing negotiation.
4689 	 */
4690 	struct scb *scb;
4691 	struct ahd_initiator_tinfo *tinfo;
4692 	struct ahd_tmode_tstate *tstate;
4693 	u_int scb_index;
4694 	u_int last_msg;
4695 	int   response = 0;
4696 
4697 	scb_index = ahd_get_scbptr(ahd);
4698 	scb = ahd_lookup_scb(ahd, scb_index);
4699 	tinfo = ahd_fetch_transinfo(ahd, devinfo->channel,
4700 				    devinfo->our_scsiid,
4701 				    devinfo->target, &tstate);
4702 	/* Might be necessary */
4703 	last_msg = ahd_inb(ahd, LAST_MSG);
4704 
4705 	if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
4706 		if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, /*full*/TRUE)
4707 		 && tinfo->goal.period <= AHD_SYNCRATE_PACED) {
4708 			/*
4709 			 * Target may not like our SPI-4 PPR Options.
4710 			 * Attempt to negotiate 80MHz which will turn
4711 			 * off these options.
4712 			 */
4713 			if (bootverbose) {
4714 				printf("(%s:%c:%d:%d): PPR Rejected. "
4715 				       "Trying simple U160 PPR\n",
4716 				       ahd_name(ahd), devinfo->channel,
4717 				       devinfo->target, devinfo->lun);
4718 			}
4719 			tinfo->goal.period = AHD_SYNCRATE_DT;
4720 			tinfo->goal.ppr_options &= MSG_EXT_PPR_IU_REQ
4721 						|  MSG_EXT_PPR_QAS_REQ
4722 						|  MSG_EXT_PPR_DT_REQ;
4723 		} else {
4724 			/*
4725 			 * Target does not support the PPR message.
4726 			 * Attempt to negotiate SPI-2 style.
4727 			 */
4728 			if (bootverbose) {
4729 				printf("(%s:%c:%d:%d): PPR Rejected. "
4730 				       "Trying WDTR/SDTR\n",
4731 				       ahd_name(ahd), devinfo->channel,
4732 				       devinfo->target, devinfo->lun);
4733 			}
4734 			tinfo->goal.ppr_options = 0;
4735 			tinfo->curr.transport_version = 2;
4736 			tinfo->goal.transport_version = 2;
4737 		}
4738 		ahd->msgout_index = 0;
4739 		ahd->msgout_len = 0;
4740 		ahd_build_transfer_msg(ahd, devinfo);
4741 		ahd->msgout_index = 0;
4742 		response = 1;
4743 	} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
4744 		/* note 8bit xfers */
4745 		printf("(%s:%c:%d:%d): refuses WIDE negotiation.  Using "
4746 		       "8bit transfers\n", ahd_name(ahd),
4747 		       devinfo->channel, devinfo->target, devinfo->lun);
4748 		ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
4749 			      AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4750 			      /*paused*/TRUE);
4751 		/*
4752 		 * No need to clear the sync rate.  If the target
4753 		 * did not accept the command, our syncrate is
4754 		 * unaffected.  If the target started the negotiation,
4755 		 * but rejected our response, we already cleared the
4756 		 * sync rate before sending our WDTR.
4757 		 */
4758 		if (tinfo->goal.offset != tinfo->curr.offset) {
4759 			/* Start the sync negotiation */
4760 			ahd->msgout_index = 0;
4761 			ahd->msgout_len = 0;
4762 			ahd_build_transfer_msg(ahd, devinfo);
4763 			ahd->msgout_index = 0;
4764 			response = 1;
4765 		}
4766 	} else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
4767 		/* note asynch xfers and clear flag */
4768 		ahd_set_syncrate(ahd, devinfo, /*period*/0,
4769 				 /*offset*/0, /*ppr_options*/0,
4770 				 AHD_TRANS_ACTIVE|AHD_TRANS_GOAL,
4771 				 /*paused*/TRUE);
4772 		printf("(%s:%c:%d:%d): refuses synchronous negotiation. "
4773 		       "Using asynchronous transfers\n",
4774 		       ahd_name(ahd), devinfo->channel,
4775 		       devinfo->target, devinfo->lun);
4776 	} else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
4777 		int tag_type;
4778 		int mask;
4779 
4780 		tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
4781 
4782 		if (tag_type == MSG_SIMPLE_TASK) {
4783 			printf("(%s:%c:%d:%d): refuses tagged commands.  "
4784 			       "Performing non-tagged I/O\n", ahd_name(ahd),
4785 			       devinfo->channel, devinfo->target, devinfo->lun);
4786 			ahd_set_tags(ahd, devinfo, AHD_QUEUE_NONE);
4787 			mask = ~0x23;
4788 		} else {
4789 			printf("(%s:%c:%d:%d): refuses %s tagged commands.  "
4790 			       "Performing simple queue tagged I/O only\n",
4791 			       ahd_name(ahd), devinfo->channel, devinfo->target,
4792 			       devinfo->lun, tag_type == MSG_ORDERED_TASK
4793 			       ? "ordered" : "head of queue");
4794 			ahd_set_tags(ahd, devinfo, AHD_QUEUE_BASIC);
4795 			mask = ~0x03;
4796 		}
4797 
4798 		/*
4799 		 * Resend the identify for this CCB as the target
4800 		 * may believe that the selection is invalid otherwise.
4801 		 */
4802 		ahd_outb(ahd, SCB_CONTROL,
4803 			 ahd_inb_scbram(ahd, SCB_CONTROL) & mask);
4804 	 	scb->hscb->control &= mask;
4805 		aic_set_transaction_tag(scb, /*enabled*/FALSE,
4806 					/*type*/MSG_SIMPLE_TASK);
4807 		ahd_outb(ahd, MSG_OUT, MSG_IDENTIFYFLAG);
4808 		ahd_assert_atn(ahd);
4809 		ahd_busy_tcl(ahd, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
4810 			     SCB_GET_TAG(scb));
4811 
4812 		/*
4813 		 * Requeue all tagged commands for this target
4814 		 * currently in our possession so they can be
4815 		 * converted to untagged commands.
4816 		 */
4817 		ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
4818 				   SCB_GET_CHANNEL(ahd, scb),
4819 				   SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
4820 				   ROLE_INITIATOR, CAM_REQUEUE_REQ,
4821 				   SEARCH_COMPLETE);
4822 	} else if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_IDENTIFYFLAG, TRUE)) {
4823 		/*
4824 		 * Most likely the device believes that we had
4825 		 * previously negotiated packetized.
4826 		 */
4827 		ahd->msg_flags |= MSG_FLAG_EXPECT_PPR_BUSFREE
4828 			       |  MSG_FLAG_IU_REQ_CHANGED;
4829 
4830 		ahd_force_renegotiation(ahd, devinfo);
4831 		ahd->msgout_index = 0;
4832 		ahd->msgout_len = 0;
4833 		ahd_build_transfer_msg(ahd, devinfo);
4834 		ahd->msgout_index = 0;
4835 		response = 1;
4836 	} else {
4837 		/*
4838 		 * Otherwise, we ignore it.
4839 		 */
4840 		printf("%s:%c:%d: Message reject for %x -- ignored\n",
4841 		       ahd_name(ahd), devinfo->channel, devinfo->target,
4842 		       last_msg);
4843 	}
4844 	return (response);
4845 }
4846 
4847 /*
4848  * Process an ignore wide residue message.
4849  */
4850 static void
4851 ahd_handle_ign_wide_residue(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
4852 {
4853 	u_int scb_index;
4854 	struct scb *scb;
4855 
4856 	scb_index = ahd_get_scbptr(ahd);
4857 	scb = ahd_lookup_scb(ahd, scb_index);
4858 	/*
4859 	 * XXX Actually check data direction in the sequencer?
4860 	 * Perhaps add datadir to some spare bits in the hscb?
4861 	 */
4862 	if ((ahd_inb(ahd, SEQ_FLAGS) & DPHASE) == 0
4863 	 || aic_get_transfer_dir(scb) != CAM_DIR_IN) {
4864 		/*
4865 		 * Ignore the message if we haven't
4866 		 * seen an appropriate data phase yet.
4867 		 */
4868 	} else {
4869 		/*
4870 		 * If the residual occurred on the last
4871 		 * transfer and the transfer request was
4872 		 * expected to end on an odd count, do
4873 		 * nothing.  Otherwise, subtract a byte
4874 		 * and update the residual count accordingly.
4875 		 */
4876 		uint32_t sgptr;
4877 
4878 		sgptr = ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR);
4879 		if ((sgptr & SG_LIST_NULL) != 0
4880 		 && (ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
4881 		     & SCB_XFERLEN_ODD) != 0) {
4882 			/*
4883 			 * If the residual occurred on the last
4884 			 * transfer and the transfer request was
4885 			 * expected to end on an odd count, do
4886 			 * nothing.
4887 			 */
4888 		} else {
4889 			uint32_t data_cnt;
4890 			uint32_t sglen;
4891 
4892 			/* Pull in the rest of the sgptr */
4893 			sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
4894 			data_cnt = ahd_inl_scbram(ahd, SCB_RESIDUAL_DATACNT);
4895 			if ((sgptr & SG_LIST_NULL) != 0) {
4896 				/*
4897 				 * The residual data count is not updated
4898 				 * for the command run to completion case.
4899 				 * Explicitly zero the count.
4900 				 */
4901 				data_cnt &= ~AHD_SG_LEN_MASK;
4902 			}
4903 			data_cnt += 1;
4904 			sgptr &= SG_PTR_MASK;
4905 			if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
4906 				struct ahd_dma64_seg *sg;
4907 
4908 				sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
4909 
4910 				/*
4911 				 * The residual sg ptr points to the next S/G
4912 				 * to load so we must go back one.
4913 				 */
4914 				sg--;
4915 				sglen = aic_le32toh(sg->len) & AHD_SG_LEN_MASK;
4916 				if (sg != scb->sg_list
4917 				 && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
4918 					sg--;
4919 					sglen = aic_le32toh(sg->len);
4920 					/*
4921 					 * Preserve High Address and SG_LIST
4922 					 * bits while setting the count to 1.
4923 					 */
4924 					data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
4925 
4926 					/*
4927 					 * Increment sg so it points to the
4928 					 * "next" sg.
4929 					 */
4930 					sg++;
4931 					sgptr = ahd_sg_virt_to_bus(ahd, scb,
4932 								   sg);
4933 				}
4934 			} else {
4935 				struct ahd_dma_seg *sg;
4936 
4937 				sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
4938 
4939 				/*
4940 				 * The residual sg ptr points to the next S/G
4941 				 * to load so we must go back one.
4942 				 */
4943 				sg--;
4944 				sglen = aic_le32toh(sg->len) & AHD_SG_LEN_MASK;
4945 				if (sg != scb->sg_list
4946 				 && sglen < (data_cnt & AHD_SG_LEN_MASK)) {
4947 					sg--;
4948 					sglen = aic_le32toh(sg->len);
4949 					/*
4950 					 * Preserve High Address and SG_LIST
4951 					 * bits while setting the count to 1.
4952 					 */
4953 					data_cnt = 1|(sglen&(~AHD_SG_LEN_MASK));
4954 
4955 					/*
4956 					 * Increment sg so it points to the
4957 					 * "next" sg.
4958 					 */
4959 					sg++;
4960 					sgptr = ahd_sg_virt_to_bus(ahd, scb,
4961 								  sg);
4962 				}
4963 			}
4964 			/*
4965 			 * Toggle the "oddness" of the transfer length
4966 			 * to handle this mid-transfer ignore wide
4967 			 * residue.  This ensures that the oddness is
4968 			 * correct for subsequent data transfers.
4969 			 */
4970 			ahd_outb(ahd, SCB_TASK_ATTRIBUTE,
4971 			    ahd_inb_scbram(ahd, SCB_TASK_ATTRIBUTE)
4972 			    ^ SCB_XFERLEN_ODD);
4973 
4974 			ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
4975 			ahd_outl(ahd, SCB_RESIDUAL_DATACNT, data_cnt);
4976 			/*
4977 			 * The FIFO's pointers will be updated if/when the
4978 			 * sequencer re-enters a data phase.
4979 			 */
4980 		}
4981 	}
4982 }
4983 
4984 /*
4985  * Reinitialize the data pointers for the active transfer
4986  * based on its current residual.
4987  */
4988 static void
4989 ahd_reinitialize_dataptrs(struct ahd_softc *ahd)
4990 {
4991 	struct		 scb *scb;
4992 	ahd_mode_state	 saved_modes;
4993 	u_int		 scb_index;
4994 	u_int		 wait;
4995 	uint32_t	 sgptr;
4996 	uint32_t	 resid;
4997 	uint64_t	 dataptr;
4998 
4999 	AHD_ASSERT_MODES(ahd, AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK,
5000 			 AHD_MODE_DFF0_MSK|AHD_MODE_DFF1_MSK);
5001 
5002 	scb_index = ahd_get_scbptr(ahd);
5003 	scb = ahd_lookup_scb(ahd, scb_index);
5004 
5005 	/*
5006 	 * Release and reacquire the FIFO so we
5007 	 * have a clean slate.
5008 	 */
5009 	ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
5010 	wait = 1000;
5011 	while (--wait && !(ahd_inb(ahd, MDFFSTAT) & FIFOFREE))
5012 		aic_delay(100);
5013 	if (wait == 0) {
5014 		ahd_print_path(ahd, scb);
5015 		printf("ahd_reinitialize_dataptrs: Forcing FIFO free.\n");
5016 		ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
5017 	}
5018 	saved_modes = ahd_save_modes(ahd);
5019 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5020 	ahd_outb(ahd, DFFSTAT,
5021 		 ahd_inb(ahd, DFFSTAT)
5022 		| (saved_modes == 0x11 ? CURRFIFO_1 : CURRFIFO_0));
5023 
5024 	/*
5025 	 * Determine initial values for data_addr and data_cnt
5026 	 * for resuming the data phase.
5027 	 */
5028 	sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
5029 	sgptr &= SG_PTR_MASK;
5030 
5031 	resid = (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 2) << 16)
5032 	      | (ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT + 1) << 8)
5033 	      | ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT);
5034 
5035 	if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
5036 		struct ahd_dma64_seg *sg;
5037 
5038 		sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5039 
5040 		/* The residual sg_ptr always points to the next sg */
5041 		sg--;
5042 
5043 		dataptr = aic_le64toh(sg->addr)
5044 			+ (aic_le32toh(sg->len) & AHD_SG_LEN_MASK)
5045 			- resid;
5046 		ahd_outl(ahd, HADDR + 4, dataptr >> 32);
5047 	} else {
5048 		struct	 ahd_dma_seg *sg;
5049 
5050 		sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
5051 
5052 		/* The residual sg_ptr always points to the next sg */
5053 		sg--;
5054 
5055 		dataptr = aic_le32toh(sg->addr)
5056 			+ (aic_le32toh(sg->len) & AHD_SG_LEN_MASK)
5057 			- resid;
5058 		ahd_outb(ahd, HADDR + 4,
5059 			 (aic_le32toh(sg->len) & ~AHD_SG_LEN_MASK) >> 24);
5060 	}
5061 	ahd_outl(ahd, HADDR, dataptr);
5062 	ahd_outb(ahd, HCNT + 2, resid >> 16);
5063 	ahd_outb(ahd, HCNT + 1, resid >> 8);
5064 	ahd_outb(ahd, HCNT, resid);
5065 }
5066 
5067 /*
5068  * Handle the effects of issuing a bus device reset message.
5069  */
5070 static void
5071 ahd_handle_devreset(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5072 		    u_int lun, cam_status status, char *message,
5073 		    int verbose_level)
5074 {
5075 #ifdef AHD_TARGET_MODE
5076 	struct ahd_tmode_tstate* tstate;
5077 #endif
5078 	int found;
5079 
5080 	found = ahd_abort_scbs(ahd, devinfo->target, devinfo->channel,
5081 			       lun, SCB_LIST_NULL, devinfo->role,
5082 			       status);
5083 
5084 #ifdef AHD_TARGET_MODE
5085 	/*
5086 	 * Send an immediate notify ccb to all target mord peripheral
5087 	 * drivers affected by this action.
5088 	 */
5089 	tstate = ahd->enabled_targets[devinfo->our_scsiid];
5090 	if (tstate != NULL) {
5091 		u_int cur_lun;
5092 		u_int max_lun;
5093 
5094 		if (lun != CAM_LUN_WILDCARD) {
5095 			cur_lun = 0;
5096 			max_lun = AHD_NUM_LUNS - 1;
5097 		} else {
5098 			cur_lun = lun;
5099 			max_lun = lun;
5100 		}
5101 		for (cur_lun <= max_lun; cur_lun++) {
5102 			struct ahd_tmode_lstate* lstate;
5103 
5104 			lstate = tstate->enabled_luns[cur_lun];
5105 			if (lstate == NULL)
5106 				continue;
5107 
5108 			ahd_queue_lstate_event(ahd, lstate, devinfo->our_scsiid,
5109 					       MSG_BUS_DEV_RESET, /*arg*/0);
5110 			ahd_send_lstate_events(ahd, lstate);
5111 		}
5112 	}
5113 #endif
5114 
5115 	/*
5116 	 * Go back to async/narrow transfers and renegotiate.
5117 	 */
5118 	ahd_set_width(ahd, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
5119 		      AHD_TRANS_CUR, /*paused*/TRUE);
5120 	ahd_set_syncrate(ahd, devinfo, /*period*/0, /*offset*/0,
5121 			 /*ppr_options*/0, AHD_TRANS_CUR,
5122 			 /*paused*/TRUE);
5123 
5124 	if (status != CAM_SEL_TIMEOUT)
5125 		ahd_send_async(ahd, devinfo->channel, devinfo->target,
5126 			       lun, AC_SENT_BDR, NULL);
5127 
5128 	if (message != NULL
5129 	 && (verbose_level <= bootverbose)) {
5130 		AHD_CORRECTABLE_ERROR(ahd);
5131 		printf("%s: %s on %c:%d. %d SCBs aborted\n", ahd_name(ahd),
5132 		       message, devinfo->channel, devinfo->target, found);
5133 	}
5134 }
5135 
5136 #ifdef AHD_TARGET_MODE
5137 static void
5138 ahd_setup_target_msgin(struct ahd_softc *ahd, struct ahd_devinfo *devinfo,
5139 		       struct scb *scb)
5140 {
5141 
5142 	/*
5143 	 * To facilitate adding multiple messages together,
5144 	 * each routine should increment the index and len
5145 	 * variables instead of setting them explicitly.
5146 	 */
5147 	ahd->msgout_index = 0;
5148 	ahd->msgout_len = 0;
5149 
5150 	if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
5151 		ahd_build_transfer_msg(ahd, devinfo);
5152 	else
5153 		panic("ahd_intr: AWAITING target message with no message");
5154 
5155 	ahd->msgout_index = 0;
5156 	ahd->msg_type = MSG_TYPE_TARGET_MSGIN;
5157 }
5158 #endif
5159 /**************************** Initialization **********************************/
5160 static u_int
5161 ahd_sglist_size(struct ahd_softc *ahd)
5162 {
5163 	bus_size_t list_size;
5164 
5165 	list_size = sizeof(struct ahd_dma_seg) * AHD_NSEG;
5166 	if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
5167 		list_size = sizeof(struct ahd_dma64_seg) * AHD_NSEG;
5168 	return (list_size);
5169 }
5170 
5171 /*
5172  * Calculate the optimum S/G List allocation size.  S/G elements used
5173  * for a given transaction must be physically contiguous.  Assume the
5174  * OS will allocate full pages to us, so it doesn't make sense to request
5175  * less than a page.
5176  */
5177 static u_int
5178 ahd_sglist_allocsize(struct ahd_softc *ahd)
5179 {
5180 	bus_size_t sg_list_increment;
5181 	bus_size_t sg_list_size;
5182 	bus_size_t max_list_size;
5183 	bus_size_t best_list_size;
5184 
5185 	/* Start out with the minimum required for AHD_NSEG. */
5186 	sg_list_increment = ahd_sglist_size(ahd);
5187 	sg_list_size = sg_list_increment;
5188 
5189 	/* Get us as close as possible to a page in size. */
5190 	while ((sg_list_size + sg_list_increment) <= PAGE_SIZE)
5191 		sg_list_size += sg_list_increment;
5192 
5193 	/*
5194 	 * Try to reduce the amount of wastage by allocating
5195 	 * multiple pages.
5196 	 */
5197 	best_list_size = sg_list_size;
5198 	max_list_size = roundup(sg_list_increment, PAGE_SIZE);
5199 	if (max_list_size < 4 * PAGE_SIZE)
5200 		max_list_size = 4 * PAGE_SIZE;
5201 	if (max_list_size > (AHD_SCB_MAX_ALLOC * sg_list_increment))
5202 		max_list_size = (AHD_SCB_MAX_ALLOC * sg_list_increment);
5203 	while ((sg_list_size + sg_list_increment) <= max_list_size
5204 	   &&  (sg_list_size % PAGE_SIZE) != 0) {
5205 		bus_size_t new_mod;
5206 		bus_size_t best_mod;
5207 
5208 		sg_list_size += sg_list_increment;
5209 		new_mod = sg_list_size % PAGE_SIZE;
5210 		best_mod = best_list_size % PAGE_SIZE;
5211 		if (new_mod > best_mod || new_mod == 0) {
5212 			best_list_size = sg_list_size;
5213 		}
5214 	}
5215 	return (best_list_size);
5216 }
5217 
5218 /*
5219  * Allocate a controller structure for a new device
5220  * and perform initial initializion.
5221  */
5222 struct ahd_softc *
5223 ahd_alloc(void *platform_arg, char *name)
5224 {
5225 	struct  ahd_softc *ahd;
5226 
5227 #ifndef	__FreeBSD__
5228 	ahd = malloc(sizeof(*ahd), M_DEVBUF, M_NOWAIT);
5229 	if (!ahd) {
5230 		printf("aic7xxx: cannot malloc softc!\n");
5231 		free(name, M_DEVBUF);
5232 		return NULL;
5233 	}
5234 #else
5235 	ahd = device_get_softc((device_t)platform_arg);
5236 #endif
5237 	memset(ahd, 0, sizeof(*ahd));
5238 	ahd->seep_config = malloc(sizeof(*ahd->seep_config),
5239 				  M_DEVBUF, M_NOWAIT);
5240 	if (ahd->seep_config == NULL) {
5241 #ifndef	__FreeBSD__
5242 		free(ahd, M_DEVBUF);
5243 #endif
5244 		free(name, M_DEVBUF);
5245 		return (NULL);
5246 	}
5247 	LIST_INIT(&ahd->pending_scbs);
5248 	LIST_INIT(&ahd->timedout_scbs);
5249 	/* We don't know our unit number until the OSM sets it */
5250 	ahd->name = name;
5251 	ahd->unit = -1;
5252 	ahd->description = NULL;
5253 	ahd->bus_description = NULL;
5254 	ahd->channel = 'A';
5255 	ahd->chip = AHD_NONE;
5256 	ahd->features = AHD_FENONE;
5257 	ahd->bugs = AHD_BUGNONE;
5258 	ahd->flags = AHD_SPCHK_ENB_A|AHD_RESET_BUS_A|AHD_TERM_ENB_A
5259 		   | AHD_EXTENDED_TRANS_A|AHD_STPWLEVEL_A;
5260 	aic_timer_init(&ahd->reset_timer);
5261 	aic_timer_init(&ahd->stat_timer);
5262 	ahd->int_coalescing_timer = AHD_INT_COALESCING_TIMER_DEFAULT;
5263 	ahd->int_coalescing_maxcmds = AHD_INT_COALESCING_MAXCMDS_DEFAULT;
5264 	ahd->int_coalescing_mincmds = AHD_INT_COALESCING_MINCMDS_DEFAULT;
5265 	ahd->int_coalescing_threshold = AHD_INT_COALESCING_THRESHOLD_DEFAULT;
5266 	ahd->int_coalescing_stop_threshold =
5267 	    AHD_INT_COALESCING_STOP_THRESHOLD_DEFAULT;
5268 
5269 	if (ahd_platform_alloc(ahd, platform_arg) != 0) {
5270 		ahd_free(ahd);
5271 		ahd = NULL;
5272 	}
5273 	ahd_lockinit(ahd);
5274 #ifdef AHD_DEBUG
5275 	if ((ahd_debug & AHD_SHOW_MEMORY) != 0) {
5276 		printf("%s: scb size = 0x%x, hscb size = 0x%x\n",
5277 		       ahd_name(ahd), (u_int)sizeof(struct scb),
5278 		       (u_int)sizeof(struct hardware_scb));
5279 	}
5280 #endif
5281 	return (ahd);
5282 }
5283 
5284 int
5285 ahd_softc_init(struct ahd_softc *ahd)
5286 {
5287 
5288 	ahd->unpause = 0;
5289 	ahd->pause = PAUSE;
5290 	return (0);
5291 }
5292 
5293 void
5294 ahd_softc_insert(struct ahd_softc *ahd)
5295 {
5296 	struct ahd_softc *list_ahd;
5297 
5298 #if AIC_PCI_CONFIG > 0
5299 	/*
5300 	 * Second Function PCI devices need to inherit some
5301 	 * settings from function 0.
5302 	 */
5303 	if ((ahd->features & AHD_MULTI_FUNC) != 0) {
5304 		TAILQ_FOREACH(list_ahd, &ahd_tailq, links) {
5305 			aic_dev_softc_t list_pci;
5306 			aic_dev_softc_t pci;
5307 
5308 			list_pci = list_ahd->dev_softc;
5309 			pci = ahd->dev_softc;
5310 			if (aic_get_pci_slot(list_pci) == aic_get_pci_slot(pci)
5311 			 && aic_get_pci_bus(list_pci) == aic_get_pci_bus(pci)) {
5312 				struct ahd_softc *master;
5313 				struct ahd_softc *slave;
5314 
5315 				if (aic_get_pci_function(list_pci) == 0) {
5316 					master = list_ahd;
5317 					slave = ahd;
5318 				} else {
5319 					master = ahd;
5320 					slave = list_ahd;
5321 				}
5322 				slave->flags &= ~AHD_BIOS_ENABLED;
5323 				slave->flags |=
5324 				    master->flags & AHD_BIOS_ENABLED;
5325 				break;
5326 			}
5327 		}
5328 	}
5329 #endif
5330 
5331 	/*
5332 	 * Insertion sort into our list of softcs.
5333 	 */
5334 	list_ahd = TAILQ_FIRST(&ahd_tailq);
5335 	while (list_ahd != NULL
5336 	    && ahd_softc_comp(ahd, list_ahd) <= 0)
5337 		list_ahd = TAILQ_NEXT(list_ahd, links);
5338 	if (list_ahd != NULL)
5339 		TAILQ_INSERT_BEFORE(list_ahd, ahd, links);
5340 	else
5341 		TAILQ_INSERT_TAIL(&ahd_tailq, ahd, links);
5342 	ahd->init_level++;
5343 }
5344 
5345 void
5346 ahd_set_unit(struct ahd_softc *ahd, int unit)
5347 {
5348 	ahd->unit = unit;
5349 }
5350 
5351 void
5352 ahd_set_name(struct ahd_softc *ahd, char *name)
5353 {
5354 	if (ahd->name != NULL)
5355 		free(ahd->name, M_DEVBUF);
5356 	ahd->name = name;
5357 }
5358 
5359 void
5360 ahd_free(struct ahd_softc *ahd)
5361 {
5362 	int i;
5363 
5364 	ahd_terminate_recovery_thread(ahd);
5365 	switch (ahd->init_level) {
5366 	default:
5367 	case 5:
5368 		ahd_shutdown(ahd);
5369 		/* FALLTHROUGH */
5370 	case 4:
5371 		aic_dmamap_unload(ahd, ahd->shared_data_dmat,
5372 				  ahd->shared_data_map.dmamap);
5373 		/* FALLTHROUGH */
5374 	case 3:
5375 		aic_dmamem_free(ahd, ahd->shared_data_dmat, ahd->qoutfifo,
5376 				ahd->shared_data_map.dmamap);
5377 		/* FALLTHROUGH */
5378 	case 2:
5379 		aic_dma_tag_destroy(ahd, ahd->shared_data_dmat);
5380 	case 1:
5381 #ifndef __linux__
5382 		aic_dma_tag_destroy(ahd, ahd->buffer_dmat);
5383 #endif
5384 		break;
5385 	case 0:
5386 		break;
5387 	}
5388 
5389 #ifndef __linux__
5390 	aic_dma_tag_destroy(ahd, ahd->parent_dmat);
5391 #endif
5392 	ahd_platform_free(ahd);
5393 	ahd_fini_scbdata(ahd);
5394 	for (i = 0; i < AHD_NUM_TARGETS; i++) {
5395 		struct ahd_tmode_tstate *tstate;
5396 
5397 		tstate = ahd->enabled_targets[i];
5398 		if (tstate != NULL) {
5399 #ifdef AHD_TARGET_MODE
5400 			int j;
5401 
5402 			for (j = 0; j < AHD_NUM_LUNS; j++) {
5403 				struct ahd_tmode_lstate *lstate;
5404 
5405 				lstate = tstate->enabled_luns[j];
5406 				if (lstate != NULL) {
5407 					xpt_free_path(lstate->path);
5408 					free(lstate, M_DEVBUF);
5409 				}
5410 			}
5411 #endif
5412 			free(tstate, M_DEVBUF);
5413 		}
5414 	}
5415 #ifdef AHD_TARGET_MODE
5416 	if (ahd->black_hole != NULL) {
5417 		xpt_free_path(ahd->black_hole->path);
5418 		free(ahd->black_hole, M_DEVBUF);
5419 	}
5420 #endif
5421 	if (ahd->name != NULL)
5422 		free(ahd->name, M_DEVBUF);
5423 	if (ahd->seep_config != NULL)
5424 		free(ahd->seep_config, M_DEVBUF);
5425 	if (ahd->saved_stack != NULL)
5426 		free(ahd->saved_stack, M_DEVBUF);
5427 #ifndef __FreeBSD__
5428 	free(ahd, M_DEVBUF);
5429 #endif
5430 	return;
5431 }
5432 
5433 void
5434 ahd_shutdown(void *arg)
5435 {
5436 	struct	ahd_softc *ahd;
5437 
5438 	ahd = (struct ahd_softc *)arg;
5439 
5440 	/*
5441 	 * Stop periodic timer callbacks.
5442 	 */
5443 	aic_timer_stop(&ahd->reset_timer);
5444 	aic_timer_stop(&ahd->stat_timer);
5445 
5446 	/* This will reset most registers to 0, but not all */
5447 	ahd_reset(ahd, /*reinit*/FALSE);
5448 }
5449 
5450 /*
5451  * Reset the controller and record some information about it
5452  * that is only available just after a reset.  If "reinit" is
5453  * non-zero, this reset occurred after initial configuration
5454  * and the caller requests that the chip be fully reinitialized
5455  * to a runable state.  Chip interrupts are *not* enabled after
5456  * a reinitialization.  The caller must enable interrupts via
5457  * ahd_intr_enable().
5458  */
5459 int
5460 ahd_reset(struct ahd_softc *ahd, int reinit)
5461 {
5462 	u_int	 sxfrctl1;
5463 	int	 wait;
5464 	uint32_t cmd;
5465 
5466 	/*
5467 	 * Preserve the value of the SXFRCTL1 register for all channels.
5468 	 * It contains settings that affect termination and we don't want
5469 	 * to disturb the integrity of the bus.
5470 	 */
5471 	ahd_pause(ahd);
5472 	ahd_update_modes(ahd);
5473 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5474 	sxfrctl1 = ahd_inb(ahd, SXFRCTL1);
5475 
5476 	cmd = aic_pci_read_config(ahd->dev_softc, PCIR_COMMAND, /*bytes*/2);
5477 	if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
5478 		uint32_t mod_cmd;
5479 
5480 		/*
5481 		 * A4 Razor #632
5482 		 * During the assertion of CHIPRST, the chip
5483 		 * does not disable its parity logic prior to
5484 		 * the start of the reset.  This may cause a
5485 		 * parity error to be detected and thus a
5486 		 * spurious SERR or PERR assertion.  Disable
5487 		 * PERR and SERR responses during the CHIPRST.
5488 		 */
5489 		mod_cmd = cmd & ~(PCIM_CMD_PERRESPEN|PCIM_CMD_SERRESPEN);
5490 		aic_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
5491 				     mod_cmd, /*bytes*/2);
5492 	}
5493 	ahd_outb(ahd, HCNTRL, CHIPRST | ahd->pause);
5494 
5495 	/*
5496 	 * Ensure that the reset has finished.  We delay 1000us
5497 	 * prior to reading the register to make sure the chip
5498 	 * has sufficiently completed its reset to handle register
5499 	 * accesses.
5500 	 */
5501 	wait = 1000;
5502 	do {
5503 		aic_delay(1000);
5504 	} while (--wait && !(ahd_inb(ahd, HCNTRL) & CHIPRSTACK));
5505 
5506 	if (wait == 0) {
5507 		printf("%s: WARNING - Failed chip reset!  "
5508 		       "Trying to initialize anyway.\n", ahd_name(ahd));
5509 		AHD_FATAL_ERROR(ahd);
5510 	}
5511 	ahd_outb(ahd, HCNTRL, ahd->pause);
5512 
5513 	if ((ahd->bugs & AHD_PCIX_CHIPRST_BUG) != 0) {
5514 		/*
5515 		 * Clear any latched PCI error status and restore
5516 		 * previous SERR and PERR response enables.
5517 		 */
5518 		aic_pci_write_config(ahd->dev_softc, PCIR_STATUS + 1,
5519 				     0xFF, /*bytes*/1);
5520 		aic_pci_write_config(ahd->dev_softc, PCIR_COMMAND,
5521 				     cmd, /*bytes*/2);
5522 	}
5523 
5524 	/*
5525 	 * Mode should be SCSI after a chip reset, but lets
5526 	 * set it just to be safe.  We touch the MODE_PTR
5527 	 * register directly so as to bypass the lazy update
5528 	 * code in ahd_set_modes().
5529 	 */
5530 	ahd_known_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5531 	ahd_outb(ahd, MODE_PTR,
5532 		 ahd_build_mode_state(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI));
5533 
5534 	/*
5535 	 * Restore SXFRCTL1.
5536 	 *
5537 	 * We must always initialize STPWEN to 1 before we
5538 	 * restore the saved values.  STPWEN is initialized
5539 	 * to a tri-state condition which can only be cleared
5540 	 * by turning it on.
5541 	 */
5542 	ahd_outb(ahd, SXFRCTL1, sxfrctl1|STPWEN);
5543 	ahd_outb(ahd, SXFRCTL1, sxfrctl1);
5544 
5545 	/* Determine chip configuration */
5546 	ahd->features &= ~AHD_WIDE;
5547 	if ((ahd_inb(ahd, SBLKCTL) & SELWIDE) != 0)
5548 		ahd->features |= AHD_WIDE;
5549 
5550 	/*
5551 	 * If a recovery action has forced a chip reset,
5552 	 * re-initialize the chip to our liking.
5553 	 */
5554 	if (reinit != 0)
5555 		ahd_chip_init(ahd);
5556 
5557 	return (0);
5558 }
5559 
5560 /*
5561  * Determine the number of SCBs available on the controller
5562  */
5563 int
5564 ahd_probe_scbs(struct ahd_softc *ahd) {
5565 	int i;
5566 
5567 	AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
5568 			 ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
5569 	for (i = 0; i < AHD_SCB_MAX; i++) {
5570 		int j;
5571 
5572 		ahd_set_scbptr(ahd, i);
5573 		ahd_outw(ahd, SCB_BASE, i);
5574 		for (j = 2; j < 64; j++)
5575 			ahd_outb(ahd, SCB_BASE+j, 0);
5576 		/* Start out life as unallocated (needing an abort) */
5577 		ahd_outb(ahd, SCB_CONTROL, MK_MESSAGE);
5578 		if (ahd_inw_scbram(ahd, SCB_BASE) != i)
5579 			break;
5580 		ahd_set_scbptr(ahd, 0);
5581 		if (ahd_inw_scbram(ahd, SCB_BASE) != 0)
5582 			break;
5583 	}
5584 	return (i);
5585 }
5586 
5587 static void
5588 ahd_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
5589 {
5590 	bus_addr_t *baddr;
5591 
5592 	baddr = (bus_addr_t *)arg;
5593 	*baddr = segs->ds_addr;
5594 }
5595 
5596 static void
5597 ahd_initialize_hscbs(struct ahd_softc *ahd)
5598 {
5599 	int i;
5600 
5601 	for (i = 0; i < ahd->scb_data.maxhscbs; i++) {
5602 		ahd_set_scbptr(ahd, i);
5603 
5604 		/* Clear the control byte. */
5605 		ahd_outb(ahd, SCB_CONTROL, 0);
5606 
5607 		/* Set the next pointer */
5608 		ahd_outw(ahd, SCB_NEXT, SCB_LIST_NULL);
5609 	}
5610 }
5611 
5612 static int
5613 ahd_init_scbdata(struct ahd_softc *ahd)
5614 {
5615 	struct	scb_data *scb_data;
5616 	int	i;
5617 
5618 	scb_data = &ahd->scb_data;
5619 	TAILQ_INIT(&scb_data->free_scbs);
5620 	for (i = 0; i < AHD_NUM_TARGETS * AHD_NUM_LUNS_NONPKT; i++)
5621 		LIST_INIT(&scb_data->free_scb_lists[i]);
5622 	LIST_INIT(&scb_data->any_dev_free_scb_list);
5623 	SLIST_INIT(&scb_data->hscb_maps);
5624 	SLIST_INIT(&scb_data->sg_maps);
5625 	SLIST_INIT(&scb_data->sense_maps);
5626 
5627 	/* Determine the number of hardware SCBs and initialize them */
5628 	scb_data->maxhscbs = ahd_probe_scbs(ahd);
5629 	if (scb_data->maxhscbs == 0) {
5630 		printf("%s: No SCB space found\n", ahd_name(ahd));
5631 		AHD_FATAL_ERROR(ahd);
5632 		return (ENXIO);
5633 	}
5634 
5635 	ahd_initialize_hscbs(ahd);
5636 
5637 	/*
5638 	 * Create our DMA tags.  These tags define the kinds of device
5639 	 * accessible memory allocations and memory mappings we will
5640 	 * need to perform during normal operation.
5641 	 *
5642 	 * Unless we need to further restrict the allocation, we rely
5643 	 * on the restrictions of the parent dmat, hence the common
5644 	 * use of MAXADDR and MAXSIZE.
5645 	 */
5646 
5647 	/* DMA tag for our hardware scb structures */
5648 	if (aic_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
5649 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5650 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5651 			       /*highaddr*/BUS_SPACE_MAXADDR,
5652 			       /*filter*/NULL, /*filterarg*/NULL,
5653 			       PAGE_SIZE, /*nsegments*/1,
5654 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5655 			       /*flags*/0, &scb_data->hscb_dmat) != 0) {
5656 		goto error_exit;
5657 	}
5658 
5659 	scb_data->init_level++;
5660 
5661 	/* DMA tag for our S/G structures. */
5662 	if (aic_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/8,
5663 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5664 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5665 			       /*highaddr*/BUS_SPACE_MAXADDR,
5666 			       /*filter*/NULL, /*filterarg*/NULL,
5667 			       ahd_sglist_allocsize(ahd), /*nsegments*/1,
5668 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5669 			       /*flags*/0, &scb_data->sg_dmat) != 0) {
5670 		goto error_exit;
5671 	}
5672 #ifdef AHD_DEBUG
5673 	if ((ahd_debug & AHD_SHOW_MEMORY) != 0)
5674 		printf("%s: ahd_sglist_allocsize = 0x%x\n", ahd_name(ahd),
5675 		       ahd_sglist_allocsize(ahd));
5676 #endif
5677 
5678 	scb_data->init_level++;
5679 
5680 	/* DMA tag for our sense buffers.  We allocate in page sized chunks */
5681 	if (aic_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
5682 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
5683 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
5684 			       /*highaddr*/BUS_SPACE_MAXADDR,
5685 			       /*filter*/NULL, /*filterarg*/NULL,
5686 			       PAGE_SIZE, /*nsegments*/1,
5687 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
5688 			       /*flags*/0, &scb_data->sense_dmat) != 0) {
5689 		goto error_exit;
5690 	}
5691 
5692 	scb_data->init_level++;
5693 
5694 	/* Perform initial CCB allocation */
5695 	while (ahd_alloc_scbs(ahd) != 0)
5696 		;
5697 
5698 	if (scb_data->numscbs == 0) {
5699 		printf("%s: ahd_init_scbdata - "
5700 		       "Unable to allocate initial scbs\n",
5701 		       ahd_name(ahd));
5702 		goto error_exit;
5703 	}
5704 
5705 	/*
5706 	 * Note that we were successful
5707 	 */
5708 	return (0);
5709 
5710 error_exit:
5711 
5712 	return (ENOMEM);
5713 }
5714 
5715 static struct scb *
5716 ahd_find_scb_by_tag(struct ahd_softc *ahd, u_int tag)
5717 {
5718 	struct scb *scb;
5719 
5720 	/*
5721 	 * Look on the pending list.
5722 	 */
5723 	LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
5724 		if (SCB_GET_TAG(scb) == tag)
5725 			return (scb);
5726 	}
5727 
5728 	/*
5729 	 * Then on all of the collision free lists.
5730 	 */
5731 	TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
5732 		struct scb *list_scb;
5733 
5734 		list_scb = scb;
5735 		do {
5736 			if (SCB_GET_TAG(list_scb) == tag)
5737 				return (list_scb);
5738 			list_scb = LIST_NEXT(list_scb, collision_links);
5739 		} while (list_scb);
5740 	}
5741 
5742 	/*
5743 	 * And finally on the generic free list.
5744 	 */
5745 	LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
5746 		if (SCB_GET_TAG(scb) == tag)
5747 			return (scb);
5748 	}
5749 
5750 	return (NULL);
5751 }
5752 
5753 static void
5754 ahd_fini_scbdata(struct ahd_softc *ahd)
5755 {
5756 	struct scb_data *scb_data;
5757 
5758 	scb_data = &ahd->scb_data;
5759 	if (scb_data == NULL)
5760 		return;
5761 
5762 	switch (scb_data->init_level) {
5763 	default:
5764 	case 7:
5765 	{
5766 		struct map_node *sns_map;
5767 
5768 		while ((sns_map = SLIST_FIRST(&scb_data->sense_maps)) != NULL) {
5769 			SLIST_REMOVE_HEAD(&scb_data->sense_maps, links);
5770 			aic_dmamap_unload(ahd, scb_data->sense_dmat,
5771 					  sns_map->dmamap);
5772 			aic_dmamem_free(ahd, scb_data->sense_dmat,
5773 					sns_map->vaddr, sns_map->dmamap);
5774 			free(sns_map, M_DEVBUF);
5775 		}
5776 		aic_dma_tag_destroy(ahd, scb_data->sense_dmat);
5777 		/* FALLTHROUGH */
5778 	}
5779 	case 6:
5780 	{
5781 		struct map_node *sg_map;
5782 
5783 		while ((sg_map = SLIST_FIRST(&scb_data->sg_maps)) != NULL) {
5784 			SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
5785 			aic_dmamap_unload(ahd, scb_data->sg_dmat,
5786 					  sg_map->dmamap);
5787 			aic_dmamem_free(ahd, scb_data->sg_dmat,
5788 					sg_map->vaddr, sg_map->dmamap);
5789 			free(sg_map, M_DEVBUF);
5790 		}
5791 		aic_dma_tag_destroy(ahd, scb_data->sg_dmat);
5792 		/* FALLTHROUGH */
5793 	}
5794 	case 5:
5795 	{
5796 		struct map_node *hscb_map;
5797 
5798 		while ((hscb_map = SLIST_FIRST(&scb_data->hscb_maps)) != NULL) {
5799 			SLIST_REMOVE_HEAD(&scb_data->hscb_maps, links);
5800 			aic_dmamap_unload(ahd, scb_data->hscb_dmat,
5801 					  hscb_map->dmamap);
5802 			aic_dmamem_free(ahd, scb_data->hscb_dmat,
5803 					hscb_map->vaddr, hscb_map->dmamap);
5804 			free(hscb_map, M_DEVBUF);
5805 		}
5806 		aic_dma_tag_destroy(ahd, scb_data->hscb_dmat);
5807 		/* FALLTHROUGH */
5808 	}
5809 	case 4:
5810 	case 3:
5811 	case 2:
5812 	case 1:
5813 	case 0:
5814 		break;
5815 	}
5816 }
5817 
5818 /*
5819  * DSP filter Bypass must be enabled until the first selection
5820  * after a change in bus mode (Razor #491 and #493).
5821  */
5822 static void
5823 ahd_setup_iocell_workaround(struct ahd_softc *ahd)
5824 {
5825 	ahd_mode_state saved_modes;
5826 
5827 	saved_modes = ahd_save_modes(ahd);
5828 	ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
5829 	ahd_outb(ahd, DSPDATACTL, ahd_inb(ahd, DSPDATACTL)
5830 	       | BYPASSENAB | RCVROFFSTDIS | XMITOFFSTDIS);
5831 	ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) | (ENSELDO|ENSELDI));
5832 #ifdef AHD_DEBUG
5833 	if ((ahd_debug & AHD_SHOW_MISC) != 0)
5834 		printf("%s: Setting up iocell workaround\n", ahd_name(ahd));
5835 #endif
5836 	ahd_restore_modes(ahd, saved_modes);
5837 	ahd->flags &= ~AHD_HAD_FIRST_SEL;
5838 }
5839 
5840 static void
5841 ahd_iocell_first_selection(struct ahd_softc *ahd)
5842 {
5843 	ahd_mode_state	saved_modes;
5844 	u_int		sblkctl;
5845 
5846 	if ((ahd->flags & AHD_HAD_FIRST_SEL) != 0)
5847 		return;
5848 	saved_modes = ahd_save_modes(ahd);
5849 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
5850 	sblkctl = ahd_inb(ahd, SBLKCTL);
5851 	ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
5852 #ifdef AHD_DEBUG
5853 	if ((ahd_debug & AHD_SHOW_MISC) != 0)
5854 		printf("%s: iocell first selection\n", ahd_name(ahd));
5855 #endif
5856 	if ((sblkctl & ENAB40) != 0) {
5857 		ahd_outb(ahd, DSPDATACTL,
5858 			 ahd_inb(ahd, DSPDATACTL) & ~BYPASSENAB);
5859 #ifdef AHD_DEBUG
5860 		if ((ahd_debug & AHD_SHOW_MISC) != 0)
5861 			printf("%s: BYPASS now disabled\n", ahd_name(ahd));
5862 #endif
5863 	}
5864 	ahd_outb(ahd, SIMODE0, ahd_inb(ahd, SIMODE0) & ~(ENSELDO|ENSELDI));
5865 	ahd_outb(ahd, CLRINT, CLRSCSIINT);
5866 	ahd_restore_modes(ahd, saved_modes);
5867 	ahd->flags |= AHD_HAD_FIRST_SEL;
5868 }
5869 
5870 /*************************** SCB Management ***********************************/
5871 static void
5872 ahd_add_col_list(struct ahd_softc *ahd, struct scb *scb, u_int col_idx)
5873 {
5874 	struct	scb_list *free_list;
5875 	struct	scb_tailq *free_tailq;
5876 	struct	scb *first_scb;
5877 
5878 	scb->flags |= SCB_ON_COL_LIST;
5879 	AHD_SET_SCB_COL_IDX(scb, col_idx);
5880 	free_list = &ahd->scb_data.free_scb_lists[col_idx];
5881 	free_tailq = &ahd->scb_data.free_scbs;
5882 	first_scb = LIST_FIRST(free_list);
5883 	if (first_scb != NULL) {
5884 		LIST_INSERT_AFTER(first_scb, scb, collision_links);
5885 	} else {
5886 		LIST_INSERT_HEAD(free_list, scb, collision_links);
5887 		TAILQ_INSERT_TAIL(free_tailq, scb, links.tqe);
5888 	}
5889 }
5890 
5891 static void
5892 ahd_rem_col_list(struct ahd_softc *ahd, struct scb *scb)
5893 {
5894 	struct	scb_list *free_list;
5895 	struct	scb_tailq *free_tailq;
5896 	struct	scb *first_scb;
5897 	u_int	col_idx;
5898 
5899 	scb->flags &= ~SCB_ON_COL_LIST;
5900 	col_idx = AHD_GET_SCB_COL_IDX(ahd, scb);
5901 	free_list = &ahd->scb_data.free_scb_lists[col_idx];
5902 	free_tailq = &ahd->scb_data.free_scbs;
5903 	first_scb = LIST_FIRST(free_list);
5904 	if (first_scb == scb) {
5905 		struct scb *next_scb;
5906 
5907 		/*
5908 		 * Maintain order in the collision free
5909 		 * lists for fairness if this device has
5910 		 * other colliding tags active.
5911 		 */
5912 		next_scb = LIST_NEXT(scb, collision_links);
5913 		if (next_scb != NULL) {
5914 			TAILQ_INSERT_AFTER(free_tailq, scb,
5915 					   next_scb, links.tqe);
5916 		}
5917 		TAILQ_REMOVE(free_tailq, scb, links.tqe);
5918 	}
5919 	LIST_REMOVE(scb, collision_links);
5920 }
5921 
5922 /*
5923  * Get a free scb. If there are none, see if we can allocate a new SCB.
5924  */
5925 struct scb *
5926 ahd_get_scb(struct ahd_softc *ahd, u_int col_idx)
5927 {
5928 	struct scb *scb;
5929 	int tries;
5930 
5931 	tries = 0;
5932 look_again:
5933 	TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
5934 		if (AHD_GET_SCB_COL_IDX(ahd, scb) != col_idx) {
5935 			ahd_rem_col_list(ahd, scb);
5936 			goto found;
5937 		}
5938 	}
5939 	if ((scb = LIST_FIRST(&ahd->scb_data.any_dev_free_scb_list)) == NULL) {
5940 		if (tries++ != 0)
5941 			return (NULL);
5942 		if (ahd_alloc_scbs(ahd) == 0)
5943 			return (NULL);
5944 		goto look_again;
5945 	}
5946 	LIST_REMOVE(scb, links.le);
5947 	if (col_idx != AHD_NEVER_COL_IDX
5948 	 && (scb->col_scb != NULL)
5949 	 && (scb->col_scb->flags & SCB_ACTIVE) == 0) {
5950 		LIST_REMOVE(scb->col_scb, links.le);
5951 		ahd_add_col_list(ahd, scb->col_scb, col_idx);
5952 	}
5953 found:
5954 	scb->flags |= SCB_ACTIVE;
5955 	return (scb);
5956 }
5957 
5958 /*
5959  * Return an SCB resource to the free list.
5960  */
5961 void
5962 ahd_free_scb(struct ahd_softc *ahd, struct scb *scb)
5963 {
5964 
5965 	/* Clean up for the next user */
5966 	scb->flags = SCB_FLAG_NONE;
5967 	scb->hscb->control = 0;
5968 	ahd->scb_data.scbindex[SCB_GET_TAG(scb)] = NULL;
5969 
5970 	if (scb->col_scb == NULL) {
5971 		/*
5972 		 * No collision possible.  Just free normally.
5973 		 */
5974 		LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5975 				 scb, links.le);
5976 	} else if ((scb->col_scb->flags & SCB_ON_COL_LIST) != 0) {
5977 		/*
5978 		 * The SCB we might have collided with is on
5979 		 * a free collision list.  Put both SCBs on
5980 		 * the generic list.
5981 		 */
5982 		ahd_rem_col_list(ahd, scb->col_scb);
5983 		LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5984 				 scb, links.le);
5985 		LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
5986 				 scb->col_scb, links.le);
5987 	} else if ((scb->col_scb->flags
5988 		  & (SCB_PACKETIZED|SCB_ACTIVE)) == SCB_ACTIVE
5989 		&& (scb->col_scb->hscb->control & TAG_ENB) != 0) {
5990 		/*
5991 		 * The SCB we might collide with on the next allocation
5992 		 * is still active in a non-packetized, tagged, context.
5993 		 * Put us on the SCB collision list.
5994 		 */
5995 		ahd_add_col_list(ahd, scb,
5996 				 AHD_GET_SCB_COL_IDX(ahd, scb->col_scb));
5997 	} else {
5998 		/*
5999 		 * The SCB we might collide with on the next allocation
6000 		 * is either active in a packetized context, or free.
6001 		 * Since we can't collide, put this SCB on the generic
6002 		 * free list.
6003 		 */
6004 		LIST_INSERT_HEAD(&ahd->scb_data.any_dev_free_scb_list,
6005 				 scb, links.le);
6006 	}
6007 
6008 	aic_platform_scb_free(ahd, scb);
6009 }
6010 
6011 int
6012 ahd_alloc_scbs(struct ahd_softc *ahd)
6013 {
6014 	struct scb_data *scb_data;
6015 	struct scb	*next_scb;
6016 	struct hardware_scb *hscb;
6017 	struct map_node *hscb_map;
6018 	struct map_node *sg_map;
6019 	struct map_node *sense_map;
6020 	uint8_t		*segs;
6021 	uint8_t		*sense_data;
6022 	bus_addr_t	 hscb_busaddr;
6023 	bus_addr_t	 sg_busaddr;
6024 	bus_addr_t	 sense_busaddr;
6025 	int		 newcount;
6026 	int		 i;
6027 
6028 	scb_data = &ahd->scb_data;
6029 	if (scb_data->numscbs >= AHD_SCB_MAX_ALLOC)
6030 		/* Can't allocate any more */
6031 		return (0);
6032 
6033 	if (scb_data->scbs_left != 0) {
6034 		int offset;
6035 
6036 		offset = (PAGE_SIZE / sizeof(*hscb)) - scb_data->scbs_left;
6037 		hscb_map = SLIST_FIRST(&scb_data->hscb_maps);
6038 		hscb = &((struct hardware_scb *)hscb_map->vaddr)[offset];
6039 		hscb_busaddr = hscb_map->busaddr + (offset * sizeof(*hscb));
6040 	} else {
6041 		hscb_map = malloc(sizeof(*hscb_map), M_DEVBUF, M_NOWAIT);
6042 
6043 		if (hscb_map == NULL)
6044 			return (0);
6045 
6046 		/* Allocate the next batch of hardware SCBs */
6047 		if (aic_dmamem_alloc(ahd, scb_data->hscb_dmat,
6048 				     (void **)&hscb_map->vaddr,
6049 				     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
6050 				     &hscb_map->dmamap) != 0) {
6051 			free(hscb_map, M_DEVBUF);
6052 			return (0);
6053 		}
6054 
6055 		SLIST_INSERT_HEAD(&scb_data->hscb_maps, hscb_map, links);
6056 
6057 		aic_dmamap_load(ahd, scb_data->hscb_dmat, hscb_map->dmamap,
6058 				hscb_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6059 				&hscb_map->busaddr, /*flags*/0);
6060 
6061 		hscb = (struct hardware_scb *)hscb_map->vaddr;
6062 		hscb_busaddr = hscb_map->busaddr;
6063 		scb_data->scbs_left = PAGE_SIZE / sizeof(*hscb);
6064 	}
6065 
6066 	if (scb_data->sgs_left != 0) {
6067 		int offset;
6068 
6069 		offset = ((ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd))
6070 		       - scb_data->sgs_left) * ahd_sglist_size(ahd);
6071 		sg_map = SLIST_FIRST(&scb_data->sg_maps);
6072 		segs = sg_map->vaddr + offset;
6073 		sg_busaddr = sg_map->busaddr + offset;
6074 	} else {
6075 		sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
6076 
6077 		if (sg_map == NULL)
6078 			return (0);
6079 
6080 		/* Allocate the next batch of S/G lists */
6081 		if (aic_dmamem_alloc(ahd, scb_data->sg_dmat,
6082 				     (void **)&sg_map->vaddr,
6083 				     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
6084 				     &sg_map->dmamap) != 0) {
6085 			free(sg_map, M_DEVBUF);
6086 			return (0);
6087 		}
6088 
6089 		SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
6090 
6091 		aic_dmamap_load(ahd, scb_data->sg_dmat, sg_map->dmamap,
6092 				sg_map->vaddr, ahd_sglist_allocsize(ahd),
6093 				ahd_dmamap_cb, &sg_map->busaddr, /*flags*/0);
6094 
6095 		segs = sg_map->vaddr;
6096 		sg_busaddr = sg_map->busaddr;
6097 		scb_data->sgs_left =
6098 		    ahd_sglist_allocsize(ahd) / ahd_sglist_size(ahd);
6099 #ifdef AHD_DEBUG
6100 		if (ahd_debug & AHD_SHOW_MEMORY)
6101 			printf("Mapped SG data\n");
6102 #endif
6103 	}
6104 
6105 	if (scb_data->sense_left != 0) {
6106 		int offset;
6107 
6108 		offset = PAGE_SIZE - (AHD_SENSE_BUFSIZE * scb_data->sense_left);
6109 		sense_map = SLIST_FIRST(&scb_data->sense_maps);
6110 		sense_data = sense_map->vaddr + offset;
6111 		sense_busaddr = sense_map->busaddr + offset;
6112 	} else {
6113 		sense_map = malloc(sizeof(*sense_map), M_DEVBUF, M_NOWAIT);
6114 
6115 		if (sense_map == NULL)
6116 			return (0);
6117 
6118 		/* Allocate the next batch of sense buffers */
6119 		if (aic_dmamem_alloc(ahd, scb_data->sense_dmat,
6120 				     (void **)&sense_map->vaddr,
6121 				     BUS_DMA_NOWAIT, &sense_map->dmamap) != 0) {
6122 			free(sense_map, M_DEVBUF);
6123 			return (0);
6124 		}
6125 
6126 		SLIST_INSERT_HEAD(&scb_data->sense_maps, sense_map, links);
6127 
6128 		aic_dmamap_load(ahd, scb_data->sense_dmat, sense_map->dmamap,
6129 				sense_map->vaddr, PAGE_SIZE, ahd_dmamap_cb,
6130 				&sense_map->busaddr, /*flags*/0);
6131 
6132 		sense_data = sense_map->vaddr;
6133 		sense_busaddr = sense_map->busaddr;
6134 		scb_data->sense_left = PAGE_SIZE / AHD_SENSE_BUFSIZE;
6135 #ifdef AHD_DEBUG
6136 		if (ahd_debug & AHD_SHOW_MEMORY)
6137 			printf("Mapped sense data\n");
6138 #endif
6139 	}
6140 
6141 	newcount = MIN(scb_data->sense_left, scb_data->scbs_left);
6142 	newcount = MIN(newcount, scb_data->sgs_left);
6143 	newcount = MIN(newcount, (AHD_SCB_MAX_ALLOC - scb_data->numscbs));
6144 	scb_data->sense_left -= newcount;
6145 	scb_data->scbs_left -= newcount;
6146 	scb_data->sgs_left -= newcount;
6147 	for (i = 0; i < newcount; i++) {
6148 		struct scb_platform_data *pdata;
6149 		u_int col_tag;
6150 #ifndef __linux__
6151 		int error;
6152 #endif
6153 
6154 		next_scb = (struct scb *)malloc(sizeof(*next_scb),
6155 						M_DEVBUF, M_NOWAIT);
6156 		if (next_scb == NULL)
6157 			break;
6158 
6159 		pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
6160 							   M_DEVBUF, M_NOWAIT);
6161 		if (pdata == NULL) {
6162 			free(next_scb, M_DEVBUF);
6163 			break;
6164 		}
6165 		next_scb->platform_data = pdata;
6166 		next_scb->hscb_map = hscb_map;
6167 		next_scb->sg_map = sg_map;
6168 		next_scb->sense_map = sense_map;
6169 		next_scb->sg_list = segs;
6170 		next_scb->sense_data = sense_data;
6171 		next_scb->sense_busaddr = sense_busaddr;
6172 		memset(hscb, 0, sizeof(*hscb));
6173 		next_scb->hscb = hscb;
6174 		hscb->hscb_busaddr = aic_htole32(hscb_busaddr);
6175 
6176 		/*
6177 		 * The sequencer always starts with the second entry.
6178 		 * The first entry is embedded in the scb.
6179 		 */
6180 		next_scb->sg_list_busaddr = sg_busaddr;
6181 		if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
6182 			next_scb->sg_list_busaddr
6183 			    += sizeof(struct ahd_dma64_seg);
6184 		else
6185 			next_scb->sg_list_busaddr += sizeof(struct ahd_dma_seg);
6186 		next_scb->ahd_softc = ahd;
6187 		next_scb->flags = SCB_FLAG_NONE;
6188 #ifndef __linux__
6189 		error = aic_dmamap_create(ahd, ahd->buffer_dmat, /*flags*/0,
6190 					  &next_scb->dmamap);
6191 		if (error != 0) {
6192 			free(next_scb, M_DEVBUF);
6193 			free(pdata, M_DEVBUF);
6194 			break;
6195 		}
6196 #endif
6197 		next_scb->hscb->tag = aic_htole16(scb_data->numscbs);
6198 		col_tag = scb_data->numscbs ^ 0x100;
6199 		next_scb->col_scb = ahd_find_scb_by_tag(ahd, col_tag);
6200 		if (next_scb->col_scb != NULL)
6201 			next_scb->col_scb->col_scb = next_scb;
6202 		aic_timer_init(&next_scb->io_timer);
6203 		ahd_free_scb(ahd, next_scb);
6204 		hscb++;
6205 		hscb_busaddr += sizeof(*hscb);
6206 		segs += ahd_sglist_size(ahd);
6207 		sg_busaddr += ahd_sglist_size(ahd);
6208 		sense_data += AHD_SENSE_BUFSIZE;
6209 		sense_busaddr += AHD_SENSE_BUFSIZE;
6210 		scb_data->numscbs++;
6211 	}
6212 	return (i);
6213 }
6214 
6215 void
6216 ahd_controller_info(struct ahd_softc *ahd, char *buf)
6217 {
6218 	const char *speed;
6219 	const char *type;
6220 	int len;
6221 
6222 	len = sprintf(buf, "%s: ", ahd_chip_names[ahd->chip & AHD_CHIPID_MASK]);
6223 	buf += len;
6224 
6225 	speed = "Ultra320 ";
6226 	if ((ahd->features & AHD_WIDE) != 0) {
6227 		type = "Wide ";
6228 	} else {
6229 		type = "Single ";
6230 	}
6231 	len = sprintf(buf, "%s%sChannel %c, SCSI Id=%d, ",
6232 		      speed, type, ahd->channel, ahd->our_id);
6233 	buf += len;
6234 
6235 	sprintf(buf, "%s, %d SCBs", ahd->bus_description,
6236 		ahd->scb_data.maxhscbs);
6237 }
6238 
6239 static const char *channel_strings[] = {
6240 	"Primary Low",
6241 	"Primary High",
6242 	"Secondary Low",
6243 	"Secondary High"
6244 };
6245 
6246 static const char *termstat_strings[] = {
6247 	"Terminated Correctly",
6248 	"Over Terminated",
6249 	"Under Terminated",
6250 	"Not Configured"
6251 };
6252 
6253 /*
6254  * Start the board, ready for normal operation
6255  */
6256 int
6257 ahd_init(struct ahd_softc *ahd)
6258 {
6259 	uint8_t		*next_vaddr;
6260 	bus_addr_t	 next_baddr;
6261 	size_t		 driver_data_size;
6262 	int		 i;
6263 	int		 error;
6264 	u_int		 warn_user;
6265 	uint8_t		 current_sensing;
6266 	uint8_t		 fstat;
6267 
6268 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
6269 
6270 	ahd->stack_size = ahd_probe_stack_size(ahd);
6271 	ahd->saved_stack = malloc(ahd->stack_size * sizeof(uint16_t),
6272 				  M_DEVBUF, M_NOWAIT);
6273 	if (ahd->saved_stack == NULL)
6274 		return (ENOMEM);
6275 
6276 	/*
6277 	 * Verify that the compiler hasn't over-agressively
6278 	 * padded important structures.
6279 	 */
6280 	if (sizeof(struct hardware_scb) != 64)
6281 		panic("Hardware SCB size is incorrect");
6282 
6283 #ifdef AHD_DEBUG
6284 	if ((ahd_debug & AHD_DEBUG_SEQUENCER) != 0)
6285 		ahd->flags |= AHD_SEQUENCER_DEBUG;
6286 #endif
6287 
6288 	/*
6289 	 * Default to allowing initiator operations.
6290 	 */
6291 	ahd->flags |= AHD_INITIATORROLE;
6292 
6293 	/*
6294 	 * Only allow target mode features if this unit has them enabled.
6295 	 */
6296 	if ((AHD_TMODE_ENABLE & (0x1 << ahd->unit)) == 0)
6297 		ahd->features &= ~AHD_TARGETMODE;
6298 
6299 #ifndef __linux__
6300 	/* DMA tag for mapping buffers into device visible space. */
6301 	if (aic_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6302 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6303 			       /*lowaddr*/ahd->flags & AHD_39BIT_ADDRESSING
6304 					? (bus_addr_t)0x7FFFFFFFFFULL
6305 					: BUS_SPACE_MAXADDR_32BIT,
6306 			       /*highaddr*/BUS_SPACE_MAXADDR,
6307 			       /*filter*/NULL, /*filterarg*/NULL,
6308 			       /*maxsize*/(AHD_NSEG - 1) * PAGE_SIZE,
6309 			       /*nsegments*/AHD_NSEG,
6310 			       /*maxsegsz*/AHD_MAXTRANSFER_SIZE,
6311 			       /*flags*/BUS_DMA_ALLOCNOW,
6312 			       &ahd->buffer_dmat) != 0) {
6313 		return (ENOMEM);
6314 	}
6315 #endif
6316 
6317 	ahd->init_level++;
6318 
6319 	/*
6320 	 * DMA tag for our command fifos and other data in system memory
6321 	 * the card's sequencer must be able to access.  For initiator
6322 	 * roles, we need to allocate space for the qoutfifo.  When providing
6323 	 * for the target mode role, we must additionally provide space for
6324 	 * the incoming target command fifo.
6325 	 */
6326 	driver_data_size = AHD_SCB_MAX * sizeof(*ahd->qoutfifo)
6327 			 + sizeof(struct hardware_scb);
6328 	if ((ahd->features & AHD_TARGETMODE) != 0)
6329 		driver_data_size += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6330 	if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0)
6331 		driver_data_size += PKT_OVERRUN_BUFSIZE;
6332 	if (aic_dma_tag_create(ahd, ahd->parent_dmat, /*alignment*/1,
6333 			       /*boundary*/BUS_SPACE_MAXADDR_32BIT + 1,
6334 			       /*lowaddr*/BUS_SPACE_MAXADDR_32BIT,
6335 			       /*highaddr*/BUS_SPACE_MAXADDR,
6336 			       /*filter*/NULL, /*filterarg*/NULL,
6337 			       driver_data_size,
6338 			       /*nsegments*/1,
6339 			       /*maxsegsz*/BUS_SPACE_MAXSIZE_32BIT,
6340 			       /*flags*/0, &ahd->shared_data_dmat) != 0) {
6341 		return (ENOMEM);
6342 	}
6343 
6344 	ahd->init_level++;
6345 
6346 	/* Allocation of driver data */
6347 	if (aic_dmamem_alloc(ahd, ahd->shared_data_dmat,
6348 			     (void **)&ahd->shared_data_map.vaddr,
6349 			     BUS_DMA_NOWAIT | BUS_DMA_COHERENT,
6350 			     &ahd->shared_data_map.dmamap) != 0) {
6351 		return (ENOMEM);
6352 	}
6353 
6354 	ahd->init_level++;
6355 
6356 	/* And permanently map it in */
6357 	aic_dmamap_load(ahd, ahd->shared_data_dmat, ahd->shared_data_map.dmamap,
6358 			ahd->shared_data_map.vaddr, driver_data_size,
6359 			ahd_dmamap_cb, &ahd->shared_data_map.busaddr,
6360 			/*flags*/0);
6361 	ahd->qoutfifo = (struct ahd_completion *)ahd->shared_data_map.vaddr;
6362 	next_vaddr = (uint8_t *)&ahd->qoutfifo[AHD_QOUT_SIZE];
6363 	next_baddr = ahd->shared_data_map.busaddr
6364 		   + AHD_QOUT_SIZE*sizeof(struct ahd_completion);
6365 	if ((ahd->features & AHD_TARGETMODE) != 0) {
6366 		ahd->targetcmds = (struct target_cmd *)next_vaddr;
6367 		next_vaddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6368 		next_baddr += AHD_TMODE_CMDS * sizeof(struct target_cmd);
6369 	}
6370 
6371 	if ((ahd->bugs & AHD_PKT_BITBUCKET_BUG) != 0) {
6372 		ahd->overrun_buf = next_vaddr;
6373 		next_vaddr += PKT_OVERRUN_BUFSIZE;
6374 		next_baddr += PKT_OVERRUN_BUFSIZE;
6375 	}
6376 
6377 	/*
6378 	 * We need one SCB to serve as the "next SCB".  Since the
6379 	 * tag identifier in this SCB will never be used, there is
6380 	 * no point in using a valid HSCB tag from an SCB pulled from
6381 	 * the standard free pool.  So, we allocate this "sentinel"
6382 	 * specially from the DMA safe memory chunk used for the QOUTFIFO.
6383 	 */
6384 	ahd->next_queued_hscb = (struct hardware_scb *)next_vaddr;
6385 	ahd->next_queued_hscb_map = &ahd->shared_data_map;
6386 	ahd->next_queued_hscb->hscb_busaddr = aic_htole32(next_baddr);
6387 
6388 	ahd->init_level++;
6389 
6390 	/* Allocate SCB data now that buffer_dmat is initialized */
6391 	if (ahd_init_scbdata(ahd) != 0)
6392 		return (ENOMEM);
6393 
6394 	if ((ahd->flags & AHD_INITIATORROLE) == 0)
6395 		ahd->flags &= ~AHD_RESET_BUS_A;
6396 
6397 	/*
6398 	 * Before committing these settings to the chip, give
6399 	 * the OSM one last chance to modify our configuration.
6400 	 */
6401 	ahd_platform_init(ahd);
6402 
6403 	/* Bring up the chip. */
6404 	ahd_chip_init(ahd);
6405 
6406 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
6407 
6408 	if ((ahd->flags & AHD_CURRENT_SENSING) == 0)
6409 		goto init_done;
6410 
6411 	/*
6412 	 * Verify termination based on current draw and
6413 	 * warn user if the bus is over/under terminated.
6414 	 */
6415 	error = ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL,
6416 				   CURSENSE_ENB);
6417 	if (error != 0) {
6418 		printf("%s: current sensing timeout 1\n", ahd_name(ahd));
6419 		goto init_done;
6420 	}
6421 	for (i = 20, fstat = FLX_FSTAT_BUSY;
6422 	     (fstat & FLX_FSTAT_BUSY) != 0 && i; i--) {
6423 		error = ahd_read_flexport(ahd, FLXADDR_FLEXSTAT, &fstat);
6424 		if (error != 0) {
6425 			printf("%s: current sensing timeout 2\n",
6426 			       ahd_name(ahd));
6427 			goto init_done;
6428 		}
6429 	}
6430 	if (i == 0) {
6431 		printf("%s: Timedout during current-sensing test\n",
6432 		       ahd_name(ahd));
6433 		goto init_done;
6434 	}
6435 
6436 	/* Latch Current Sensing status. */
6437 	error = ahd_read_flexport(ahd, FLXADDR_CURRENT_STAT, &current_sensing);
6438 	if (error != 0) {
6439 		printf("%s: current sensing timeout 3\n", ahd_name(ahd));
6440 		goto init_done;
6441 	}
6442 
6443 	/* Diable current sensing. */
6444 	ahd_write_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, 0);
6445 
6446 #ifdef AHD_DEBUG
6447 	if ((ahd_debug & AHD_SHOW_TERMCTL) != 0) {
6448 		printf("%s: current_sensing == 0x%x\n",
6449 		       ahd_name(ahd), current_sensing);
6450 	}
6451 #endif
6452 	warn_user = 0;
6453 	for (i = 0; i < 4; i++, current_sensing >>= FLX_CSTAT_SHIFT) {
6454 		u_int term_stat;
6455 
6456 		term_stat = (current_sensing & FLX_CSTAT_MASK);
6457 		switch (term_stat) {
6458 		case FLX_CSTAT_OVER:
6459 		case FLX_CSTAT_UNDER:
6460 			warn_user++;
6461 		case FLX_CSTAT_INVALID:
6462 		case FLX_CSTAT_OKAY:
6463 			if (warn_user == 0 && bootverbose == 0)
6464 				break;
6465 			printf("%s: %s Channel %s\n", ahd_name(ahd),
6466 			       channel_strings[i], termstat_strings[term_stat]);
6467 			break;
6468 		}
6469 	}
6470 	if (warn_user) {
6471 		printf("%s: WARNING. Termination is not configured correctly.\n"
6472 		       "%s: WARNING. SCSI bus operations may FAIL.\n",
6473 		       ahd_name(ahd), ahd_name(ahd));
6474 		AHD_CORRECTABLE_ERROR(ahd);
6475 	}
6476 init_done:
6477 	ahd_restart(ahd);
6478 	aic_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_MS,
6479 			ahd_stat_timer, ahd);
6480 	return (0);
6481 }
6482 
6483 /*
6484  * (Re)initialize chip state after a chip reset.
6485  */
6486 static void
6487 ahd_chip_init(struct ahd_softc *ahd)
6488 {
6489 	uint32_t busaddr;
6490 	u_int	 sxfrctl1;
6491 	u_int	 scsiseq_template;
6492 	u_int	 wait;
6493 	u_int	 i;
6494 	u_int	 target;
6495 
6496 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6497 	/*
6498 	 * Take the LED out of diagnostic mode
6499 	 */
6500 	ahd_outb(ahd, SBLKCTL, ahd_inb(ahd, SBLKCTL) & ~(DIAGLEDEN|DIAGLEDON));
6501 
6502 	/*
6503 	 * Return HS_MAILBOX to its default value.
6504 	 */
6505 	ahd->hs_mailbox = 0;
6506 	ahd_outb(ahd, HS_MAILBOX, 0);
6507 
6508 	/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1. */
6509 	ahd_outb(ahd, IOWNID, ahd->our_id);
6510 	ahd_outb(ahd, TOWNID, ahd->our_id);
6511 	sxfrctl1 = (ahd->flags & AHD_TERM_ENB_A) != 0 ? STPWEN : 0;
6512 	sxfrctl1 |= (ahd->flags & AHD_SPCHK_ENB_A) != 0 ? ENSPCHK : 0;
6513 	if ((ahd->bugs & AHD_LONG_SETIMO_BUG)
6514 	 && (ahd->seltime != STIMESEL_MIN)) {
6515 		/*
6516 		 * The selection timer duration is twice as long
6517 		 * as it should be.  Halve it by adding "1" to
6518 		 * the user specified setting.
6519 		 */
6520 		sxfrctl1 |= ahd->seltime + STIMESEL_BUG_ADJ;
6521 	} else {
6522 		sxfrctl1 |= ahd->seltime;
6523 	}
6524 
6525 	ahd_outb(ahd, SXFRCTL0, DFON);
6526 	ahd_outb(ahd, SXFRCTL1, sxfrctl1|ahd->seltime|ENSTIMER|ACTNEGEN);
6527 	ahd_outb(ahd, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
6528 
6529 	/*
6530 	 * Now that termination is set, wait for up
6531 	 * to 500ms for our transceivers to settle.  If
6532 	 * the adapter does not have a cable attached,
6533 	 * the transceivers may never settle, so don't
6534 	 * complain if we fail here.
6535 	 */
6536 	for (wait = 10000;
6537 	     (ahd_inb(ahd, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
6538 	     wait--)
6539 		aic_delay(100);
6540 
6541 	/* Clear any false bus resets due to the transceivers settling */
6542 	ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
6543 	ahd_outb(ahd, CLRINT, CLRSCSIINT);
6544 
6545 	/* Initialize mode specific S/G state. */
6546 	for (i = 0; i < 2; i++) {
6547 		ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
6548 		ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
6549 		ahd_outb(ahd, SG_STATE, 0);
6550 		ahd_outb(ahd, CLRSEQINTSRC, 0xFF);
6551 		ahd_outb(ahd, SEQIMODE,
6552 			 ENSAVEPTRS|ENCFG4DATA|ENCFG4ISTAT
6553 			|ENCFG4TSTAT|ENCFG4ICMD|ENCFG4TCMD);
6554 	}
6555 
6556 	ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
6557 	ahd_outb(ahd, DSCOMMAND0, ahd_inb(ahd, DSCOMMAND0)|MPARCKEN|CACHETHEN);
6558 	ahd_outb(ahd, DFF_THRSH, RD_DFTHRSH_75|WR_DFTHRSH_75);
6559 	ahd_outb(ahd, SIMODE0, ENIOERR|ENOVERRUN);
6560 	ahd_outb(ahd, SIMODE3, ENNTRAMPERR|ENOSRAMPERR);
6561 	if ((ahd->bugs & AHD_BUSFREEREV_BUG) != 0) {
6562 		ahd_outb(ahd, OPTIONMODE, AUTOACKEN|AUTO_MSGOUT_DE);
6563 	} else {
6564 		ahd_outb(ahd, OPTIONMODE, AUTOACKEN|BUSFREEREV|AUTO_MSGOUT_DE);
6565 	}
6566 	ahd_outb(ahd, SCSCHKN, CURRFIFODEF|WIDERESEN|SHVALIDSTDIS);
6567 	if ((ahd->chip & AHD_BUS_MASK) == AHD_PCIX)
6568 		/*
6569 		 * Do not issue a target abort when a split completion
6570 		 * error occurs.  Let our PCIX interrupt handler deal
6571 		 * with it instead. H2A4 Razor #625
6572 		 */
6573 		ahd_outb(ahd, PCIXCTL, ahd_inb(ahd, PCIXCTL) | SPLTSTADIS);
6574 
6575 	if ((ahd->bugs & AHD_LQOOVERRUN_BUG) != 0)
6576 		ahd_outb(ahd, LQOSCSCTL, LQONOCHKOVER);
6577 
6578 	/*
6579 	 * Tweak IOCELL settings.
6580 	 */
6581 	if ((ahd->flags & AHD_HP_BOARD) != 0) {
6582 		for (i = 0; i < NUMDSPS; i++) {
6583 			ahd_outb(ahd, DSPSELECT, i);
6584 			ahd_outb(ahd, WRTBIASCTL, WRTBIASCTL_HP_DEFAULT);
6585 		}
6586 #ifdef AHD_DEBUG
6587 		if ((ahd_debug & AHD_SHOW_MISC) != 0)
6588 			printf("%s: WRTBIASCTL now 0x%x\n", ahd_name(ahd),
6589 			       WRTBIASCTL_HP_DEFAULT);
6590 #endif
6591 	}
6592 	ahd_setup_iocell_workaround(ahd);
6593 
6594 	/*
6595 	 * Enable LQI Manager interrupts.
6596 	 */
6597 	ahd_outb(ahd, LQIMODE1, ENLQIPHASE_LQ|ENLQIPHASE_NLQ|ENLIQABORT
6598 			      | ENLQICRCI_LQ|ENLQICRCI_NLQ|ENLQIBADLQI
6599 			      | ENLQIOVERI_LQ|ENLQIOVERI_NLQ);
6600 	ahd_outb(ahd, LQOMODE0, ENLQOATNLQ|ENLQOATNPKT|ENLQOTCRC);
6601 	/*
6602 	 * We choose to have the sequencer catch LQOPHCHGINPKT errors
6603 	 * manually for the command phase at the start of a packetized
6604 	 * selection case.  ENLQOBUSFREE should be made redundant by
6605 	 * the BUSFREE interrupt, but it seems that some LQOBUSFREE
6606 	 * events fail to assert the BUSFREE interrupt so we must
6607 	 * also enable LQOBUSFREE interrupts.
6608 	 */
6609 	ahd_outb(ahd, LQOMODE1, ENLQOBUSFREE);
6610 
6611 	/*
6612 	 * Setup sequencer interrupt handlers.
6613 	 */
6614 	ahd_outw(ahd, INTVEC1_ADDR, ahd_resolve_seqaddr(ahd, LABEL_seq_isr));
6615 	ahd_outw(ahd, INTVEC2_ADDR, ahd_resolve_seqaddr(ahd, LABEL_timer_isr));
6616 
6617 	/*
6618 	 * Setup SCB Offset registers.
6619 	 */
6620 	if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
6621 		ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb,
6622 			 pkt_long_lun));
6623 	} else {
6624 		ahd_outb(ahd, LUNPTR, offsetof(struct hardware_scb, lun));
6625 	}
6626 	ahd_outb(ahd, CMDLENPTR, offsetof(struct hardware_scb, cdb_len));
6627 	ahd_outb(ahd, ATTRPTR, offsetof(struct hardware_scb, task_attribute));
6628 	ahd_outb(ahd, FLAGPTR, offsetof(struct hardware_scb, task_management));
6629 	ahd_outb(ahd, CMDPTR, offsetof(struct hardware_scb,
6630 				       shared_data.idata.cdb));
6631 	ahd_outb(ahd, QNEXTPTR,
6632 		 offsetof(struct hardware_scb, next_hscb_busaddr));
6633 	ahd_outb(ahd, ABRTBITPTR, MK_MESSAGE_BIT_OFFSET);
6634 	ahd_outb(ahd, ABRTBYTEPTR, offsetof(struct hardware_scb, control));
6635 	if ((ahd->bugs & AHD_PKT_LUN_BUG) != 0) {
6636 		ahd_outb(ahd, LUNLEN,
6637 			 sizeof(ahd->next_queued_hscb->pkt_long_lun) - 1);
6638 	} else {
6639 		ahd_outb(ahd, LUNLEN, LUNLEN_SINGLE_LEVEL_LUN);
6640 	}
6641 	ahd_outb(ahd, CDBLIMIT, SCB_CDB_LEN_PTR - 1);
6642 	ahd_outb(ahd, MAXCMD, 0xFF);
6643 	ahd_outb(ahd, SCBAUTOPTR,
6644 		 AUSCBPTR_EN | offsetof(struct hardware_scb, tag));
6645 
6646 	/* We haven't been enabled for target mode yet. */
6647 	ahd_outb(ahd, MULTARGID, 0);
6648 	ahd_outb(ahd, MULTARGID + 1, 0);
6649 
6650 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6651 	/* Initialize the negotiation table. */
6652 	if ((ahd->features & AHD_NEW_IOCELL_OPTS) == 0) {
6653 		/*
6654 		 * Clear the spare bytes in the neg table to avoid
6655 		 * spurious parity errors.
6656 		 */
6657 		for (target = 0; target < AHD_NUM_TARGETS; target++) {
6658 			ahd_outb(ahd, NEGOADDR, target);
6659 			ahd_outb(ahd, ANNEXCOL, AHD_ANNEXCOL_PER_DEV0);
6660 			for (i = 0; i < AHD_NUM_PER_DEV_ANNEXCOLS; i++)
6661 				ahd_outb(ahd, ANNEXDAT, 0);
6662 		}
6663 	}
6664 	for (target = 0; target < AHD_NUM_TARGETS; target++) {
6665 		struct	 ahd_devinfo devinfo;
6666 		struct	 ahd_initiator_tinfo *tinfo;
6667 		struct	 ahd_tmode_tstate *tstate;
6668 
6669 		tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6670 					    target, &tstate);
6671 		ahd_compile_devinfo(&devinfo, ahd->our_id,
6672 				    target, CAM_LUN_WILDCARD,
6673 				    'A', ROLE_INITIATOR);
6674 		ahd_update_neg_table(ahd, &devinfo, &tinfo->curr);
6675 	}
6676 
6677 	ahd_outb(ahd, CLRSINT3, NTRAMPERR|OSRAMPERR);
6678 	ahd_outb(ahd, CLRINT, CLRSCSIINT);
6679 
6680 #ifdef NEEDS_MORE_TESTING
6681 	/*
6682 	 * Always enable abort on incoming L_Qs if this feature is
6683 	 * supported.  We use this to catch invalid SCB references.
6684 	 */
6685 	if ((ahd->bugs & AHD_ABORT_LQI_BUG) == 0)
6686 		ahd_outb(ahd, LQCTL1, ABORTPENDING);
6687 	else
6688 #endif
6689 		ahd_outb(ahd, LQCTL1, 0);
6690 
6691 	/* All of our queues are empty */
6692 	ahd->qoutfifonext = 0;
6693 	ahd->qoutfifonext_valid_tag = QOUTFIFO_ENTRY_VALID;
6694 	ahd_outb(ahd, QOUTFIFO_ENTRY_VALID_TAG, QOUTFIFO_ENTRY_VALID);
6695 	for (i = 0; i < AHD_QOUT_SIZE; i++)
6696 		ahd->qoutfifo[i].valid_tag = 0;
6697 	ahd_sync_qoutfifo(ahd, BUS_DMASYNC_PREREAD);
6698 
6699 	ahd->qinfifonext = 0;
6700 	for (i = 0; i < AHD_QIN_SIZE; i++)
6701 		ahd->qinfifo[i] = SCB_LIST_NULL;
6702 
6703 	if ((ahd->features & AHD_TARGETMODE) != 0) {
6704 		/* All target command blocks start out invalid. */
6705 		for (i = 0; i < AHD_TMODE_CMDS; i++)
6706 			ahd->targetcmds[i].cmd_valid = 0;
6707 		ahd_sync_tqinfifo(ahd, BUS_DMASYNC_PREREAD);
6708 		ahd->tqinfifonext = 1;
6709 		ahd_outb(ahd, KERNEL_TQINPOS, ahd->tqinfifonext - 1);
6710 		ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
6711 	}
6712 
6713 	/* Initialize Scratch Ram. */
6714 	ahd_outb(ahd, SEQ_FLAGS, 0);
6715 	ahd_outb(ahd, SEQ_FLAGS2, 0);
6716 
6717 	/* We don't have any waiting selections */
6718 	ahd_outw(ahd, WAITING_TID_HEAD, SCB_LIST_NULL);
6719 	ahd_outw(ahd, WAITING_TID_TAIL, SCB_LIST_NULL);
6720 	ahd_outw(ahd, MK_MESSAGE_SCB, SCB_LIST_NULL);
6721 	ahd_outw(ahd, MK_MESSAGE_SCSIID, 0xFF);
6722 	for (i = 0; i < AHD_NUM_TARGETS; i++)
6723 		ahd_outw(ahd, WAITING_SCB_TAILS + (2 * i), SCB_LIST_NULL);
6724 
6725 	/*
6726 	 * Nobody is waiting to be DMAed into the QOUTFIFO.
6727 	 */
6728 	ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
6729 	ahd_outw(ahd, COMPLETE_SCB_DMAINPROG_HEAD, SCB_LIST_NULL);
6730 	ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
6731 	ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
6732 	ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
6733 
6734 	/*
6735 	 * The Freeze Count is 0.
6736 	 */
6737 	ahd->qfreeze_cnt = 0;
6738 	ahd_outw(ahd, QFREEZE_COUNT, 0);
6739 	ahd_outw(ahd, KERNEL_QFREEZE_COUNT, 0);
6740 
6741 	/*
6742 	 * Tell the sequencer where it can find our arrays in memory.
6743 	 */
6744 	busaddr = ahd->shared_data_map.busaddr;
6745 	ahd_outl(ahd, SHARED_DATA_ADDR, busaddr);
6746 	ahd_outl(ahd, QOUTFIFO_NEXT_ADDR, busaddr);
6747 
6748 	/*
6749 	 * Setup the allowed SCSI Sequences based on operational mode.
6750 	 * If we are a target, we'll enable select in operations once
6751 	 * we've had a lun enabled.
6752 	 */
6753 	scsiseq_template = ENAUTOATNP;
6754 	if ((ahd->flags & AHD_INITIATORROLE) != 0)
6755 		scsiseq_template |= ENRSELI;
6756 	ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq_template);
6757 
6758 	/* There are no busy SCBs yet. */
6759 	for (target = 0; target < AHD_NUM_TARGETS; target++) {
6760 		int lun;
6761 
6762 		for (lun = 0; lun < AHD_NUM_LUNS_NONPKT; lun++)
6763 			ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(target, 'A', lun));
6764 	}
6765 
6766 	/*
6767 	 * Initialize the group code to command length table.
6768 	 * Vendor Unique codes are set to 0 so we only capture
6769 	 * the first byte of the cdb.  These can be overridden
6770 	 * when target mode is enabled.
6771 	 */
6772 	ahd_outb(ahd, CMDSIZE_TABLE, 5);
6773 	ahd_outb(ahd, CMDSIZE_TABLE + 1, 9);
6774 	ahd_outb(ahd, CMDSIZE_TABLE + 2, 9);
6775 	ahd_outb(ahd, CMDSIZE_TABLE + 3, 0);
6776 	ahd_outb(ahd, CMDSIZE_TABLE + 4, 15);
6777 	ahd_outb(ahd, CMDSIZE_TABLE + 5, 11);
6778 	ahd_outb(ahd, CMDSIZE_TABLE + 6, 0);
6779 	ahd_outb(ahd, CMDSIZE_TABLE + 7, 0);
6780 
6781 	/* Tell the sequencer of our initial queue positions */
6782 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
6783 	ahd_outb(ahd, QOFF_CTLSTA, SCB_QSIZE_512);
6784 	ahd->qinfifonext = 0;
6785 	ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
6786 	ahd_set_hescb_qoff(ahd, 0);
6787 	ahd_set_snscb_qoff(ahd, 0);
6788 	ahd_set_sescb_qoff(ahd, 0);
6789 	ahd_set_sdscb_qoff(ahd, 0);
6790 
6791 	/*
6792 	 * Tell the sequencer which SCB will be the next one it receives.
6793 	 */
6794 	busaddr = aic_le32toh(ahd->next_queued_hscb->hscb_busaddr);
6795 	ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
6796 
6797 	/*
6798 	 * Default to coalescing disabled.
6799 	 */
6800 	ahd_outw(ahd, INT_COALESCING_CMDCOUNT, 0);
6801 	ahd_outw(ahd, CMDS_PENDING, 0);
6802 	ahd_update_coalescing_values(ahd, ahd->int_coalescing_timer,
6803 				     ahd->int_coalescing_maxcmds,
6804 				     ahd->int_coalescing_mincmds);
6805 	ahd_enable_coalescing(ahd, FALSE);
6806 
6807 	ahd_loadseq(ahd);
6808 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
6809 }
6810 
6811 /*
6812  * Setup default device and controller settings.
6813  * This should only be called if our probe has
6814  * determined that no configuration data is available.
6815  */
6816 int
6817 ahd_default_config(struct ahd_softc *ahd)
6818 {
6819 	int	targ;
6820 
6821 	ahd->our_id = 7;
6822 
6823 	/*
6824 	 * Allocate a tstate to house information for our
6825 	 * initiator presence on the bus as well as the user
6826 	 * data for any target mode initiator.
6827 	 */
6828 	if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
6829 		printf("%s: unable to allocate ahd_tmode_tstate.  "
6830 		       "Failing attach\n", ahd_name(ahd));
6831 		AHD_FATAL_ERROR(ahd);
6832 		return (ENOMEM);
6833 	}
6834 
6835 	for (targ = 0; targ < AHD_NUM_TARGETS; targ++) {
6836 		struct	 ahd_devinfo devinfo;
6837 		struct	 ahd_initiator_tinfo *tinfo;
6838 		struct	 ahd_tmode_tstate *tstate;
6839 		uint16_t target_mask;
6840 
6841 		tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6842 					    targ, &tstate);
6843 		/*
6844 		 * We support SPC2 and SPI4.
6845 		 */
6846 		tinfo->user.protocol_version = 4;
6847 		tinfo->user.transport_version = 4;
6848 
6849 		target_mask = 0x01 << targ;
6850 		ahd->user_discenable |= target_mask;
6851 		tstate->discenable |= target_mask;
6852 		ahd->user_tagenable |= target_mask;
6853 #ifdef AHD_FORCE_160
6854 		tinfo->user.period = AHD_SYNCRATE_DT;
6855 #else
6856 		tinfo->user.period = AHD_SYNCRATE_160;
6857 #endif
6858 		tinfo->user.offset = MAX_OFFSET;
6859 		tinfo->user.ppr_options = MSG_EXT_PPR_RD_STRM
6860 					| MSG_EXT_PPR_WR_FLOW
6861 					| MSG_EXT_PPR_HOLD_MCS
6862 					| MSG_EXT_PPR_IU_REQ
6863 					| MSG_EXT_PPR_QAS_REQ
6864 					| MSG_EXT_PPR_DT_REQ;
6865 		if ((ahd->features & AHD_RTI) != 0)
6866 			tinfo->user.ppr_options |= MSG_EXT_PPR_RTI;
6867 
6868 		tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
6869 
6870 		/*
6871 		 * Start out Async/Narrow/Untagged and with
6872 		 * conservative protocol support.
6873 		 */
6874 		tinfo->goal.protocol_version = 2;
6875 		tinfo->goal.transport_version = 2;
6876 		tinfo->curr.protocol_version = 2;
6877 		tinfo->curr.transport_version = 2;
6878 		ahd_compile_devinfo(&devinfo, ahd->our_id,
6879 				    targ, CAM_LUN_WILDCARD,
6880 				    'A', ROLE_INITIATOR);
6881 		tstate->tagenable &= ~target_mask;
6882 		ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6883 			      AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
6884 		ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
6885 				 /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
6886 				 /*paused*/TRUE);
6887 	}
6888 	return (0);
6889 }
6890 
6891 /*
6892  * Parse device configuration information.
6893  */
6894 int
6895 ahd_parse_cfgdata(struct ahd_softc *ahd, struct seeprom_config *sc)
6896 {
6897 	int targ;
6898 	int max_targ;
6899 
6900 	max_targ = sc->max_targets & CFMAXTARG;
6901 	ahd->our_id = sc->brtime_id & CFSCSIID;
6902 
6903 	/*
6904 	 * Allocate a tstate to house information for our
6905 	 * initiator presence on the bus as well as the user
6906 	 * data for any target mode initiator.
6907 	 */
6908 	if (ahd_alloc_tstate(ahd, ahd->our_id, 'A') == NULL) {
6909 		printf("%s: unable to allocate ahd_tmode_tstate.  "
6910 		       "Failing attach\n", ahd_name(ahd));
6911 		AHD_FATAL_ERROR(ahd);
6912 		return (ENOMEM);
6913 	}
6914 
6915 	for (targ = 0; targ < max_targ; targ++) {
6916 		struct	 ahd_devinfo devinfo;
6917 		struct	 ahd_initiator_tinfo *tinfo;
6918 		struct	 ahd_transinfo *user_tinfo;
6919 		struct	 ahd_tmode_tstate *tstate;
6920 		uint16_t target_mask;
6921 
6922 		tinfo = ahd_fetch_transinfo(ahd, 'A', ahd->our_id,
6923 					    targ, &tstate);
6924 		user_tinfo = &tinfo->user;
6925 
6926 		/*
6927 		 * We support SPC2 and SPI4.
6928 		 */
6929 		tinfo->user.protocol_version = 4;
6930 		tinfo->user.transport_version = 4;
6931 
6932 		target_mask = 0x01 << targ;
6933 		ahd->user_discenable &= ~target_mask;
6934 		tstate->discenable &= ~target_mask;
6935 		ahd->user_tagenable &= ~target_mask;
6936 		if (sc->device_flags[targ] & CFDISC) {
6937 			tstate->discenable |= target_mask;
6938 			ahd->user_discenable |= target_mask;
6939 			ahd->user_tagenable |= target_mask;
6940 		} else {
6941 			/*
6942 			 * Cannot be packetized without disconnection.
6943 			 */
6944 			sc->device_flags[targ] &= ~CFPACKETIZED;
6945 		}
6946 
6947 		user_tinfo->ppr_options = 0;
6948 		user_tinfo->period = (sc->device_flags[targ] & CFXFER);
6949 		if (user_tinfo->period < CFXFER_ASYNC) {
6950 			if (user_tinfo->period <= AHD_PERIOD_10MHz)
6951 				user_tinfo->ppr_options |= MSG_EXT_PPR_DT_REQ;
6952 			user_tinfo->offset = MAX_OFFSET;
6953 		} else  {
6954 			user_tinfo->offset = 0;
6955 			user_tinfo->period = AHD_ASYNC_XFER_PERIOD;
6956 		}
6957 #ifdef AHD_FORCE_160
6958 		if (user_tinfo->period <= AHD_SYNCRATE_160)
6959 			user_tinfo->period = AHD_SYNCRATE_DT;
6960 #endif
6961 
6962 		if ((sc->device_flags[targ] & CFPACKETIZED) != 0) {
6963 			user_tinfo->ppr_options |= MSG_EXT_PPR_RD_STRM
6964 						|  MSG_EXT_PPR_WR_FLOW
6965 						|  MSG_EXT_PPR_HOLD_MCS
6966 						|  MSG_EXT_PPR_IU_REQ;
6967 			if ((ahd->features & AHD_RTI) != 0)
6968 				user_tinfo->ppr_options |= MSG_EXT_PPR_RTI;
6969 		}
6970 
6971 		if ((sc->device_flags[targ] & CFQAS) != 0)
6972 			user_tinfo->ppr_options |= MSG_EXT_PPR_QAS_REQ;
6973 
6974 		if ((sc->device_flags[targ] & CFWIDEB) != 0)
6975 			user_tinfo->width = MSG_EXT_WDTR_BUS_16_BIT;
6976 		else
6977 			user_tinfo->width = MSG_EXT_WDTR_BUS_8_BIT;
6978 #ifdef AHD_DEBUG
6979 		if ((ahd_debug & AHD_SHOW_MISC) != 0)
6980 			printf("(%d): %x:%x:%x:%x\n", targ, user_tinfo->width,
6981 			       user_tinfo->period, user_tinfo->offset,
6982 			       user_tinfo->ppr_options);
6983 #endif
6984 		/*
6985 		 * Start out Async/Narrow/Untagged and with
6986 		 * conservative protocol support.
6987 		 */
6988 		tstate->tagenable &= ~target_mask;
6989 		tinfo->goal.protocol_version = 2;
6990 		tinfo->goal.transport_version = 2;
6991 		tinfo->curr.protocol_version = 2;
6992 		tinfo->curr.transport_version = 2;
6993 		ahd_compile_devinfo(&devinfo, ahd->our_id,
6994 				    targ, CAM_LUN_WILDCARD,
6995 				    'A', ROLE_INITIATOR);
6996 		ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
6997 			      AHD_TRANS_CUR|AHD_TRANS_GOAL, /*paused*/TRUE);
6998 		ahd_set_syncrate(ahd, &devinfo, /*period*/0, /*offset*/0,
6999 				 /*ppr_options*/0, AHD_TRANS_CUR|AHD_TRANS_GOAL,
7000 				 /*paused*/TRUE);
7001 	}
7002 
7003 	ahd->flags &= ~AHD_SPCHK_ENB_A;
7004 	if (sc->bios_control & CFSPARITY)
7005 		ahd->flags |= AHD_SPCHK_ENB_A;
7006 
7007 	ahd->flags &= ~AHD_RESET_BUS_A;
7008 	if (sc->bios_control & CFRESETB)
7009 		ahd->flags |= AHD_RESET_BUS_A;
7010 
7011 	ahd->flags &= ~AHD_EXTENDED_TRANS_A;
7012 	if (sc->bios_control & CFEXTEND)
7013 		ahd->flags |= AHD_EXTENDED_TRANS_A;
7014 
7015 	ahd->flags &= ~AHD_BIOS_ENABLED;
7016 	if ((sc->bios_control & CFBIOSSTATE) == CFBS_ENABLED)
7017 		ahd->flags |= AHD_BIOS_ENABLED;
7018 
7019 	ahd->flags &= ~AHD_STPWLEVEL_A;
7020 	if ((sc->adapter_control & CFSTPWLEVEL) != 0)
7021 		ahd->flags |= AHD_STPWLEVEL_A;
7022 
7023 	return (0);
7024 }
7025 
7026 /*
7027  * Parse device configuration information.
7028  */
7029 int
7030 ahd_parse_vpddata(struct ahd_softc *ahd, struct vpd_config *vpd)
7031 {
7032 	int error;
7033 
7034 	error = ahd_verify_vpd_cksum(vpd);
7035 	if (error == 0)
7036 		return (EINVAL);
7037 	if ((vpd->bios_flags & VPDBOOTHOST) != 0)
7038 		ahd->flags |= AHD_BOOT_CHANNEL;
7039 	return (0);
7040 }
7041 
7042 void
7043 ahd_intr_enable(struct ahd_softc *ahd, int enable)
7044 {
7045 	u_int hcntrl;
7046 
7047 	hcntrl = ahd_inb(ahd, HCNTRL);
7048 	hcntrl &= ~INTEN;
7049 	ahd->pause &= ~INTEN;
7050 	ahd->unpause &= ~INTEN;
7051 	if (enable) {
7052 		hcntrl |= INTEN;
7053 		ahd->pause |= INTEN;
7054 		ahd->unpause |= INTEN;
7055 	}
7056 	ahd_outb(ahd, HCNTRL, hcntrl);
7057 }
7058 
7059 void
7060 ahd_update_coalescing_values(struct ahd_softc *ahd, u_int timer, u_int maxcmds,
7061 			     u_int mincmds)
7062 {
7063 	if (timer > AHD_TIMER_MAX_US)
7064 		timer = AHD_TIMER_MAX_US;
7065 	ahd->int_coalescing_timer = timer;
7066 
7067 	if (maxcmds > AHD_INT_COALESCING_MAXCMDS_MAX)
7068 		maxcmds = AHD_INT_COALESCING_MAXCMDS_MAX;
7069 	if (mincmds > AHD_INT_COALESCING_MINCMDS_MAX)
7070 		mincmds = AHD_INT_COALESCING_MINCMDS_MAX;
7071 	ahd->int_coalescing_maxcmds = maxcmds;
7072 	ahd_outw(ahd, INT_COALESCING_TIMER, timer / AHD_TIMER_US_PER_TICK);
7073 	ahd_outb(ahd, INT_COALESCING_MAXCMDS, -maxcmds);
7074 	ahd_outb(ahd, INT_COALESCING_MINCMDS, -mincmds);
7075 }
7076 
7077 void
7078 ahd_enable_coalescing(struct ahd_softc *ahd, int enable)
7079 {
7080 
7081 	ahd->hs_mailbox &= ~ENINT_COALESCE;
7082 	if (enable)
7083 		ahd->hs_mailbox |= ENINT_COALESCE;
7084 	ahd_outb(ahd, HS_MAILBOX, ahd->hs_mailbox);
7085 	ahd_flush_device_writes(ahd);
7086 	ahd_run_qoutfifo(ahd);
7087 }
7088 
7089 /*
7090  * Ensure that the card is paused in a location
7091  * outside of all critical sections and that all
7092  * pending work is completed prior to returning.
7093  * This routine should only be called from outside
7094  * an interrupt context.
7095  */
7096 void
7097 ahd_pause_and_flushwork(struct ahd_softc *ahd)
7098 {
7099 	u_int intstat;
7100 	u_int maxloops;
7101 
7102 	maxloops = 1000;
7103 	ahd->flags |= AHD_ALL_INTERRUPTS;
7104 	ahd_pause(ahd);
7105 	/*
7106 	 * Freeze the outgoing selections.  We do this only
7107 	 * until we are safely paused without further selections
7108 	 * pending.
7109 	 */
7110 	ahd->qfreeze_cnt--;
7111 	ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7112 	ahd_outb(ahd, SEQ_FLAGS2, ahd_inb(ahd, SEQ_FLAGS2) | SELECTOUT_QFROZEN);
7113 	do {
7114 		ahd_unpause(ahd);
7115 		/*
7116 		 * Give the sequencer some time to service
7117 		 * any active selections.
7118 		 */
7119 		aic_delay(500);
7120 
7121 		ahd_intr(ahd);
7122 		ahd_pause(ahd);
7123 		intstat = ahd_inb(ahd, INTSTAT);
7124 		if ((intstat & INT_PEND) == 0) {
7125 			ahd_clear_critical_section(ahd);
7126 			intstat = ahd_inb(ahd, INTSTAT);
7127 		}
7128 	} while (--maxloops
7129 	      && (intstat != 0xFF || (ahd->features & AHD_REMOVABLE) == 0)
7130 	      && ((intstat & INT_PEND) != 0
7131 	       || (ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
7132 	       || (ahd_inb(ahd, SSTAT0) & (SELDO|SELINGO)) != 0));
7133 
7134 	if (maxloops == 0) {
7135 		printf("Infinite interrupt loop, INTSTAT = %x",
7136 		      ahd_inb(ahd, INTSTAT));
7137 		AHD_FATAL_ERROR(ahd);
7138 	}
7139 	ahd->qfreeze_cnt++;
7140 	ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
7141 
7142 	ahd_flush_qoutfifo(ahd);
7143 
7144 	ahd_platform_flushwork(ahd);
7145 	ahd->flags &= ~AHD_ALL_INTERRUPTS;
7146 }
7147 
7148 int
7149 ahd_suspend(struct ahd_softc *ahd)
7150 {
7151 
7152 	ahd_pause_and_flushwork(ahd);
7153 
7154 	if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
7155 		ahd_unpause(ahd);
7156 		return (EBUSY);
7157 	}
7158 	ahd_shutdown(ahd);
7159 	return (0);
7160 }
7161 
7162 int
7163 ahd_resume(struct ahd_softc *ahd)
7164 {
7165 
7166 	ahd_reset(ahd, /*reinit*/TRUE);
7167 	ahd_intr_enable(ahd, TRUE);
7168 	ahd_restart(ahd);
7169 	return (0);
7170 }
7171 
7172 /************************** Busy Target Table *********************************/
7173 /*
7174  * Set SCBPTR to the SCB that contains the busy
7175  * table entry for TCL.  Return the offset into
7176  * the SCB that contains the entry for TCL.
7177  * saved_scbid is dereferenced and set to the
7178  * scbid that should be restored once manipualtion
7179  * of the TCL entry is complete.
7180  */
7181 static __inline u_int
7182 ahd_index_busy_tcl(struct ahd_softc *ahd, u_int *saved_scbid, u_int tcl)
7183 {
7184 	/*
7185 	 * Index to the SCB that contains the busy entry.
7186 	 */
7187 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7188 	*saved_scbid = ahd_get_scbptr(ahd);
7189 	ahd_set_scbptr(ahd, TCL_LUN(tcl)
7190 		     | ((TCL_TARGET_OFFSET(tcl) & 0xC) << 4));
7191 
7192 	/*
7193 	 * And now calculate the SCB offset to the entry.
7194 	 * Each entry is 2 bytes wide, hence the
7195 	 * multiplication by 2.
7196 	 */
7197 	return (((TCL_TARGET_OFFSET(tcl) & 0x3) << 1) + SCB_DISCONNECTED_LISTS);
7198 }
7199 
7200 /*
7201  * Return the untagged transaction id for a given target/channel lun.
7202  */
7203 u_int
7204 ahd_find_busy_tcl(struct ahd_softc *ahd, u_int tcl)
7205 {
7206 	u_int scbid;
7207 	u_int scb_offset;
7208 	u_int saved_scbptr;
7209 
7210 	scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
7211 	scbid = ahd_inw_scbram(ahd, scb_offset);
7212 	ahd_set_scbptr(ahd, saved_scbptr);
7213 	return (scbid);
7214 }
7215 
7216 void
7217 ahd_busy_tcl(struct ahd_softc *ahd, u_int tcl, u_int scbid)
7218 {
7219 	u_int scb_offset;
7220 	u_int saved_scbptr;
7221 
7222 	scb_offset = ahd_index_busy_tcl(ahd, &saved_scbptr, tcl);
7223 	ahd_outw(ahd, scb_offset, scbid);
7224 	ahd_set_scbptr(ahd, saved_scbptr);
7225 }
7226 
7227 /************************** SCB and SCB queue management **********************/
7228 int
7229 ahd_match_scb(struct ahd_softc *ahd, struct scb *scb, int target,
7230 	      char channel, int lun, u_int tag, role_t role)
7231 {
7232 	int targ = SCB_GET_TARGET(ahd, scb);
7233 	char chan = SCB_GET_CHANNEL(ahd, scb);
7234 	int slun = SCB_GET_LUN(scb);
7235 	int match;
7236 
7237 	match = ((chan == channel) || (channel == ALL_CHANNELS));
7238 	if (match != 0)
7239 		match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
7240 	if (match != 0)
7241 		match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
7242 	if (match != 0) {
7243 #ifdef AHD_TARGET_MODE
7244 		int group;
7245 
7246 		group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
7247 		if (role == ROLE_INITIATOR) {
7248 			match = (group != XPT_FC_GROUP_TMODE)
7249 			      && ((tag == SCB_GET_TAG(scb))
7250 			       || (tag == SCB_LIST_NULL));
7251 		} else if (role == ROLE_TARGET) {
7252 			match = (group == XPT_FC_GROUP_TMODE)
7253 			      && ((tag == scb->io_ctx->csio.tag_id)
7254 			       || (tag == SCB_LIST_NULL));
7255 		}
7256 #else /* !AHD_TARGET_MODE */
7257 		match = ((tag == SCB_GET_TAG(scb)) || (tag == SCB_LIST_NULL));
7258 #endif /* AHD_TARGET_MODE */
7259 	}
7260 
7261 	return match;
7262 }
7263 
7264 void
7265 ahd_freeze_devq(struct ahd_softc *ahd, struct scb *scb)
7266 {
7267 	int	target;
7268 	char	channel;
7269 	int	lun;
7270 
7271 	target = SCB_GET_TARGET(ahd, scb);
7272 	lun = SCB_GET_LUN(scb);
7273 	channel = SCB_GET_CHANNEL(ahd, scb);
7274 
7275 	ahd_search_qinfifo(ahd, target, channel, lun,
7276 			   /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
7277 			   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
7278 
7279 	ahd_platform_freeze_devq(ahd, scb);
7280 }
7281 
7282 void
7283 ahd_qinfifo_requeue_tail(struct ahd_softc *ahd, struct scb *scb)
7284 {
7285 	struct scb	*prev_scb;
7286 	ahd_mode_state	 saved_modes;
7287 
7288 	saved_modes = ahd_save_modes(ahd);
7289 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7290 	prev_scb = NULL;
7291 	if (ahd_qinfifo_count(ahd) != 0) {
7292 		u_int prev_tag;
7293 		u_int prev_pos;
7294 
7295 		prev_pos = AHD_QIN_WRAP(ahd->qinfifonext - 1);
7296 		prev_tag = ahd->qinfifo[prev_pos];
7297 		prev_scb = ahd_lookup_scb(ahd, prev_tag);
7298 	}
7299 	ahd_qinfifo_requeue(ahd, prev_scb, scb);
7300 	ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
7301 	ahd_restore_modes(ahd, saved_modes);
7302 }
7303 
7304 static void
7305 ahd_qinfifo_requeue(struct ahd_softc *ahd, struct scb *prev_scb,
7306 		    struct scb *scb)
7307 {
7308 	if (prev_scb == NULL) {
7309 		uint32_t busaddr;
7310 
7311 		busaddr = aic_le32toh(scb->hscb->hscb_busaddr);
7312 		ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
7313 	} else {
7314 		prev_scb->hscb->next_hscb_busaddr = scb->hscb->hscb_busaddr;
7315 		ahd_sync_scb(ahd, prev_scb,
7316 			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
7317 	}
7318 	ahd->qinfifo[AHD_QIN_WRAP(ahd->qinfifonext)] = SCB_GET_TAG(scb);
7319 	ahd->qinfifonext++;
7320 	scb->hscb->next_hscb_busaddr = ahd->next_queued_hscb->hscb_busaddr;
7321 	ahd_sync_scb(ahd, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
7322 }
7323 
7324 static int
7325 ahd_qinfifo_count(struct ahd_softc *ahd)
7326 {
7327 	u_int qinpos;
7328 	u_int wrap_qinpos;
7329 	u_int wrap_qinfifonext;
7330 
7331 	AHD_ASSERT_MODES(ahd, AHD_MODE_CCHAN_MSK, AHD_MODE_CCHAN_MSK);
7332 	qinpos = ahd_get_snscb_qoff(ahd);
7333 	wrap_qinpos = AHD_QIN_WRAP(qinpos);
7334 	wrap_qinfifonext = AHD_QIN_WRAP(ahd->qinfifonext);
7335 	if (wrap_qinfifonext >= wrap_qinpos)
7336 		return (wrap_qinfifonext - wrap_qinpos);
7337 	else
7338 		return (wrap_qinfifonext
7339 		      + NUM_ELEMENTS(ahd->qinfifo) - wrap_qinpos);
7340 }
7341 
7342 void
7343 ahd_reset_cmds_pending(struct ahd_softc *ahd)
7344 {
7345 	struct		scb *scb;
7346 	ahd_mode_state	saved_modes;
7347 	u_int		pending_cmds;
7348 
7349 	saved_modes = ahd_save_modes(ahd);
7350 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7351 
7352 	/*
7353 	 * Don't count any commands as outstanding that the
7354 	 * sequencer has already marked for completion.
7355 	 */
7356 	ahd_flush_qoutfifo(ahd);
7357 
7358 	pending_cmds = 0;
7359 	LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
7360 		pending_cmds++;
7361 	}
7362 	ahd_outw(ahd, CMDS_PENDING, pending_cmds - ahd_qinfifo_count(ahd));
7363 	ahd_restore_modes(ahd, saved_modes);
7364 	ahd->flags &= ~AHD_UPDATE_PEND_CMDS;
7365 }
7366 
7367 void
7368 ahd_done_with_status(struct ahd_softc *ahd, struct scb *scb, uint32_t status)
7369 {
7370 	cam_status ostat;
7371 	cam_status cstat;
7372 
7373 	ostat = aic_get_transaction_status(scb);
7374 	if (ostat == CAM_REQ_INPROG)
7375 		aic_set_transaction_status(scb, status);
7376 	cstat = aic_get_transaction_status(scb);
7377 	if (cstat != CAM_REQ_CMP)
7378 		aic_freeze_scb(scb);
7379 	ahd_done(ahd, scb);
7380 }
7381 
7382 int
7383 ahd_search_qinfifo(struct ahd_softc *ahd, int target, char channel,
7384 		   int lun, u_int tag, role_t role, uint32_t status,
7385 		   ahd_search_action action)
7386 {
7387 	struct scb	*scb;
7388 	struct scb	*mk_msg_scb;
7389 	struct scb	*prev_scb;
7390 	ahd_mode_state	 saved_modes;
7391 	u_int		 qinstart;
7392 	u_int		 qinpos;
7393 	u_int		 qintail;
7394 	u_int		 tid_next;
7395 	u_int		 tid_prev;
7396 	u_int		 scbid;
7397 	u_int		 seq_flags2;
7398 	u_int		 savedscbptr;
7399 	uint32_t	 busaddr;
7400 	int		 found;
7401 	int		 targets;
7402 
7403 	/* Must be in CCHAN mode */
7404 	saved_modes = ahd_save_modes(ahd);
7405 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
7406 
7407 	/*
7408 	 * Halt any pending SCB DMA.  The sequencer will reinitiate
7409 	 * this dma if the qinfifo is not empty once we unpause.
7410 	 */
7411 	if ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN|CCSCBDIR))
7412 	 == (CCARREN|CCSCBEN|CCSCBDIR)) {
7413 		ahd_outb(ahd, CCSCBCTL,
7414 			 ahd_inb(ahd, CCSCBCTL) & ~(CCARREN|CCSCBEN));
7415 		while ((ahd_inb(ahd, CCSCBCTL) & (CCARREN|CCSCBEN)) != 0)
7416 			;
7417 	}
7418 	/* Determine sequencer's position in the qinfifo. */
7419 	qintail = AHD_QIN_WRAP(ahd->qinfifonext);
7420 	qinstart = ahd_get_snscb_qoff(ahd);
7421 	qinpos = AHD_QIN_WRAP(qinstart);
7422 	found = 0;
7423 	prev_scb = NULL;
7424 
7425 	if (action == SEARCH_PRINT) {
7426 		printf("qinstart = %d qinfifonext = %d\nQINFIFO:",
7427 		       qinstart, ahd->qinfifonext);
7428 	}
7429 
7430 	/*
7431 	 * Start with an empty queue.  Entries that are not chosen
7432 	 * for removal will be re-added to the queue as we go.
7433 	 */
7434 	ahd->qinfifonext = qinstart;
7435 	busaddr = aic_le32toh(ahd->next_queued_hscb->hscb_busaddr);
7436 	ahd_outl(ahd, NEXT_QUEUED_SCB_ADDR, busaddr);
7437 
7438 	while (qinpos != qintail) {
7439 		scb = ahd_lookup_scb(ahd, ahd->qinfifo[qinpos]);
7440 		if (scb == NULL) {
7441 			printf("qinpos = %d, SCB index = %d\n",
7442 				qinpos, ahd->qinfifo[qinpos]);
7443 			AHD_FATAL_ERROR(ahd);
7444 			panic("Loop 1\n");
7445 		}
7446 
7447 		if (ahd_match_scb(ahd, scb, target, channel, lun, tag, role)) {
7448 			/*
7449 			 * We found an scb that needs to be acted on.
7450 			 */
7451 			found++;
7452 			switch (action) {
7453 			case SEARCH_COMPLETE:
7454 				if ((scb->flags & SCB_ACTIVE) == 0)
7455 					printf("Inactive SCB in qinfifo\n");
7456 				ahd_done_with_status(ahd, scb, status);
7457 				/* FALLTHROUGH */
7458 			case SEARCH_REMOVE:
7459 				break;
7460 			case SEARCH_PRINT:
7461 				printf(" 0x%x", ahd->qinfifo[qinpos]);
7462 				/* FALLTHROUGH */
7463 			case SEARCH_COUNT:
7464 				ahd_qinfifo_requeue(ahd, prev_scb, scb);
7465 				prev_scb = scb;
7466 				break;
7467 			}
7468 		} else {
7469 			ahd_qinfifo_requeue(ahd, prev_scb, scb);
7470 			prev_scb = scb;
7471 		}
7472 		qinpos = AHD_QIN_WRAP(qinpos+1);
7473 	}
7474 
7475 	ahd_set_hnscb_qoff(ahd, ahd->qinfifonext);
7476 
7477 	if (action == SEARCH_PRINT)
7478 		printf("\nWAITING_TID_QUEUES:\n");
7479 
7480 	/*
7481 	 * Search waiting for selection lists.  We traverse the
7482 	 * list of "their ids" waiting for selection and, if
7483 	 * appropriate, traverse the SCBs of each "their id"
7484 	 * looking for matches.
7485 	 */
7486 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7487 	seq_flags2 = ahd_inb(ahd, SEQ_FLAGS2);
7488 	if ((seq_flags2 & PENDING_MK_MESSAGE) != 0) {
7489 		scbid = ahd_inw(ahd, MK_MESSAGE_SCB);
7490 		mk_msg_scb = ahd_lookup_scb(ahd, scbid);
7491 	} else
7492 		mk_msg_scb = NULL;
7493 	savedscbptr = ahd_get_scbptr(ahd);
7494 	tid_next = ahd_inw(ahd, WAITING_TID_HEAD);
7495 	tid_prev = SCB_LIST_NULL;
7496 	targets = 0;
7497 	for (scbid = tid_next; !SCBID_IS_NULL(scbid); scbid = tid_next) {
7498 		u_int tid_head;
7499 		u_int tid_tail;
7500 
7501 		targets++;
7502 		if (targets > AHD_NUM_TARGETS)
7503 			panic("TID LIST LOOP");
7504 
7505 		if (scbid >= ahd->scb_data.numscbs) {
7506 			printf("%s: Waiting TID List inconsistency. "
7507 			       "SCB index == 0x%x, yet numscbs == 0x%x.",
7508 			       ahd_name(ahd), scbid, ahd->scb_data.numscbs);
7509 			ahd_dump_card_state(ahd);
7510 			panic("for safety");
7511 		}
7512 		scb = ahd_lookup_scb(ahd, scbid);
7513 		if (scb == NULL) {
7514 			printf("%s: SCB = 0x%x Not Active!\n",
7515 			       ahd_name(ahd), scbid);
7516 			panic("Waiting TID List traversal\n");
7517 		}
7518 		ahd_set_scbptr(ahd, scbid);
7519 		tid_next = ahd_inw_scbram(ahd, SCB_NEXT2);
7520 		if (ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
7521 				  SCB_LIST_NULL, ROLE_UNKNOWN) == 0) {
7522 			tid_prev = scbid;
7523 			continue;
7524 		}
7525 
7526 		/*
7527 		 * We found a list of scbs that needs to be searched.
7528 		 */
7529 		if (action == SEARCH_PRINT)
7530 			printf("       %d ( ", SCB_GET_TARGET(ahd, scb));
7531 		tid_head = scbid;
7532 		found += ahd_search_scb_list(ahd, target, channel,
7533 					     lun, tag, role, status,
7534 					     action, &tid_head, &tid_tail,
7535 					     SCB_GET_TARGET(ahd, scb));
7536 		/*
7537 		 * Check any MK_MESSAGE SCB that is still waiting to
7538 		 * enter this target's waiting for selection queue.
7539 		 */
7540 		if (mk_msg_scb != NULL
7541 		 && ahd_match_scb(ahd, mk_msg_scb, target, channel,
7542 				  lun, tag, role)) {
7543 			/*
7544 			 * We found an scb that needs to be acted on.
7545 			 */
7546 			found++;
7547 			switch (action) {
7548 			case SEARCH_COMPLETE:
7549 				if ((mk_msg_scb->flags & SCB_ACTIVE) == 0)
7550 					printf("Inactive SCB pending MK_MSG\n");
7551 				ahd_done_with_status(ahd, mk_msg_scb, status);
7552 				/* FALLTHROUGH */
7553 			case SEARCH_REMOVE:
7554 			{
7555 				u_int tail_offset;
7556 
7557 				printf("Removing MK_MSG scb\n");
7558 
7559 				/*
7560 				 * Reset our tail to the tail of the
7561 				 * main per-target list.
7562 				 */
7563 				tail_offset = WAITING_SCB_TAILS
7564 				    + (2 * SCB_GET_TARGET(ahd, mk_msg_scb));
7565 				ahd_outw(ahd, tail_offset, tid_tail);
7566 
7567 				seq_flags2 &= ~PENDING_MK_MESSAGE;
7568 				ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
7569 				ahd_outw(ahd, CMDS_PENDING,
7570 					 ahd_inw(ahd, CMDS_PENDING)-1);
7571 				mk_msg_scb = NULL;
7572 				break;
7573 			}
7574 			case SEARCH_PRINT:
7575 				printf(" 0x%x", SCB_GET_TAG(scb));
7576 				/* FALLTHROUGH */
7577 			case SEARCH_COUNT:
7578 				break;
7579 			}
7580 		}
7581 
7582 		if (mk_msg_scb != NULL
7583 		 && SCBID_IS_NULL(tid_head)
7584 		 && ahd_match_scb(ahd, scb, target, channel, CAM_LUN_WILDCARD,
7585 				  SCB_LIST_NULL, ROLE_UNKNOWN)) {
7586 			/*
7587 			 * When removing the last SCB for a target
7588 			 * queue with a pending MK_MESSAGE scb, we
7589 			 * must queue the MK_MESSAGE scb.
7590 			 */
7591 			printf("Queueing mk_msg_scb\n");
7592 			tid_head = ahd_inw(ahd, MK_MESSAGE_SCB);
7593 			seq_flags2 &= ~PENDING_MK_MESSAGE;
7594 			ahd_outb(ahd, SEQ_FLAGS2, seq_flags2);
7595 			mk_msg_scb = NULL;
7596 		}
7597 		if (tid_head != scbid)
7598 			ahd_stitch_tid_list(ahd, tid_prev, tid_head, tid_next);
7599 		if (!SCBID_IS_NULL(tid_head))
7600 			tid_prev = tid_head;
7601 		if (action == SEARCH_PRINT)
7602 			printf(")\n");
7603 	}
7604 
7605 	/* Restore saved state. */
7606 	ahd_set_scbptr(ahd, savedscbptr);
7607 	ahd_restore_modes(ahd, saved_modes);
7608 	return (found);
7609 }
7610 
7611 static int
7612 ahd_search_scb_list(struct ahd_softc *ahd, int target, char channel,
7613 		    int lun, u_int tag, role_t role, uint32_t status,
7614 		    ahd_search_action action, u_int *list_head,
7615 		    u_int *list_tail, u_int tid)
7616 {
7617 	struct	scb *scb;
7618 	u_int	scbid;
7619 	u_int	next;
7620 	u_int	prev;
7621 	int	found;
7622 
7623 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7624 	found = 0;
7625 	prev = SCB_LIST_NULL;
7626 	next = *list_head;
7627 	*list_tail = SCB_LIST_NULL;
7628 	for (scbid = next; !SCBID_IS_NULL(scbid); scbid = next) {
7629 		if (scbid >= ahd->scb_data.numscbs) {
7630 			printf("%s:SCB List inconsistency. "
7631 			       "SCB == 0x%x, yet numscbs == 0x%x.",
7632 			       ahd_name(ahd), scbid, ahd->scb_data.numscbs);
7633 			ahd_dump_card_state(ahd);
7634 			panic("for safety");
7635 		}
7636 		scb = ahd_lookup_scb(ahd, scbid);
7637 		if (scb == NULL) {
7638 			printf("%s: SCB = %d Not Active!\n",
7639 			       ahd_name(ahd), scbid);
7640 			panic("Waiting List traversal\n");
7641 		}
7642 		ahd_set_scbptr(ahd, scbid);
7643 		*list_tail = scbid;
7644 		next = ahd_inw_scbram(ahd, SCB_NEXT);
7645 		if (ahd_match_scb(ahd, scb, target, channel,
7646 				  lun, SCB_LIST_NULL, role) == 0) {
7647 			prev = scbid;
7648 			continue;
7649 		}
7650 		found++;
7651 		switch (action) {
7652 		case SEARCH_COMPLETE:
7653 			if ((scb->flags & SCB_ACTIVE) == 0)
7654 				printf("Inactive SCB in Waiting List\n");
7655 			ahd_done_with_status(ahd, scb, status);
7656 			/* FALLTHROUGH */
7657 		case SEARCH_REMOVE:
7658 			ahd_rem_wscb(ahd, scbid, prev, next, tid);
7659 			*list_tail = prev;
7660 			if (SCBID_IS_NULL(prev))
7661 				*list_head = next;
7662 			break;
7663 		case SEARCH_PRINT:
7664 			printf("0x%x ", scbid);
7665 		case SEARCH_COUNT:
7666 			prev = scbid;
7667 			break;
7668 		}
7669 		if (found > AHD_SCB_MAX)
7670 			panic("SCB LIST LOOP");
7671 	}
7672 	if (action == SEARCH_COMPLETE
7673 	 || action == SEARCH_REMOVE)
7674 		ahd_outw(ahd, CMDS_PENDING, ahd_inw(ahd, CMDS_PENDING) - found);
7675 	return (found);
7676 }
7677 
7678 static void
7679 ahd_stitch_tid_list(struct ahd_softc *ahd, u_int tid_prev,
7680 		    u_int tid_cur, u_int tid_next)
7681 {
7682 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7683 
7684 	if (SCBID_IS_NULL(tid_cur)) {
7685 		/* Bypass current TID list */
7686 		if (SCBID_IS_NULL(tid_prev)) {
7687 			ahd_outw(ahd, WAITING_TID_HEAD, tid_next);
7688 		} else {
7689 			ahd_set_scbptr(ahd, tid_prev);
7690 			ahd_outw(ahd, SCB_NEXT2, tid_next);
7691 		}
7692 		if (SCBID_IS_NULL(tid_next))
7693 			ahd_outw(ahd, WAITING_TID_TAIL, tid_prev);
7694 	} else {
7695 		/* Stitch through tid_cur */
7696 		if (SCBID_IS_NULL(tid_prev)) {
7697 			ahd_outw(ahd, WAITING_TID_HEAD, tid_cur);
7698 		} else {
7699 			ahd_set_scbptr(ahd, tid_prev);
7700 			ahd_outw(ahd, SCB_NEXT2, tid_cur);
7701 		}
7702 		ahd_set_scbptr(ahd, tid_cur);
7703 		ahd_outw(ahd, SCB_NEXT2, tid_next);
7704 
7705 		if (SCBID_IS_NULL(tid_next))
7706 			ahd_outw(ahd, WAITING_TID_TAIL, tid_cur);
7707 	}
7708 }
7709 
7710 /*
7711  * Manipulate the waiting for selection list and return the
7712  * scb that follows the one that we remove.
7713  */
7714 static u_int
7715 ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
7716 	     u_int prev, u_int next, u_int tid)
7717 {
7718 	u_int tail_offset;
7719 
7720 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7721 	if (!SCBID_IS_NULL(prev)) {
7722 		ahd_set_scbptr(ahd, prev);
7723 		ahd_outw(ahd, SCB_NEXT, next);
7724 	}
7725 
7726 	/*
7727 	 * SCBs that have MK_MESSAGE set in them may
7728 	 * cause the tail pointer to be updated without
7729 	 * setting the next pointer of the previous tail.
7730 	 * Only clear the tail if the removed SCB was
7731 	 * the tail.
7732 	 */
7733 	tail_offset = WAITING_SCB_TAILS + (2 * tid);
7734 	if (SCBID_IS_NULL(next)
7735 	 && ahd_inw(ahd, tail_offset) == scbid)
7736 		ahd_outw(ahd, tail_offset, prev);
7737 
7738 	ahd_add_scb_to_free_list(ahd, scbid);
7739 	return (next);
7740 }
7741 
7742 /*
7743  * Add the SCB as selected by SCBPTR onto the on chip list of
7744  * free hardware SCBs.  This list is empty/unused if we are not
7745  * performing SCB paging.
7746  */
7747 static void
7748 ahd_add_scb_to_free_list(struct ahd_softc *ahd, u_int scbid)
7749 {
7750 /* XXX Need some other mechanism to designate "free". */
7751 	/*
7752 	 * Invalidate the tag so that our abort
7753 	 * routines don't think it's active.
7754 	ahd_outb(ahd, SCB_TAG, SCB_LIST_NULL);
7755 	 */
7756 }
7757 
7758 /******************************** Error Handling ******************************/
7759 /*
7760  * Abort all SCBs that match the given description (target/channel/lun/tag),
7761  * setting their status to the passed in status if the status has not already
7762  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
7763  * is paused before it is called.
7764  */
7765 int
7766 ahd_abort_scbs(struct ahd_softc *ahd, int target, char channel,
7767 	       int lun, u_int tag, role_t role, uint32_t status)
7768 {
7769 	struct		scb *scbp;
7770 	struct		scb *scbp_next;
7771 	u_int		i, j;
7772 	u_int		maxtarget;
7773 	u_int		minlun;
7774 	u_int		maxlun;
7775 	int		found;
7776 	ahd_mode_state	saved_modes;
7777 
7778 	/* restore this when we're done */
7779 	saved_modes = ahd_save_modes(ahd);
7780 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7781 
7782 	found = ahd_search_qinfifo(ahd, target, channel, lun, SCB_LIST_NULL,
7783 				   role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
7784 
7785 	/*
7786 	 * Clean out the busy target table for any untagged commands.
7787 	 */
7788 	i = 0;
7789 	maxtarget = 16;
7790 	if (target != CAM_TARGET_WILDCARD) {
7791 		i = target;
7792 		if (channel == 'B')
7793 			i += 8;
7794 		maxtarget = i + 1;
7795 	}
7796 
7797 	if (lun == CAM_LUN_WILDCARD) {
7798 		minlun = 0;
7799 		maxlun = AHD_NUM_LUNS_NONPKT;
7800 	} else if (lun >= AHD_NUM_LUNS_NONPKT) {
7801 		minlun = maxlun = 0;
7802 	} else {
7803 		minlun = lun;
7804 		maxlun = lun + 1;
7805 	}
7806 
7807 	if (role != ROLE_TARGET) {
7808 		for (;i < maxtarget; i++) {
7809 			for (j = minlun;j < maxlun; j++) {
7810 				u_int scbid;
7811 				u_int tcl;
7812 
7813 				tcl = BUILD_TCL_RAW(i, 'A', j);
7814 				scbid = ahd_find_busy_tcl(ahd, tcl);
7815 				scbp = ahd_lookup_scb(ahd, scbid);
7816 				if (scbp == NULL
7817 				 || ahd_match_scb(ahd, scbp, target, channel,
7818 						  lun, tag, role) == 0)
7819 					continue;
7820 				ahd_unbusy_tcl(ahd, BUILD_TCL_RAW(i, 'A', j));
7821 			}
7822 		}
7823 	}
7824 
7825 	/*
7826 	 * Don't abort commands that have already completed,
7827 	 * but haven't quite made it up to the host yet.
7828 	 */
7829 	ahd_flush_qoutfifo(ahd);
7830 
7831 	/*
7832 	 * Go through the pending CCB list and look for
7833 	 * commands for this target that are still active.
7834 	 * These are other tagged commands that were
7835 	 * disconnected when the reset occurred.
7836 	 */
7837 	scbp_next = LIST_FIRST(&ahd->pending_scbs);
7838 	while (scbp_next != NULL) {
7839 		scbp = scbp_next;
7840 		scbp_next = LIST_NEXT(scbp, pending_links);
7841 		if (ahd_match_scb(ahd, scbp, target, channel, lun, tag, role)) {
7842 			cam_status ostat;
7843 
7844 			ostat = aic_get_transaction_status(scbp);
7845 			if (ostat == CAM_REQ_INPROG)
7846 				aic_set_transaction_status(scbp, status);
7847 			if (aic_get_transaction_status(scbp) != CAM_REQ_CMP)
7848 				aic_freeze_scb(scbp);
7849 			if ((scbp->flags & SCB_ACTIVE) == 0)
7850 				printf("Inactive SCB on pending list\n");
7851 			ahd_done(ahd, scbp);
7852 			found++;
7853 		}
7854 	}
7855 	ahd_restore_modes(ahd, saved_modes);
7856 	ahd_platform_abort_scbs(ahd, target, channel, lun, tag, role, status);
7857 	ahd->flags |= AHD_UPDATE_PEND_CMDS;
7858 	return found;
7859 }
7860 
7861 static void
7862 ahd_reset_current_bus(struct ahd_softc *ahd)
7863 {
7864 	uint8_t scsiseq;
7865 
7866 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7867 	ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) & ~ENSCSIRST);
7868 	scsiseq = ahd_inb(ahd, SCSISEQ0) & ~(ENSELO|ENARBO|SCSIRSTO);
7869 	ahd_outb(ahd, SCSISEQ0, scsiseq | SCSIRSTO);
7870 	ahd_flush_device_writes(ahd);
7871 	aic_delay(AHD_BUSRESET_DELAY);
7872 	/* Turn off the bus reset */
7873 	ahd_outb(ahd, SCSISEQ0, scsiseq);
7874 	ahd_flush_device_writes(ahd);
7875 	aic_delay(AHD_BUSRESET_DELAY);
7876 	if ((ahd->bugs & AHD_SCSIRST_BUG) != 0) {
7877 		/*
7878 		 * 2A Razor #474
7879 		 * Certain chip state is not cleared for
7880 		 * SCSI bus resets that we initiate, so
7881 		 * we must reset the chip.
7882 		 */
7883 		ahd_reset(ahd, /*reinit*/TRUE);
7884 		ahd_intr_enable(ahd, /*enable*/TRUE);
7885 		AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
7886 	}
7887 
7888 	ahd_clear_intstat(ahd);
7889 }
7890 
7891 int
7892 ahd_reset_channel(struct ahd_softc *ahd, char channel, int initiate_reset)
7893 {
7894 	struct	ahd_devinfo devinfo;
7895 	u_int	initiator;
7896 	u_int	target;
7897 	u_int	max_scsiid;
7898 	int	found;
7899 	u_int	fifo;
7900 	u_int	next_fifo;
7901 
7902 	ahd->pending_device = NULL;
7903 
7904 	ahd_compile_devinfo(&devinfo,
7905 			    CAM_TARGET_WILDCARD,
7906 			    CAM_TARGET_WILDCARD,
7907 			    CAM_LUN_WILDCARD,
7908 			    channel, ROLE_UNKNOWN);
7909 	ahd_pause(ahd);
7910 
7911 	/* Make sure the sequencer is in a safe location. */
7912 	ahd_clear_critical_section(ahd);
7913 
7914 #ifdef AHD_TARGET_MODE
7915 	if ((ahd->flags & AHD_TARGETROLE) != 0) {
7916 		ahd_run_tqinfifo(ahd, /*paused*/TRUE);
7917 	}
7918 #endif
7919 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7920 
7921 	/*
7922 	 * Disable selections so no automatic hardware
7923 	 * functions will modify chip state.
7924 	 */
7925 	ahd_outb(ahd, SCSISEQ0, 0);
7926 	ahd_outb(ahd, SCSISEQ1, 0);
7927 
7928 	/*
7929 	 * Safely shut down our DMA engines.  Always start with
7930 	 * the FIFO that is not currently active (if any are
7931 	 * actively connected).
7932 	 */
7933 	next_fifo = fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
7934 	if (next_fifo > CURRFIFO_1)
7935 		/* If disconneced, arbitrarily start with FIFO1. */
7936 		next_fifo = fifo = 0;
7937 	do {
7938 		next_fifo ^= CURRFIFO_1;
7939 		ahd_set_modes(ahd, next_fifo, next_fifo);
7940 		ahd_outb(ahd, DFCNTRL,
7941 			 ahd_inb(ahd, DFCNTRL) & ~(SCSIEN|HDMAEN));
7942 		while ((ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0)
7943 			aic_delay(10);
7944 		/*
7945 		 * Set CURRFIFO to the now inactive channel.
7946 		 */
7947 		ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
7948 		ahd_outb(ahd, DFFSTAT, next_fifo);
7949 	} while (next_fifo != fifo);
7950 
7951 	/*
7952 	 * Reset the bus if we are initiating this reset
7953 	 */
7954 	ahd_clear_msg_state(ahd);
7955 	ahd_outb(ahd, SIMODE1,
7956 		 ahd_inb(ahd, SIMODE1) & ~(ENBUSFREE|ENSCSIRST));
7957 
7958 	if (initiate_reset)
7959 		ahd_reset_current_bus(ahd);
7960 
7961 	ahd_clear_intstat(ahd);
7962 
7963 	/*
7964 	 * Clean up all the state information for the
7965 	 * pending transactions on this bus.
7966 	 */
7967 	found = ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, channel,
7968 			       CAM_LUN_WILDCARD, SCB_LIST_NULL,
7969 			       ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
7970 
7971 	/*
7972 	 * Cleanup anything left in the FIFOs.
7973 	 */
7974 	ahd_clear_fifo(ahd, 0);
7975 	ahd_clear_fifo(ahd, 1);
7976 
7977 	/*
7978 	 * Revert to async/narrow transfers until we renegotiate.
7979 	 */
7980 	max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7;
7981 	for (target = 0; target <= max_scsiid; target++) {
7982 		if (ahd->enabled_targets[target] == NULL)
7983 			continue;
7984 		for (initiator = 0; initiator <= max_scsiid; initiator++) {
7985 			struct ahd_devinfo devinfo;
7986 
7987 			ahd_compile_devinfo(&devinfo, target, initiator,
7988 					    CAM_LUN_WILDCARD,
7989 					    'A', ROLE_UNKNOWN);
7990 			ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
7991 				      AHD_TRANS_CUR, /*paused*/TRUE);
7992 			ahd_set_syncrate(ahd, &devinfo, /*period*/0,
7993 					 /*offset*/0, /*ppr_options*/0,
7994 					 AHD_TRANS_CUR, /*paused*/TRUE);
7995 		}
7996 	}
7997 
7998 #ifdef AHD_TARGET_MODE
7999 	max_scsiid = (ahd->features & AHD_WIDE) ? 15 : 7;
8000 
8001 	/*
8002 	 * Send an immediate notify ccb to all target more peripheral
8003 	 * drivers affected by this action.
8004 	 */
8005 	for (target = 0; target <= max_scsiid; target++) {
8006 		struct ahd_tmode_tstate* tstate;
8007 		u_int lun;
8008 
8009 		tstate = ahd->enabled_targets[target];
8010 		if (tstate == NULL)
8011 			continue;
8012 		for (lun = 0; lun < AHD_NUM_LUNS; lun++) {
8013 			struct ahd_tmode_lstate* lstate;
8014 
8015 			lstate = tstate->enabled_luns[lun];
8016 			if (lstate == NULL)
8017 				continue;
8018 
8019 			ahd_queue_lstate_event(ahd, lstate, CAM_TARGET_WILDCARD,
8020 					       EVENT_TYPE_BUS_RESET, /*arg*/0);
8021 			ahd_send_lstate_events(ahd, lstate);
8022 		}
8023 	}
8024 #endif
8025 	/* Notify the XPT that a bus reset occurred */
8026 	ahd_send_async(ahd, devinfo.channel, CAM_TARGET_WILDCARD,
8027 		       CAM_LUN_WILDCARD, AC_BUS_RESET, NULL);
8028 	ahd_restart(ahd);
8029 	/*
8030 	 * Freeze the SIMQ until our poller can determine that
8031 	 * the bus reset has really gone away.  We set the initial
8032 	 * timer to 0 to have the check performed as soon as possible
8033 	 * from the timer context.
8034 	 */
8035 	if ((ahd->flags & AHD_RESET_POLL_ACTIVE) == 0) {
8036 		ahd->flags |= AHD_RESET_POLL_ACTIVE;
8037 		aic_freeze_simq(ahd);
8038 		aic_timer_reset(&ahd->reset_timer, 0, ahd_reset_poll, ahd);
8039 	}
8040 	return (found);
8041 }
8042 
8043 #define AHD_RESET_POLL_MS 1
8044 static void
8045 ahd_reset_poll(void *arg)
8046 {
8047 	struct	ahd_softc *ahd = (struct ahd_softc *)arg;
8048 	u_int	scsiseq1;
8049 
8050 	ahd_lock(ahd);
8051 	ahd_pause(ahd);
8052 	ahd_update_modes(ahd);
8053 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8054 	ahd_outb(ahd, CLRSINT1, CLRSCSIRSTI);
8055 	if ((ahd_inb(ahd, SSTAT1) & SCSIRSTI) != 0) {
8056 		aic_timer_reset(&ahd->reset_timer, AHD_RESET_POLL_MS,
8057 				ahd_reset_poll, ahd);
8058 		ahd_unpause(ahd);
8059 		ahd_unlock(ahd);
8060 		return;
8061 	}
8062 
8063 	/* Reset is now low.  Complete chip reinitialization. */
8064 	ahd_outb(ahd, SIMODE1, ahd_inb(ahd, SIMODE1) | ENSCSIRST);
8065 	scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
8066 	ahd_outb(ahd, SCSISEQ1, scsiseq1 & (ENSELI|ENRSELI|ENAUTOATNP));
8067 	ahd_unpause(ahd);
8068 	ahd->flags &= ~AHD_RESET_POLL_ACTIVE;
8069 	aic_release_simq(ahd);
8070 	ahd_unlock(ahd);
8071 }
8072 
8073 /**************************** Statistics Processing ***************************/
8074 static void
8075 ahd_stat_timer(void *arg)
8076 {
8077 	struct	ahd_softc *ahd = (struct ahd_softc *)arg;
8078 	int	enint_coal;
8079 
8080 	ahd_lock(ahd);
8081 	enint_coal = ahd->hs_mailbox & ENINT_COALESCE;
8082 	if (ahd->cmdcmplt_total > ahd->int_coalescing_threshold)
8083 		enint_coal |= ENINT_COALESCE;
8084 	else if (ahd->cmdcmplt_total < ahd->int_coalescing_stop_threshold)
8085 		enint_coal &= ~ENINT_COALESCE;
8086 
8087 	if (enint_coal != (ahd->hs_mailbox & ENINT_COALESCE)) {
8088 		ahd_enable_coalescing(ahd, enint_coal);
8089 #ifdef AHD_DEBUG
8090 		if ((ahd_debug & AHD_SHOW_INT_COALESCING) != 0)
8091 			printf("%s: Interrupt coalescing "
8092 			       "now %sabled. Cmds %d\n",
8093 			       ahd_name(ahd),
8094 			       (enint_coal & ENINT_COALESCE) ? "en" : "dis",
8095 			       ahd->cmdcmplt_total);
8096 #endif
8097 	}
8098 
8099 	ahd->cmdcmplt_bucket = (ahd->cmdcmplt_bucket+1) & (AHD_STAT_BUCKETS-1);
8100 	ahd->cmdcmplt_total -= ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket];
8101 	ahd->cmdcmplt_counts[ahd->cmdcmplt_bucket] = 0;
8102 	aic_timer_reset(&ahd->stat_timer, AHD_STAT_UPDATE_MS,
8103 			ahd_stat_timer, ahd);
8104 	ahd_unlock(ahd);
8105 }
8106 
8107 /****************************** Status Processing *****************************/
8108 void
8109 ahd_handle_scb_status(struct ahd_softc *ahd, struct scb *scb)
8110 {
8111 	if (scb->hscb->shared_data.istatus.scsi_status != 0) {
8112 		ahd_handle_scsi_status(ahd, scb);
8113 	} else {
8114 		ahd_calc_residual(ahd, scb);
8115 		ahd_done(ahd, scb);
8116 	}
8117 }
8118 
8119 void
8120 ahd_handle_scsi_status(struct ahd_softc *ahd, struct scb *scb)
8121 {
8122 	struct	hardware_scb *hscb;
8123 	int	paused;
8124 
8125 	/*
8126 	 * The sequencer freezes its select-out queue
8127 	 * anytime a SCSI status error occurs.  We must
8128 	 * handle the error and increment our qfreeze count
8129 	 * to allow the sequencer to continue.  We don't
8130 	 * bother clearing critical sections here since all
8131 	 * operations are on data structures that the sequencer
8132 	 * is not touching once the queue is frozen.
8133 	 */
8134 	hscb = scb->hscb;
8135 
8136 	if (ahd_is_paused(ahd)) {
8137 		paused = 1;
8138 	} else {
8139 		paused = 0;
8140 		ahd_pause(ahd);
8141 	}
8142 
8143 	/* Freeze the queue until the client sees the error. */
8144 	ahd_freeze_devq(ahd, scb);
8145 	aic_freeze_scb(scb);
8146 	ahd->qfreeze_cnt++;
8147 	ahd_outw(ahd, KERNEL_QFREEZE_COUNT, ahd->qfreeze_cnt);
8148 
8149 	if (paused == 0)
8150 		ahd_unpause(ahd);
8151 
8152 	/* Don't want to clobber the original sense code */
8153 	if ((scb->flags & SCB_SENSE) != 0) {
8154 		/*
8155 		 * Clear the SCB_SENSE Flag and perform
8156 		 * a normal command completion.
8157 		 */
8158 		scb->flags &= ~SCB_SENSE;
8159 		aic_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
8160 		ahd_done(ahd, scb);
8161 		return;
8162 	}
8163 	aic_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
8164 	aic_set_scsi_status(scb, hscb->shared_data.istatus.scsi_status);
8165 	switch (hscb->shared_data.istatus.scsi_status) {
8166 	case STATUS_PKT_SENSE:
8167 	{
8168 		struct scsi_status_iu_header *siu;
8169 
8170 		ahd_sync_sense(ahd, scb, BUS_DMASYNC_POSTREAD);
8171 		siu = (struct scsi_status_iu_header *)scb->sense_data;
8172 		aic_set_scsi_status(scb, siu->status);
8173 #ifdef AHD_DEBUG
8174 		if ((ahd_debug & AHD_SHOW_SENSE) != 0) {
8175 			ahd_print_path(ahd, scb);
8176 			printf("SCB 0x%x Received PKT Status of 0x%x\n",
8177 			       SCB_GET_TAG(scb), siu->status);
8178 			printf("\tflags = 0x%x, sense len = 0x%x, "
8179 			       "pktfail = 0x%x\n",
8180 			       siu->flags, scsi_4btoul(siu->sense_length),
8181 			       scsi_4btoul(siu->pkt_failures_length));
8182 		}
8183 #endif
8184 		if ((siu->flags & SIU_RSPVALID) != 0) {
8185 			ahd_print_path(ahd, scb);
8186 			if (scsi_4btoul(siu->pkt_failures_length) < 4) {
8187 				printf("Unable to parse pkt_failures\n");
8188 			} else {
8189 				switch (SIU_PKTFAIL_CODE(siu)) {
8190 				case SIU_PFC_NONE:
8191 					printf("No packet failure found\n");
8192 					AHD_UNCORRECTABLE_ERROR(ahd);
8193 					break;
8194 				case SIU_PFC_CIU_FIELDS_INVALID:
8195 					printf("Invalid Command IU Field\n");
8196 					AHD_UNCORRECTABLE_ERROR(ahd);
8197 					break;
8198 				case SIU_PFC_TMF_NOT_SUPPORTED:
8199 					printf("TMF not supportd\n");
8200 					AHD_UNCORRECTABLE_ERROR(ahd);
8201 					break;
8202 				case SIU_PFC_TMF_FAILED:
8203 					printf("TMF failed\n");
8204 					AHD_UNCORRECTABLE_ERROR(ahd);
8205 					break;
8206 				case SIU_PFC_INVALID_TYPE_CODE:
8207 					printf("Invalid L_Q Type code\n");
8208 					AHD_UNCORRECTABLE_ERROR(ahd);
8209 					break;
8210 				case SIU_PFC_ILLEGAL_REQUEST:
8211 					AHD_UNCORRECTABLE_ERROR(ahd);
8212 					printf("Illegal request\n");
8213 				default:
8214 					break;
8215 				}
8216 			}
8217 			if (siu->status == SCSI_STATUS_OK)
8218 				aic_set_transaction_status(scb,
8219 							   CAM_REQ_CMP_ERR);
8220 		}
8221 		if ((siu->flags & SIU_SNSVALID) != 0) {
8222 			scb->flags |= SCB_PKT_SENSE;
8223 #ifdef AHD_DEBUG
8224 			if ((ahd_debug & AHD_SHOW_SENSE) != 0)
8225 				printf("Sense data available\n");
8226 #endif
8227 		}
8228 		ahd_done(ahd, scb);
8229 		break;
8230 	}
8231 	case SCSI_STATUS_CMD_TERMINATED:
8232 	case SCSI_STATUS_CHECK_COND:
8233 	{
8234 		struct ahd_devinfo devinfo;
8235 		struct ahd_dma_seg *sg;
8236 		struct scsi_sense *sc;
8237 		struct ahd_initiator_tinfo *targ_info;
8238 		struct ahd_tmode_tstate *tstate;
8239 		struct ahd_transinfo *tinfo;
8240 #ifdef AHD_DEBUG
8241 		if (ahd_debug & AHD_SHOW_SENSE) {
8242 			ahd_print_path(ahd, scb);
8243 			printf("SCB %d: requests Check Status\n",
8244 			       SCB_GET_TAG(scb));
8245 		}
8246 #endif
8247 
8248 		if (aic_perform_autosense(scb) == 0)
8249 			break;
8250 
8251 		ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
8252 				    SCB_GET_TARGET(ahd, scb),
8253 				    SCB_GET_LUN(scb),
8254 				    SCB_GET_CHANNEL(ahd, scb),
8255 				    ROLE_INITIATOR);
8256 		targ_info = ahd_fetch_transinfo(ahd,
8257 						devinfo.channel,
8258 						devinfo.our_scsiid,
8259 						devinfo.target,
8260 						&tstate);
8261 		tinfo = &targ_info->curr;
8262 		sg = scb->sg_list;
8263 		sc = (struct scsi_sense *)hscb->shared_data.idata.cdb;
8264 		/*
8265 		 * Save off the residual if there is one.
8266 		 */
8267 		ahd_update_residual(ahd, scb);
8268 #ifdef AHD_DEBUG
8269 		if (ahd_debug & AHD_SHOW_SENSE) {
8270 			ahd_print_path(ahd, scb);
8271 			printf("Sending Sense\n");
8272 		}
8273 #endif
8274 		scb->sg_count = 0;
8275 		sg = ahd_sg_setup(ahd, scb, sg, ahd_get_sense_bufaddr(ahd, scb),
8276 				  aic_get_sense_bufsize(ahd, scb),
8277 				  /*last*/TRUE);
8278 		sc->opcode = REQUEST_SENSE;
8279 		sc->byte2 = 0;
8280 		if (tinfo->protocol_version <= SCSI_REV_2
8281 		 && SCB_GET_LUN(scb) < 8)
8282 			sc->byte2 = SCB_GET_LUN(scb) << 5;
8283 		sc->unused[0] = 0;
8284 		sc->unused[1] = 0;
8285 		sc->length = aic_get_sense_bufsize(ahd, scb);
8286 		sc->control = 0;
8287 
8288 		/*
8289 		 * We can't allow the target to disconnect.
8290 		 * This will be an untagged transaction and
8291 		 * having the target disconnect will make this
8292 		 * transaction indestinguishable from outstanding
8293 		 * tagged transactions.
8294 		 */
8295 		hscb->control = 0;
8296 
8297 		/*
8298 		 * This request sense could be because the
8299 		 * the device lost power or in some other
8300 		 * way has lost our transfer negotiations.
8301 		 * Renegotiate if appropriate.  Unit attention
8302 		 * errors will be reported before any data
8303 		 * phases occur.
8304 		 */
8305 		if (aic_get_residual(scb) == aic_get_transfer_length(scb)) {
8306 			ahd_update_neg_request(ahd, &devinfo,
8307 					       tstate, targ_info,
8308 					       AHD_NEG_IF_NON_ASYNC);
8309 		}
8310 		if (tstate->auto_negotiate & devinfo.target_mask) {
8311 			hscb->control |= MK_MESSAGE;
8312 			scb->flags &=
8313 			    ~(SCB_NEGOTIATE|SCB_ABORT|SCB_DEVICE_RESET);
8314 			scb->flags |= SCB_AUTO_NEGOTIATE;
8315 		}
8316 		hscb->cdb_len = sizeof(*sc);
8317 		ahd_setup_data_scb(ahd, scb);
8318 		scb->flags |= SCB_SENSE;
8319 		ahd_queue_scb(ahd, scb);
8320 		/*
8321 		 * Ensure we have enough time to actually
8322 		 * retrieve the sense, but only schedule
8323 		 * the timer if we are not in recovery or
8324 		 * this is a recovery SCB that is allowed
8325 		 * to have an active timer.
8326 		 */
8327 		if (ahd->scb_data.recovery_scbs == 0
8328 		 || (scb->flags & SCB_RECOVERY_SCB) != 0)
8329 			aic_scb_timer_reset(scb, 5 * 1000);
8330 		break;
8331 	}
8332 	case SCSI_STATUS_OK:
8333 		printf("%s: Interrupted for staus of 0???\n",
8334 		       ahd_name(ahd));
8335 		/* FALLTHROUGH */
8336 	default:
8337 		ahd_done(ahd, scb);
8338 		break;
8339 	}
8340 }
8341 
8342 /*
8343  * Calculate the residual for a just completed SCB.
8344  */
8345 void
8346 ahd_calc_residual(struct ahd_softc *ahd, struct scb *scb)
8347 {
8348 	struct hardware_scb *hscb;
8349 	struct initiator_status *spkt;
8350 	uint32_t sgptr;
8351 	uint32_t resid_sgptr;
8352 	uint32_t resid;
8353 
8354 	/*
8355 	 * 5 cases.
8356 	 * 1) No residual.
8357 	 *    SG_STATUS_VALID clear in sgptr.
8358 	 * 2) Transferless command
8359 	 * 3) Never performed any transfers.
8360 	 *    sgptr has SG_FULL_RESID set.
8361 	 * 4) No residual but target did not
8362 	 *    save data pointers after the
8363 	 *    last transfer, so sgptr was
8364 	 *    never updated.
8365 	 * 5) We have a partial residual.
8366 	 *    Use residual_sgptr to determine
8367 	 *    where we are.
8368 	 */
8369 
8370 	hscb = scb->hscb;
8371 	sgptr = aic_le32toh(hscb->sgptr);
8372 	if ((sgptr & SG_STATUS_VALID) == 0)
8373 		/* Case 1 */
8374 		return;
8375 	sgptr &= ~SG_STATUS_VALID;
8376 
8377 	if ((sgptr & SG_LIST_NULL) != 0)
8378 		/* Case 2 */
8379 		return;
8380 
8381 	/*
8382 	 * Residual fields are the same in both
8383 	 * target and initiator status packets,
8384 	 * so we can always use the initiator fields
8385 	 * regardless of the role for this SCB.
8386 	 */
8387 	spkt = &hscb->shared_data.istatus;
8388 	resid_sgptr = aic_le32toh(spkt->residual_sgptr);
8389 	if ((sgptr & SG_FULL_RESID) != 0) {
8390 		/* Case 3 */
8391 		resid = aic_get_transfer_length(scb);
8392 	} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
8393 		/* Case 4 */
8394 		return;
8395 	} else if ((resid_sgptr & SG_OVERRUN_RESID) != 0) {
8396 		ahd_print_path(ahd, scb);
8397 		printf("data overrun detected Tag == 0x%x.\n",
8398 		       SCB_GET_TAG(scb));
8399 		ahd_freeze_devq(ahd, scb);
8400 		aic_set_transaction_status(scb, CAM_DATA_RUN_ERR);
8401 		aic_freeze_scb(scb);
8402 		return;
8403 	} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
8404 		panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
8405 		/* NOTREACHED */
8406 	} else {
8407 		struct ahd_dma_seg *sg;
8408 
8409 		/*
8410 		 * Remainder of the SG where the transfer
8411 		 * stopped.
8412 		 */
8413 		resid = aic_le32toh(spkt->residual_datacnt) & AHD_SG_LEN_MASK;
8414 		sg = ahd_sg_bus_to_virt(ahd, scb, resid_sgptr & SG_PTR_MASK);
8415 
8416 		/* The residual sg_ptr always points to the next sg */
8417 		sg--;
8418 
8419 		/*
8420 		 * Add up the contents of all residual
8421 		 * SG segments that are after the SG where
8422 		 * the transfer stopped.
8423 		 */
8424 		while ((aic_le32toh(sg->len) & AHD_DMA_LAST_SEG) == 0) {
8425 			sg++;
8426 			resid += aic_le32toh(sg->len) & AHD_SG_LEN_MASK;
8427 		}
8428 	}
8429 	if ((scb->flags & SCB_SENSE) == 0)
8430 		aic_set_residual(scb, resid);
8431 	else
8432 		aic_set_sense_residual(scb, resid);
8433 
8434 #ifdef AHD_DEBUG
8435 	if ((ahd_debug & AHD_SHOW_MISC) != 0) {
8436 		ahd_print_path(ahd, scb);
8437 		printf("Handled %sResidual of %d bytes\n",
8438 		       (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
8439 	}
8440 #endif
8441 }
8442 
8443 /******************************* Target Mode **********************************/
8444 #ifdef AHD_TARGET_MODE
8445 /*
8446  * Add a target mode event to this lun's queue
8447  */
8448 static void
8449 ahd_queue_lstate_event(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate,
8450 		       u_int initiator_id, u_int event_type, u_int event_arg)
8451 {
8452 	struct ahd_tmode_event *event;
8453 	int pending;
8454 
8455 	xpt_freeze_devq(lstate->path, /*count*/1);
8456 	if (lstate->event_w_idx >= lstate->event_r_idx)
8457 		pending = lstate->event_w_idx - lstate->event_r_idx;
8458 	else
8459 		pending = AHD_TMODE_EVENT_BUFFER_SIZE + 1
8460 			- (lstate->event_r_idx - lstate->event_w_idx);
8461 
8462 	if (event_type == EVENT_TYPE_BUS_RESET
8463 	 || event_type == MSG_BUS_DEV_RESET) {
8464 		/*
8465 		 * Any earlier events are irrelevant, so reset our buffer.
8466 		 * This has the effect of allowing us to deal with reset
8467 		 * floods (an external device holding down the reset line)
8468 		 * without losing the event that is really interesting.
8469 		 */
8470 		lstate->event_r_idx = 0;
8471 		lstate->event_w_idx = 0;
8472 		xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
8473 	}
8474 
8475 	if (pending == AHD_TMODE_EVENT_BUFFER_SIZE) {
8476 		xpt_print_path(lstate->path);
8477 		printf("immediate event %x:%x lost\n",
8478 		       lstate->event_buffer[lstate->event_r_idx].event_type,
8479 		       lstate->event_buffer[lstate->event_r_idx].event_arg);
8480 		lstate->event_r_idx++;
8481 		if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8482 			lstate->event_r_idx = 0;
8483 		xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
8484 	}
8485 
8486 	event = &lstate->event_buffer[lstate->event_w_idx];
8487 	event->initiator_id = initiator_id;
8488 	event->event_type = event_type;
8489 	event->event_arg = event_arg;
8490 	lstate->event_w_idx++;
8491 	if (lstate->event_w_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8492 		lstate->event_w_idx = 0;
8493 }
8494 
8495 /*
8496  * Send any target mode events queued up waiting
8497  * for immediate notify resources.
8498  */
8499 void
8500 ahd_send_lstate_events(struct ahd_softc *ahd, struct ahd_tmode_lstate *lstate)
8501 {
8502 	struct ccb_hdr *ccbh;
8503 	struct ccb_immediate_notify *inot;
8504 
8505 	while (lstate->event_r_idx != lstate->event_w_idx
8506 	    && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
8507 		struct ahd_tmode_event *event;
8508 
8509 		event = &lstate->event_buffer[lstate->event_r_idx];
8510 		SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
8511 		inot = (struct ccb_immediate_notify *)ccbh;
8512 		switch (event->event_type) {
8513 		case EVENT_TYPE_BUS_RESET:
8514 			ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
8515 			break;
8516 		default:
8517 			ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
8518 			inot->arg = event->event_type;
8519 			inot->seq_id = event->event_arg;
8520 			break;
8521 		}
8522 		inot->initiator_id = event->initiator_id;
8523 		xpt_done((union ccb *)inot);
8524 		lstate->event_r_idx++;
8525 		if (lstate->event_r_idx == AHD_TMODE_EVENT_BUFFER_SIZE)
8526 			lstate->event_r_idx = 0;
8527 	}
8528 }
8529 #endif
8530 
8531 /******************** Sequencer Program Patching/Download *********************/
8532 
8533 #ifdef AHD_DUMP_SEQ
8534 void
8535 ahd_dumpseq(struct ahd_softc* ahd)
8536 {
8537 	int i;
8538 	int max_prog;
8539 
8540 	max_prog = 2048;
8541 
8542 	ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
8543 	ahd_outw(ahd, PRGMCNT, 0);
8544 	for (i = 0; i < max_prog; i++) {
8545 		uint8_t ins_bytes[4];
8546 
8547 		ahd_insb(ahd, SEQRAM, ins_bytes, 4);
8548 		printf("0x%08x\n", ins_bytes[0] << 24
8549 				 | ins_bytes[1] << 16
8550 				 | ins_bytes[2] << 8
8551 				 | ins_bytes[3]);
8552 	}
8553 }
8554 #endif
8555 
8556 static void
8557 ahd_loadseq(struct ahd_softc *ahd)
8558 {
8559 	struct	cs cs_table[num_critical_sections];
8560 	u_int	begin_set[num_critical_sections];
8561 	u_int	end_set[num_critical_sections];
8562 	struct	patch *cur_patch;
8563 	u_int	cs_count;
8564 	u_int	cur_cs;
8565 	u_int	i;
8566 	int	downloaded;
8567 	u_int	skip_addr;
8568 	u_int	sg_prefetch_cnt;
8569 	u_int	sg_prefetch_cnt_limit;
8570 	u_int	sg_prefetch_align;
8571 	u_int	sg_size;
8572 	u_int	cacheline_mask;
8573 	uint8_t	download_consts[DOWNLOAD_CONST_COUNT];
8574 
8575 	if (bootverbose)
8576 		printf("%s: Downloading Sequencer Program...",
8577 		       ahd_name(ahd));
8578 
8579 #if DOWNLOAD_CONST_COUNT != 8
8580 #error "Download Const Mismatch"
8581 #endif
8582 	/*
8583 	 * Start out with 0 critical sections
8584 	 * that apply to this firmware load.
8585 	 */
8586 	cs_count = 0;
8587 	cur_cs = 0;
8588 	memset(begin_set, 0, sizeof(begin_set));
8589 	memset(end_set, 0, sizeof(end_set));
8590 
8591 	/*
8592 	 * Setup downloadable constant table.
8593 	 *
8594 	 * The computation for the S/G prefetch variables is
8595 	 * a bit complicated.  We would like to always fetch
8596 	 * in terms of cachelined sized increments.  However,
8597 	 * if the cacheline is not an even multiple of the
8598 	 * SG element size or is larger than our SG RAM, using
8599 	 * just the cache size might leave us with only a portion
8600 	 * of an SG element at the tail of a prefetch.  If the
8601 	 * cacheline is larger than our S/G prefetch buffer less
8602 	 * the size of an SG element, we may round down to a cacheline
8603 	 * that doesn't contain any or all of the S/G of interest
8604 	 * within the bounds of our S/G ram.  Provide variables to
8605 	 * the sequencer that will allow it to handle these edge
8606 	 * cases.
8607 	 */
8608 	/* Start by aligning to the nearest cacheline. */
8609 	sg_prefetch_align = ahd->pci_cachesize;
8610 	if (sg_prefetch_align == 0)
8611 		sg_prefetch_align = 8;
8612 	/* Round down to the nearest power of 2. */
8613 	while (powerof2(sg_prefetch_align) == 0)
8614 		sg_prefetch_align--;
8615 
8616 	cacheline_mask = sg_prefetch_align - 1;
8617 
8618 	/*
8619 	 * If the cacheline boundary is greater than half our prefetch RAM
8620 	 * we risk not being able to fetch even a single complete S/G
8621 	 * segment if we align to that boundary.
8622 	 */
8623 	if (sg_prefetch_align > CCSGADDR_MAX/2)
8624 		sg_prefetch_align = CCSGADDR_MAX/2;
8625 	/* Start by fetching a single cacheline. */
8626 	sg_prefetch_cnt = sg_prefetch_align;
8627 	/*
8628 	 * Increment the prefetch count by cachelines until
8629 	 * at least one S/G element will fit.
8630 	 */
8631 	sg_size = sizeof(struct ahd_dma_seg);
8632 	if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0)
8633 		sg_size = sizeof(struct ahd_dma64_seg);
8634 	while (sg_prefetch_cnt < sg_size)
8635 		sg_prefetch_cnt += sg_prefetch_align;
8636 	/*
8637 	 * If the cacheline is not an even multiple of
8638 	 * the S/G size, we may only get a partial S/G when
8639 	 * we align. Add a cacheline if this is the case.
8640 	 */
8641 	if ((sg_prefetch_align % sg_size) != 0
8642 	 && (sg_prefetch_cnt < CCSGADDR_MAX))
8643 		sg_prefetch_cnt += sg_prefetch_align;
8644 	/*
8645 	 * Lastly, compute a value that the sequencer can use
8646 	 * to determine if the remainder of the CCSGRAM buffer
8647 	 * has a full S/G element in it.
8648 	 */
8649 	sg_prefetch_cnt_limit = -(sg_prefetch_cnt - sg_size + 1);
8650 	download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
8651 	download_consts[SG_PREFETCH_CNT_LIMIT] = sg_prefetch_cnt_limit;
8652 	download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_align - 1);
8653 	download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_align - 1);
8654 	download_consts[SG_SIZEOF] = sg_size;
8655 	download_consts[PKT_OVERRUN_BUFOFFSET] =
8656 		(ahd->overrun_buf - (uint8_t *)ahd->qoutfifo) / 256;
8657 	download_consts[SCB_TRANSFER_SIZE] = SCB_TRANSFER_SIZE_1BYTE_LUN;
8658 	download_consts[CACHELINE_MASK] = cacheline_mask;
8659 	cur_patch = patches;
8660 	downloaded = 0;
8661 	skip_addr = 0;
8662 	ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
8663 	ahd_outw(ahd, PRGMCNT, 0);
8664 
8665 	for (i = 0; i < sizeof(seqprog)/4; i++) {
8666 		if (ahd_check_patch(ahd, &cur_patch, i, &skip_addr) == 0) {
8667 			/*
8668 			 * Don't download this instruction as it
8669 			 * is in a patch that was removed.
8670 			 */
8671 			continue;
8672 		}
8673 		/*
8674 		 * Move through the CS table until we find a CS
8675 		 * that might apply to this instruction.
8676 		 */
8677 		for (; cur_cs < num_critical_sections; cur_cs++) {
8678 			if (critical_sections[cur_cs].end <= i) {
8679 				if (begin_set[cs_count] == TRUE
8680 				 && end_set[cs_count] == FALSE) {
8681 					cs_table[cs_count].end = downloaded;
8682 				 	end_set[cs_count] = TRUE;
8683 					cs_count++;
8684 				}
8685 				continue;
8686 			}
8687 			if (critical_sections[cur_cs].begin <= i
8688 			 && begin_set[cs_count] == FALSE) {
8689 				cs_table[cs_count].begin = downloaded;
8690 				begin_set[cs_count] = TRUE;
8691 			}
8692 			break;
8693 		}
8694 		ahd_download_instr(ahd, i, download_consts);
8695 		downloaded++;
8696 	}
8697 
8698 	ahd->num_critical_sections = cs_count;
8699 	if (cs_count != 0) {
8700 		cs_count *= sizeof(struct cs);
8701 		ahd->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
8702 		if (ahd->critical_sections == NULL)
8703 			panic("ahd_loadseq: Could not malloc");
8704 		memcpy(ahd->critical_sections, cs_table, cs_count);
8705 	}
8706 	ahd_outb(ahd, SEQCTL0, PERRORDIS|FAILDIS|FASTMODE);
8707 
8708 	if (bootverbose) {
8709 		printf(" %d instructions downloaded\n", downloaded);
8710 		printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
8711 		       ahd_name(ahd), ahd->features, ahd->bugs, ahd->flags);
8712 	}
8713 }
8714 
8715 static int
8716 ahd_check_patch(struct ahd_softc *ahd, struct patch **start_patch,
8717 		u_int start_instr, u_int *skip_addr)
8718 {
8719 	struct	patch *cur_patch;
8720 	struct	patch *last_patch;
8721 	u_int	num_patches;
8722 
8723 	num_patches = sizeof(patches)/sizeof(struct patch);
8724 	last_patch = &patches[num_patches];
8725 	cur_patch = *start_patch;
8726 
8727 	while (cur_patch < last_patch && start_instr == cur_patch->begin) {
8728 		if (cur_patch->patch_func(ahd) == 0) {
8729 			/* Start rejecting code */
8730 			*skip_addr = start_instr + cur_patch->skip_instr;
8731 			cur_patch += cur_patch->skip_patch;
8732 		} else {
8733 			/* Accepted this patch.  Advance to the next
8734 			 * one and wait for our instruction pointer to
8735 			 * hit this point.
8736 			 */
8737 			cur_patch++;
8738 		}
8739 	}
8740 
8741 	*start_patch = cur_patch;
8742 	if (start_instr < *skip_addr)
8743 		/* Still skipping */
8744 		return (0);
8745 
8746 	return (1);
8747 }
8748 
8749 static u_int
8750 ahd_resolve_seqaddr(struct ahd_softc *ahd, u_int address)
8751 {
8752 	struct patch *cur_patch;
8753 	int address_offset;
8754 	u_int skip_addr;
8755 	u_int i;
8756 
8757 	address_offset = 0;
8758 	cur_patch = patches;
8759 	skip_addr = 0;
8760 
8761 	for (i = 0; i < address;) {
8762 		ahd_check_patch(ahd, &cur_patch, i, &skip_addr);
8763 
8764 		if (skip_addr > i) {
8765 			int end_addr;
8766 
8767 			end_addr = MIN(address, skip_addr);
8768 			address_offset += end_addr - i;
8769 			i = skip_addr;
8770 		} else {
8771 			i++;
8772 		}
8773 	}
8774 	return (address - address_offset);
8775 }
8776 
8777 static void
8778 ahd_download_instr(struct ahd_softc *ahd, u_int instrptr, uint8_t *dconsts)
8779 {
8780 	union	ins_formats instr;
8781 	struct	ins_format1 *fmt1_ins;
8782 	struct	ins_format3 *fmt3_ins;
8783 	u_int	opcode;
8784 
8785 	/*
8786 	 * The firmware is always compiled into a little endian format.
8787 	 */
8788 	instr.integer = aic_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
8789 
8790 	fmt1_ins = &instr.format1;
8791 	fmt3_ins = NULL;
8792 
8793 	/* Pull the opcode */
8794 	opcode = instr.format1.opcode;
8795 	switch (opcode) {
8796 	case AIC_OP_JMP:
8797 	case AIC_OP_JC:
8798 	case AIC_OP_JNC:
8799 	case AIC_OP_CALL:
8800 	case AIC_OP_JNE:
8801 	case AIC_OP_JNZ:
8802 	case AIC_OP_JE:
8803 	case AIC_OP_JZ:
8804 	{
8805 		fmt3_ins = &instr.format3;
8806 		fmt3_ins->address = ahd_resolve_seqaddr(ahd, fmt3_ins->address);
8807 		/* FALLTHROUGH */
8808 	}
8809 	case AIC_OP_OR:
8810 	case AIC_OP_AND:
8811 	case AIC_OP_XOR:
8812 	case AIC_OP_ADD:
8813 	case AIC_OP_ADC:
8814 	case AIC_OP_BMOV:
8815 		if (fmt1_ins->parity != 0) {
8816 			fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
8817 		}
8818 		fmt1_ins->parity = 0;
8819 		/* FALLTHROUGH */
8820 	case AIC_OP_ROL:
8821 	{
8822 		int i, count;
8823 
8824 		/* Calculate odd parity for the instruction */
8825 		for (i = 0, count = 0; i < 31; i++) {
8826 			uint32_t mask;
8827 
8828 			mask = 0x01 << i;
8829 			if ((instr.integer & mask) != 0)
8830 				count++;
8831 		}
8832 		if ((count & 0x01) == 0)
8833 			instr.format1.parity = 1;
8834 
8835 		/* The sequencer is a little endian cpu */
8836 		instr.integer = aic_htole32(instr.integer);
8837 		ahd_outsb(ahd, SEQRAM, instr.bytes, 4);
8838 		break;
8839 	}
8840 	default:
8841 		panic("Unknown opcode encountered in seq program");
8842 		break;
8843 	}
8844 }
8845 
8846 static int
8847 ahd_probe_stack_size(struct ahd_softc *ahd)
8848 {
8849 	int last_probe;
8850 
8851 	last_probe = 0;
8852 	while (1) {
8853 		int i;
8854 
8855 		/*
8856 		 * We avoid using 0 as a pattern to avoid
8857 		 * confusion if the stack implementation
8858 		 * "back-fills" with zeros when "poping'
8859 		 * entries.
8860 		 */
8861 		for (i = 1; i <= last_probe+1; i++) {
8862 		       ahd_outb(ahd, STACK, i & 0xFF);
8863 		       ahd_outb(ahd, STACK, (i >> 8) & 0xFF);
8864 		}
8865 
8866 		/* Verify */
8867 		for (i = last_probe+1; i > 0; i--) {
8868 			u_int stack_entry;
8869 
8870 			stack_entry = ahd_inb(ahd, STACK)
8871 				    |(ahd_inb(ahd, STACK) << 8);
8872 			if (stack_entry != i)
8873 				goto sized;
8874 		}
8875 		last_probe++;
8876 	}
8877 sized:
8878 	return (last_probe);
8879 }
8880 
8881 void
8882 ahd_dump_all_cards_state(void)
8883 {
8884 	struct ahd_softc *list_ahd;
8885 
8886 	TAILQ_FOREACH(list_ahd, &ahd_tailq, links) {
8887 		ahd_dump_card_state(list_ahd);
8888 	}
8889 }
8890 
8891 int
8892 ahd_print_register(ahd_reg_parse_entry_t *table, u_int num_entries,
8893 		   const char *name, u_int address, u_int value,
8894 		   u_int *cur_column, u_int wrap_point)
8895 {
8896 	int	printed;
8897 	u_int	printed_mask;
8898 	u_int	dummy_column;
8899 
8900 	if (cur_column == NULL) {
8901 		dummy_column = 0;
8902 		cur_column = &dummy_column;
8903 	}
8904 
8905 	if (cur_column != NULL && *cur_column >= wrap_point) {
8906 		printf("\n");
8907 		*cur_column = 0;
8908 	}
8909 	printed = printf("%s[0x%x]", name, value);
8910 	if (table == NULL) {
8911 		printed += printf(" ");
8912 		*cur_column += printed;
8913 		return (printed);
8914 	}
8915 	printed_mask = 0;
8916 	while (printed_mask != 0xFF) {
8917 		int entry;
8918 
8919 		for (entry = 0; entry < num_entries; entry++) {
8920 			if (((value & table[entry].mask)
8921 			  != table[entry].value)
8922 			 || ((printed_mask & table[entry].mask)
8923 			  == table[entry].mask))
8924 				continue;
8925 
8926 			printed += printf("%s%s",
8927 					  printed_mask == 0 ? ":(" : "|",
8928 					  table[entry].name);
8929 			printed_mask |= table[entry].mask;
8930 
8931 			break;
8932 		}
8933 		if (entry >= num_entries)
8934 			break;
8935 	}
8936 	if (printed_mask != 0)
8937 		printed += printf(") ");
8938 	else
8939 		printed += printf(" ");
8940 	*cur_column += printed;
8941 	return (printed);
8942 }
8943 
8944 void
8945 ahd_dump_card_state(struct ahd_softc *ahd)
8946 {
8947 	struct scb	*scb;
8948 	ahd_mode_state	 saved_modes;
8949 	u_int		 dffstat;
8950 	int		 paused;
8951 	u_int		 scb_index;
8952 	u_int		 saved_scb_index;
8953 	u_int		 cur_col;
8954 	int		 i;
8955 
8956 	if (ahd_is_paused(ahd)) {
8957 		paused = 1;
8958 	} else {
8959 		paused = 0;
8960 		ahd_pause(ahd);
8961 	}
8962 	saved_modes = ahd_save_modes(ahd);
8963 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
8964 	printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
8965 	       "%s: Dumping Card State at program address 0x%x Mode 0x%x\n",
8966 	       ahd_name(ahd),
8967 	       ahd_inw(ahd, CURADDR),
8968 	       ahd_build_mode_state(ahd, ahd->saved_src_mode,
8969 				    ahd->saved_dst_mode));
8970 	if (paused)
8971 		printf("Card was paused\n");
8972 
8973 	if (ahd_check_cmdcmpltqueues(ahd))
8974 		printf("Completions are pending\n");
8975 
8976 	/*
8977 	 * Mode independent registers.
8978 	 */
8979 	cur_col = 0;
8980 	ahd_intstat_print(ahd_inb(ahd, INTSTAT), &cur_col, 50);
8981 	ahd_seloid_print(ahd_inb(ahd, SELOID), &cur_col, 50);
8982 	ahd_selid_print(ahd_inb(ahd, SELID), &cur_col, 50);
8983 	ahd_hs_mailbox_print(ahd_inb(ahd, LOCAL_HS_MAILBOX), &cur_col, 50);
8984 	ahd_intctl_print(ahd_inb(ahd, INTCTL), &cur_col, 50);
8985 	ahd_seqintstat_print(ahd_inb(ahd, SEQINTSTAT), &cur_col, 50);
8986 	ahd_saved_mode_print(ahd_inb(ahd, SAVED_MODE), &cur_col, 50);
8987 	ahd_dffstat_print(ahd_inb(ahd, DFFSTAT), &cur_col, 50);
8988 	ahd_scsisigi_print(ahd_inb(ahd, SCSISIGI), &cur_col, 50);
8989 	ahd_scsiphase_print(ahd_inb(ahd, SCSIPHASE), &cur_col, 50);
8990 	ahd_scsibus_print(ahd_inb(ahd, SCSIBUS), &cur_col, 50);
8991 	ahd_lastphase_print(ahd_inb(ahd, LASTPHASE), &cur_col, 50);
8992 	ahd_scsiseq0_print(ahd_inb(ahd, SCSISEQ0), &cur_col, 50);
8993 	ahd_scsiseq1_print(ahd_inb(ahd, SCSISEQ1), &cur_col, 50);
8994 	ahd_seqctl0_print(ahd_inb(ahd, SEQCTL0), &cur_col, 50);
8995 	ahd_seqintctl_print(ahd_inb(ahd, SEQINTCTL), &cur_col, 50);
8996 	ahd_seq_flags_print(ahd_inb(ahd, SEQ_FLAGS), &cur_col, 50);
8997 	ahd_seq_flags2_print(ahd_inb(ahd, SEQ_FLAGS2), &cur_col, 50);
8998 	ahd_qfreeze_count_print(ahd_inw(ahd, QFREEZE_COUNT), &cur_col, 50);
8999 	ahd_kernel_qfreeze_count_print(ahd_inw(ahd, KERNEL_QFREEZE_COUNT),
9000 				       &cur_col, 50);
9001 	ahd_mk_message_scb_print(ahd_inw(ahd, MK_MESSAGE_SCB), &cur_col, 50);
9002 	ahd_mk_message_scsiid_print(ahd_inb(ahd, MK_MESSAGE_SCSIID),
9003 				    &cur_col, 50);
9004 	ahd_sstat0_print(ahd_inb(ahd, SSTAT0), &cur_col, 50);
9005 	ahd_sstat1_print(ahd_inb(ahd, SSTAT1), &cur_col, 50);
9006 	ahd_sstat2_print(ahd_inb(ahd, SSTAT2), &cur_col, 50);
9007 	ahd_sstat3_print(ahd_inb(ahd, SSTAT3), &cur_col, 50);
9008 	ahd_perrdiag_print(ahd_inb(ahd, PERRDIAG), &cur_col, 50);
9009 	ahd_simode1_print(ahd_inb(ahd, SIMODE1), &cur_col, 50);
9010 	ahd_lqistat0_print(ahd_inb(ahd, LQISTAT0), &cur_col, 50);
9011 	ahd_lqistat1_print(ahd_inb(ahd, LQISTAT1), &cur_col, 50);
9012 	ahd_lqistat2_print(ahd_inb(ahd, LQISTAT2), &cur_col, 50);
9013 	ahd_lqostat0_print(ahd_inb(ahd, LQOSTAT0), &cur_col, 50);
9014 	ahd_lqostat1_print(ahd_inb(ahd, LQOSTAT1), &cur_col, 50);
9015 	ahd_lqostat2_print(ahd_inb(ahd, LQOSTAT2), &cur_col, 50);
9016 	printf("\n");
9017 	printf("\nSCB Count = %d CMDS_PENDING = %d LASTSCB 0x%x "
9018 	       "CURRSCB 0x%x NEXTSCB 0x%x\n",
9019 	       ahd->scb_data.numscbs, ahd_inw(ahd, CMDS_PENDING),
9020 	       ahd_inw(ahd, LASTSCB), ahd_inw(ahd, CURRSCB),
9021 	       ahd_inw(ahd, NEXTSCB));
9022 	cur_col = 0;
9023 	/* QINFIFO */
9024 	ahd_search_qinfifo(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
9025 			   CAM_LUN_WILDCARD, SCB_LIST_NULL,
9026 			   ROLE_UNKNOWN, /*status*/0, SEARCH_PRINT);
9027 	saved_scb_index = ahd_get_scbptr(ahd);
9028 	printf("Pending list:");
9029 	i = 0;
9030 	LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
9031 		if (i++ > AHD_SCB_MAX)
9032 			break;
9033 		cur_col = printf("\n%3d FIFO_USE[0x%x] ", SCB_GET_TAG(scb),
9034 				 ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT));
9035 		ahd_set_scbptr(ahd, SCB_GET_TAG(scb));
9036 		ahd_scb_control_print(ahd_inb_scbram(ahd, SCB_CONTROL),
9037 				      &cur_col, 60);
9038 		ahd_scb_scsiid_print(ahd_inb_scbram(ahd, SCB_SCSIID),
9039 				     &cur_col, 60);
9040 	}
9041 	printf("\nTotal %d\n", i);
9042 
9043 	printf("Kernel Free SCB lists: ");
9044 	i = 0;
9045 	TAILQ_FOREACH(scb, &ahd->scb_data.free_scbs, links.tqe) {
9046 		struct scb *list_scb;
9047 
9048 		printf("\n  COLIDX[%d]: ", AHD_GET_SCB_COL_IDX(ahd, scb));
9049 		list_scb = scb;
9050 		do {
9051 			printf("%d ", SCB_GET_TAG(list_scb));
9052 			list_scb = LIST_NEXT(list_scb, collision_links);
9053 		} while (list_scb && i++ < AHD_SCB_MAX);
9054 	}
9055 
9056 	printf("\n  Any Device: ");
9057 	LIST_FOREACH(scb, &ahd->scb_data.any_dev_free_scb_list, links.le) {
9058 		if (i++ > AHD_SCB_MAX)
9059 			break;
9060 		printf("%d ", SCB_GET_TAG(scb));
9061 	}
9062 	printf("\n");
9063 
9064 	printf("Sequencer Complete DMA-inprog list: ");
9065 	scb_index = ahd_inw(ahd, COMPLETE_SCB_DMAINPROG_HEAD);
9066 	i = 0;
9067 	while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9068 		ahd_set_scbptr(ahd, scb_index);
9069 		printf("%d ", scb_index);
9070 		scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9071 	}
9072 	printf("\n");
9073 
9074 	printf("Sequencer Complete list: ");
9075 	scb_index = ahd_inw(ahd, COMPLETE_SCB_HEAD);
9076 	i = 0;
9077 	while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9078 		ahd_set_scbptr(ahd, scb_index);
9079 		printf("%d ", scb_index);
9080 		scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9081 	}
9082 	printf("\n");
9083 
9084 	printf("Sequencer DMA-Up and Complete list: ");
9085 	scb_index = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
9086 	i = 0;
9087 	while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9088 		ahd_set_scbptr(ahd, scb_index);
9089 		printf("%d ", scb_index);
9090 		scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9091 	}
9092 	printf("\n");
9093 	printf("Sequencer On QFreeze and Complete list: ");
9094 	scb_index = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
9095 	i = 0;
9096 	while (!SCBID_IS_NULL(scb_index) && i++ < AHD_SCB_MAX) {
9097 		ahd_set_scbptr(ahd, scb_index);
9098 		printf("%d ", scb_index);
9099 		scb_index = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
9100 	}
9101 	printf("\n");
9102 	ahd_set_scbptr(ahd, saved_scb_index);
9103 	dffstat = ahd_inb(ahd, DFFSTAT);
9104 	for (i = 0; i < 2; i++) {
9105 #ifdef AHD_DEBUG
9106 		struct scb *fifo_scb;
9107 #endif
9108 		u_int	    fifo_scbptr;
9109 
9110 		ahd_set_modes(ahd, AHD_MODE_DFF0 + i, AHD_MODE_DFF0 + i);
9111 		fifo_scbptr = ahd_get_scbptr(ahd);
9112 		printf("\n\n%s: FIFO%d %s, LONGJMP == 0x%x, SCB 0x%x\n",
9113 		       ahd_name(ahd), i,
9114 		       (dffstat & (FIFO0FREE << i)) ? "Free" : "Active",
9115 		       ahd_inw(ahd, LONGJMP_ADDR), fifo_scbptr);
9116 		cur_col = 0;
9117 		ahd_seqimode_print(ahd_inb(ahd, SEQIMODE), &cur_col, 50);
9118 		ahd_seqintsrc_print(ahd_inb(ahd, SEQINTSRC), &cur_col, 50);
9119 		ahd_dfcntrl_print(ahd_inb(ahd, DFCNTRL), &cur_col, 50);
9120 		ahd_dfstatus_print(ahd_inb(ahd, DFSTATUS), &cur_col, 50);
9121 		ahd_sg_cache_shadow_print(ahd_inb(ahd, SG_CACHE_SHADOW),
9122 					  &cur_col, 50);
9123 		ahd_sg_state_print(ahd_inb(ahd, SG_STATE), &cur_col, 50);
9124 		ahd_dffsxfrctl_print(ahd_inb(ahd, DFFSXFRCTL), &cur_col, 50);
9125 		ahd_soffcnt_print(ahd_inb(ahd, SOFFCNT), &cur_col, 50);
9126 		ahd_mdffstat_print(ahd_inb(ahd, MDFFSTAT), &cur_col, 50);
9127 		if (cur_col > 50) {
9128 			printf("\n");
9129 			cur_col = 0;
9130 		}
9131 		cur_col += printf("SHADDR = 0x%x%x, SHCNT = 0x%x ",
9132 				  ahd_inl(ahd, SHADDR+4),
9133 				  ahd_inl(ahd, SHADDR),
9134 				  (ahd_inb(ahd, SHCNT)
9135 				| (ahd_inb(ahd, SHCNT + 1) << 8)
9136 				| (ahd_inb(ahd, SHCNT + 2) << 16)));
9137 		if (cur_col > 50) {
9138 			printf("\n");
9139 			cur_col = 0;
9140 		}
9141 		cur_col += printf("HADDR = 0x%x%x, HCNT = 0x%x ",
9142 				  ahd_inl(ahd, HADDR+4),
9143 				  ahd_inl(ahd, HADDR),
9144 				  (ahd_inb(ahd, HCNT)
9145 				| (ahd_inb(ahd, HCNT + 1) << 8)
9146 				| (ahd_inb(ahd, HCNT + 2) << 16)));
9147 		ahd_ccsgctl_print(ahd_inb(ahd, CCSGCTL), &cur_col, 50);
9148 #ifdef AHD_DEBUG
9149 		if ((ahd_debug & AHD_SHOW_SG) != 0) {
9150 			fifo_scb = ahd_lookup_scb(ahd, fifo_scbptr);
9151 			if (fifo_scb != NULL)
9152 				ahd_dump_sglist(fifo_scb);
9153 		}
9154 #endif
9155 	}
9156 	printf("\nLQIN: ");
9157 	for (i = 0; i < 20; i++)
9158 		printf("0x%x ", ahd_inb(ahd, LQIN + i));
9159 	printf("\n");
9160 	ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
9161 	printf("%s: LQISTATE = 0x%x, LQOSTATE = 0x%x, OPTIONMODE = 0x%x\n",
9162 	       ahd_name(ahd), ahd_inb(ahd, LQISTATE), ahd_inb(ahd, LQOSTATE),
9163 	       ahd_inb(ahd, OPTIONMODE));
9164 	printf("%s: OS_SPACE_CNT = 0x%x MAXCMDCNT = 0x%x\n",
9165 	       ahd_name(ahd), ahd_inb(ahd, OS_SPACE_CNT),
9166 	       ahd_inb(ahd, MAXCMDCNT));
9167 	printf("%s: SAVED_SCSIID = 0x%x SAVED_LUN = 0x%x\n",
9168 	       ahd_name(ahd), ahd_inb(ahd, SAVED_SCSIID),
9169 	       ahd_inb(ahd, SAVED_LUN));
9170 	ahd_simode0_print(ahd_inb(ahd, SIMODE0), &cur_col, 50);
9171 	printf("\n");
9172 	ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
9173 	cur_col = 0;
9174 	ahd_ccscbctl_print(ahd_inb(ahd, CCSCBCTL), &cur_col, 50);
9175 	printf("\n");
9176 	ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
9177 	printf("%s: REG0 == 0x%x, SINDEX = 0x%x, DINDEX = 0x%x\n",
9178 	       ahd_name(ahd), ahd_inw(ahd, REG0), ahd_inw(ahd, SINDEX),
9179 	       ahd_inw(ahd, DINDEX));
9180 	printf("%s: SCBPTR == 0x%x, SCB_NEXT == 0x%x, SCB_NEXT2 == 0x%x\n",
9181 	       ahd_name(ahd), ahd_get_scbptr(ahd),
9182 	       ahd_inw_scbram(ahd, SCB_NEXT),
9183 	       ahd_inw_scbram(ahd, SCB_NEXT2));
9184 	printf("CDB %x %x %x %x %x %x\n",
9185 	       ahd_inb_scbram(ahd, SCB_CDB_STORE),
9186 	       ahd_inb_scbram(ahd, SCB_CDB_STORE+1),
9187 	       ahd_inb_scbram(ahd, SCB_CDB_STORE+2),
9188 	       ahd_inb_scbram(ahd, SCB_CDB_STORE+3),
9189 	       ahd_inb_scbram(ahd, SCB_CDB_STORE+4),
9190 	       ahd_inb_scbram(ahd, SCB_CDB_STORE+5));
9191 	printf("STACK:");
9192 	for (i = 0; i < ahd->stack_size; i++) {
9193 		ahd->saved_stack[i] =
9194 		    ahd_inb(ahd, STACK)|(ahd_inb(ahd, STACK) << 8);
9195 		printf(" 0x%x", ahd->saved_stack[i]);
9196 	}
9197 	for (i = ahd->stack_size-1; i >= 0; i--) {
9198 		ahd_outb(ahd, STACK, ahd->saved_stack[i] & 0xFF);
9199 		ahd_outb(ahd, STACK, (ahd->saved_stack[i] >> 8) & 0xFF);
9200 	}
9201 	printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
9202 	ahd_platform_dump_card_state(ahd);
9203 	ahd_restore_modes(ahd, saved_modes);
9204 	if (paused == 0)
9205 		ahd_unpause(ahd);
9206 }
9207 
9208 void
9209 ahd_dump_scbs(struct ahd_softc *ahd)
9210 {
9211 	ahd_mode_state saved_modes;
9212 	u_int	       saved_scb_index;
9213 	int	       i;
9214 
9215 	saved_modes = ahd_save_modes(ahd);
9216 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
9217 	saved_scb_index = ahd_get_scbptr(ahd);
9218 	for (i = 0; i < AHD_SCB_MAX; i++) {
9219 		ahd_set_scbptr(ahd, i);
9220 		printf("%3d", i);
9221 		printf("(CTRL 0x%x ID 0x%x N 0x%x N2 0x%x SG 0x%x, RSG 0x%x)\n",
9222 		       ahd_inb_scbram(ahd, SCB_CONTROL),
9223 		       ahd_inb_scbram(ahd, SCB_SCSIID),
9224 		       ahd_inw_scbram(ahd, SCB_NEXT),
9225 		       ahd_inw_scbram(ahd, SCB_NEXT2),
9226 		       ahd_inl_scbram(ahd, SCB_SGPTR),
9227 		       ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR));
9228 	}
9229 	printf("\n");
9230 	ahd_set_scbptr(ahd, saved_scb_index);
9231 	ahd_restore_modes(ahd, saved_modes);
9232 }
9233 
9234 /*************************** Timeout Handling *********************************/
9235 void
9236 ahd_timeout(struct scb *scb)
9237 {
9238 	struct ahd_softc *ahd;
9239 
9240 	ahd = scb->ahd_softc;
9241 	if ((scb->flags & SCB_ACTIVE) != 0) {
9242 		if ((scb->flags & SCB_TIMEDOUT) == 0) {
9243 			LIST_INSERT_HEAD(&ahd->timedout_scbs, scb,
9244 					 timedout_links);
9245 			scb->flags |= SCB_TIMEDOUT;
9246 		}
9247 		ahd_wakeup_recovery_thread(ahd);
9248 	}
9249 }
9250 
9251 /*
9252  * ahd_recover_commands determines if any of the commands that have currently
9253  * timedout are the root cause for this timeout.  Innocent commands are given
9254  * a new timeout while we wait for the command executing on the bus to timeout.
9255  * This routine is invoked from a thread context so we are allowed to sleep.
9256  * Our lock is not held on entry.
9257  */
9258 void
9259 ahd_recover_commands(struct ahd_softc *ahd)
9260 {
9261 	struct	scb *scb;
9262 	struct	scb *active_scb;
9263 	int	found;
9264 	int	was_paused;
9265 	u_int	active_scbptr;
9266 	u_int	last_phase;
9267 
9268 	/*
9269 	 * Pause the controller and manually flush any
9270 	 * commands that have just completed but that our
9271 	 * interrupt handler has yet to see.
9272 	 */
9273 	was_paused = ahd_is_paused(ahd);
9274 
9275 	printf("%s: Recovery Initiated - Card was %spaused\n", ahd_name(ahd),
9276 	       was_paused ? "" : "not ");
9277 	AHD_CORRECTABLE_ERROR(ahd);
9278 	ahd_dump_card_state(ahd);
9279 
9280 	ahd_pause_and_flushwork(ahd);
9281 
9282 	if (LIST_EMPTY(&ahd->timedout_scbs) != 0) {
9283 		/*
9284 		 * The timedout commands have already
9285 		 * completed.  This typically means
9286 		 * that either the timeout value was on
9287 		 * the hairy edge of what the device
9288 		 * requires or - more likely - interrupts
9289 		 * are not happening.
9290 		 */
9291 		printf("%s: Timedout SCBs already complete. "
9292 		       "Interrupts may not be functioning.\n", ahd_name(ahd));
9293 		ahd_unpause(ahd);
9294 		return;
9295 	}
9296 
9297 	/*
9298 	 * Determine identity of SCB acting on the bus.
9299 	 * This test only catches non-packetized transactions.
9300 	 * Due to the fleeting nature of packetized operations,
9301 	 * we can't easily determine that a packetized operation
9302 	 * is on the bus.
9303 	 */
9304 	ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
9305 	last_phase = ahd_inb(ahd, LASTPHASE);
9306 	active_scbptr = ahd_get_scbptr(ahd);
9307 	active_scb = NULL;
9308 	if (last_phase != P_BUSFREE
9309 	 || (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) == 0)
9310 		active_scb = ahd_lookup_scb(ahd, active_scbptr);
9311 
9312 	while ((scb = LIST_FIRST(&ahd->timedout_scbs)) != NULL) {
9313 		int	target;
9314 		int	lun;
9315 		char	channel;
9316 
9317 		target = SCB_GET_TARGET(ahd, scb);
9318 		channel = SCB_GET_CHANNEL(ahd, scb);
9319 		lun = SCB_GET_LUN(scb);
9320 
9321 		ahd_print_path(ahd, scb);
9322 		printf("SCB %d - timed out\n", SCB_GET_TAG(scb));
9323 
9324 		if (scb->flags & (SCB_DEVICE_RESET|SCB_ABORT)) {
9325 			/*
9326 			 * Been down this road before.
9327 			 * Do a full bus reset.
9328 			 */
9329 			aic_set_transaction_status(scb, CAM_CMD_TIMEOUT);
9330 bus_reset:
9331 			found = ahd_reset_channel(ahd, channel,
9332 						  /*Initiate Reset*/TRUE);
9333 			printf("%s: Issued Channel %c Bus Reset. "
9334 			       "%d SCBs aborted\n", ahd_name(ahd), channel,
9335 			       found);
9336 			continue;
9337 		}
9338 
9339 		/*
9340 		 * Remove the command from the timedout list in
9341 		 * preparation for requeing it.
9342 		 */
9343 		LIST_REMOVE(scb, timedout_links);
9344 		scb->flags &= ~SCB_TIMEDOUT;
9345 
9346 		if (active_scb != NULL) {
9347 			if (active_scb != scb) {
9348 				/*
9349 				 * If the active SCB is not us, assume that
9350 				 * the active SCB has a longer timeout than
9351 				 * the timedout SCB, and wait for the active
9352 				 * SCB to timeout.  As a safeguard, only
9353 				 * allow this deferral to continue if some
9354 				 * untimed-out command is outstanding.
9355 				 */
9356 				if (ahd_other_scb_timeout(ahd, scb,
9357 							  active_scb) == 0)
9358 					goto bus_reset;
9359 				continue;
9360 			}
9361 
9362 			/*
9363 			 * We're active on the bus, so assert ATN
9364 			 * and hope that the target responds.
9365 			 */
9366 			ahd_set_recoveryscb(ahd, active_scb);
9367                 	active_scb->flags |= SCB_RECOVERY_SCB|SCB_DEVICE_RESET;
9368 			ahd_outb(ahd, MSG_OUT, HOST_MSG);
9369 			ahd_outb(ahd, SCSISIGO, last_phase|ATNO);
9370 			ahd_print_path(ahd, active_scb);
9371 			printf("BDR message in message buffer\n");
9372 			aic_scb_timer_reset(scb, 2 * 1000);
9373 			break;
9374 		} else if (last_phase != P_BUSFREE
9375 			&& ahd_inb(ahd, SCSIPHASE) == 0) {
9376 			/*
9377 			 * SCB is not identified, there
9378 			 * is no pending REQ, and the sequencer
9379 			 * has not seen a busfree.  Looks like
9380 			 * a stuck connection waiting to
9381 			 * go busfree.  Reset the bus.
9382 			 */
9383 			printf("%s: Connection stuck awaiting busfree or "
9384 			       "Identify Msg.\n", ahd_name(ahd));
9385 			goto bus_reset;
9386 		} else if (ahd_search_qinfifo(ahd, target, channel, lun,
9387 					      SCB_GET_TAG(scb),
9388 					      ROLE_INITIATOR, /*status*/0,
9389 					      SEARCH_COUNT) > 0) {
9390 			/*
9391 			 * We haven't even gone out on the bus
9392 			 * yet, so the timeout must be due to
9393 			 * some other command.  Reset the timer
9394 			 * and go on.
9395 			 */
9396 			if (ahd_other_scb_timeout(ahd, scb, NULL) == 0)
9397 				goto bus_reset;
9398 		} else {
9399 			/*
9400 			 * This SCB is for a disconnected transaction
9401 			 * and we haven't found a better candidate on
9402 			 * the bus to explain this timeout.
9403 			 */
9404 			ahd_set_recoveryscb(ahd, scb);
9405 
9406 			/*
9407 			 * Actually re-queue this SCB in an attempt
9408 			 * to select the device before it reconnects.
9409 			 * In either case (selection or reselection),
9410 			 * we will now issue a target reset to the
9411 			 * timed-out device.
9412 			 */
9413 			scb->flags |= SCB_DEVICE_RESET;
9414 			scb->hscb->cdb_len = 0;
9415 			scb->hscb->task_attribute = 0;
9416 			scb->hscb->task_management = SIU_TASKMGMT_ABORT_TASK;
9417 
9418 			ahd_set_scbptr(ahd, SCB_GET_TAG(scb));
9419 			if ((scb->flags & SCB_PACKETIZED) != 0) {
9420 				/*
9421 				 * Mark the SCB has having an outstanding
9422 				 * task management function.  Should the command
9423 				 * complete normally before the task management
9424 				 * function can be sent, the host will be
9425 				 * notified to abort our requeued SCB.
9426 				 */
9427 				ahd_outb(ahd, SCB_TASK_MANAGEMENT,
9428 					 scb->hscb->task_management);
9429 			} else {
9430 				/*
9431 				 * If non-packetized, set the MK_MESSAGE control
9432 				 * bit indicating that we desire to send a
9433 				 * message.  We also set the disconnected flag
9434 				 * since there is no guarantee that our SCB
9435 				 * control byte matches the version on the
9436 				 * card.  We don't want the sequencer to abort
9437 				 * the command thinking an unsolicited
9438 				 * reselection occurred.
9439 				 */
9440 				scb->hscb->control |= MK_MESSAGE|DISCONNECTED;
9441 
9442 				/*
9443 				 * The sequencer will never re-reference the
9444 				 * in-core SCB.  To make sure we are notified
9445 				 * during reslection, set the MK_MESSAGE flag in
9446 				 * the card's copy of the SCB.
9447 				 */
9448 				ahd_outb(ahd, SCB_CONTROL,
9449 					 ahd_inb(ahd, SCB_CONTROL)|MK_MESSAGE);
9450 			}
9451 
9452 			/*
9453 			 * Clear out any entries in the QINFIFO first
9454 			 * so we are the next SCB for this target
9455 			 * to run.
9456 			 */
9457 			ahd_search_qinfifo(ahd, target, channel, lun,
9458 					   SCB_LIST_NULL, ROLE_INITIATOR,
9459 					   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
9460 			ahd_qinfifo_requeue_tail(ahd, scb);
9461 			ahd_set_scbptr(ahd, active_scbptr);
9462 			ahd_print_path(ahd, scb);
9463 			printf("Queuing a BDR SCB\n");
9464 			aic_scb_timer_reset(scb, 2 * 1000);
9465 			break;
9466 		}
9467 	}
9468 
9469 	/*
9470 	 * Any remaining SCBs were not the "culprit", so remove
9471 	 * them from the timeout list.  The timer for these commands
9472 	 * will be reset once the recovery SCB completes.
9473 	 */
9474 	while ((scb = LIST_FIRST(&ahd->timedout_scbs)) != NULL) {
9475 		LIST_REMOVE(scb, timedout_links);
9476 		scb->flags &= ~SCB_TIMEDOUT;
9477 	}
9478 
9479 	ahd_unpause(ahd);
9480 }
9481 
9482 /*
9483  * Re-schedule a timeout for the passed in SCB if we determine that some
9484  * other SCB is in the process of recovery or an SCB with a longer
9485  * timeout is still pending.  Limit our search to just "other_scb"
9486  * if it is non-NULL.
9487  */
9488 static int
9489 ahd_other_scb_timeout(struct ahd_softc *ahd, struct scb *scb,
9490 		      struct scb *other_scb)
9491 {
9492 	u_int	newtimeout;
9493 	int	found;
9494 
9495 	ahd_print_path(ahd, scb);
9496 	printf("Other SCB Timeout%s",
9497  	       (scb->flags & SCB_OTHERTCL_TIMEOUT) != 0
9498 	       ? " again\n" : "\n");
9499 
9500 	AHD_UNCORRECTABLE_ERROR(ahd);
9501 	newtimeout = aic_get_timeout(scb);
9502 	scb->flags |= SCB_OTHERTCL_TIMEOUT;
9503 	found = 0;
9504 	if (other_scb != NULL) {
9505 		if ((other_scb->flags
9506 		   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
9507 		 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
9508 			found++;
9509 			newtimeout = MAX(aic_get_timeout(other_scb),
9510 					 newtimeout);
9511 		}
9512 	} else {
9513 		LIST_FOREACH(other_scb, &ahd->pending_scbs, pending_links) {
9514 			if ((other_scb->flags
9515 			   & (SCB_OTHERTCL_TIMEOUT|SCB_TIMEDOUT)) == 0
9516 			 || (other_scb->flags & SCB_RECOVERY_SCB) != 0) {
9517 				found++;
9518 				newtimeout = MAX(aic_get_timeout(other_scb),
9519 						 newtimeout);
9520 			}
9521 		}
9522 	}
9523 
9524 	if (found != 0)
9525 		aic_scb_timer_reset(scb, newtimeout);
9526 	else {
9527 		ahd_print_path(ahd, scb);
9528 		printf("No other SCB worth waiting for...\n");
9529 	}
9530 
9531 	return (found != 0);
9532 }
9533 
9534 /**************************** Flexport Logic **********************************/
9535 /*
9536  * Read count 16bit words from 16bit word address start_addr from the
9537  * SEEPROM attached to the controller, into buf, using the controller's
9538  * SEEPROM reading state machine.  Optionally treat the data as a byte
9539  * stream in terms of byte order.
9540  */
9541 int
9542 ahd_read_seeprom(struct ahd_softc *ahd, uint16_t *buf,
9543 		 u_int start_addr, u_int count, int bytestream)
9544 {
9545 	u_int cur_addr;
9546 	u_int end_addr;
9547 	int   error;
9548 
9549 	/*
9550 	 * If we never make it through the loop even once,
9551 	 * we were passed invalid arguments.
9552 	 */
9553 	error = EINVAL;
9554 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9555 	end_addr = start_addr + count;
9556 	for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
9557 		ahd_outb(ahd, SEEADR, cur_addr);
9558 		ahd_outb(ahd, SEECTL, SEEOP_READ | SEESTART);
9559 
9560 		error = ahd_wait_seeprom(ahd);
9561 		if (error)
9562 			break;
9563 		if (bytestream != 0) {
9564 			uint8_t *bytestream_ptr;
9565 
9566 			bytestream_ptr = (uint8_t *)buf;
9567 			*bytestream_ptr++ = ahd_inb(ahd, SEEDAT);
9568 			*bytestream_ptr = ahd_inb(ahd, SEEDAT+1);
9569 		} else {
9570 			/*
9571 			 * ahd_inw() already handles machine byte order.
9572 			 */
9573 			*buf = ahd_inw(ahd, SEEDAT);
9574 		}
9575 		buf++;
9576 	}
9577 	return (error);
9578 }
9579 
9580 /*
9581  * Write count 16bit words from buf, into SEEPROM attache to the
9582  * controller starting at 16bit word address start_addr, using the
9583  * controller's SEEPROM writing state machine.
9584  */
9585 int
9586 ahd_write_seeprom(struct ahd_softc *ahd, uint16_t *buf,
9587 		  u_int start_addr, u_int count)
9588 {
9589 	u_int cur_addr;
9590 	u_int end_addr;
9591 	int   error;
9592 	int   retval;
9593 
9594 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9595 	error = ENOENT;
9596 
9597 	/* Place the chip into write-enable mode */
9598 	ahd_outb(ahd, SEEADR, SEEOP_EWEN_ADDR);
9599 	ahd_outb(ahd, SEECTL, SEEOP_EWEN | SEESTART);
9600 	error = ahd_wait_seeprom(ahd);
9601 	if (error)
9602 		return (error);
9603 
9604 	/*
9605 	 * Write the data.  If we don't get through the loop at
9606 	 * least once, the arguments were invalid.
9607 	 */
9608 	retval = EINVAL;
9609 	end_addr = start_addr + count;
9610 	for (cur_addr = start_addr; cur_addr < end_addr; cur_addr++) {
9611 		ahd_outw(ahd, SEEDAT, *buf++);
9612 		ahd_outb(ahd, SEEADR, cur_addr);
9613 		ahd_outb(ahd, SEECTL, SEEOP_WRITE | SEESTART);
9614 
9615 		retval = ahd_wait_seeprom(ahd);
9616 		if (retval)
9617 			break;
9618 	}
9619 
9620 	/*
9621 	 * Disable writes.
9622 	 */
9623 	ahd_outb(ahd, SEEADR, SEEOP_EWDS_ADDR);
9624 	ahd_outb(ahd, SEECTL, SEEOP_EWDS | SEESTART);
9625 	error = ahd_wait_seeprom(ahd);
9626 	if (error)
9627 		return (error);
9628 	return (retval);
9629 }
9630 
9631 /*
9632  * Wait ~100us for the serial eeprom to satisfy our request.
9633  */
9634 int
9635 ahd_wait_seeprom(struct ahd_softc *ahd)
9636 {
9637 	int cnt;
9638 
9639 	cnt = 5000;
9640 	while ((ahd_inb(ahd, SEESTAT) & (SEEARBACK|SEEBUSY)) != 0 && --cnt)
9641 		aic_delay(5);
9642 
9643 	if (cnt == 0)
9644 		return (ETIMEDOUT);
9645 	return (0);
9646 }
9647 
9648 /*
9649  * Validate the two checksums in the per_channel
9650  * vital product data struct.
9651  */
9652 int
9653 ahd_verify_vpd_cksum(struct vpd_config *vpd)
9654 {
9655 	int i;
9656 	int maxaddr;
9657 	uint32_t checksum;
9658 	uint8_t *vpdarray;
9659 
9660 	vpdarray = (uint8_t *)vpd;
9661 	maxaddr = offsetof(struct vpd_config, vpd_checksum);
9662 	checksum = 0;
9663 	for (i = offsetof(struct vpd_config, resource_type); i < maxaddr; i++)
9664 		checksum = checksum + vpdarray[i];
9665 	if (checksum == 0
9666 	 || (-checksum & 0xFF) != vpd->vpd_checksum)
9667 		return (0);
9668 
9669 	checksum = 0;
9670 	maxaddr = offsetof(struct vpd_config, checksum);
9671 	for (i = offsetof(struct vpd_config, default_target_flags);
9672 	     i < maxaddr; i++)
9673 		checksum = checksum + vpdarray[i];
9674 	if (checksum == 0
9675 	 || (-checksum & 0xFF) != vpd->checksum)
9676 		return (0);
9677 	return (1);
9678 }
9679 
9680 int
9681 ahd_verify_cksum(struct seeprom_config *sc)
9682 {
9683 	int i;
9684 	int maxaddr;
9685 	uint32_t checksum;
9686 	uint16_t *scarray;
9687 
9688 	maxaddr = (sizeof(*sc)/2) - 1;
9689 	checksum = 0;
9690 	scarray = (uint16_t *)sc;
9691 
9692 	for (i = 0; i < maxaddr; i++)
9693 		checksum = checksum + scarray[i];
9694 	if (checksum == 0
9695 	 || (checksum & 0xFFFF) != sc->checksum) {
9696 		return (0);
9697 	} else {
9698 		return (1);
9699 	}
9700 }
9701 
9702 int
9703 ahd_acquire_seeprom(struct ahd_softc *ahd)
9704 {
9705 	/*
9706 	 * We should be able to determine the SEEPROM type
9707 	 * from the flexport logic, but unfortunately not
9708 	 * all implementations have this logic and there is
9709 	 * no programatic method for determining if the logic
9710 	 * is present.
9711 	 */
9712 	return (1);
9713 #if 0
9714 	uint8_t	seetype;
9715 	int	error;
9716 
9717 	error = ahd_read_flexport(ahd, FLXADDR_ROMSTAT_CURSENSECTL, &seetype);
9718 	if (error != 0
9719          || ((seetype & FLX_ROMSTAT_SEECFG) == FLX_ROMSTAT_SEE_NONE))
9720 		return (0);
9721 	return (1);
9722 #endif
9723 }
9724 
9725 void
9726 ahd_release_seeprom(struct ahd_softc *ahd)
9727 {
9728 	/* Currently a no-op */
9729 }
9730 
9731 int
9732 ahd_write_flexport(struct ahd_softc *ahd, u_int addr, u_int value)
9733 {
9734 	int error;
9735 
9736 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9737 	if (addr > 7)
9738 		panic("ahd_write_flexport: address out of range");
9739 	ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
9740 	error = ahd_wait_flexport(ahd);
9741 	if (error != 0)
9742 		return (error);
9743 	ahd_outb(ahd, BRDDAT, value);
9744 	ahd_flush_device_writes(ahd);
9745 	ahd_outb(ahd, BRDCTL, BRDSTB|BRDEN|(addr << 3));
9746 	ahd_flush_device_writes(ahd);
9747 	ahd_outb(ahd, BRDCTL, BRDEN|(addr << 3));
9748 	ahd_flush_device_writes(ahd);
9749 	ahd_outb(ahd, BRDCTL, 0);
9750 	ahd_flush_device_writes(ahd);
9751 	return (0);
9752 }
9753 
9754 int
9755 ahd_read_flexport(struct ahd_softc *ahd, u_int addr, uint8_t *value)
9756 {
9757 	int	error;
9758 
9759 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9760 	if (addr > 7)
9761 		panic("ahd_read_flexport: address out of range");
9762 	ahd_outb(ahd, BRDCTL, BRDRW|BRDEN|(addr << 3));
9763 	error = ahd_wait_flexport(ahd);
9764 	if (error != 0)
9765 		return (error);
9766 	*value = ahd_inb(ahd, BRDDAT);
9767 	ahd_outb(ahd, BRDCTL, 0);
9768 	ahd_flush_device_writes(ahd);
9769 	return (0);
9770 }
9771 
9772 /*
9773  * Wait at most 2 seconds for flexport arbitration to succeed.
9774  */
9775 int
9776 ahd_wait_flexport(struct ahd_softc *ahd)
9777 {
9778 	int cnt;
9779 
9780 	AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
9781 	cnt = 1000000 * 2 / 5;
9782 	while ((ahd_inb(ahd, BRDCTL) & FLXARBACK) == 0 && --cnt)
9783 		aic_delay(5);
9784 
9785 	if (cnt == 0)
9786 		return (ETIMEDOUT);
9787 	return (0);
9788 }
9789 
9790 /************************* Target Mode ****************************************/
9791 #ifdef AHD_TARGET_MODE
9792 cam_status
9793 ahd_find_tmode_devs(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb,
9794 		    struct ahd_tmode_tstate **tstate,
9795 		    struct ahd_tmode_lstate **lstate,
9796 		    int notfound_failure)
9797 {
9798 
9799 	if ((ahd->features & AHD_TARGETMODE) == 0)
9800 		return (CAM_REQ_INVALID);
9801 
9802 	/*
9803 	 * Handle the 'black hole' device that sucks up
9804 	 * requests to unattached luns on enabled targets.
9805 	 */
9806 	if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
9807 	 && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
9808 		*tstate = NULL;
9809 		*lstate = ahd->black_hole;
9810 	} else {
9811 		u_int max_id;
9812 
9813 		max_id = (ahd->features & AHD_WIDE) ? 15 : 7;
9814 		if (ccb->ccb_h.target_id > max_id)
9815 			return (CAM_TID_INVALID);
9816 
9817 		if (ccb->ccb_h.target_lun >= AHD_NUM_LUNS)
9818 			return (CAM_LUN_INVALID);
9819 
9820 		*tstate = ahd->enabled_targets[ccb->ccb_h.target_id];
9821 		*lstate = NULL;
9822 		if (*tstate != NULL)
9823 			*lstate =
9824 			    (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
9825 	}
9826 
9827 	if (notfound_failure != 0 && *lstate == NULL)
9828 		return (CAM_PATH_INVALID);
9829 
9830 	return (CAM_REQ_CMP);
9831 }
9832 
9833 void
9834 ahd_handle_en_lun(struct ahd_softc *ahd, struct cam_sim *sim, union ccb *ccb)
9835 {
9836 #if NOT_YET
9837 	struct	   ahd_tmode_tstate *tstate;
9838 	struct	   ahd_tmode_lstate *lstate;
9839 	struct	   ccb_en_lun *cel;
9840 	cam_status status;
9841 	u_int	   target;
9842 	u_int	   lun;
9843 	u_int	   target_mask;
9844 	u_long	   s;
9845 	char	   channel;
9846 
9847 	status = ahd_find_tmode_devs(ahd, sim, ccb, &tstate, &lstate,
9848 				     /*notfound_failure*/FALSE);
9849 
9850 	if (status != CAM_REQ_CMP) {
9851 		ccb->ccb_h.status = status;
9852 		return;
9853 	}
9854 
9855 	if ((ahd->features & AHD_MULTIROLE) != 0) {
9856 		u_int	   our_id;
9857 
9858 		our_id = ahd->our_id;
9859 		if (ccb->ccb_h.target_id != our_id
9860 		 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
9861 			if ((ahd->features & AHD_MULTI_TID) != 0
9862 		   	 && (ahd->flags & AHD_INITIATORROLE) != 0) {
9863 				/*
9864 				 * Only allow additional targets if
9865 				 * the initiator role is disabled.
9866 				 * The hardware cannot handle a re-select-in
9867 				 * on the initiator id during a re-select-out
9868 				 * on a different target id.
9869 				 */
9870 				status = CAM_TID_INVALID;
9871 			} else if ((ahd->flags & AHD_INITIATORROLE) != 0
9872 				|| ahd->enabled_luns > 0) {
9873 				/*
9874 				 * Only allow our target id to change
9875 				 * if the initiator role is not configured
9876 				 * and there are no enabled luns which
9877 				 * are attached to the currently registered
9878 				 * scsi id.
9879 				 */
9880 				status = CAM_TID_INVALID;
9881 			}
9882 		}
9883 	}
9884 
9885 	if (status != CAM_REQ_CMP) {
9886 		ccb->ccb_h.status = status;
9887 		return;
9888 	}
9889 
9890 	/*
9891 	 * We now have an id that is valid.
9892 	 * If we aren't in target mode, switch modes.
9893 	 */
9894 	if ((ahd->flags & AHD_TARGETROLE) == 0
9895 	 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
9896 		printf("Configuring Target Mode\n");
9897 		if (LIST_FIRST(&ahd->pending_scbs) != NULL) {
9898 			ccb->ccb_h.status = CAM_BUSY;
9899 			return;
9900 		}
9901 		ahd->flags |= AHD_TARGETROLE;
9902 		if ((ahd->features & AHD_MULTIROLE) == 0)
9903 			ahd->flags &= ~AHD_INITIATORROLE;
9904 		ahd_pause(ahd);
9905 		ahd_loadseq(ahd);
9906 		ahd_restart(ahd);
9907 	}
9908 	cel = &ccb->cel;
9909 	target = ccb->ccb_h.target_id;
9910 	lun = ccb->ccb_h.target_lun;
9911 	channel = SIM_CHANNEL(ahd, sim);
9912 	target_mask = 0x01 << target;
9913 	if (channel == 'B')
9914 		target_mask <<= 8;
9915 
9916 	if (cel->enable != 0) {
9917 		u_int scsiseq1;
9918 
9919 		/* Are we already enabled?? */
9920 		if (lstate != NULL) {
9921 			xpt_print_path(ccb->ccb_h.path);
9922 			printf("Lun already enabled\n");
9923 			AHD_CORRECTABLE_ERROR(ahd);
9924 			ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
9925 			return;
9926 		}
9927 
9928 		if (cel->grp6_len != 0
9929 		 || cel->grp7_len != 0) {
9930 			/*
9931 			 * Don't (yet?) support vendor
9932 			 * specific commands.
9933 			 */
9934 			ccb->ccb_h.status = CAM_REQ_INVALID;
9935 			printf("Non-zero Group Codes\n");
9936 			return;
9937 		}
9938 
9939 		/*
9940 		 * Seems to be okay.
9941 		 * Setup our data structures.
9942 		 */
9943 		if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
9944 			tstate = ahd_alloc_tstate(ahd, target, channel);
9945 			if (tstate == NULL) {
9946 				xpt_print_path(ccb->ccb_h.path);
9947 				printf("Couldn't allocate tstate\n");
9948 				ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9949 				return;
9950 			}
9951 		}
9952 		lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
9953 		if (lstate == NULL) {
9954 			xpt_print_path(ccb->ccb_h.path);
9955 			printf("Couldn't allocate lstate\n");
9956 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9957 			return;
9958 		}
9959 		memset(lstate, 0, sizeof(*lstate));
9960 		status = xpt_create_path(&lstate->path, /*periph*/NULL,
9961 					 xpt_path_path_id(ccb->ccb_h.path),
9962 					 xpt_path_target_id(ccb->ccb_h.path),
9963 					 xpt_path_lun_id(ccb->ccb_h.path));
9964 		if (status != CAM_REQ_CMP) {
9965 			free(lstate, M_DEVBUF);
9966 			xpt_print_path(ccb->ccb_h.path);
9967 			printf("Couldn't allocate path\n");
9968 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
9969 			return;
9970 		}
9971 		SLIST_INIT(&lstate->accept_tios);
9972 		SLIST_INIT(&lstate->immed_notifies);
9973 		ahd_pause(ahd);
9974 		if (target != CAM_TARGET_WILDCARD) {
9975 			tstate->enabled_luns[lun] = lstate;
9976 			ahd->enabled_luns++;
9977 
9978 			if ((ahd->features & AHD_MULTI_TID) != 0) {
9979 				u_int targid_mask;
9980 
9981 				targid_mask = ahd_inw(ahd, TARGID);
9982 				targid_mask |= target_mask;
9983 				ahd_outw(ahd, TARGID, targid_mask);
9984 				ahd_update_scsiid(ahd, targid_mask);
9985 			} else {
9986 				u_int our_id;
9987 				char  channel;
9988 
9989 				channel = SIM_CHANNEL(ahd, sim);
9990 				our_id = SIM_SCSI_ID(ahd, sim);
9991 
9992 				/*
9993 				 * This can only happen if selections
9994 				 * are not enabled
9995 				 */
9996 				if (target != our_id) {
9997 					u_int sblkctl;
9998 					char  cur_channel;
9999 					int   swap;
10000 
10001 					sblkctl = ahd_inb(ahd, SBLKCTL);
10002 					cur_channel = (sblkctl & SELBUSB)
10003 						    ? 'B' : 'A';
10004 					if ((ahd->features & AHD_TWIN) == 0)
10005 						cur_channel = 'A';
10006 					swap = cur_channel != channel;
10007 					ahd->our_id = target;
10008 
10009 					if (swap)
10010 						ahd_outb(ahd, SBLKCTL,
10011 							 sblkctl ^ SELBUSB);
10012 
10013 					ahd_outb(ahd, SCSIID, target);
10014 
10015 					if (swap)
10016 						ahd_outb(ahd, SBLKCTL, sblkctl);
10017 				}
10018 			}
10019 		} else
10020 			ahd->black_hole = lstate;
10021 		/* Allow select-in operations */
10022 		if (ahd->black_hole != NULL && ahd->enabled_luns > 0) {
10023 			scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
10024 			scsiseq1 |= ENSELI;
10025 			ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
10026 			scsiseq1 = ahd_inb(ahd, SCSISEQ1);
10027 			scsiseq1 |= ENSELI;
10028 			ahd_outb(ahd, SCSISEQ1, scsiseq1);
10029 		}
10030 		ahd_unpause(ahd);
10031 		ccb->ccb_h.status = CAM_REQ_CMP;
10032 		xpt_print_path(ccb->ccb_h.path);
10033 		printf("Lun now enabled for target mode\n");
10034 	} else {
10035 		struct scb *scb;
10036 		int i, empty;
10037 
10038 		if (lstate == NULL) {
10039 			ccb->ccb_h.status = CAM_LUN_INVALID;
10040 			return;
10041 		}
10042 
10043 		ccb->ccb_h.status = CAM_REQ_CMP;
10044 		LIST_FOREACH(scb, &ahd->pending_scbs, pending_links) {
10045 			struct ccb_hdr *ccbh;
10046 
10047 			ccbh = &scb->io_ctx->ccb_h;
10048 			if (ccbh->func_code == XPT_CONT_TARGET_IO
10049 			 && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
10050 				printf("CTIO pending\n");
10051 				ccb->ccb_h.status = CAM_REQ_INVALID;
10052 				return;
10053 			}
10054 		}
10055 
10056 		if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
10057 			printf("ATIOs pending\n");
10058 			ccb->ccb_h.status = CAM_REQ_INVALID;
10059 		}
10060 
10061 		if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
10062 			printf("INOTs pending\n");
10063 			ccb->ccb_h.status = CAM_REQ_INVALID;
10064 		}
10065 
10066 		if (ccb->ccb_h.status != CAM_REQ_CMP) {
10067 			return;
10068 		}
10069 
10070 		xpt_print_path(ccb->ccb_h.path);
10071 		printf("Target mode disabled\n");
10072 		xpt_free_path(lstate->path);
10073 		free(lstate, M_DEVBUF);
10074 
10075 		ahd_pause(ahd);
10076 		/* Can we clean up the target too? */
10077 		if (target != CAM_TARGET_WILDCARD) {
10078 			tstate->enabled_luns[lun] = NULL;
10079 			ahd->enabled_luns--;
10080 			for (empty = 1, i = 0; i < 8; i++)
10081 				if (tstate->enabled_luns[i] != NULL) {
10082 					empty = 0;
10083 					break;
10084 				}
10085 
10086 			if (empty) {
10087 				ahd_free_tstate(ahd, target, channel,
10088 						/*force*/FALSE);
10089 				if (ahd->features & AHD_MULTI_TID) {
10090 					u_int targid_mask;
10091 
10092 					targid_mask = ahd_inw(ahd, TARGID);
10093 					targid_mask &= ~target_mask;
10094 					ahd_outw(ahd, TARGID, targid_mask);
10095 					ahd_update_scsiid(ahd, targid_mask);
10096 				}
10097 			}
10098 		} else {
10099 			ahd->black_hole = NULL;
10100 
10101 			/*
10102 			 * We can't allow selections without
10103 			 * our black hole device.
10104 			 */
10105 			empty = TRUE;
10106 		}
10107 		if (ahd->enabled_luns == 0) {
10108 			/* Disallow select-in */
10109 			u_int scsiseq1;
10110 
10111 			scsiseq1 = ahd_inb(ahd, SCSISEQ_TEMPLATE);
10112 			scsiseq1 &= ~ENSELI;
10113 			ahd_outb(ahd, SCSISEQ_TEMPLATE, scsiseq1);
10114 			scsiseq1 = ahd_inb(ahd, SCSISEQ1);
10115 			scsiseq1 &= ~ENSELI;
10116 			ahd_outb(ahd, SCSISEQ1, scsiseq1);
10117 
10118 			if ((ahd->features & AHD_MULTIROLE) == 0) {
10119 				printf("Configuring Initiator Mode\n");
10120 				ahd->flags &= ~AHD_TARGETROLE;
10121 				ahd->flags |= AHD_INITIATORROLE;
10122 				ahd_pause(ahd);
10123 				ahd_loadseq(ahd);
10124 				ahd_restart(ahd);
10125 				/*
10126 				 * Unpaused.  The extra unpause
10127 				 * that follows is harmless.
10128 				 */
10129 			}
10130 		}
10131 		ahd_unpause(ahd);
10132 	}
10133 #endif
10134 }
10135 
10136 static void
10137 ahd_update_scsiid(struct ahd_softc *ahd, u_int targid_mask)
10138 {
10139 #if NOT_YET
10140 	u_int scsiid_mask;
10141 	u_int scsiid;
10142 
10143 	if ((ahd->features & AHD_MULTI_TID) == 0)
10144 		panic("ahd_update_scsiid called on non-multitid unit\n");
10145 
10146 	/*
10147 	 * Since we will rely on the TARGID mask
10148 	 * for selection enables, ensure that OID
10149 	 * in SCSIID is not set to some other ID
10150 	 * that we don't want to allow selections on.
10151 	 */
10152 	if ((ahd->features & AHD_ULTRA2) != 0)
10153 		scsiid = ahd_inb(ahd, SCSIID_ULTRA2);
10154 	else
10155 		scsiid = ahd_inb(ahd, SCSIID);
10156 	scsiid_mask = 0x1 << (scsiid & OID);
10157 	if ((targid_mask & scsiid_mask) == 0) {
10158 		u_int our_id;
10159 
10160 		/* ffs counts from 1 */
10161 		our_id = ffs(targid_mask);
10162 		if (our_id == 0)
10163 			our_id = ahd->our_id;
10164 		else
10165 			our_id--;
10166 		scsiid &= TID;
10167 		scsiid |= our_id;
10168 	}
10169 	if ((ahd->features & AHD_ULTRA2) != 0)
10170 		ahd_outb(ahd, SCSIID_ULTRA2, scsiid);
10171 	else
10172 		ahd_outb(ahd, SCSIID, scsiid);
10173 #endif
10174 }
10175 
10176 void
10177 ahd_run_tqinfifo(struct ahd_softc *ahd, int paused)
10178 {
10179 	struct target_cmd *cmd;
10180 
10181 	ahd_sync_tqinfifo(ahd, BUS_DMASYNC_POSTREAD);
10182 	while ((cmd = &ahd->targetcmds[ahd->tqinfifonext])->cmd_valid != 0) {
10183 		/*
10184 		 * Only advance through the queue if we
10185 		 * have the resources to process the command.
10186 		 */
10187 		if (ahd_handle_target_cmd(ahd, cmd) != 0)
10188 			break;
10189 
10190 		cmd->cmd_valid = 0;
10191 		ahd_dmamap_sync(ahd, ahd->shared_data_dmat,
10192 				ahd->shared_data_dmamap,
10193 				ahd_targetcmd_offset(ahd, ahd->tqinfifonext),
10194 				sizeof(struct target_cmd),
10195 				BUS_DMASYNC_PREREAD);
10196 		ahd->tqinfifonext++;
10197 
10198 		/*
10199 		 * Lazily update our position in the target mode incoming
10200 		 * command queue as seen by the sequencer.
10201 		 */
10202 		if ((ahd->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
10203 			u_int hs_mailbox;
10204 
10205 			hs_mailbox = ahd_inb(ahd, HS_MAILBOX);
10206 			hs_mailbox &= ~HOST_TQINPOS;
10207 			hs_mailbox |= ahd->tqinfifonext & HOST_TQINPOS;
10208 			ahd_outb(ahd, HS_MAILBOX, hs_mailbox);
10209 		}
10210 	}
10211 }
10212 
10213 static int
10214 ahd_handle_target_cmd(struct ahd_softc *ahd, struct target_cmd *cmd)
10215 {
10216 	struct	  ahd_tmode_tstate *tstate;
10217 	struct	  ahd_tmode_lstate *lstate;
10218 	struct	  ccb_accept_tio *atio;
10219 	uint8_t *byte;
10220 	int	  initiator;
10221 	int	  target;
10222 	int	  lun;
10223 
10224 	initiator = SCSIID_TARGET(ahd, cmd->scsiid);
10225 	target = SCSIID_OUR_ID(cmd->scsiid);
10226 	lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
10227 
10228 	byte = cmd->bytes;
10229 	tstate = ahd->enabled_targets[target];
10230 	lstate = NULL;
10231 	if (tstate != NULL)
10232 		lstate = tstate->enabled_luns[lun];
10233 
10234 	/*
10235 	 * Commands for disabled luns go to the black hole driver.
10236 	 */
10237 	if (lstate == NULL)
10238 		lstate = ahd->black_hole;
10239 
10240 	atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
10241 	if (atio == NULL) {
10242 		ahd->flags |= AHD_TQINFIFO_BLOCKED;
10243 		/*
10244 		 * Wait for more ATIOs from the peripheral driver for this lun.
10245 		 */
10246 		return (1);
10247 	} else
10248 		ahd->flags &= ~AHD_TQINFIFO_BLOCKED;
10249 #ifdef AHD_DEBUG
10250 	if ((ahd_debug & AHD_SHOW_TQIN) != 0)
10251 		printf("Incoming command from %d for %d:%d%s\n",
10252 		       initiator, target, lun,
10253 		       lstate == ahd->black_hole ? "(Black Holed)" : "");
10254 #endif
10255 	SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
10256 
10257 	if (lstate == ahd->black_hole) {
10258 		/* Fill in the wildcards */
10259 		atio->ccb_h.target_id = target;
10260 		atio->ccb_h.target_lun = lun;
10261 	}
10262 
10263 	/*
10264 	 * Package it up and send it off to
10265 	 * whomever has this lun enabled.
10266 	 */
10267 	atio->sense_len = 0;
10268 	atio->init_id = initiator;
10269 	if (byte[0] != 0xFF) {
10270 		/* Tag was included */
10271 		atio->tag_action = *byte++;
10272 		atio->tag_id = *byte++;
10273 		atio->ccb_h.flags |= CAM_TAG_ACTION_VALID;
10274 	} else {
10275 		atio->ccb_h.flags &= ~CAM_TAG_ACTION_VALID;
10276 	}
10277 	byte++;
10278 
10279 	/* Okay.  Now determine the cdb size based on the command code */
10280 	switch (*byte >> CMD_GROUP_CODE_SHIFT) {
10281 	case 0:
10282 		atio->cdb_len = 6;
10283 		break;
10284 	case 1:
10285 	case 2:
10286 		atio->cdb_len = 10;
10287 		break;
10288 	case 4:
10289 		atio->cdb_len = 16;
10290 		break;
10291 	case 5:
10292 		atio->cdb_len = 12;
10293 		break;
10294 	case 3:
10295 	default:
10296 		/* Only copy the opcode. */
10297 		atio->cdb_len = 1;
10298 		printf("Reserved or VU command code type encountered\n");
10299 		break;
10300 	}
10301 
10302 	memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
10303 
10304 	atio->ccb_h.status |= CAM_CDB_RECVD;
10305 
10306 	if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
10307 		/*
10308 		 * We weren't allowed to disconnect.
10309 		 * We're hanging on the bus until a
10310 		 * continue target I/O comes in response
10311 		 * to this accept tio.
10312 		 */
10313 #ifdef AHD_DEBUG
10314 		if ((ahd_debug & AHD_SHOW_TQIN) != 0)
10315 			printf("Received Immediate Command %d:%d:%d - %p\n",
10316 			       initiator, target, lun, ahd->pending_device);
10317 #endif
10318 		ahd->pending_device = lstate;
10319 		ahd_freeze_ccb((union ccb *)atio);
10320 		atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
10321 	}
10322 	xpt_done((union ccb*)atio);
10323 	return (0);
10324 }
10325 
10326 #endif
10327