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