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