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