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