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