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