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