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