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