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