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