Home | History | Annotate | Line # | Download | only in ic
aic7xxx.c revision 1.116
      1 /*	$NetBSD: aic7xxx.c,v 1.116 2005/09/10 19:15:44 tsutsui 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-2002 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: aic7xxx.c,v 1.116 2005/09/10 19:15:44 tsutsui Exp $
     43  *
     44  * //depot/aic7xxx/aic7xxx/aic7xxx.c#112 $
     45  *
     46  * $FreeBSD: /repoman/r/ncvs/src/sys/dev/aic7xxx/aic7xxx.c,v 1.88 2003/01/20 20:44:55 gibbs Exp $
     47  */
     48 /*
     49  * Ported from FreeBSD by Pascal Renauld, Network Storage Solutions, Inc. - April 2003
     50  */
     51 
     52 #include <sys/cdefs.h>
     53 __KERNEL_RCSID(0, "$NetBSD: aic7xxx.c,v 1.116 2005/09/10 19:15:44 tsutsui Exp $");
     54 
     55 #include <dev/ic/aic7xxx_osm.h>
     56 #include <dev/ic/aic7xxx_inline.h>
     57 #include <dev/ic/aic7xxx_cam.h>
     58 
     59 /****************************** Softc Data ************************************/
     60 struct ahc_softc_tailq ahc_tailq = TAILQ_HEAD_INITIALIZER(ahc_tailq);
     61 
     62 /***************************** Lookup Tables **********************************/
     63 const char *ahc_chip_names[] =
     64 {
     65 	"NONE",
     66 	"aic7770",
     67 	"aic7850",
     68 	"aic7855",
     69 	"aic7859",
     70 	"aic7860",
     71 	"aic7870",
     72 	"aic7880",
     73 	"aic7895",
     74 	"aic7895C",
     75 	"aic7890/91",
     76 	"aic7896/97",
     77 	"aic7892",
     78 	"aic7899"
     79 };
     80 
     81 /*
     82  * Hardware error codes.
     83  */
     84 struct ahc_hard_error_entry {
     85         uint8_t errno;
     86 	const char *errmesg;
     87 };
     88 
     89 static struct ahc_hard_error_entry ahc_hard_errors[] = {
     90 	{ ILLHADDR,	"Illegal Host Access" },
     91 	{ ILLSADDR,	"Illegal Sequencer Address referrenced" },
     92 	{ ILLOPCODE,	"Illegal Opcode in sequencer program" },
     93 	{ SQPARERR,	"Sequencer Parity Error" },
     94 	{ DPARERR,	"Data-path Parity Error" },
     95 	{ MPARERR,	"Scratch or SCB Memory Parity Error" },
     96 	{ PCIERRSTAT,	"PCI Error detected" },
     97 	{ CIOPARERR,	"CIOBUS Parity Error" },
     98 };
     99 static const u_int num_errors = NUM_ELEMENTS(ahc_hard_errors);
    100 
    101 static struct ahc_phase_table_entry ahc_phase_table[] =
    102 {
    103 	{ P_DATAOUT,	MSG_NOOP,		"in Data-out phase"	},
    104 	{ P_DATAIN,	MSG_INITIATOR_DET_ERR,	"in Data-in phase"	},
    105 	{ P_DATAOUT_DT,	MSG_NOOP,		"in DT Data-out phase"	},
    106 	{ P_DATAIN_DT,	MSG_INITIATOR_DET_ERR,	"in DT Data-in phase"	},
    107 	{ P_COMMAND,	MSG_NOOP,		"in Command phase"	},
    108 	{ P_MESGOUT,	MSG_NOOP,		"in Message-out phase"	},
    109 	{ P_STATUS,	MSG_INITIATOR_DET_ERR,	"in Status phase"	},
    110 	{ P_MESGIN,	MSG_PARITY_ERROR,	"in Message-in phase"	},
    111 	{ P_BUSFREE,	MSG_NOOP,		"while idle"		},
    112 	{ 0,		MSG_NOOP,		"in unknown phase"	}
    113 };
    114 
    115 /*
    116  * In most cases we only wish to itterate over real phases, so
    117  * exclude the last element from the count.
    118  */
    119 static const u_int num_phases = NUM_ELEMENTS(ahc_phase_table) - 1;
    120 
    121 /*
    122  * Valid SCSIRATE values.  (p. 3-17)
    123  * Provides a mapping of transfer periods in ns to the proper value to
    124  * stick in the scsixfer reg.
    125  */
    126 static struct ahc_syncrate ahc_syncrates[] =
    127 {
    128       /* ultra2    fast/ultra  period     rate */
    129 	{ 0x42,      0x000,      9,      "80.0" },
    130 	{ 0x03,      0x000,     10,      "40.0" },
    131 	{ 0x04,      0x000,     11,      "33.0" },
    132 	{ 0x05,      0x100,     12,      "20.0" },
    133 	{ 0x06,      0x110,     15,      "16.0" },
    134 	{ 0x07,      0x120,     18,      "13.4" },
    135 	{ 0x08,      0x000,     25,      "10.0" },
    136 	{ 0x19,      0x010,     31,      "8.0"  },
    137 	{ 0x1a,      0x020,     37,      "6.67" },
    138 	{ 0x1b,      0x030,     43,      "5.7"  },
    139 	{ 0x1c,      0x040,     50,      "5.0"  },
    140 	{ 0x00,      0x050,     56,      "4.4"  },
    141 	{ 0x00,      0x060,     62,      "4.0"  },
    142 	{ 0x00,      0x070,     68,      "3.6"  },
    143 	{ 0x00,      0x000,      0,      NULL   }
    144 };
    145 
    146 /* Our Sequencer Program */
    147 #include <dev/microcode/aic7xxx/aic7xxx_seq.h>
    148 
    149 /**************************** Function Declarations ***************************/
    150 static void		ahc_force_renegotiation(struct ahc_softc *ahc);
    151 static struct ahc_tmode_tstate*
    152 			ahc_alloc_tstate(struct ahc_softc *ahc,
    153 					 u_int scsi_id, char channel);
    154 #ifdef AHC_TARGET_MODE
    155 static void		ahc_free_tstate(struct ahc_softc *ahc,
    156 					u_int scsi_id, char channel, int force);
    157 #endif
    158 static struct ahc_syncrate*
    159 			ahc_devlimited_syncrate(struct ahc_softc *ahc,
    160 					        struct ahc_initiator_tinfo *,
    161 						u_int *period,
    162 						u_int *ppr_options,
    163 						role_t role);
    164 static void		ahc_update_pending_scbs(struct ahc_softc *ahc);
    165 static void		ahc_fetch_devinfo(struct ahc_softc *ahc,
    166 					  struct ahc_devinfo *devinfo);
    167 static void		ahc_scb_devinfo(struct ahc_softc *ahc,
    168 					struct ahc_devinfo *devinfo,
    169 					struct scb *scb);
    170 static void		ahc_assert_atn(struct ahc_softc *ahc);
    171 static void		ahc_setup_initiator_msgout(struct ahc_softc *ahc,
    172 						   struct ahc_devinfo *devinfo,
    173 						   struct scb *scb);
    174 static void		ahc_build_transfer_msg(struct ahc_softc *ahc,
    175 					       struct ahc_devinfo *devinfo);
    176 static void		ahc_construct_sdtr(struct ahc_softc *ahc,
    177 					   struct ahc_devinfo *devinfo,
    178 					   u_int period, u_int offset);
    179 static void		ahc_construct_wdtr(struct ahc_softc *ahc,
    180 					   struct ahc_devinfo *devinfo,
    181 					   u_int bus_width);
    182 static void		ahc_construct_ppr(struct ahc_softc *ahc,
    183 					  struct ahc_devinfo *devinfo,
    184 					  u_int period, u_int offset,
    185 					  u_int bus_width, u_int ppr_options);
    186 static void		ahc_clear_msg_state(struct ahc_softc *ahc);
    187 static void		ahc_handle_proto_violation(struct ahc_softc *ahc);
    188 static void		ahc_handle_message_phase(struct ahc_softc *ahc);
    189 typedef enum {
    190 	AHCMSG_1B,
    191 	AHCMSG_2B,
    192 	AHCMSG_EXT
    193 } ahc_msgtype;
    194 static int		ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
    195 				     u_int msgval, int full);
    196 static int		ahc_parse_msg(struct ahc_softc *ahc,
    197 				      struct ahc_devinfo *devinfo);
    198 static int		ahc_handle_msg_reject(struct ahc_softc *ahc,
    199 					      struct ahc_devinfo *devinfo);
    200 static void		ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
    201 						struct ahc_devinfo *devinfo);
    202 static void		ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
    203 static void		ahc_handle_devreset(struct ahc_softc *ahc,
    204 					    struct ahc_devinfo *devinfo,
    205 					    cam_status status,
    206 					    const char *message,
    207 					    int verbose_level);
    208 #if AHC_TARGET_MODE
    209 static void		ahc_setup_target_msgin(struct ahc_softc *ahc,
    210 					       struct ahc_devinfo *devinfo,
    211 					       struct scb *scb);
    212 #endif
    213 
    214 //static bus_dmamap_callback_t	ahc_dmamap_cb;
    215 static void			ahc_build_free_scb_list(struct ahc_softc *ahc);
    216 static int			ahc_init_scbdata(struct ahc_softc *ahc);
    217 static void			ahc_fini_scbdata(struct ahc_softc *ahc);
    218 static void		ahc_qinfifo_requeue(struct ahc_softc *ahc,
    219 					    struct scb *prev_scb,
    220 					    struct scb *scb);
    221 static int		ahc_qinfifo_count(struct ahc_softc *ahc);
    222 static u_int		ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
    223 						   u_int prev, u_int scbptr);
    224 static void		ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
    225 static u_int		ahc_rem_wscb(struct ahc_softc *ahc,
    226 				     u_int scbpos, u_int prev);
    227 static void		ahc_reset_current_bus(struct ahc_softc *ahc);
    228 #ifdef AHC_DUMP_SEQ
    229 static void		ahc_dumpseq(struct ahc_softc *ahc);
    230 #endif
    231 static void		ahc_loadseq(struct ahc_softc *ahc);
    232 static int		ahc_check_patch(struct ahc_softc *ahc,
    233 					struct patch **start_patch,
    234 					u_int start_instr, u_int *skip_addr);
    235 static void		ahc_download_instr(struct ahc_softc *ahc,
    236 					   u_int instrptr, uint8_t *dconsts);
    237 #ifdef AHC_TARGET_MODE
    238 static void		ahc_queue_lstate_event(struct ahc_softc *ahc,
    239 					       struct ahc_tmode_lstate *lstate,
    240 					       u_int initiator_id,
    241 					       u_int event_type,
    242 					       u_int event_arg);
    243 static void		ahc_update_scsiid(struct ahc_softc *ahc,
    244 					  u_int targid_mask);
    245 static int		ahc_handle_target_cmd(struct ahc_softc *ahc,
    246 					      struct target_cmd *cmd);
    247 #endif
    248 
    249 /************************** Added for porting to NetBSD ***********************/
    250 static int ahc_createdmamem(bus_dma_tag_t tag,
    251 			    int size,
    252 			    int flags,
    253 			    bus_dmamap_t *mapp,
    254 			    caddr_t *vaddr,
    255 			    bus_addr_t *baddr,
    256 			    bus_dma_segment_t *seg,
    257 			    int *nseg,
    258 			    const char *myname, const char *what);
    259 static void ahc_freedmamem(bus_dma_tag_t tag,
    260 			   int size,
    261 			   bus_dmamap_t map,
    262 			   caddr_t vaddr,
    263 			   bus_dma_segment_t *seg,
    264 			   int nseg);
    265 
    266 /************************* Sequencer Execution Control ************************/
    267 /*
    268  * Restart the sequencer program from address zero
    269  */
    270 void
    271 ahc_restart(struct ahc_softc *ahc)
    272 {
    273 
    274 	ahc_pause(ahc);
    275 
    276 	/* No more pending messages. */
    277 	ahc_clear_msg_state(ahc);
    278 
    279 	ahc_outb(ahc, SCSISIGO, 0);		/* De-assert BSY */
    280 	ahc_outb(ahc, MSG_OUT, MSG_NOOP);	/* No message to send */
    281 	ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
    282 	ahc_outb(ahc, LASTPHASE, P_BUSFREE);
    283 	ahc_outb(ahc, SAVED_SCSIID, 0xFF);
    284 	ahc_outb(ahc, SAVED_LUN, 0xFF);
    285 
    286 	/*
    287 	 * Ensure that the sequencer's idea of TQINPOS
    288 	 * matches our own.  The sequencer increments TQINPOS
    289 	 * only after it sees a DMA complete and a reset could
    290 	 * occur before the increment leaving the kernel to believe
    291 	 * the command arrived but the sequencer to not.
    292 	 */
    293 	ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
    294 
    295 	/* Always allow reselection */
    296 	ahc_outb(ahc, SCSISEQ,
    297 		 ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
    298 	if ((ahc->features & AHC_CMD_CHAN) != 0) {
    299 		/* Ensure that no DMA operations are in progress */
    300 		ahc_outb(ahc, CCSCBCNT, 0);
    301 		ahc_outb(ahc, CCSGCTL, 0);
    302 		ahc_outb(ahc, CCSCBCTL, 0);
    303 	}
    304 	/*
    305 	 * If we were in the process of DMA'ing SCB data into
    306 	 * an SCB, replace that SCB on the free list.  This prevents
    307 	 * an SCB leak.
    308 	 */
    309 	if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
    310 		ahc_add_curscb_to_free_list(ahc);
    311 		ahc_outb(ahc, SEQ_FLAGS2,
    312 			 ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
    313 	}
    314 	ahc_outb(ahc, MWI_RESIDUAL, 0);
    315 	ahc_outb(ahc, SEQCTL, FASTMODE);
    316 	ahc_outb(ahc, SEQADDR0, 0);
    317 	ahc_outb(ahc, SEQADDR1, 0);
    318 	ahc_unpause(ahc);
    319 }
    320 
    321 /************************* Input/Output Queues ********************************/
    322 void
    323 ahc_run_qoutfifo(struct ahc_softc *ahc)
    324 {
    325 	struct scb *scb;
    326 	u_int  scb_index;
    327 
    328 	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
    329 	while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
    330 
    331 		scb_index = ahc->qoutfifo[ahc->qoutfifonext];
    332 		if ((ahc->qoutfifonext & 0x03) == 0x03) {
    333 			u_int modnext;
    334 
    335 			/*
    336 			 * Clear 32bits of QOUTFIFO at a time
    337 			 * so that we don't clobber an incoming
    338 			 * byte DMA to the array on architectures
    339 			 * that only support 32bit load and store
    340 			 * operations.
    341 			 */
    342 			modnext = ahc->qoutfifonext & ~0x3;
    343 			*((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
    344 			ahc_dmamap_sync(ahc, ahc->parent_dmat /*shared_data_dmat*/,
    345 					ahc->shared_data_dmamap,
    346 					/*offset*/modnext, /*len*/4,
    347 					BUS_DMASYNC_PREREAD);
    348 		}
    349 		ahc->qoutfifonext++;
    350 
    351 		scb = ahc_lookup_scb(ahc, scb_index);
    352 		if (scb == NULL) {
    353 			printf("%s: WARNING no command for scb %d "
    354 			       "(cmdcmplt)\nQOUTPOS = %d\n",
    355 			       ahc_name(ahc), scb_index,
    356 			       (ahc->qoutfifonext - 1) & 0xFF);
    357 			continue;
    358 		}
    359 
    360 		/*
    361 		 * Save off the residual
    362 		 * if there is one.
    363 		 */
    364 		ahc_update_residual(ahc, scb);
    365 		ahc_done(ahc, scb);
    366 	}
    367 }
    368 
    369 void
    370 ahc_run_untagged_queues(struct ahc_softc *ahc)
    371 {
    372 	int i;
    373 
    374 	for (i = 0; i < 16; i++)
    375 		ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
    376 }
    377 
    378 void
    379 ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
    380 {
    381 	struct scb *scb;
    382 
    383 	if (ahc->untagged_queue_lock != 0)
    384 		return;
    385 
    386 	if ((scb = TAILQ_FIRST(queue)) != NULL
    387 	    && (scb->flags & SCB_ACTIVE) == 0) {
    388 		scb->flags |= SCB_ACTIVE;
    389 		ahc_queue_scb(ahc, scb);
    390 	}
    391 }
    392 
    393 /************************* Interrupt Handling *********************************/
    394 void
    395 ahc_handle_brkadrint(struct ahc_softc *ahc)
    396 {
    397 	/*
    398 	 * We upset the sequencer :-(
    399 	 * Lookup the error message
    400 	 */
    401 	int i;
    402 	int error;
    403 
    404 	error = ahc_inb(ahc, ERROR);
    405 	for (i = 0; error != 1 && i < num_errors; i++)
    406 		error >>= 1;
    407 	printf("%s: brkadrint, %s at seqaddr = 0x%x\n",
    408 	       ahc_name(ahc), ahc_hard_errors[i].errmesg,
    409 	       ahc_inb(ahc, SEQADDR0) |
    410 	       (ahc_inb(ahc, SEQADDR1) << 8));
    411 
    412 	ahc_dump_card_state(ahc);
    413 
    414 	/* Tell everyone that this HBA is no longer available */
    415 	ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
    416 		       CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
    417 		       CAM_NO_HBA);
    418 
    419 	/* Disable all interrupt sources by resetting the controller */
    420 	ahc_shutdown(ahc);
    421 }
    422 
    423 void
    424 ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
    425 {
    426 	struct scb *scb;
    427 	struct ahc_devinfo devinfo;
    428 
    429 	ahc_fetch_devinfo(ahc, &devinfo);
    430 
    431 	/*
    432 	 * Clear the upper byte that holds SEQINT status
    433 	 * codes and clear the SEQINT bit. We will unpause
    434 	 * the sequencer, if appropriate, after servicing
    435 	 * the request.
    436 	 */
    437 	ahc_outb(ahc, CLRINT, CLRSEQINT);
    438 	switch (intstat & SEQINT_MASK) {
    439 	case BAD_STATUS:
    440 	{
    441 		u_int  scb_index;
    442 		struct hardware_scb *hscb;
    443 
    444 		/*
    445 		 * Set the default return value to 0 (don't
    446 		 * send sense).  The sense code will change
    447 		 * this if needed.
    448 		 */
    449 		ahc_outb(ahc, RETURN_1, 0);
    450 
    451 		/*
    452 		 * The sequencer will notify us when a command
    453 		 * has an error that would be of interest to
    454 		 * the kernel.  This allows us to leave the sequencer
    455 		 * running in the common case of command completes
    456 		 * without error.  The sequencer will already have
    457 		 * DMA'd the SCB back up to us, so we can reference
    458 		 * the in kernel copy directly.
    459 		 */
    460 		scb_index = ahc_inb(ahc, SCB_TAG);
    461 		scb = ahc_lookup_scb(ahc, scb_index);
    462 		if (scb == NULL) {
    463 			ahc_print_devinfo(ahc, &devinfo);
    464 			printf("ahc_intr - referenced scb "
    465 			       "not valid during seqint 0x%x scb(%d)\n",
    466 			       intstat, scb_index);
    467 			ahc_dump_card_state(ahc);
    468 			panic("for safety");
    469 			goto unpause;
    470 		}
    471 
    472 		hscb = scb->hscb;
    473 
    474 		/* Don't want to clobber the original sense code */
    475 		if ((scb->flags & SCB_SENSE) != 0) {
    476 			/*
    477 			 * Clear the SCB_SENSE Flag and have
    478 			 * the sequencer do a normal command
    479 			 * complete.
    480 			 */
    481 			scb->flags &= ~SCB_SENSE;
    482 			break;
    483 		}
    484 		/* Freeze the queue until the client sees the error. */
    485 		ahc_freeze_devq(ahc, scb);
    486 		ahc_freeze_scb(scb);
    487 		ahc_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
    488 		switch (hscb->shared_data.status.scsi_status) {
    489 		case SCSI_STATUS_OK:
    490 			printf("%s: Interrupted for status of 0 (?)\n",
    491 			       ahc_name(ahc));
    492 			break;
    493 		case SCSI_STATUS_CMD_TERMINATED:
    494 		case SCSI_STATUS_CHECK_COND:
    495 		{
    496 			struct ahc_dma_seg *sg;
    497 			struct scsi_request_sense *sc;
    498 			struct ahc_initiator_tinfo *targ_info;
    499 			struct ahc_tmode_tstate *tstate;
    500 			struct ahc_transinfo *tinfo;
    501 			uint32_t len;
    502 #ifdef AHC_DEBUG
    503 			if (ahc_debug & AHC_SHOW_SENSE) {
    504 				ahc_print_path(ahc, scb);
    505 				printf("SCB %d: requests Check Status\n",
    506 				       scb->hscb->tag);
    507 			}
    508 #endif
    509 
    510 			if (ahc_perform_autosense(scb) == 0)
    511 				break;
    512 
    513 			targ_info = ahc_fetch_transinfo(ahc,
    514 							devinfo.channel,
    515 							devinfo.our_scsiid,
    516 							devinfo.target,
    517 							&tstate);
    518 			tinfo = &targ_info->curr;
    519 			sg = scb->sg_list;
    520 			sc = (struct scsi_request_sense *)(&hscb->shared_data.cdb);
    521 			/*
    522 			 * Save off the residual if there is one.
    523 			 */
    524 			ahc_update_residual(ahc, scb);
    525 #ifdef AHC_DEBUG
    526 			if (ahc_debug & AHC_SHOW_SENSE) {
    527 				ahc_print_path(ahc, scb);
    528 				printf("Sending Sense\n");
    529 			}
    530 #endif
    531 			sg->addr = ahc_htole32(ahc_get_sense_bufaddr(ahc, scb));
    532 			len = ahc_get_sense_bufsize(ahc, scb);
    533 			sg->len = ahc_htole32(len | AHC_DMA_LAST_SEG);
    534 
    535 			memset(sc, 0, sizeof(*sc));
    536 			sc->opcode = SCSI_REQUEST_SENSE;
    537 			if (tinfo->protocol_version <= SCSI_REV_2
    538 			    && SCB_GET_LUN(scb) < 8)
    539 				sc->byte2 = SCB_GET_LUN(scb) << 5;
    540 			sc->length = len;
    541 
    542 			/*
    543 			 * We can't allow the target to disconnect.
    544 			 * This will be an untagged transaction and
    545 			 * having the target disconnect will make this
    546 			 * transaction indistinguishable from outstanding
    547 			 * tagged transactions.
    548 			 */
    549 			hscb->control = 0;
    550 
    551 			/*
    552 			 * This request sense could be because the
    553 			 * the device lost power or in some other
    554 			 * way has lost our transfer negotiations.
    555 			 * Renegotiate if appropriate.  Unit attention
    556 			 * errors will be reported before any data
    557 			 * phases occur.
    558 			 */
    559 			if (ahc_get_residual(scb)
    560 			    == ahc_get_transfer_length(scb)) {
    561 				ahc_update_neg_request(ahc, &devinfo,
    562 						       tstate, targ_info,
    563 						       AHC_NEG_IF_NON_ASYNC);
    564 			}
    565 			if (tstate->auto_negotiate & devinfo.target_mask) {
    566 				hscb->control |= MK_MESSAGE;
    567 				scb->flags &= ~SCB_NEGOTIATE;
    568 				scb->flags |= SCB_AUTO_NEGOTIATE;
    569 			}
    570 			hscb->cdb_len = sizeof(*sc);
    571 			hscb->dataptr = sg->addr;
    572 			hscb->datacnt = sg->len;
    573 			hscb->sgptr =
    574 			    ahc_htole32(scb->sg_list_phys | SG_FULL_RESID);
    575 			scb->sg_count = 1;
    576 			scb->flags |= SCB_SENSE;
    577 			ahc_qinfifo_requeue_tail(ahc, scb);
    578 			ahc_outb(ahc, RETURN_1, SEND_SENSE);
    579 			/*
    580 			 * Ensure we have enough time to actually
    581 			 * retrieve the sense.
    582 			 */
    583 			ahc_scb_timer_reset(scb, 5 * 1000000);
    584 			break;
    585 		}
    586 		default:
    587 			break;
    588 		}
    589 		break;
    590 	}
    591 	case NO_MATCH:
    592 	{
    593 		/* Ensure we don't leave the selection hardware on */
    594 		ahc_outb(ahc, SCSISEQ,
    595 			 ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
    596 
    597 		printf("%s:%c:%d: no active SCB for reconnecting "
    598 		       "target - issuing BUS DEVICE RESET\n",
    599 		       ahc_name(ahc), devinfo.channel, devinfo.target);
    600 		printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
    601 		       "ARG_1 == 0x%x ACCUM = 0x%x\n",
    602 		       ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
    603 		       ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
    604 		printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
    605 		       "SINDEX == 0x%x\n",
    606 		       ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
    607 		       ahc_index_busy_tcl(ahc,
    608 			    BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
    609 				      ahc_inb(ahc, SAVED_LUN))),
    610 		       ahc_inb(ahc, SINDEX));
    611 		printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
    612 		       "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
    613 		       ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
    614 		       ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
    615 		       ahc_inb(ahc, SCB_CONTROL));
    616 		printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
    617 		       ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
    618 		printf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
    619 		printf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
    620 		ahc_dump_card_state(ahc);
    621 		ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
    622 		ahc->msgout_len = 1;
    623 		ahc->msgout_index = 0;
    624 		ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
    625 		ahc_outb(ahc, MSG_OUT, HOST_MSG);
    626 		ahc_assert_atn(ahc);
    627 		break;
    628 	}
    629 	case SEND_REJECT:
    630 	{
    631 		u_int rejbyte = ahc_inb(ahc, ACCUM);
    632 		printf("%s:%c:%d: Warning - unknown message received from "
    633 		       "target (0x%x).  Rejecting\n",
    634 		       ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
    635 		break;
    636 	}
    637 	case PROTO_VIOLATION:
    638 	{
    639 		ahc_handle_proto_violation(ahc);
    640 		break;
    641 	}
    642 	case IGN_WIDE_RES:
    643 		ahc_handle_ign_wide_residue(ahc, &devinfo);
    644 		break;
    645 	case PDATA_REINIT:
    646 		ahc_reinitialize_dataptrs(ahc);
    647 		break;
    648 	case BAD_PHASE:
    649 	{
    650 		u_int lastphase;
    651 
    652 		lastphase = ahc_inb(ahc, LASTPHASE);
    653 		printf("%s:%c:%d: unknown scsi bus phase %x, "
    654 		       "lastphase = 0x%x.  Attempting to continue\n",
    655 		       ahc_name(ahc), devinfo.channel, devinfo.target,
    656 		       lastphase, ahc_inb(ahc, SCSISIGI));
    657 		break;
    658 	}
    659 	case MISSED_BUSFREE:
    660 	{
    661 		u_int lastphase;
    662 
    663 		lastphase = ahc_inb(ahc, LASTPHASE);
    664 		printf("%s:%c:%d: Missed busfree. "
    665 		       "Lastphase = 0x%x, Curphase = 0x%x\n",
    666 		       ahc_name(ahc), devinfo.channel, devinfo.target,
    667 		       lastphase, ahc_inb(ahc, SCSISIGI));
    668 		ahc_restart(ahc);
    669 		return;
    670 	}
    671 	case HOST_MSG_LOOP:
    672 	{
    673 		/*
    674 		 * The sequencer has encountered a message phase
    675 		 * that requires host assistance for completion.
    676 		 * While handling the message phase(s), we will be
    677 		 * notified by the sequencer after each byte is
    678 		 * transferred so we can track bus phase changes.
    679 		 *
    680 		 * If this is the first time we've seen a HOST_MSG_LOOP
    681 		 * interrupt, initialize the state of the host message
    682 		 * loop.
    683 		 */
    684 		if (ahc->msg_type == MSG_TYPE_NONE) {
    685 			struct scb *scb1;
    686 			u_int scb_index;
    687 			u_int bus_phase;
    688 
    689 			bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
    690 			if (bus_phase != P_MESGIN
    691 			 && bus_phase != P_MESGOUT) {
    692 				printf("ahc_intr: HOST_MSG_LOOP bad "
    693 				       "phase 0x%x\n",
    694 				      bus_phase);
    695 				/*
    696 				 * Probably transitioned to bus free before
    697 				 * we got here.  Just punt the message.
    698 				 */
    699 				ahc_clear_intstat(ahc);
    700 				ahc_restart(ahc);
    701 				return;
    702 			}
    703 
    704 			scb_index = ahc_inb(ahc, SCB_TAG);
    705 			scb1 = ahc_lookup_scb(ahc, scb_index);
    706 			if (devinfo.role == ROLE_INITIATOR) {
    707 				if (scb1 == NULL)
    708 					panic("HOST_MSG_LOOP with "
    709 					      "invalid SCB %x\n", scb_index);
    710 
    711 				if (bus_phase == P_MESGOUT)
    712 					ahc_setup_initiator_msgout(ahc,
    713 								   &devinfo,
    714 								   scb1);
    715 				else {
    716 					ahc->msg_type =
    717 					    MSG_TYPE_INITIATOR_MSGIN;
    718 					ahc->msgin_index = 0;
    719 				}
    720 			}
    721 #if AHC_TARGET_MODE
    722 			else {
    723 				if (bus_phase == P_MESGOUT) {
    724 					ahc->msg_type =
    725 					    MSG_TYPE_TARGET_MSGOUT;
    726 					ahc->msgin_index = 0;
    727 				}
    728 				else
    729 					ahc_setup_target_msgin(ahc,
    730 							       &devinfo,
    731 							       scb1);
    732 			}
    733 #endif
    734 		}
    735 
    736 		ahc_handle_message_phase(ahc);
    737 		break;
    738 	}
    739 	case PERR_DETECTED:
    740 	{
    741 		/*
    742 		 * If we've cleared the parity error interrupt
    743 		 * but the sequencer still believes that SCSIPERR
    744 		 * is true, it must be that the parity error is
    745 		 * for the currently presented byte on the bus,
    746 		 * and we are not in a phase (data-in) where we will
    747 		 * eventually ack this byte.  Ack the byte and
    748 		 * throw it away in the hope that the target will
    749 		 * take us to message out to deliver the appropriate
    750 		 * error message.
    751 		 */
    752 		if ((intstat & SCSIINT) == 0
    753 		 && (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
    754 
    755 			if ((ahc->features & AHC_DT) == 0) {
    756 				u_int curphase;
    757 
    758 				/*
    759 				 * The hardware will only let you ack bytes
    760 				 * if the expected phase in SCSISIGO matches
    761 				 * the current phase.  Make sure this is
    762 				 * currently the case.
    763 				 */
    764 				curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
    765 				ahc_outb(ahc, LASTPHASE, curphase);
    766 				ahc_outb(ahc, SCSISIGO, curphase);
    767 			}
    768 			if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
    769 				int wait;
    770 
    771 				/*
    772 				 * In a data phase.  Faster to bitbucket
    773 				 * the data than to individually ack each
    774 				 * byte.  This is also the only strategy
    775 				 * that will work with AUTOACK enabled.
    776 				 */
    777 				ahc_outb(ahc, SXFRCTL1,
    778 					 ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
    779 				wait = 5000;
    780 				while (--wait != 0) {
    781 					if ((ahc_inb(ahc, SCSISIGI)
    782 					  & (CDI|MSGI)) != 0)
    783 						break;
    784 					ahc_delay(100);
    785 				}
    786 				ahc_outb(ahc, SXFRCTL1,
    787 					 ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
    788 				if (wait == 0) {
    789 					struct	scb *scb1;
    790 					u_int	scb_index;
    791 
    792 					ahc_print_devinfo(ahc, &devinfo);
    793 					printf("Unable to clear parity error.  "
    794 					       "Resetting bus.\n");
    795 					scb_index = ahc_inb(ahc, SCB_TAG);
    796 					scb1 = ahc_lookup_scb(ahc, scb_index);
    797 					if (scb1 != NULL)
    798 						ahc_set_transaction_status(scb1,
    799 						    CAM_UNCOR_PARITY);
    800 					ahc_reset_channel(ahc, devinfo.channel,
    801 							  /*init reset*/TRUE);
    802 				}
    803 			} else {
    804 				ahc_inb(ahc, SCSIDATL);
    805 			}
    806 		}
    807 		break;
    808 	}
    809 	case DATA_OVERRUN:
    810 	{
    811 		/*
    812 		 * When the sequencer detects an overrun, it
    813 		 * places the controller in "BITBUCKET" mode
    814 		 * and allows the target to complete its transfer.
    815 		 * Unfortunately, none of the counters get updated
    816 		 * when the controller is in this mode, so we have
    817 		 * no way of knowing how large the overrun was.
    818 		 */
    819 		u_int scbindex = ahc_inb(ahc, SCB_TAG);
    820 		u_int lastphase = ahc_inb(ahc, LASTPHASE);
    821 		u_int i;
    822 
    823 		scb = ahc_lookup_scb(ahc, scbindex);
    824 		for (i = 0; i < num_phases; i++) {
    825 			if (lastphase == ahc_phase_table[i].phase)
    826 				break;
    827 		}
    828 		ahc_print_path(ahc, scb);
    829 		printf("data overrun detected %s."
    830 		       "  Tag == 0x%x.\n",
    831 		       ahc_phase_table[i].phasemsg,
    832   		       scb->hscb->tag);
    833 		ahc_print_path(ahc, scb);
    834 		printf("%s seen Data Phase.  Length = %ld.  NumSGs = %d.\n",
    835 		       ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
    836 		       ahc_get_transfer_length(scb), scb->sg_count);
    837 		if (scb->sg_count > 0) {
    838 			for (i = 0; i < scb->sg_count; i++) {
    839 
    840 				printf("sg[%d] - Addr 0x%x%x : Length %d\n",
    841 				       i,
    842 				       (ahc_le32toh(scb->sg_list[i].len) >> 24
    843 				        & SG_HIGH_ADDR_BITS),
    844 				       ahc_le32toh(scb->sg_list[i].addr),
    845 				       ahc_le32toh(scb->sg_list[i].len)
    846 				       & AHC_SG_LEN_MASK);
    847 			}
    848 		}
    849 		/*
    850 		 * Set this and it will take effect when the
    851 		 * target does a command complete.
    852 		 */
    853 		ahc_freeze_devq(ahc, scb);
    854 		if ((scb->flags & SCB_SENSE) == 0) {
    855 			ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
    856 		} else {
    857 			scb->flags &= ~SCB_SENSE;
    858 			ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
    859 		}
    860 		ahc_freeze_scb(scb);
    861 
    862 		if ((ahc->features & AHC_ULTRA2) != 0) {
    863 			/*
    864 			 * Clear the channel in case we return
    865 			 * to data phase later.
    866 			 */
    867 			ahc_outb(ahc, SXFRCTL0,
    868 				 ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
    869 			ahc_outb(ahc, SXFRCTL0,
    870 				 ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
    871 		}
    872 		if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
    873 			u_int dscommand1;
    874 
    875 			/* Ensure HHADDR is 0 for future DMA operations. */
    876 			dscommand1 = ahc_inb(ahc, DSCOMMAND1);
    877 			ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
    878 			ahc_outb(ahc, HADDR, 0);
    879 			ahc_outb(ahc, DSCOMMAND1, dscommand1);
    880 		}
    881 		break;
    882 	}
    883 	case MKMSG_FAILED:
    884 	{
    885 		u_int scbindex;
    886 
    887 		printf("%s:%c:%d:%d: Attempt to issue message failed\n",
    888 		       ahc_name(ahc), devinfo.channel, devinfo.target,
    889 		       devinfo.lun);
    890 		scbindex = ahc_inb(ahc, SCB_TAG);
    891 		scb = ahc_lookup_scb(ahc, scbindex);
    892 		if (scb != NULL
    893 		 && (scb->flags & SCB_RECOVERY_SCB) != 0)
    894 			/*
    895 			 * Ensure that we didn't put a second instance of this
    896 			 * SCB into the QINFIFO.
    897 			 */
    898 			ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
    899 					   SCB_GET_CHANNEL(ahc, scb),
    900 					   SCB_GET_LUN(scb), scb->hscb->tag,
    901 					   ROLE_INITIATOR, /*status*/0,
    902 					   SEARCH_REMOVE);
    903 		break;
    904 	}
    905 	case NO_FREE_SCB:
    906 	{
    907 		printf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
    908 		ahc_dump_card_state(ahc);
    909 		panic("for safety");
    910 		break;
    911 	}
    912 	case SCB_MISMATCH:
    913 	{
    914 		u_int scbptr;
    915 
    916 		scbptr = ahc_inb(ahc, SCBPTR);
    917 		printf("Bogus TAG after DMA.  SCBPTR %d, tag %d, our tag %d\n",
    918 		       scbptr, ahc_inb(ahc, ARG_1),
    919 		       ahc->scb_data->hscbs[scbptr].tag);
    920 		ahc_dump_card_state(ahc);
    921 		panic("for saftey");
    922 		break;
    923 	}
    924 	case OUT_OF_RANGE:
    925 	{
    926 		printf("%s: BTT calculation out of range\n", ahc_name(ahc));
    927 		printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
    928 		       "ARG_1 == 0x%x ACCUM = 0x%x\n",
    929 		       ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
    930 		       ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
    931 		printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
    932 		       "SINDEX == 0x%x\n, A == 0x%x\n",
    933 		       ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
    934 		       ahc_index_busy_tcl(ahc,
    935 			    BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
    936 				      ahc_inb(ahc, SAVED_LUN))),
    937 		       ahc_inb(ahc, SINDEX),
    938 		       ahc_inb(ahc, ACCUM));
    939 		printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
    940 		       "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
    941 		       ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
    942 		       ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
    943 		       ahc_inb(ahc, SCB_CONTROL));
    944 		printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
    945 		       ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
    946 		ahc_dump_card_state(ahc);
    947 		panic("for safety");
    948 		break;
    949 	}
    950 	default:
    951 		printf("ahc_intr: seqint, "
    952 		       "intstat == 0x%x, scsisigi = 0x%x\n",
    953 		       intstat, ahc_inb(ahc, SCSISIGI));
    954 		break;
    955 	}
    956 unpause:
    957 	/*
    958 	 *  The sequencer is paused immediately on
    959 	 *  a SEQINT, so we should restart it when
    960 	 *  we're done.
    961 	 */
    962 	ahc_unpause(ahc);
    963 }
    964 
    965 void
    966 ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
    967 {
    968 	u_int	scb_index;
    969 	u_int	status0;
    970 	u_int	status;
    971 	struct	scb *scb;
    972 	char	cur_channel;
    973 	char	intr_channel;
    974 
    975 	if ((ahc->features & AHC_TWIN) != 0
    976 	    && ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
    977 		cur_channel = 'B';
    978 	else
    979 		cur_channel = 'A';
    980 	intr_channel = cur_channel;
    981 
    982 	if ((ahc->features & AHC_ULTRA2) != 0)
    983 		status0 = ahc_inb(ahc, SSTAT0) & IOERR;
    984 	else
    985 		status0 = 0;
    986 	status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
    987 	if (status == 0 && status0 == 0) {
    988 		if ((ahc->features & AHC_TWIN) != 0) {
    989 			/* Try the other channel */
    990 		 	ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
    991 			status = ahc_inb(ahc, SSTAT1)
    992 			       & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
    993 			intr_channel = (cur_channel == 'A') ? 'B' : 'A';
    994 		}
    995 		if (status == 0) {
    996 			printf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
    997 			ahc_outb(ahc, CLRINT, CLRSCSIINT);
    998 			ahc_unpause(ahc);
    999 			return;
   1000 		}
   1001 	}
   1002 
   1003 	/* Make sure the sequencer is in a safe location. */
   1004 	ahc_clear_critical_section(ahc);
   1005 
   1006 	scb_index = ahc_inb(ahc, SCB_TAG);
   1007 	scb = ahc_lookup_scb(ahc, scb_index);
   1008 	if (scb != NULL
   1009 	 && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
   1010 		scb = NULL;
   1011 
   1012 	if ((ahc->features & AHC_ULTRA2) != 0
   1013 	 && (status0 & IOERR) != 0) {
   1014 		int now_lvd;
   1015 
   1016 		now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
   1017 		printf("%s: Transceiver State Has Changed to %s mode\n",
   1018 		       ahc_name(ahc), now_lvd ? "LVD" : "SE");
   1019 		ahc_outb(ahc, CLRSINT0, CLRIOERR);
   1020 		/*
   1021 		 * When transitioning to SE mode, the reset line
   1022 		 * glitches, triggering an arbitration bug in some
   1023 		 * Ultra2 controllers.  This bug is cleared when we
   1024 		 * assert the reset line.  Since a reset glitch has
   1025 		 * already occurred with this transition and a
   1026 		 * transceiver state change is handled just like
   1027 		 * a bus reset anyway, asserting the reset line
   1028 		 * ourselves is safe.
   1029 		 */
   1030 		ahc_reset_channel(ahc, intr_channel,
   1031 				 /*Initiate Reset*/now_lvd == 0);
   1032 	} else if ((status & SCSIRSTI) != 0) {
   1033 		printf("%s: Someone reset channel %c\n",
   1034 			ahc_name(ahc), intr_channel);
   1035 		if (intr_channel != cur_channel)
   1036 		 	ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
   1037 		ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
   1038 	} else if ((status & SCSIPERR) != 0) {
   1039 		/*
   1040 		 * Determine the bus phase and queue an appropriate message.
   1041 		 * SCSIPERR is latched true as soon as a parity error
   1042 		 * occurs.  If the sequencer acked the transfer that
   1043 		 * caused the parity error and the currently presented
   1044 		 * transfer on the bus has correct parity, SCSIPERR will
   1045 		 * be cleared by CLRSCSIPERR.  Use this to determine if
   1046 		 * we should look at the last phase the sequencer recorded,
   1047 		 * or the current phase presented on the bus.
   1048 		 */
   1049 		u_int mesg_out;
   1050 		u_int curphase;
   1051 		u_int errorphase;
   1052 		u_int lastphase;
   1053 		u_int scsirate;
   1054 		u_int i;
   1055 		u_int sstat2;
   1056 		int   silent;
   1057 
   1058 		lastphase = ahc_inb(ahc, LASTPHASE);
   1059 		curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
   1060 		sstat2 = ahc_inb(ahc, SSTAT2);
   1061 		ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
   1062 		/*
   1063 		 * For all phases save DATA, the sequencer won't
   1064 		 * automatically ack a byte that has a parity error
   1065 		 * in it.  So the only way that the current phase
   1066 		 * could be 'data-in' is if the parity error is for
   1067 		 * an already acked byte in the data phase.  During
   1068 		 * synchronous data-in transfers, we may actually
   1069 		 * ack bytes before latching the current phase in
   1070 		 * LASTPHASE, leading to the discrepancy between
   1071 		 * curphase and lastphase.
   1072 		 */
   1073 		if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
   1074 		 || curphase == P_DATAIN || curphase == P_DATAIN_DT)
   1075 			errorphase = curphase;
   1076 		else
   1077 			errorphase = lastphase;
   1078 
   1079 		for (i = 0; i < num_phases; i++) {
   1080 			if (errorphase == ahc_phase_table[i].phase)
   1081 				break;
   1082 		}
   1083 		mesg_out = ahc_phase_table[i].mesg_out;
   1084 		silent = FALSE;
   1085 		if (scb != NULL) {
   1086 			if (SCB_IS_SILENT(scb))
   1087 				silent = TRUE;
   1088 			else
   1089 				ahc_print_path(ahc, scb);
   1090 			scb->flags |= SCB_TRANSMISSION_ERROR;
   1091 		} else
   1092 			printf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
   1093 			       SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
   1094 		scsirate = ahc_inb(ahc, SCSIRATE);
   1095 		if (silent == FALSE) {
   1096 			printf("parity error detected %s. "
   1097 			       "SEQADDR(0x%x) SCSIRATE(0x%x)\n",
   1098 			       ahc_phase_table[i].phasemsg,
   1099 			       ahc_inw(ahc, SEQADDR0),
   1100 			       scsirate);
   1101 			if ((ahc->features & AHC_DT) != 0) {
   1102 				if ((sstat2 & CRCVALERR) != 0)
   1103 					printf("\tCRC Value Mismatch\n");
   1104 				if ((sstat2 & CRCENDERR) != 0)
   1105 					printf("\tNo terminal CRC packet "
   1106 					       "recevied\n");
   1107 				if ((sstat2 & CRCREQERR) != 0)
   1108 					printf("\tIllegal CRC packet "
   1109 					       "request\n");
   1110 				if ((sstat2 & DUAL_EDGE_ERR) != 0)
   1111 					printf("\tUnexpected %sDT Data Phase\n",
   1112 					       (scsirate & SINGLE_EDGE)
   1113 					     ? "" : "non-");
   1114 			}
   1115 		}
   1116 
   1117 		if ((ahc->features & AHC_DT) != 0
   1118 		 && (sstat2 & DUAL_EDGE_ERR) != 0) {
   1119 			/*
   1120 			 * This error applies regardless of
   1121 			 * data direction, so ignore the value
   1122 			 * in the phase table.
   1123 			 */
   1124 			mesg_out = MSG_INITIATOR_DET_ERR;
   1125 		}
   1126 
   1127 		/*
   1128 		 * We've set the hardware to assert ATN if we
   1129 		 * get a parity error on "in" phases, so all we
   1130 		 * need to do is stuff the message buffer with
   1131 		 * the appropriate message.  "In" phases have set
   1132 		 * mesg_out to something other than MSG_NOP.
   1133 		 */
   1134 		if (mesg_out != MSG_NOOP) {
   1135 			if (ahc->msg_type != MSG_TYPE_NONE)
   1136 				ahc->send_msg_perror = TRUE;
   1137 			else
   1138 				ahc_outb(ahc, MSG_OUT, mesg_out);
   1139 		}
   1140 		/*
   1141 		 * Force a renegotiation with this target just in
   1142 		 * case we are out of sync for some external reason
   1143 		 * unknown (or unreported) by the target.
   1144 		 */
   1145 		ahc_force_renegotiation(ahc);
   1146 		ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1147 		ahc_unpause(ahc);
   1148 	} else if ((status & SELTO) != 0) {
   1149 		u_int	scbptr;
   1150 
   1151 		/* Stop the selection */
   1152 		ahc_outb(ahc, SCSISEQ, 0);
   1153 
   1154 		/* No more pending messages */
   1155 		ahc_clear_msg_state(ahc);
   1156 
   1157 		/* Clear interrupt state */
   1158 		ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
   1159 		ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
   1160 
   1161 		/*
   1162 		 * Although the driver does not care about the
   1163 		 * 'Selection in Progress' status bit, the busy
   1164 		 * LED does.  SELINGO is only cleared by a sucessfull
   1165 		 * selection, so we must manually clear it to insure
   1166 		 * the LED turns off just incase no future successful
   1167 		 * selections occur (e.g. no devices on the bus).
   1168 		 */
   1169 		ahc_outb(ahc, CLRSINT0, CLRSELINGO);
   1170 
   1171 		scbptr = ahc_inb(ahc, WAITING_SCBH);
   1172 		ahc_outb(ahc, SCBPTR, scbptr);
   1173 		scb_index = ahc_inb(ahc, SCB_TAG);
   1174 
   1175 		scb = ahc_lookup_scb(ahc, scb_index);
   1176 		if (scb == NULL) {
   1177 			printf("%s: ahc_intr - referenced scb not "
   1178 			       "valid during SELTO scb(%d, %d)\n",
   1179 			       ahc_name(ahc), scbptr, scb_index);
   1180 			ahc_dump_card_state(ahc);
   1181 		} else {
   1182 #ifdef AHC_DEBUG
   1183 			if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
   1184 				ahc_print_path(ahc, scb);
   1185 				printf("Saw Selection Timeout for SCB 0x%x\n",
   1186 				       scb_index);
   1187 			}
   1188 #endif
   1189 			/*
   1190 			 * Force a renegotiation with this target just in
   1191 			 * case the cable was pulled and will later be
   1192 			 * re-attached.  The target may forget its negotiation
   1193 			 * settings with us should it attempt to reselect
   1194 			 * during the interruption.  The target will not issue
   1195 			 * a unit attention in this case, so we must always
   1196 			 * renegotiate.
   1197 			 */
   1198 			ahc_force_renegotiation(ahc);
   1199 			ahc_set_transaction_status(scb, CAM_SEL_TIMEOUT);
   1200 			ahc_freeze_devq(ahc, scb);
   1201 		}
   1202 		ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1203 		ahc_restart(ahc);
   1204 	} else if ((status & BUSFREE) != 0
   1205 		&& (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
   1206 		u_int lastphase;
   1207 		u_int saved_scsiid;
   1208 		u_int saved_lun;
   1209 		u_int target;
   1210 		u_int initiator_role_id;
   1211 		char channel;
   1212 		int printerror;
   1213 
   1214 		/*
   1215 		 * Clear our selection hardware as soon as possible.
   1216 		 * We may have an entry in the waiting Q for this target,
   1217 		 * that is affected by this busfree and we don't want to
   1218 		 * go about selecting the target while we handle the event.
   1219 		 */
   1220 		ahc_outb(ahc, SCSISEQ,
   1221 			 ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
   1222 
   1223 		/*
   1224 		 * Disable busfree interrupts and clear the busfree
   1225 		 * interrupt status.  We do this here so that several
   1226 		 * bus transactions occur prior to clearing the SCSIINT
   1227 		 * latch.  It can take a bit for the clearing to take effect.
   1228 		 */
   1229 		ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
   1230 		ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
   1231 
   1232 		/*
   1233 		 * Look at what phase we were last in.
   1234 		 * If its message out, chances are pretty good
   1235 		 * that the busfree was in response to one of
   1236 		 * our abort requests.
   1237 		 */
   1238 		lastphase = ahc_inb(ahc, LASTPHASE);
   1239 		saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
   1240 		saved_lun = ahc_inb(ahc, SAVED_LUN);
   1241 		target = SCSIID_TARGET(ahc, saved_scsiid);
   1242 		initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
   1243 		channel = SCSIID_CHANNEL(ahc, saved_scsiid);
   1244 		printerror = 1;
   1245 
   1246 		if (lastphase == P_MESGOUT) {
   1247 			struct ahc_devinfo devinfo;
   1248 			u_int tag;
   1249 
   1250 			ahc_fetch_devinfo(ahc, &devinfo);
   1251 			tag = SCB_LIST_NULL;
   1252 			if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
   1253 			    || ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
   1254 				if (ahc->msgout_buf[ahc->msgout_index - 1]
   1255 				    == MSG_ABORT_TAG)
   1256 				tag = scb->hscb->tag;
   1257 				ahc_print_path(ahc, scb);
   1258 				printf("SCB %d - Abort%s Completed.\n",
   1259 				       scb->hscb->tag, tag == SCB_LIST_NULL ?
   1260 				       "" : " Tag");
   1261 				ahc_abort_scbs(ahc, target, channel,
   1262 					       saved_lun, tag,
   1263 					       ROLE_INITIATOR,
   1264 					       CAM_REQ_ABORTED);
   1265 				printerror = 0;
   1266 			} else if (ahc_sent_msg(ahc, AHCMSG_1B,
   1267 						MSG_BUS_DEV_RESET, TRUE)) {
   1268 #ifdef __FreeBSD__
   1269 				/*
   1270 				 * Don't mark the user's request for this BDR
   1271 				 * as completing with CAM_BDR_SENT.  CAM3
   1272 				 * specifies CAM_REQ_CMP.
   1273 				 */
   1274 				if (scb != NULL
   1275 				 && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
   1276 				 && ahc_match_scb(ahc, scb, target, channel,
   1277 						  CAM_LUN_WILDCARD,
   1278 						  SCB_LIST_NULL,
   1279 						  ROLE_INITIATOR)) {
   1280 					ahc_set_transaction_status(scb, CAM_REQ_CMP);
   1281 				}
   1282 #endif
   1283 				ahc_compile_devinfo(&devinfo,
   1284 						    initiator_role_id,
   1285 						    target,
   1286 						    CAM_LUN_WILDCARD,
   1287 						    channel,
   1288 						    ROLE_INITIATOR);
   1289 				ahc_handle_devreset(ahc, &devinfo,
   1290 						    CAM_BDR_SENT,
   1291 						    "Bus Device Reset",
   1292 						    /*verbose_level*/0);
   1293 				printerror = 0;
   1294 			} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
   1295 						MSG_EXT_PPR, FALSE)) {
   1296 				struct ahc_initiator_tinfo *tinfo;
   1297 				struct ahc_tmode_tstate *tstate;
   1298 
   1299 				/*
   1300 				 * PPR Rejected.  Try non-ppr negotiation
   1301 				 * and retry command.
   1302 				 */
   1303 				tinfo = ahc_fetch_transinfo(ahc,
   1304 							    devinfo.channel,
   1305 							    devinfo.our_scsiid,
   1306 							    devinfo.target,
   1307 							    &tstate);
   1308 				tinfo->curr.transport_version = 2;
   1309 				tinfo->goal.transport_version = 2;
   1310 				tinfo->goal.ppr_options = 0;
   1311 				ahc_qinfifo_requeue_tail(ahc, scb);
   1312 				printerror = 0;
   1313 			} else if (ahc_sent_msg(ahc, AHCMSG_EXT,
   1314 						MSG_EXT_WDTR, FALSE)
   1315 				|| ahc_sent_msg(ahc, AHCMSG_EXT,
   1316 						MSG_EXT_SDTR, FALSE)) {
   1317 				/*
   1318 				 * Negotiation Rejected.  Go-async and
   1319 				 * retry command.
   1320 				 */
   1321 				ahc_set_width(ahc, &devinfo,
   1322 					      MSG_EXT_WDTR_BUS_8_BIT,
   1323 					      AHC_TRANS_CUR|AHC_TRANS_GOAL,
   1324 					      /*paused*/TRUE);
   1325 				ahc_set_syncrate(ahc, &devinfo,
   1326 						/*syncrate*/NULL,
   1327 						/*period*/0, /*offset*/0,
   1328 						/*ppr_options*/0,
   1329 						AHC_TRANS_CUR|AHC_TRANS_GOAL,
   1330 						/*paused*/TRUE);
   1331 				ahc_qinfifo_requeue_tail(ahc, scb);
   1332 				printerror = 0;
   1333 			}
   1334 		}
   1335 		if (printerror != 0) {
   1336 			u_int i;
   1337 
   1338 			if (scb != NULL) {
   1339 				u_int tag;
   1340 
   1341 				if ((scb->hscb->control & TAG_ENB) != 0)
   1342 					tag = scb->hscb->tag;
   1343 				else
   1344 					tag = SCB_LIST_NULL;
   1345 				ahc_print_path(ahc, scb);
   1346 				ahc_abort_scbs(ahc, target, channel,
   1347 					       SCB_GET_LUN(scb), tag,
   1348 					       ROLE_INITIATOR,
   1349 					       CAM_UNEXP_BUSFREE);
   1350 			} else {
   1351 				/*
   1352 				 * We had not fully identified this connection,
   1353 				 * so we cannot abort anything.
   1354 				 */
   1355 				printf("%s: ", ahc_name(ahc));
   1356 			}
   1357 			for (i = 0; i < num_phases; i++) {
   1358 				if (lastphase == ahc_phase_table[i].phase)
   1359 					break;
   1360 			}
   1361 			/*
   1362 			 * Renegotiate with this device at the
   1363 			 * next opportunity just in case this busfree
   1364 			 * is due to a negotiation mismatch with the
   1365 			 * device.
   1366 			 */
   1367 			ahc_force_renegotiation(ahc);
   1368 			printf("Unexpected busfree %s\n"
   1369 			       "SEQADDR == 0x%x\n",
   1370 			       ahc_phase_table[i].phasemsg,
   1371 			       ahc_inb(ahc, SEQADDR0)
   1372 				| (ahc_inb(ahc, SEQADDR1) << 8));
   1373 		}
   1374 		ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1375 		ahc_restart(ahc);
   1376 	} else {
   1377 		printf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
   1378 		       ahc_name(ahc), status);
   1379 		ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1380 	}
   1381 }
   1382 
   1383 /*
   1384  * Force renegotiation to occur the next time we initiate
   1385  * a command to the current device.
   1386  */
   1387 static void
   1388 ahc_force_renegotiation(struct ahc_softc *ahc)
   1389 {
   1390 	struct	ahc_devinfo devinfo;
   1391 	struct	ahc_initiator_tinfo *targ_info;
   1392 	struct	ahc_tmode_tstate *tstate;
   1393 
   1394 	ahc_fetch_devinfo(ahc, &devinfo);
   1395 	targ_info = ahc_fetch_transinfo(ahc,
   1396 					devinfo.channel,
   1397 					devinfo.our_scsiid,
   1398 					devinfo.target,
   1399 					&tstate);
   1400 	ahc_update_neg_request(ahc, &devinfo, tstate,
   1401 			       targ_info, AHC_NEG_IF_NON_ASYNC);
   1402 }
   1403 
   1404 #define AHC_MAX_STEPS 2000
   1405 void
   1406 ahc_clear_critical_section(struct ahc_softc *ahc)
   1407 {
   1408 	int	stepping;
   1409 	int	steps;
   1410 	u_int	simode0;
   1411 	u_int	simode1;
   1412 
   1413 	if (ahc->num_critical_sections == 0)
   1414 		return;
   1415 
   1416 	stepping = FALSE;
   1417 	steps = 0;
   1418 	simode0 = 0;
   1419 	simode1 = 0;
   1420 	for (;;) {
   1421 		struct	cs *cs;
   1422 		u_int	seqaddr;
   1423 		u_int	i;
   1424 
   1425 		seqaddr = ahc_inb(ahc, SEQADDR0)
   1426 			| (ahc_inb(ahc, SEQADDR1) << 8);
   1427 
   1428 		/*
   1429 		 * Seqaddr represents the next instruction to execute,
   1430 		 * so we are really executing the instruction just
   1431 		 * before it.
   1432 		 */
   1433 		if (seqaddr != 0)
   1434 			seqaddr -= 1;
   1435 		cs = ahc->critical_sections;
   1436 		for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
   1437 
   1438 			if (cs->begin < seqaddr && cs->end >= seqaddr)
   1439 				break;
   1440 		}
   1441 
   1442 		if (i == ahc->num_critical_sections)
   1443 			break;
   1444 
   1445 		if (steps > AHC_MAX_STEPS) {
   1446 			printf("%s: Infinite loop in critical section\n",
   1447 			       ahc_name(ahc));
   1448 			ahc_dump_card_state(ahc);
   1449 			panic("critical section loop");
   1450 		}
   1451 
   1452 		steps++;
   1453 		if (stepping == FALSE) {
   1454 
   1455 			/*
   1456 			 * Disable all interrupt sources so that the
   1457 			 * sequencer will not be stuck by a pausing
   1458 			 * interrupt condition while we attempt to
   1459 			 * leave a critical section.
   1460 			 */
   1461 			simode0 = ahc_inb(ahc, SIMODE0);
   1462 			ahc_outb(ahc, SIMODE0, 0);
   1463 			simode1 = ahc_inb(ahc, SIMODE1);
   1464 			if ((ahc->features & AHC_DT) != 0)
   1465 				/*
   1466 				 * On DT class controllers, we
   1467 				 * use the enhanced busfree logic.
   1468 				 * Unfortunately we cannot re-enable
   1469 				 * busfree detection within the
   1470 				 * current connection, so we must
   1471 				 * leave it on while single stepping.
   1472 				 */
   1473 				ahc_outb(ahc, SIMODE1, ENBUSFREE);
   1474 			else
   1475 				ahc_outb(ahc, SIMODE1, 0);
   1476 			ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1477 			ahc_outb(ahc, SEQCTL, ahc_inb(ahc, SEQCTL) | STEP);
   1478 			stepping = TRUE;
   1479 		}
   1480 		if ((ahc->features & AHC_DT) != 0) {
   1481 			ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
   1482 			ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1483 		}
   1484 		ahc_outb(ahc, HCNTRL, ahc->unpause);
   1485 		while (!ahc_is_paused(ahc))
   1486 			ahc_delay(200);
   1487 	}
   1488 	if (stepping) {
   1489 		ahc_outb(ahc, SIMODE0, simode0);
   1490 		ahc_outb(ahc, SIMODE1, simode1);
   1491 		ahc_outb(ahc, SEQCTL, ahc_inb(ahc, SEQCTL) & ~STEP);
   1492 	}
   1493 }
   1494 
   1495 /*
   1496  * Clear any pending interrupt status.
   1497  */
   1498 void
   1499 ahc_clear_intstat(struct ahc_softc *ahc)
   1500 {
   1501 	/* Clear any interrupt conditions this may have caused */
   1502 	ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
   1503 				|CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
   1504 				CLRREQINIT);
   1505 	ahc_flush_device_writes(ahc);
   1506 	ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
   1507  	ahc_flush_device_writes(ahc);
   1508 	ahc_outb(ahc, CLRINT, CLRSCSIINT);
   1509 	ahc_flush_device_writes(ahc);
   1510 }
   1511 
   1512 /**************************** Debugging Routines ******************************/
   1513 #ifdef AHC_DEBUG
   1514 uint32_t ahc_debug = 0; /* AHC_SHOW_MISC|AHC_SHOW_SENSE|AHC_DEBUG_OPTS;*/
   1515 #endif
   1516 
   1517 void
   1518 ahc_print_scb(struct scb *scb)
   1519 {
   1520 	int i;
   1521 
   1522 	struct hardware_scb *hscb = scb->hscb;
   1523 
   1524 	printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
   1525 	       (void *)scb,
   1526 	       hscb->control,
   1527 	       hscb->scsiid,
   1528 	       hscb->lun,
   1529 	       hscb->cdb_len);
   1530 	printf("Shared Data: ");
   1531 	for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
   1532 		printf("%#02x", hscb->shared_data.cdb[i]);
   1533 	printf("        dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
   1534 		ahc_le32toh(hscb->dataptr),
   1535 		ahc_le32toh(hscb->datacnt),
   1536 		ahc_le32toh(hscb->sgptr),
   1537 		hscb->tag);
   1538 	if (scb->sg_count > 0) {
   1539 		for (i = 0; i < scb->sg_count; i++) {
   1540 			printf("sg[%d] - Addr 0x%x%x : Length %d\n",
   1541 			       i,
   1542 			       (ahc_le32toh(scb->sg_list[i].len) >> 24
   1543 			        & SG_HIGH_ADDR_BITS),
   1544 			       ahc_le32toh(scb->sg_list[i].addr),
   1545 			       ahc_le32toh(scb->sg_list[i].len));
   1546 		}
   1547 	}
   1548 }
   1549 
   1550 /************************* Transfer Negotiation *******************************/
   1551 /*
   1552  * Allocate per target mode instance (ID we respond to as a target)
   1553  * transfer negotiation data structures.
   1554  */
   1555 static struct ahc_tmode_tstate *
   1556 ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
   1557 {
   1558 	struct ahc_tmode_tstate *master_tstate;
   1559 	struct ahc_tmode_tstate *tstate;
   1560 	int i;
   1561 
   1562 	master_tstate = ahc->enabled_targets[ahc->our_id];
   1563 	if (channel == 'B') {
   1564 		scsi_id += 8;
   1565 		master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
   1566 	}
   1567 	if (ahc->enabled_targets[scsi_id] != NULL
   1568 	    && ahc->enabled_targets[scsi_id] != master_tstate)
   1569 		panic("%s: ahc_alloc_tstate - Target already allocated",
   1570 		      ahc_name(ahc));
   1571 	tstate = (struct ahc_tmode_tstate*)malloc(sizeof(*tstate),
   1572 						   M_DEVBUF, M_NOWAIT);
   1573 	if (tstate == NULL)
   1574 		return (NULL);
   1575 
   1576 	/*
   1577 	 * If we have allocated a master tstate, copy user settings from
   1578 	 * the master tstate (taken from SRAM or the EEPROM) for this
   1579 	 * channel, but reset our current and goal settings to async/narrow
   1580 	 * until an initiator talks to us.
   1581 	 */
   1582 	if (master_tstate != NULL) {
   1583 		memcpy(tstate, master_tstate, sizeof(*tstate));
   1584 		memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
   1585 		tstate->ultraenb = 0;
   1586 		for (i = 0; i < AHC_NUM_TARGETS; i++) {
   1587 			memset(&tstate->transinfo[i].curr, 0,
   1588 			      sizeof(tstate->transinfo[i].curr));
   1589 			memset(&tstate->transinfo[i].goal, 0,
   1590 			      sizeof(tstate->transinfo[i].goal));
   1591 		}
   1592 	} else
   1593 		memset(tstate, 0, sizeof(*tstate));
   1594 	ahc->enabled_targets[scsi_id] = tstate;
   1595 	return (tstate);
   1596 }
   1597 
   1598 #ifdef AHC_TARGET_MODE
   1599 /*
   1600  * Free per target mode instance (ID we respond to as a target)
   1601  * transfer negotiation data structures.
   1602  */
   1603 static void
   1604 ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
   1605 {
   1606 	struct ahc_tmode_tstate *tstate;
   1607 
   1608 	/*
   1609 	 * Don't clean up our "master" tstate.
   1610 	 * It has our default user settings.
   1611 	 */
   1612 	if (((channel == 'B' && scsi_id == ahc->our_id_b)
   1613 	  || (channel == 'A' && scsi_id == ahc->our_id))
   1614 	 && force == FALSE)
   1615 		return;
   1616 
   1617 	if (channel == 'B')
   1618 		scsi_id += 8;
   1619 	tstate = ahc->enabled_targets[scsi_id];
   1620 	if (tstate != NULL)
   1621 		free(tstate, M_DEVBUF);
   1622 	ahc->enabled_targets[scsi_id] = NULL;
   1623 }
   1624 #endif
   1625 
   1626 /*
   1627  * Called when we have an active connection to a target on the bus,
   1628  * this function finds the nearest syncrate to the input period limited
   1629  * by the capabilities of the bus connectivity of and sync settings for
   1630  * the target.
   1631  */
   1632 struct ahc_syncrate *
   1633 ahc_devlimited_syncrate(struct ahc_softc *ahc,
   1634 			struct ahc_initiator_tinfo *tinfo,
   1635 			u_int *period, u_int *ppr_options, role_t role)
   1636 {
   1637 	struct	ahc_transinfo *transinfo;
   1638 	u_int	maxsync;
   1639 
   1640 	if ((ahc->features & AHC_ULTRA2) != 0) {
   1641 		if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
   1642 		 && (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
   1643 			maxsync = AHC_SYNCRATE_DT;
   1644 		} else {
   1645 			maxsync = AHC_SYNCRATE_ULTRA;
   1646 			/* Can't do DT on an SE bus */
   1647 			*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
   1648 		}
   1649 	} else if ((ahc->features & AHC_ULTRA) != 0) {
   1650 		maxsync = AHC_SYNCRATE_ULTRA;
   1651 	} else {
   1652 		maxsync = AHC_SYNCRATE_FAST;
   1653 	}
   1654 	/*
   1655 	 * Never allow a value higher than our current goal
   1656 	 * period otherwise we may allow a target initiated
   1657 	 * negotiation to go above the limit as set by the
   1658 	 * user.  In the case of an initiator initiated
   1659 	 * sync negotiation, we limit based on the user
   1660 	 * setting.  This allows the system to still accept
   1661 	 * incoming negotiations even if target initiated
   1662 	 * negotiation is not performed.
   1663 	 */
   1664 	if (role == ROLE_TARGET)
   1665 		transinfo = &tinfo->user;
   1666 	else
   1667 		transinfo = &tinfo->goal;
   1668 	*ppr_options &= transinfo->ppr_options;
   1669 	if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
   1670 		maxsync = MAX(maxsync, AHC_SYNCRATE_ULTRA2);
   1671 		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
   1672 	}
   1673 	if (transinfo->period == 0) {
   1674 		*period = 0;
   1675 		*ppr_options = 0;
   1676 		return (NULL);
   1677 	}
   1678 	*period = MAX(*period, transinfo->period);
   1679 	return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
   1680 }
   1681 
   1682 /*
   1683  * Look up the valid period to SCSIRATE conversion in our table.
   1684  * Return the period and offset that should be sent to the target
   1685  * if this was the beginning of an SDTR.
   1686  */
   1687 struct ahc_syncrate *
   1688 ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
   1689 		  u_int *ppr_options, u_int maxsync)
   1690 {
   1691 	struct ahc_syncrate *syncrate;
   1692 
   1693 	if ((ahc->features & AHC_DT) == 0)
   1694 		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
   1695 
   1696 	/* Skip all DT only entries if DT is not available */
   1697 	if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
   1698 	 && maxsync < AHC_SYNCRATE_ULTRA2)
   1699 		maxsync = AHC_SYNCRATE_ULTRA2;
   1700 
   1701 	for (syncrate = &ahc_syncrates[maxsync];
   1702 	     syncrate->rate != NULL;
   1703 	     syncrate++) {
   1704 
   1705 		/*
   1706 		 * The Ultra2 table doesn't go as low
   1707 		 * as for the Fast/Ultra cards.
   1708 		 */
   1709 		if ((ahc->features & AHC_ULTRA2) != 0
   1710 		 && (syncrate->sxfr_u2 == 0))
   1711 			break;
   1712 
   1713 		if (*period <= syncrate->period) {
   1714 			/*
   1715 			 * When responding to a target that requests
   1716 			 * sync, the requested rate may fall between
   1717 			 * two rates that we can output, but still be
   1718 			 * a rate that we can receive.  Because of this,
   1719 			 * we want to respond to the target with
   1720 			 * the same rate that it sent to us even
   1721 			 * if the period we use to send data to it
   1722 			 * is lower.  Only lower the response period
   1723 			 * if we must.
   1724 			 */
   1725 			if (syncrate == &ahc_syncrates[maxsync])
   1726 				*period = syncrate->period;
   1727 
   1728 			/*
   1729 			 * At some speeds, we only support
   1730 			 * ST transfers.
   1731 			 */
   1732 		 	if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
   1733 				*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
   1734 			break;
   1735 		}
   1736 	}
   1737 
   1738 	if ((*period == 0)
   1739 	 || (syncrate->rate == NULL)
   1740 	 || ((ahc->features & AHC_ULTRA2) != 0
   1741 	  && (syncrate->sxfr_u2 == 0))) {
   1742 		/* Use asynchronous transfers. */
   1743 		*period = 0;
   1744 		syncrate = NULL;
   1745 		*ppr_options &= ~MSG_EXT_PPR_DT_REQ;
   1746 	}
   1747 	return (syncrate);
   1748 }
   1749 
   1750 /*
   1751  * Convert from an entry in our syncrate table to the SCSI equivalent
   1752  * sync "period" factor.
   1753  */
   1754 u_int
   1755 ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
   1756 {
   1757 	struct ahc_syncrate *syncrate;
   1758 
   1759 	if ((ahc->features & AHC_ULTRA2) != 0)
   1760 		scsirate &= SXFR_ULTRA2;
   1761 	else
   1762 		scsirate &= SXFR;
   1763 
   1764 	syncrate = &ahc_syncrates[maxsync];
   1765 	while (syncrate->rate != NULL) {
   1766 
   1767 		if ((ahc->features & AHC_ULTRA2) != 0) {
   1768 			if (syncrate->sxfr_u2 == 0)
   1769 				break;
   1770 			else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
   1771 				return (syncrate->period);
   1772 		} else if (scsirate == (syncrate->sxfr & SXFR)) {
   1773 				return (syncrate->period);
   1774 		}
   1775 		syncrate++;
   1776 	}
   1777 	return (0); /* async */
   1778 }
   1779 
   1780 /*
   1781  * Truncate the given synchronous offset to a value the
   1782  * current adapter type and syncrate are capable of.
   1783  */
   1784 void
   1785 ahc_validate_offset(struct ahc_softc *ahc,
   1786 		    struct ahc_initiator_tinfo *tinfo,
   1787 		    struct ahc_syncrate *syncrate,
   1788 		    u_int *offset, int wide, role_t role)
   1789 {
   1790 	u_int maxoffset;
   1791 
   1792 	/* Limit offset to what we can do */
   1793 	if (syncrate == NULL) {
   1794 		maxoffset = 0;
   1795 	} else if ((ahc->features & AHC_ULTRA2) != 0) {
   1796 		maxoffset = MAX_OFFSET_ULTRA2;
   1797 	} else {
   1798 		if (wide)
   1799 			maxoffset = MAX_OFFSET_16BIT;
   1800 		else
   1801 			maxoffset = MAX_OFFSET_8BIT;
   1802 	}
   1803 	*offset = MIN(*offset, maxoffset);
   1804 	if (tinfo != NULL) {
   1805 		if (role == ROLE_TARGET)
   1806 			*offset = MIN(*offset, tinfo->user.offset);
   1807 		else
   1808 			*offset = MIN(*offset, tinfo->goal.offset);
   1809 	}
   1810 }
   1811 
   1812 /*
   1813  * Truncate the given transfer width parameter to a value the
   1814  * current adapter type is capable of.
   1815  */
   1816 void
   1817 ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
   1818 		   u_int *bus_width, role_t role)
   1819 {
   1820 	switch (*bus_width) {
   1821 	default:
   1822 		if (ahc->features & AHC_WIDE) {
   1823 			/* Respond Wide */
   1824 			*bus_width = MSG_EXT_WDTR_BUS_16_BIT;
   1825 			break;
   1826 		}
   1827 		/* FALLTHROUGH */
   1828 	case MSG_EXT_WDTR_BUS_8_BIT:
   1829 		*bus_width = MSG_EXT_WDTR_BUS_8_BIT;
   1830 		break;
   1831 	}
   1832 	if (tinfo != NULL) {
   1833 		if (role == ROLE_TARGET)
   1834 			*bus_width = MIN(tinfo->user.width, *bus_width);
   1835 		else
   1836 			*bus_width = MIN(tinfo->goal.width, *bus_width);
   1837 	}
   1838 }
   1839 
   1840 /*
   1841  * Update the bitmask of targets for which the controller should
   1842  * negotiate with at the next convenient opportunity.  This currently
   1843  * means the next time we send the initial identify messages for
   1844  * a new transaction.
   1845  */
   1846 int
   1847 ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   1848 		       struct ahc_tmode_tstate *tstate,
   1849 		       struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
   1850 {
   1851 	u_int auto_negotiate_orig;
   1852 
   1853 	auto_negotiate_orig = tstate->auto_negotiate;
   1854 	if (neg_type == AHC_NEG_ALWAYS) {
   1855 		/*
   1856 		 * Force our "current" settings to be
   1857 		 * unknown so that unless a bus reset
   1858 		 * occurs the need to renegotiate is
   1859 		 * recorded persistently.
   1860 		 */
   1861 		if ((ahc->features & AHC_WIDE) != 0)
   1862 			tinfo->curr.width = AHC_WIDTH_UNKNOWN;
   1863 		tinfo->curr.period = AHC_PERIOD_UNKNOWN;
   1864 		tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
   1865 	}
   1866 	if (tinfo->curr.period != tinfo->goal.period
   1867 	 || tinfo->curr.width != tinfo->goal.width
   1868 	 || tinfo->curr.offset != tinfo->goal.offset
   1869 	 || tinfo->curr.ppr_options != tinfo->goal.ppr_options
   1870 	 || (neg_type == AHC_NEG_IF_NON_ASYNC
   1871 	  && (tinfo->goal.offset != 0
   1872 	   || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
   1873 	   || tinfo->goal.ppr_options != 0)))
   1874 		tstate->auto_negotiate |= devinfo->target_mask;
   1875 	else
   1876 		tstate->auto_negotiate &= ~devinfo->target_mask;
   1877 
   1878 	return (auto_negotiate_orig != tstate->auto_negotiate);
   1879 }
   1880 
   1881 /*
   1882  * Update the user/goal/curr tables of synchronous negotiation
   1883  * parameters as well as, in the case of a current or active update,
   1884  * any data structures on the host controller.  In the case of an
   1885  * active update, the specified target is currently talking to us on
   1886  * the bus, so the transfer parameter update must take effect
   1887  * immediately.
   1888  */
   1889 void
   1890 ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   1891 		 struct ahc_syncrate *syncrate, u_int period,
   1892 		 u_int offset, u_int ppr_options, u_int type, int paused)
   1893 {
   1894 	struct	ahc_initiator_tinfo *tinfo;
   1895 	struct	ahc_tmode_tstate *tstate;
   1896 	u_int	old_period;
   1897 	u_int	old_offset;
   1898 	u_int	old_ppr;
   1899 	int	active;
   1900 	int	update_needed;
   1901 
   1902 	active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
   1903 	update_needed = 0;
   1904 
   1905 	if (syncrate == NULL) {
   1906 		period = 0;
   1907 		offset = 0;
   1908 	}
   1909 
   1910 	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
   1911 				    devinfo->target, &tstate);
   1912 
   1913 	if ((type & AHC_TRANS_USER) != 0) {
   1914 		tinfo->user.period = period;
   1915 		tinfo->user.offset = offset;
   1916 		tinfo->user.ppr_options = ppr_options;
   1917 	}
   1918 
   1919 	if ((type & AHC_TRANS_GOAL) != 0) {
   1920 		tinfo->goal.period = period;
   1921 		tinfo->goal.offset = offset;
   1922 		tinfo->goal.ppr_options = ppr_options;
   1923 	}
   1924 
   1925 	old_period = tinfo->curr.period;
   1926 	old_offset = tinfo->curr.offset;
   1927 	old_ppr	   = tinfo->curr.ppr_options;
   1928 
   1929 	if ((type & AHC_TRANS_CUR) != 0
   1930 	 && (old_period != period
   1931 	  || old_offset != offset
   1932 	  || old_ppr != ppr_options)) {
   1933 		u_int	scsirate;
   1934 
   1935 		update_needed++;
   1936 		scsirate = tinfo->scsirate;
   1937 		if ((ahc->features & AHC_ULTRA2) != 0) {
   1938 
   1939 			scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
   1940 			if (syncrate != NULL) {
   1941 				scsirate |= syncrate->sxfr_u2;
   1942 				if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
   1943 					scsirate |= ENABLE_CRC;
   1944 				else
   1945 					scsirate |= SINGLE_EDGE;
   1946 			}
   1947 		} else {
   1948 
   1949 			scsirate &= ~(SXFR|SOFS);
   1950 			/*
   1951 			 * Ensure Ultra mode is set properly for
   1952 			 * this target.
   1953 			 */
   1954 			tstate->ultraenb &= ~devinfo->target_mask;
   1955 			if (syncrate != NULL) {
   1956 				if (syncrate->sxfr & ULTRA_SXFR) {
   1957 					tstate->ultraenb |=
   1958 						devinfo->target_mask;
   1959 				}
   1960 				scsirate |= syncrate->sxfr & SXFR;
   1961 				scsirate |= offset & SOFS;
   1962 			}
   1963 			if (active) {
   1964 				u_int sxfrctl0;
   1965 
   1966 				sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
   1967 				sxfrctl0 &= ~FAST20;
   1968 				if (tstate->ultraenb & devinfo->target_mask)
   1969 					sxfrctl0 |= FAST20;
   1970 				ahc_outb(ahc, SXFRCTL0, sxfrctl0);
   1971 			}
   1972 		}
   1973 		if (active) {
   1974 			ahc_outb(ahc, SCSIRATE, scsirate);
   1975 			if ((ahc->features & AHC_ULTRA2) != 0)
   1976 				ahc_outb(ahc, SCSIOFFSET, offset);
   1977 		}
   1978 
   1979 		tinfo->scsirate = scsirate;
   1980 		tinfo->curr.period = period;
   1981 		tinfo->curr.offset = offset;
   1982 		tinfo->curr.ppr_options = ppr_options;
   1983 
   1984 		ahc_send_async(ahc, devinfo->channel, devinfo->target,
   1985 		  CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
   1986 		if (bootverbose) {
   1987 			if (offset != 0) {
   1988 				printf("%s: target %d synchronous at %sMHz%s, "
   1989 				       "offset = 0x%x\n", ahc_name(ahc),
   1990 				       devinfo->target, syncrate->rate,
   1991 				       (ppr_options & MSG_EXT_PPR_DT_REQ)
   1992 				       ? " DT" : "", offset);
   1993 			} else {
   1994 				printf("%s: target %d using "
   1995 				       "asynchronous transfers\n",
   1996 				       ahc_name(ahc), devinfo->target);
   1997 			}
   1998 		}
   1999 	}
   2000 
   2001 	update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
   2002 						tinfo, AHC_NEG_TO_GOAL);
   2003 
   2004 	if (update_needed)
   2005 		ahc_update_pending_scbs(ahc);
   2006 }
   2007 
   2008 /*
   2009  * Update the user/goal/curr tables of wide negotiation
   2010  * parameters as well as, in the case of a current or active update,
   2011  * any data structures on the host controller.  In the case of an
   2012  * active update, the specified target is currently talking to us on
   2013  * the bus, so the transfer parameter update must take effect
   2014  * immediately.
   2015  */
   2016 void
   2017 ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2018 	      u_int width, u_int type, int paused)
   2019 {
   2020 	struct	ahc_initiator_tinfo *tinfo;
   2021 	struct	ahc_tmode_tstate *tstate;
   2022 	u_int	oldwidth;
   2023 	int	active;
   2024 	int	update_needed;
   2025 
   2026 	active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
   2027 	update_needed = 0;
   2028 	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
   2029 				    devinfo->target, &tstate);
   2030 
   2031 	if ((type & AHC_TRANS_USER) != 0)
   2032 		tinfo->user.width = width;
   2033 
   2034 	if ((type & AHC_TRANS_GOAL) != 0)
   2035 		tinfo->goal.width = width;
   2036 
   2037 	oldwidth = tinfo->curr.width;
   2038 	if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
   2039 		u_int	scsirate;
   2040 
   2041 		update_needed++;
   2042 		scsirate =  tinfo->scsirate;
   2043 		scsirate &= ~WIDEXFER;
   2044 		if (width == MSG_EXT_WDTR_BUS_16_BIT)
   2045 			scsirate |= WIDEXFER;
   2046 
   2047 		tinfo->scsirate = scsirate;
   2048 
   2049 		if (active)
   2050 			ahc_outb(ahc, SCSIRATE, scsirate);
   2051 
   2052 		tinfo->curr.width = width;
   2053 
   2054 		ahc_send_async(ahc, devinfo->channel, devinfo->target,
   2055 			       CAM_LUN_WILDCARD, AC_TRANSFER_NEG, NULL);
   2056 		if (bootverbose) {
   2057 			printf("%s: target %d using %dbit transfers\n",
   2058 			       ahc_name(ahc), devinfo->target,
   2059 			       8 * (0x01 << width));
   2060 		}
   2061 	}
   2062 
   2063 	update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
   2064 						tinfo, AHC_NEG_TO_GOAL);
   2065 	if (update_needed)
   2066 		ahc_update_pending_scbs(ahc);
   2067 }
   2068 
   2069 /*
   2070  * Update the current state of tagged queuing for a given target.
   2071  */
   2072 void
   2073 ahc_set_tags(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2074 	     ahc_queue_alg alg)
   2075 {
   2076  	ahc_platform_set_tags(ahc, devinfo, alg);
   2077 }
   2078 
   2079 /*
   2080  * When the transfer settings for a connection change, update any
   2081  * in-transit SCBs to contain the new data so the hardware will
   2082  * be set correctly during future (re)selections.
   2083  */
   2084 static void
   2085 ahc_update_pending_scbs(struct ahc_softc *ahc)
   2086 {
   2087 	struct	scb *pending_scb;
   2088 	int	pending_scb_count;
   2089 	int	i;
   2090 	int	paused;
   2091 	u_int	saved_scbptr;
   2092 
   2093 	/*
   2094 	 * Traverse the pending SCB list and ensure that all of the
   2095 	 * SCBs there have the proper settings.
   2096 	 */
   2097 	pending_scb_count = 0;
   2098 	LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
   2099 		struct ahc_devinfo devinfo;
   2100 		struct hardware_scb *pending_hscb;
   2101 		struct ahc_initiator_tinfo *tinfo;
   2102 		struct ahc_tmode_tstate *tstate;
   2103 
   2104 		ahc_scb_devinfo(ahc, &devinfo, pending_scb);
   2105 		tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
   2106 					    devinfo.our_scsiid,
   2107 					    devinfo.target, &tstate);
   2108 		pending_hscb = pending_scb->hscb;
   2109 		pending_hscb->control &= ~ULTRAENB;
   2110 		if ((tstate->ultraenb & devinfo.target_mask) != 0)
   2111 			pending_hscb->control |= ULTRAENB;
   2112 		pending_hscb->scsirate = tinfo->scsirate;
   2113 		pending_hscb->scsioffset = tinfo->curr.offset;
   2114 		if ((tstate->auto_negotiate & devinfo.target_mask) == 0
   2115 		 && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
   2116 			pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
   2117 			pending_hscb->control &= ~MK_MESSAGE;
   2118 		}
   2119 		ahc_sync_scb(ahc, pending_scb,
   2120 			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
   2121 		pending_scb_count++;
   2122 	}
   2123 
   2124 	if (pending_scb_count == 0)
   2125 		return;
   2126 
   2127 	if (ahc_is_paused(ahc)) {
   2128 		paused = 1;
   2129 	} else {
   2130 		paused = 0;
   2131 		ahc_pause(ahc);
   2132 	}
   2133 
   2134 	saved_scbptr = ahc_inb(ahc, SCBPTR);
   2135 	/* Ensure that the hscbs down on the card match the new information */
   2136 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
   2137 		struct	hardware_scb *pending_hscb;
   2138 		u_int	control;
   2139 		u_int	scb_tag;
   2140 
   2141 		ahc_outb(ahc, SCBPTR, i);
   2142 		scb_tag = ahc_inb(ahc, SCB_TAG);
   2143 		pending_scb = ahc_lookup_scb(ahc, scb_tag);
   2144 		if (pending_scb == NULL)
   2145 			continue;
   2146 
   2147 		pending_hscb = pending_scb->hscb;
   2148 		control = ahc_inb(ahc, SCB_CONTROL);
   2149 		control &= ~(ULTRAENB|MK_MESSAGE);
   2150 		control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
   2151 		ahc_outb(ahc, SCB_CONTROL, control);
   2152 		ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
   2153 		ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
   2154 	}
   2155 	ahc_outb(ahc, SCBPTR, saved_scbptr);
   2156 
   2157 	if (paused == 0)
   2158 		ahc_unpause(ahc);
   2159 }
   2160 
   2161 /**************************** Pathing Information *****************************/
   2162 static void
   2163 ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   2164 {
   2165 	u_int	saved_scsiid;
   2166 	role_t	role;
   2167 	int	our_id;
   2168 
   2169 	if (ahc_inb(ahc, SSTAT0) & TARGET)
   2170 		role = ROLE_TARGET;
   2171 	else
   2172 		role = ROLE_INITIATOR;
   2173 
   2174 	if (role == ROLE_TARGET
   2175 	 && (ahc->features & AHC_MULTI_TID) != 0
   2176 	 && (ahc_inb(ahc, SEQ_FLAGS)
   2177  	   & (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
   2178 		/* We were selected, so pull our id from TARGIDIN */
   2179 		our_id = ahc_inb(ahc, TARGIDIN) & OID;
   2180 	} else if ((ahc->features & AHC_ULTRA2) != 0)
   2181 		our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
   2182 	else
   2183 		our_id = ahc_inb(ahc, SCSIID) & OID;
   2184 
   2185 	saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
   2186 	ahc_compile_devinfo(devinfo,
   2187 			    our_id,
   2188 			    SCSIID_TARGET(ahc, saved_scsiid),
   2189 			    ahc_inb(ahc, SAVED_LUN),
   2190 			    SCSIID_CHANNEL(ahc, saved_scsiid),
   2191 			    role);
   2192 }
   2193 
   2194 struct ahc_phase_table_entry*
   2195 ahc_lookup_phase_entry(int phase)
   2196 {
   2197 	struct ahc_phase_table_entry *entry;
   2198 	struct ahc_phase_table_entry *last_entry;
   2199 
   2200 	/*
   2201 	 * num_phases doesn't include the default entry which
   2202 	 * will be returned if the phase doesn't match.
   2203 	 */
   2204 	last_entry = &ahc_phase_table[num_phases];
   2205 	for (entry = ahc_phase_table; entry < last_entry; entry++) {
   2206 		if (phase == entry->phase)
   2207 			break;
   2208 	}
   2209 	return (entry);
   2210 }
   2211 
   2212 void
   2213 ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
   2214 		    u_int lun, char channel, role_t role)
   2215 {
   2216 	devinfo->our_scsiid = our_id;
   2217 	devinfo->target = target;
   2218 	devinfo->lun = lun;
   2219 	devinfo->target_offset = target;
   2220 	devinfo->channel = channel;
   2221 	devinfo->role = role;
   2222 	if (channel == 'B')
   2223 		devinfo->target_offset += 8;
   2224 	devinfo->target_mask = (0x01 << devinfo->target_offset);
   2225 }
   2226 
   2227 void
   2228 ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   2229 {
   2230 	printf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
   2231 	       devinfo->target, devinfo->lun);
   2232 }
   2233 
   2234 static void
   2235 ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2236 		struct scb *scb)
   2237 {
   2238 	role_t	role;
   2239 	int	our_id;
   2240 
   2241 	our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
   2242 	role = ROLE_INITIATOR;
   2243 	if ((scb->flags & SCB_TARGET_SCB) != 0)
   2244 		role = ROLE_TARGET;
   2245 	ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
   2246 			    SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
   2247 }
   2248 
   2249 
   2250 /************************ Message Phase Processing ****************************/
   2251 static void
   2252 ahc_assert_atn(struct ahc_softc *ahc)
   2253 {
   2254 	u_int scsisigo;
   2255 
   2256 	scsisigo = ATNO;
   2257 	if ((ahc->features & AHC_DT) == 0)
   2258 		scsisigo |= ahc_inb(ahc, SCSISIGI);
   2259 	ahc_outb(ahc, SCSISIGO, scsisigo);
   2260 }
   2261 
   2262 /*
   2263  * When an initiator transaction with the MK_MESSAGE flag either reconnects
   2264  * or enters the initial message out phase, we are interrupted.  Fill our
   2265  * outgoing message buffer with the appropriate message and begin handing
   2266  * the message phase(s) manually.
   2267  */
   2268 static void
   2269 ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2270 			   struct scb *scb)
   2271 {
   2272 	/*
   2273 	 * To facilitate adding multiple messages together,
   2274 	 * each routine should increment the index and len
   2275 	 * variables instead of setting them explicitly.
   2276 	 */
   2277 	ahc->msgout_index = 0;
   2278 	ahc->msgout_len = 0;
   2279 
   2280 	if ((scb->flags & SCB_DEVICE_RESET) == 0
   2281 	 && ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
   2282 		u_int identify_msg;
   2283 
   2284 		identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
   2285 		if ((scb->hscb->control & DISCENB) != 0)
   2286 			identify_msg |= MSG_IDENTIFY_DISCFLAG;
   2287 		ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
   2288 		ahc->msgout_len++;
   2289 
   2290 		if ((scb->hscb->control & TAG_ENB) != 0) {
   2291 			ahc->msgout_buf[ahc->msgout_index++] =
   2292 			    scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
   2293 			ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
   2294 			ahc->msgout_len += 2;
   2295 		}
   2296 	}
   2297 
   2298 	if (scb->flags & SCB_DEVICE_RESET) {
   2299 		ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
   2300 		ahc->msgout_len++;
   2301 		ahc_print_path(ahc, scb);
   2302 		printf("Bus Device Reset Message Sent\n");
   2303 		/*
   2304 		 * Clear our selection hardware in advance of
   2305 		 * the busfree.  We may have an entry in the waiting
   2306 		 * Q for this target, and we don't want to go about
   2307 		 * selecting while we handle the busfree and blow it
   2308 		 * away.
   2309 		 */
   2310 		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
   2311 	} else if ((scb->flags & SCB_ABORT) != 0) {
   2312 		if ((scb->hscb->control & TAG_ENB) != 0)
   2313 			ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
   2314 		else
   2315 			ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
   2316 		ahc->msgout_len++;
   2317 		ahc_print_path(ahc, scb);
   2318 		printf("Abort%s Message Sent\n",
   2319 		       (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
   2320 		/*
   2321 		 * Clear our selection hardware in advance of
   2322 		 * the busfree.  We may have an entry in the waiting
   2323 		 * Q for this target, and we don't want to go about
   2324 		 * selecting while we handle the busfree and blow it
   2325 		 * away.
   2326 		 */
   2327 		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
   2328 	} else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
   2329 		ahc_build_transfer_msg(ahc, devinfo);
   2330 	} else {
   2331 		printf("ahc_intr: AWAITING_MSG for an SCB that "
   2332 		       "does not have a waiting message\n");
   2333 		printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
   2334 		       devinfo->target_mask);
   2335 		panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
   2336 		      "SCB flags = %x", scb->hscb->tag, scb->hscb->control,
   2337 		      ahc_inb(ahc, MSG_OUT), scb->flags);
   2338 	}
   2339 
   2340 	/*
   2341 	 * Clear the MK_MESSAGE flag from the SCB so we aren't
   2342 	 * asked to send this message again.
   2343 	 */
   2344 	ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
   2345 	scb->hscb->control &= ~MK_MESSAGE;
   2346 	ahc->msgout_index = 0;
   2347 	ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
   2348 }
   2349 
   2350 /*
   2351  * Build an appropriate transfer negotiation message for the
   2352  * currently active target.
   2353  */
   2354 static void
   2355 ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   2356 {
   2357 	/*
   2358 	 * We need to initiate transfer negotiations.
   2359 	 * If our current and goal settings are identical,
   2360 	 * we want to renegotiate due to a check condition.
   2361 	 */
   2362 	struct	ahc_initiator_tinfo *tinfo;
   2363 	struct	ahc_tmode_tstate *tstate;
   2364 	struct	ahc_syncrate *rate;
   2365 	int	dowide;
   2366 	int	dosync;
   2367 	int	doppr;
   2368 	u_int	period;
   2369 	u_int	ppr_options;
   2370 	u_int	offset;
   2371 
   2372 	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
   2373 				    devinfo->target, &tstate);
   2374 	/*
   2375 	 * Filter our period based on the current connection.
   2376 	 * If we can't perform DT transfers on this segment (not in LVD
   2377 	 * mode for instance), then our decision to issue a PPR message
   2378 	 * may change.
   2379 	 */
   2380 	period = tinfo->goal.period;
   2381 	ppr_options = tinfo->goal.ppr_options;
   2382 	/* Target initiated PPR is not allowed in the SCSI spec */
   2383 	if (devinfo->role == ROLE_TARGET)
   2384 		ppr_options = 0;
   2385 	rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
   2386 				       &ppr_options, devinfo->role);
   2387 	dowide = tinfo->curr.width != tinfo->goal.width;
   2388 	dosync = tinfo->curr.period != period;
   2389 	/*
   2390 	 * Only use PPR if we have options that need it, even if the device
   2391 	 * claims to support it.  There might be an expander in the way
   2392 	 * that doesn't.
   2393 	 */
   2394 	doppr = ppr_options != 0;
   2395 
   2396 	if (!dowide && !dosync && !doppr) {
   2397 		dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
   2398 		dosync = tinfo->goal.offset != 0;
   2399 	}
   2400 
   2401 	if (!dowide && !dosync && !doppr) {
   2402 		/*
   2403 		 * Force async with a WDTR message if we have a wide bus,
   2404 		 * or just issue an SDTR with a 0 offset.
   2405 		 */
   2406 		if ((ahc->features & AHC_WIDE) != 0)
   2407 			dowide = 1;
   2408 		else
   2409 			dosync = 1;
   2410 
   2411 		if (bootverbose) {
   2412 			ahc_print_devinfo(ahc, devinfo);
   2413 			printf("Ensuring async\n");
   2414 		}
   2415 	}
   2416 
   2417 	/* Target initiated PPR is not allowed in the SCSI spec */
   2418 	if (devinfo->role == ROLE_TARGET)
   2419 		doppr = 0;
   2420 
   2421 	/*
   2422 	 * Both the PPR message and SDTR message require the
   2423 	 * goal syncrate to be limited to what the target device
   2424 	 * is capable of handling (based on whether an LVD->SE
   2425 	 * expander is on the bus), so combine these two cases.
   2426 	 * Regardless, guarantee that if we are using WDTR and SDTR
   2427 	 * messages that WDTR comes first.
   2428 	 */
   2429 	if (doppr || (dosync && !dowide)) {
   2430 
   2431 		offset = tinfo->goal.offset;
   2432 		ahc_validate_offset(ahc, tinfo, rate, &offset,
   2433 				    doppr ? tinfo->goal.width
   2434 					  : tinfo->curr.width,
   2435 				    devinfo->role);
   2436 		if (doppr) {
   2437 			ahc_construct_ppr(ahc, devinfo, period, offset,
   2438 					  tinfo->goal.width, ppr_options);
   2439 		} else {
   2440 			ahc_construct_sdtr(ahc, devinfo, period, offset);
   2441 		}
   2442 	} else {
   2443 		ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
   2444 	}
   2445 }
   2446 
   2447 /*
   2448  * Build a synchronous negotiation message in our message
   2449  * buffer based on the input parameters.
   2450  */
   2451 static void
   2452 ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2453 		   u_int period, u_int offset)
   2454 {
   2455 	if (offset == 0)
   2456 		period = AHC_ASYNC_XFER_PERIOD;
   2457 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
   2458 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR_LEN;
   2459 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_SDTR;
   2460 	ahc->msgout_buf[ahc->msgout_index++] = period;
   2461 	ahc->msgout_buf[ahc->msgout_index++] = offset;
   2462 	ahc->msgout_len += 5;
   2463 	if (bootverbose) {
   2464 		printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
   2465 		       ahc_name(ahc), devinfo->channel, devinfo->target,
   2466 		       devinfo->lun, period, offset);
   2467 	}
   2468 }
   2469 
   2470 /*
   2471  * Build a wide negotiation message in our message
   2472  * buffer based on the input parameters.
   2473  */
   2474 static void
   2475 ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2476 		   u_int bus_width)
   2477 {
   2478 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
   2479 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR_LEN;
   2480 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_WDTR;
   2481 	ahc->msgout_buf[ahc->msgout_index++] = bus_width;
   2482 	ahc->msgout_len += 4;
   2483 	if (bootverbose) {
   2484 		printf("(%s:%c:%d:%d): Sending WDTR %x\n",
   2485 		       ahc_name(ahc), devinfo->channel, devinfo->target,
   2486 		       devinfo->lun, bus_width);
   2487 	}
   2488 }
   2489 
   2490 /*
   2491  * Build a parallel protocol request message in our message
   2492  * buffer based on the input parameters.
   2493  */
   2494 static void
   2495 ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   2496 		  u_int period, u_int offset, u_int bus_width,
   2497 		  u_int ppr_options)
   2498 {
   2499 	if (offset == 0)
   2500 		period = AHC_ASYNC_XFER_PERIOD;
   2501 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXTENDED;
   2502 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR_LEN;
   2503 	ahc->msgout_buf[ahc->msgout_index++] = MSG_EXT_PPR;
   2504 	ahc->msgout_buf[ahc->msgout_index++] = period;
   2505 	ahc->msgout_buf[ahc->msgout_index++] = 0;
   2506 	ahc->msgout_buf[ahc->msgout_index++] = offset;
   2507 	ahc->msgout_buf[ahc->msgout_index++] = bus_width;
   2508 	ahc->msgout_buf[ahc->msgout_index++] = ppr_options;
   2509 	ahc->msgout_len += 8;
   2510 	if (bootverbose) {
   2511 		printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
   2512 		       "offset %x, ppr_options %x\n", ahc_name(ahc),
   2513 		       devinfo->channel, devinfo->target, devinfo->lun,
   2514 		       bus_width, period, offset, ppr_options);
   2515 	}
   2516 }
   2517 
   2518 /*
   2519  * Clear any active message state.
   2520  */
   2521 static void
   2522 ahc_clear_msg_state(struct ahc_softc *ahc)
   2523 {
   2524 	ahc->msgout_len = 0;
   2525 	ahc->msgin_index = 0;
   2526 	ahc->msg_type = MSG_TYPE_NONE;
   2527 	if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
   2528 		/*
   2529 		 * The target didn't care to respond to our
   2530 		 * message request, so clear ATN.
   2531 		 */
   2532 		ahc_outb(ahc, CLRSINT1, CLRATNO);
   2533 	}
   2534 	ahc_outb(ahc, MSG_OUT, MSG_NOOP);
   2535 	ahc_outb(ahc, SEQ_FLAGS2,
   2536 		 ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
   2537 }
   2538 
   2539 static void
   2540 ahc_handle_proto_violation(struct ahc_softc *ahc)
   2541 {
   2542 	struct	ahc_devinfo devinfo;
   2543 	struct	scb *scb;
   2544 	u_int	scbid;
   2545 	u_int	seq_flags;
   2546 	u_int	curphase;
   2547 	u_int	lastphase;
   2548 	int	found;
   2549 
   2550 	ahc_fetch_devinfo(ahc, &devinfo);
   2551 	scbid = ahc_inb(ahc, SCB_TAG);
   2552 	scb = ahc_lookup_scb(ahc, scbid);
   2553 	seq_flags = ahc_inb(ahc, SEQ_FLAGS);
   2554 	curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
   2555 	lastphase = ahc_inb(ahc, LASTPHASE);
   2556 	if ((seq_flags & NOT_IDENTIFIED) != 0) {
   2557 
   2558 		/*
   2559 		 * The reconnecting target either did not send an
   2560 		 * identify message, or did, but we didn't find an SCB
   2561 		 * to match.
   2562 		 */
   2563 		ahc_print_devinfo(ahc, &devinfo);
   2564 		printf("Target did not send an IDENTIFY message. "
   2565 		       "LASTPHASE = 0x%x.\n", lastphase);
   2566 		scb = NULL;
   2567 	} else if (scb == NULL) {
   2568 		/*
   2569 		 * We don't seem to have an SCB active for this
   2570 		 * transaction.  Print an error and reset the bus.
   2571 		 */
   2572 		ahc_print_devinfo(ahc, &devinfo);
   2573 		printf("No SCB found during protocol violation\n");
   2574 		goto proto_violation_reset;
   2575 	} else {
   2576 		ahc_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
   2577 		if ((seq_flags & NO_CDB_SENT) != 0) {
   2578 			ahc_print_path(ahc, scb);
   2579 			printf("No or incomplete CDB sent to device.\n");
   2580 		} else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
   2581 			/*
   2582 			 * The target never bothered to provide status to
   2583 			 * us prior to completing the command.  Since we don't
   2584 			 * know the disposition of this command, we must attempt
   2585 			 * to abort it.  Assert ATN and prepare to send an abort
   2586 			 * message.
   2587 			 */
   2588 			ahc_print_path(ahc, scb);
   2589 			printf("Completed command without status.\n");
   2590 		} else {
   2591 			ahc_print_path(ahc, scb);
   2592 			printf("Unknown protocol violation.\n");
   2593 			ahc_dump_card_state(ahc);
   2594 		}
   2595 	}
   2596 	if ((lastphase & ~P_DATAIN_DT) == 0
   2597 	 || lastphase == P_COMMAND) {
   2598 proto_violation_reset:
   2599 		/*
   2600 		 * Target either went directly to data/command
   2601 		 * phase or didn't respond to our ATN.
   2602 		 * The only safe thing to do is to blow
   2603 		 * it away with a bus reset.
   2604 		 */
   2605 		found = ahc_reset_channel(ahc, 'A', TRUE);
   2606 		printf("%s: Issued Channel %c Bus Reset. "
   2607 		       "%d SCBs aborted\n", ahc_name(ahc), 'A', found);
   2608 	} else {
   2609 		/*
   2610 		 * Leave the selection hardware off in case
   2611 		 * this abort attempt will affect yet to
   2612 		 * be sent commands.
   2613 		 */
   2614 		ahc_outb(ahc, SCSISEQ,
   2615 			 ahc_inb(ahc, SCSISEQ) & ~ENSELO);
   2616 		ahc_assert_atn(ahc);
   2617 		ahc_outb(ahc, MSG_OUT, HOST_MSG);
   2618 		if (scb == NULL) {
   2619 			ahc_print_devinfo(ahc, &devinfo);
   2620 			ahc->msgout_buf[0] = MSG_ABORT_TASK;
   2621 			ahc->msgout_len = 1;
   2622 			ahc->msgout_index = 0;
   2623 			ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
   2624 		} else {
   2625 			ahc_print_path(ahc, scb);
   2626 			scb->flags |= SCB_ABORT;
   2627 		}
   2628 		printf("Protocol violation %s.  Attempting to abort.\n",
   2629 		       ahc_lookup_phase_entry(curphase)->phasemsg);
   2630 	}
   2631 }
   2632 
   2633 /*
   2634  * Manual message loop handler.
   2635  */
   2636 static void
   2637 ahc_handle_message_phase(struct ahc_softc *ahc)
   2638 {
   2639 	struct	ahc_devinfo devinfo;
   2640 	u_int	bus_phase;
   2641 	int	end_session;
   2642 
   2643 	ahc_fetch_devinfo(ahc, &devinfo);
   2644 	end_session = FALSE;
   2645 	bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
   2646 
   2647 reswitch:
   2648 	switch (ahc->msg_type) {
   2649 	case MSG_TYPE_INITIATOR_MSGOUT:
   2650 	{
   2651 		int lastbyte;
   2652 		int phasemis;
   2653 		int msgdone;
   2654 
   2655 		if (ahc->msgout_len == 0)
   2656 			panic("HOST_MSG_LOOP interrupt with no active message");
   2657 
   2658 #ifdef AHC_DEBUG
   2659 		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
   2660 			ahc_print_devinfo(ahc, &devinfo);
   2661 			printf("INITIATOR_MSG_OUT");
   2662 		}
   2663 #endif
   2664 		phasemis = bus_phase != P_MESGOUT;
   2665 		if (phasemis) {
   2666 #ifdef AHC_DEBUG
   2667 			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
   2668 				printf(" PHASEMIS %s\n",
   2669 				       ahc_lookup_phase_entry(bus_phase)
   2670 							     ->phasemsg);
   2671 			}
   2672 #endif
   2673 			if (bus_phase == P_MESGIN) {
   2674 				/*
   2675 				 * Change gears and see if
   2676 				 * this messages is of interest to
   2677 				 * us or should be passed back to
   2678 				 * the sequencer.
   2679 				 */
   2680 				ahc_outb(ahc, CLRSINT1, CLRATNO);
   2681 				ahc->send_msg_perror = FALSE;
   2682 				ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
   2683 				ahc->msgin_index = 0;
   2684 				goto reswitch;
   2685 			}
   2686 			end_session = TRUE;
   2687 			break;
   2688 		}
   2689 
   2690 		if (ahc->send_msg_perror) {
   2691 			ahc_outb(ahc, CLRSINT1, CLRATNO);
   2692 			ahc_outb(ahc, CLRSINT1, CLRREQINIT);
   2693 #ifdef AHC_DEBUG
   2694 			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
   2695 				printf(" byte 0x%x\n", ahc->send_msg_perror);
   2696 #endif
   2697 			ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
   2698 			break;
   2699 		}
   2700 
   2701 		msgdone	= ahc->msgout_index == ahc->msgout_len;
   2702 		if (msgdone) {
   2703 			/*
   2704 			 * The target has requested a retry.
   2705 			 * Re-assert ATN, reset our message index to
   2706 			 * 0, and try again.
   2707 			 */
   2708 			ahc->msgout_index = 0;
   2709 			ahc_assert_atn(ahc);
   2710 		}
   2711 
   2712 		lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
   2713 		if (lastbyte) {
   2714 			/* Last byte is signified by dropping ATN */
   2715 			ahc_outb(ahc, CLRSINT1, CLRATNO);
   2716 		}
   2717 
   2718 		/*
   2719 		 * Clear our interrupt status and present
   2720 		 * the next byte on the bus.
   2721 		 */
   2722 		ahc_outb(ahc, CLRSINT1, CLRREQINIT);
   2723 #ifdef AHC_DEBUG
   2724 		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
   2725 			printf(" byte 0x%x\n",
   2726 			       ahc->msgout_buf[ahc->msgout_index]);
   2727 #endif
   2728 		ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
   2729 		break;
   2730 	}
   2731 	case MSG_TYPE_INITIATOR_MSGIN:
   2732 	{
   2733 		int phasemis;
   2734 		int message_done;
   2735 
   2736 #ifdef AHC_DEBUG
   2737 		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
   2738 			ahc_print_devinfo(ahc, &devinfo);
   2739 			printf("INITIATOR_MSG_IN");
   2740 		}
   2741 #endif
   2742 		phasemis = bus_phase != P_MESGIN;
   2743 		if (phasemis) {
   2744 #ifdef AHC_DEBUG
   2745 			if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
   2746 				printf(" PHASEMIS %s\n",
   2747 				       ahc_lookup_phase_entry(bus_phase)
   2748 							     ->phasemsg);
   2749 			}
   2750 #endif
   2751 			ahc->msgin_index = 0;
   2752 			if (bus_phase == P_MESGOUT
   2753 			 && (ahc->send_msg_perror == TRUE
   2754 			  || (ahc->msgout_len != 0
   2755 			   && ahc->msgout_index == 0))) {
   2756 				ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
   2757 				goto reswitch;
   2758 			}
   2759 			end_session = TRUE;
   2760 			break;
   2761 		}
   2762 
   2763 		/* Pull the byte in without acking it */
   2764 		ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIBUSL);
   2765 #ifdef AHC_DEBUG
   2766 		if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
   2767 			printf(" byte 0x%x\n",
   2768 			       ahc->msgin_buf[ahc->msgin_index]);
   2769 #endif
   2770 
   2771 		message_done = ahc_parse_msg(ahc, &devinfo);
   2772 
   2773 		if (message_done) {
   2774 			/*
   2775 			 * Clear our incoming message buffer in case there
   2776 			 * is another message following this one.
   2777 			 */
   2778 			ahc->msgin_index = 0;
   2779 
   2780 			/*
   2781 			 * If this message illicited a response,
   2782 			 * assert ATN so the target takes us to the
   2783 			 * message out phase.
   2784 			 */
   2785 			if (ahc->msgout_len != 0) {
   2786 #ifdef AHC_DEBUG
   2787 				if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
   2788 					ahc_print_devinfo(ahc, &devinfo);
   2789 					printf("Asserting ATN for response\n");
   2790 				}
   2791 #endif
   2792 				ahc_assert_atn(ahc);
   2793 			}
   2794 		} else
   2795 			ahc->msgin_index++;
   2796 
   2797 		if (message_done == MSGLOOP_TERMINATED) {
   2798 			end_session = TRUE;
   2799 		} else {
   2800 			/* Ack the byte */
   2801 			ahc_outb(ahc, CLRSINT1, CLRREQINIT);
   2802 			ahc_inb(ahc, SCSIDATL);
   2803 		}
   2804 		break;
   2805 	}
   2806 	case MSG_TYPE_TARGET_MSGIN:
   2807 	{
   2808 		int msgdone;
   2809 		int msgout_request;
   2810 
   2811 		if (ahc->msgout_len == 0)
   2812 			panic("Target MSGIN with no active message");
   2813 
   2814 		/*
   2815 		 * If we interrupted a mesgout session, the initiator
   2816 		 * will not know this until our first REQ.  So, we
   2817 		 * only honor mesgout requests after we've sent our
   2818 		 * first byte.
   2819 		 */
   2820 		if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0
   2821 		 && ahc->msgout_index > 0)
   2822 			msgout_request = TRUE;
   2823 		else
   2824 			msgout_request = FALSE;
   2825 
   2826 		if (msgout_request) {
   2827 
   2828 			/*
   2829 			 * Change gears and see if
   2830 			 * this messages is of interest to
   2831 			 * us or should be passed back to
   2832 			 * the sequencer.
   2833 			 */
   2834 			ahc->msg_type = MSG_TYPE_TARGET_MSGOUT;
   2835 			ahc_outb(ahc, SCSISIGO, P_MESGOUT | BSYO);
   2836 			ahc->msgin_index = 0;
   2837 			/* Dummy read to REQ for first byte */
   2838 			ahc_inb(ahc, SCSIDATL);
   2839 			ahc_outb(ahc, SXFRCTL0,
   2840 				 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
   2841 			break;
   2842 		}
   2843 
   2844 		msgdone = ahc->msgout_index == ahc->msgout_len;
   2845 		if (msgdone) {
   2846 			ahc_outb(ahc, SXFRCTL0,
   2847 				 ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
   2848 			end_session = TRUE;
   2849 			break;
   2850 		}
   2851 
   2852 		/*
   2853 		 * Present the next byte on the bus.
   2854 		 */
   2855 		ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) | SPIOEN);
   2856 		ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
   2857 		break;
   2858 	}
   2859 	case MSG_TYPE_TARGET_MSGOUT:
   2860 	{
   2861 		int lastbyte;
   2862 		int msgdone;
   2863 
   2864 		/*
   2865 		 * The initiator signals that this is
   2866 		 * the last byte by dropping ATN.
   2867 		 */
   2868 		lastbyte = (ahc_inb(ahc, SCSISIGI) & ATNI) == 0;
   2869 
   2870 		/*
   2871 		 * Read the latched byte, but turn off SPIOEN first
   2872 		 * so that we don't inadvertently cause a REQ for the
   2873 		 * next byte.
   2874 		 */
   2875 		ahc_outb(ahc, SXFRCTL0, ahc_inb(ahc, SXFRCTL0) & ~SPIOEN);
   2876 		ahc->msgin_buf[ahc->msgin_index] = ahc_inb(ahc, SCSIDATL);
   2877 		msgdone = ahc_parse_msg(ahc, &devinfo);
   2878 		if (msgdone == MSGLOOP_TERMINATED) {
   2879 			/*
   2880 			 * The message is *really* done in that it caused
   2881 			 * us to go to bus free.  The sequencer has already
   2882 			 * been reset at this point, so pull the ejection
   2883 			 * handle.
   2884 			 */
   2885 			return;
   2886 		}
   2887 
   2888 		ahc->msgin_index++;
   2889 
   2890 		/*
   2891 		 * XXX Read spec about initiator dropping ATN too soon
   2892 		 *     and use msgdone to detect it.
   2893 		 */
   2894 		if (msgdone == MSGLOOP_MSGCOMPLETE) {
   2895 			ahc->msgin_index = 0;
   2896 
   2897 			/*
   2898 			 * If this message illicited a response, transition
   2899 			 * to the Message in phase and send it.
   2900 			 */
   2901 			if (ahc->msgout_len != 0) {
   2902 				ahc_outb(ahc, SCSISIGO, P_MESGIN | BSYO);
   2903 				ahc_outb(ahc, SXFRCTL0,
   2904 					 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
   2905 				ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
   2906 				ahc->msgin_index = 0;
   2907 				break;
   2908 			}
   2909 		}
   2910 
   2911 		if (lastbyte)
   2912 			end_session = TRUE;
   2913 		else {
   2914 			/* Ask for the next byte. */
   2915 			ahc_outb(ahc, SXFRCTL0,
   2916 				 ahc_inb(ahc, SXFRCTL0) | SPIOEN);
   2917 		}
   2918 
   2919 		break;
   2920 	}
   2921 	default:
   2922 		panic("Unknown REQINIT message type");
   2923 	}
   2924 
   2925 	if (end_session) {
   2926 		ahc_clear_msg_state(ahc);
   2927 		ahc_outb(ahc, RETURN_1, EXIT_MSG_LOOP);
   2928 	} else
   2929 		ahc_outb(ahc, RETURN_1, CONT_MSG_LOOP);
   2930 }
   2931 
   2932 /*
   2933  * See if we sent a particular extended message to the target.
   2934  * If "full" is true, return true only if the target saw the full
   2935  * message.  If "full" is false, return true if the target saw at
   2936  * least the first byte of the message.
   2937  */
   2938 static int
   2939 ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type, u_int msgval, int full)
   2940 {
   2941 	int found;
   2942 	u_int index;
   2943 
   2944 	found = FALSE;
   2945 	index = 0;
   2946 
   2947 	while (index < ahc->msgout_len) {
   2948 		if (ahc->msgout_buf[index] == MSG_EXTENDED) {
   2949 			u_int end_index;
   2950 
   2951 			end_index = index + 1 + ahc->msgout_buf[index + 1];
   2952 			if (ahc->msgout_buf[index+2] == msgval
   2953 			 && type == AHCMSG_EXT) {
   2954 
   2955 				if (full) {
   2956 					if (ahc->msgout_index > end_index)
   2957 						found = TRUE;
   2958 				} else if (ahc->msgout_index > index)
   2959 					found = TRUE;
   2960 			}
   2961 			index = end_index;
   2962 		} else if (ahc->msgout_buf[index] >= MSG_SIMPLE_TASK
   2963 			&& ahc->msgout_buf[index] <= MSG_IGN_WIDE_RESIDUE) {
   2964 
   2965 			/* Skip tag type and tag id or residue param*/
   2966 			index += 2;
   2967 		} else {
   2968 			/* Single byte message */
   2969 			if (type == AHCMSG_1B
   2970 			 && ahc->msgout_buf[index] == msgval
   2971 			 && ahc->msgout_index > index)
   2972 				found = TRUE;
   2973 			index++;
   2974 		}
   2975 
   2976 		if (found)
   2977 			break;
   2978 	}
   2979 	return (found);
   2980 }
   2981 
   2982 /*
   2983  * Wait for a complete incoming message, parse it, and respond accordingly.
   2984  */
   2985 static int
   2986 ahc_parse_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   2987 {
   2988 	struct	ahc_initiator_tinfo *tinfo;
   2989 	struct	ahc_tmode_tstate *tstate;
   2990 	int	reject;
   2991 	int	done;
   2992 	int	response;
   2993 	u_int	targ_scsirate;
   2994 
   2995 	done = MSGLOOP_IN_PROG;
   2996 	response = FALSE;
   2997 	reject = FALSE;
   2998 	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
   2999 				    devinfo->target, &tstate);
   3000 	targ_scsirate = tinfo->scsirate;
   3001 
   3002 	/*
   3003 	 * Parse as much of the message as is available,
   3004 	 * rejecting it if we don't support it.  When
   3005 	 * the entire message is available and has been
   3006 	 * handled, return MSGLOOP_MSGCOMPLETE, indicating
   3007 	 * that we have parsed an entire message.
   3008 	 *
   3009 	 * In the case of extended messages, we accept the length
   3010 	 * byte outright and perform more checking once we know the
   3011 	 * extended message type.
   3012 	 */
   3013 	switch (ahc->msgin_buf[0]) {
   3014 	case MSG_DISCONNECT:
   3015 	case MSG_SAVEDATAPOINTER:
   3016 	case MSG_CMDCOMPLETE:
   3017 	case MSG_RESTOREPOINTERS:
   3018 	case MSG_IGN_WIDE_RESIDUE:
   3019 		/*
   3020 		 * End our message loop as these are messages
   3021 		 * the sequencer handles on its own.
   3022 		 */
   3023 		done = MSGLOOP_TERMINATED;
   3024 		break;
   3025 	case MSG_MESSAGE_REJECT:
   3026 		response = ahc_handle_msg_reject(ahc, devinfo);
   3027 		/* FALLTHROUGH */
   3028 	case MSG_NOOP:
   3029 		done = MSGLOOP_MSGCOMPLETE;
   3030 		break;
   3031 	case MSG_EXTENDED:
   3032 	{
   3033 		/* Wait for enough of the message to begin validation */
   3034 		if (ahc->msgin_index < 2)
   3035 			break;
   3036 		switch (ahc->msgin_buf[2]) {
   3037 		case MSG_EXT_SDTR:
   3038 		{
   3039 			struct	 ahc_syncrate *syncrate;
   3040 			u_int	 period;
   3041 			u_int	 ppr_options;
   3042 			u_int	 offset;
   3043 			u_int	 saved_offset;
   3044 
   3045 			if (ahc->msgin_buf[1] != MSG_EXT_SDTR_LEN) {
   3046 				reject = TRUE;
   3047 				break;
   3048 			}
   3049 
   3050 			/*
   3051 			 * Wait until we have both args before validating
   3052 			 * and acting on this message.
   3053 			 *
   3054 			 * Add one to MSG_EXT_SDTR_LEN to account for
   3055 			 * the extended message preamble.
   3056 			 */
   3057 			if (ahc->msgin_index < (MSG_EXT_SDTR_LEN + 1))
   3058 				break;
   3059 
   3060 			period = ahc->msgin_buf[3];
   3061 			ppr_options = 0;
   3062 			saved_offset = offset = ahc->msgin_buf[4];
   3063 			syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
   3064 							   &ppr_options,
   3065 							   devinfo->role);
   3066 			ahc_validate_offset(ahc, tinfo, syncrate, &offset,
   3067 					    targ_scsirate & WIDEXFER,
   3068 					    devinfo->role);
   3069 			if (bootverbose) {
   3070 				printf("(%s:%c:%d:%d): Received "
   3071 				       "SDTR period %x, offset %x\n\t"
   3072 				       "Filtered to period %x, offset %x\n",
   3073 				       ahc_name(ahc), devinfo->channel,
   3074 				       devinfo->target, devinfo->lun,
   3075 				       ahc->msgin_buf[3], saved_offset,
   3076 				       period, offset);
   3077 			}
   3078 			ahc_set_syncrate(ahc, devinfo,
   3079 					 syncrate, period,
   3080 					 offset, ppr_options,
   3081 					 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3082 					 /*paused*/TRUE);
   3083 
   3084 			/*
   3085 			 * See if we initiated Sync Negotiation
   3086 			 * and didn't have to fall down to async
   3087 			 * transfers.
   3088 			 */
   3089 			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, TRUE)) {
   3090 				/* We started it */
   3091 				if (saved_offset != offset) {
   3092 					/* Went too low - force async */
   3093 					reject = TRUE;
   3094 				}
   3095 			} else {
   3096 				/*
   3097 				 * Send our own SDTR in reply
   3098 				 */
   3099 				if (bootverbose
   3100 				 && devinfo->role == ROLE_INITIATOR) {
   3101 					printf("(%s:%c:%d:%d): Target "
   3102 					       "Initiated SDTR\n",
   3103 					       ahc_name(ahc), devinfo->channel,
   3104 					       devinfo->target, devinfo->lun);
   3105 				}
   3106 				ahc->msgout_index = 0;
   3107 				ahc->msgout_len = 0;
   3108 				ahc_construct_sdtr(ahc, devinfo,
   3109 						   period, offset);
   3110 				ahc->msgout_index = 0;
   3111 				response = TRUE;
   3112 			}
   3113 			done = MSGLOOP_MSGCOMPLETE;
   3114 			break;
   3115 		}
   3116 		case MSG_EXT_WDTR:
   3117 		{
   3118 			u_int bus_width;
   3119 			u_int saved_width;
   3120 			u_int sending_reply;
   3121 
   3122 			sending_reply = FALSE;
   3123 			if (ahc->msgin_buf[1] != MSG_EXT_WDTR_LEN) {
   3124 				reject = TRUE;
   3125 				break;
   3126 			}
   3127 
   3128 			/*
   3129 			 * Wait until we have our arg before validating
   3130 			 * and acting on this message.
   3131 			 *
   3132 			 * Add one to MSG_EXT_WDTR_LEN to account for
   3133 			 * the extended message preamble.
   3134 			 */
   3135 			if (ahc->msgin_index < (MSG_EXT_WDTR_LEN + 1))
   3136 				break;
   3137 
   3138 			bus_width = ahc->msgin_buf[3];
   3139 			saved_width = bus_width;
   3140 			ahc_validate_width(ahc, tinfo, &bus_width,
   3141 					   devinfo->role);
   3142 			if (bootverbose) {
   3143 				printf("(%s:%c:%d:%d): Received WDTR "
   3144 				       "%x filtered to %x\n",
   3145 				       ahc_name(ahc), devinfo->channel,
   3146 				       devinfo->target, devinfo->lun,
   3147 				       saved_width, bus_width);
   3148 			}
   3149 
   3150 			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, TRUE)) {
   3151 				/*
   3152 				 * Don't send a WDTR back to the
   3153 				 * target, since we asked first.
   3154 				 * If the width went higher than our
   3155 				 * request, reject it.
   3156 				 */
   3157 				if (saved_width > bus_width) {
   3158 					reject = TRUE;
   3159 					printf("(%s:%c:%d:%d): requested %dBit "
   3160 					       "transfers.  Rejecting...\n",
   3161 					       ahc_name(ahc), devinfo->channel,
   3162 					       devinfo->target, devinfo->lun,
   3163 					       8 * (0x01 << bus_width));
   3164 					bus_width = 0;
   3165 				}
   3166 			} else {
   3167 				/*
   3168 				 * Send our own WDTR in reply
   3169 				 */
   3170 				if (bootverbose
   3171 				 && devinfo->role == ROLE_INITIATOR) {
   3172 					printf("(%s:%c:%d:%d): Target "
   3173 					       "Initiated WDTR\n",
   3174 					       ahc_name(ahc), devinfo->channel,
   3175 					       devinfo->target, devinfo->lun);
   3176 				}
   3177 				ahc->msgout_index = 0;
   3178 				ahc->msgout_len = 0;
   3179 				ahc_construct_wdtr(ahc, devinfo, bus_width);
   3180 				ahc->msgout_index = 0;
   3181 				response = TRUE;
   3182 				sending_reply = TRUE;
   3183 			}
   3184 			ahc_set_width(ahc, devinfo, bus_width,
   3185 				      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3186 				      /*paused*/TRUE);
   3187 			/* After a wide message, we are async */
   3188 			ahc_set_syncrate(ahc, devinfo,
   3189 					 /*syncrate*/NULL, /*period*/0,
   3190 					 /*offset*/0, /*ppr_options*/0,
   3191 					 AHC_TRANS_ACTIVE, /*paused*/TRUE);
   3192 			if (sending_reply == FALSE && reject == FALSE) {
   3193 
   3194 				if (tinfo->goal.offset) {
   3195 					ahc->msgout_index = 0;
   3196 					ahc->msgout_len = 0;
   3197 					ahc_build_transfer_msg(ahc, devinfo);
   3198 					ahc->msgout_index = 0;
   3199 					response = TRUE;
   3200 				}
   3201 			}
   3202 			done = MSGLOOP_MSGCOMPLETE;
   3203 			break;
   3204 		}
   3205 		case MSG_EXT_PPR:
   3206 		{
   3207 			struct	ahc_syncrate *syncrate;
   3208 			u_int	period;
   3209 			u_int	offset;
   3210 			u_int	bus_width;
   3211 			u_int	ppr_options;
   3212 			u_int	saved_width;
   3213 			u_int	saved_offset;
   3214 			u_int	saved_ppr_options;
   3215 
   3216 			if (ahc->msgin_buf[1] != MSG_EXT_PPR_LEN) {
   3217 				reject = TRUE;
   3218 				break;
   3219 			}
   3220 
   3221 			/*
   3222 			 * Wait until we have all args before validating
   3223 			 * and acting on this message.
   3224 			 *
   3225 			 * Add one to MSG_EXT_PPR_LEN to account for
   3226 			 * the extended message preamble.
   3227 			 */
   3228 			if (ahc->msgin_index < (MSG_EXT_PPR_LEN + 1))
   3229 				break;
   3230 
   3231 			period = ahc->msgin_buf[3];
   3232 			offset = ahc->msgin_buf[5];
   3233 			bus_width = ahc->msgin_buf[6];
   3234 			saved_width = bus_width;
   3235 			ppr_options = ahc->msgin_buf[7];
   3236 			/*
   3237 			 * According to the spec, a DT only
   3238 			 * period factor with no DT option
   3239 			 * set implies async.
   3240 			 */
   3241 			if ((ppr_options & MSG_EXT_PPR_DT_REQ) == 0
   3242 			 && period == 9)
   3243 				offset = 0;
   3244 			saved_ppr_options = ppr_options;
   3245 			saved_offset = offset;
   3246 
   3247 			/*
   3248 			 * Mask out any options we don't support
   3249 			 * on any controller.  Transfer options are
   3250 			 * only available if we are negotiating wide.
   3251 			 */
   3252 			ppr_options &= MSG_EXT_PPR_DT_REQ;
   3253 			if (bus_width == 0)
   3254 				ppr_options = 0;
   3255 
   3256 			ahc_validate_width(ahc, tinfo, &bus_width,
   3257 					   devinfo->role);
   3258 			syncrate = ahc_devlimited_syncrate(ahc, tinfo, &period,
   3259 							   &ppr_options,
   3260 							   devinfo->role);
   3261 			ahc_validate_offset(ahc, tinfo, syncrate,
   3262 					    &offset, bus_width,
   3263 					    devinfo->role);
   3264 
   3265 			if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, TRUE)) {
   3266 				/*
   3267 				 * If we are unable to do any of the
   3268 				 * requested options (we went too low),
   3269 				 * then we'll have to reject the message.
   3270 				 */
   3271 				if (saved_width > bus_width
   3272 				 || saved_offset != offset
   3273 				 || saved_ppr_options != ppr_options) {
   3274 					reject = TRUE;
   3275 					period = 0;
   3276 					offset = 0;
   3277 					bus_width = 0;
   3278 					ppr_options = 0;
   3279 					syncrate = NULL;
   3280 				}
   3281 			} else {
   3282 				if (devinfo->role != ROLE_TARGET)
   3283 					printf("(%s:%c:%d:%d): Target "
   3284 					       "Initiated PPR\n",
   3285 					       ahc_name(ahc), devinfo->channel,
   3286 					       devinfo->target, devinfo->lun);
   3287 				else
   3288 					printf("(%s:%c:%d:%d): Initiator "
   3289 					       "Initiated PPR\n",
   3290 					       ahc_name(ahc), devinfo->channel,
   3291 					       devinfo->target, devinfo->lun);
   3292 				ahc->msgout_index = 0;
   3293 				ahc->msgout_len = 0;
   3294 				ahc_construct_ppr(ahc, devinfo, period, offset,
   3295 						  bus_width, ppr_options);
   3296 				ahc->msgout_index = 0;
   3297 				response = TRUE;
   3298 			}
   3299 			if (bootverbose) {
   3300 				printf("(%s:%c:%d:%d): Received PPR width %x, "
   3301 				       "period %x, offset %x,options %x\n"
   3302 				       "\tFiltered to width %x, period %x, "
   3303 				       "offset %x, options %x\n",
   3304 				       ahc_name(ahc), devinfo->channel,
   3305 				       devinfo->target, devinfo->lun,
   3306 				       saved_width, ahc->msgin_buf[3],
   3307 				       saved_offset, saved_ppr_options,
   3308 				       bus_width, period, offset, ppr_options);
   3309 			}
   3310 			ahc_set_width(ahc, devinfo, bus_width,
   3311 				      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3312 				      /*paused*/TRUE);
   3313 			ahc_set_syncrate(ahc, devinfo,
   3314 					 syncrate, period,
   3315 					 offset, ppr_options,
   3316 					 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3317 					 /*paused*/TRUE);
   3318 			done = MSGLOOP_MSGCOMPLETE;
   3319 			break;
   3320 		}
   3321 		default:
   3322 			/* Unknown extended message.  Reject it. */
   3323 			reject = TRUE;
   3324 			break;
   3325 		}
   3326 		break;
   3327 	}
   3328 #ifdef AHC_TARGET_MODE
   3329 	case MSG_BUS_DEV_RESET:
   3330 		ahc_handle_devreset(ahc, devinfo,
   3331 				    CAM_BDR_SENT,
   3332 				    "Bus Device Reset Received",
   3333 				    /*verbose_level*/0);
   3334 		ahc_restart(ahc);
   3335 		done = MSGLOOP_TERMINATED;
   3336 		break;
   3337 	case MSG_ABORT_TAG:
   3338 	case MSG_ABORT:
   3339 	case MSG_CLEAR_QUEUE:
   3340 	{
   3341 		int tag;
   3342 
   3343 		/* Target mode messages */
   3344 		if (devinfo->role != ROLE_TARGET) {
   3345 			reject = TRUE;
   3346 			break;
   3347 		}
   3348 		tag = SCB_LIST_NULL;
   3349 		if (ahc->msgin_buf[0] == MSG_ABORT_TAG)
   3350 			tag = ahc_inb(ahc, INITIATOR_TAG);
   3351 		ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
   3352 			       devinfo->lun, tag, ROLE_TARGET,
   3353 			       CAM_REQ_ABORTED);
   3354 
   3355 		tstate = ahc->enabled_targets[devinfo->our_scsiid];
   3356 		if (tstate != NULL) {
   3357 			struct ahc_tmode_lstate* lstate;
   3358 
   3359 			lstate = tstate->enabled_luns[devinfo->lun];
   3360 			if (lstate != NULL) {
   3361 				ahc_queue_lstate_event(ahc, lstate,
   3362 						       devinfo->our_scsiid,
   3363 						       ahc->msgin_buf[0],
   3364 						       /*arg*/tag);
   3365 				ahc_send_lstate_events(ahc, lstate);
   3366 			}
   3367 		}
   3368 		ahc_restart(ahc);
   3369 		done = MSGLOOP_TERMINATED;
   3370 		break;
   3371 	}
   3372 #endif
   3373 	case MSG_TERM_IO_PROC:
   3374 	default:
   3375 		reject = TRUE;
   3376 		break;
   3377 	}
   3378 
   3379 	if (reject) {
   3380 		/*
   3381 		 * Setup to reject the message.
   3382 		 */
   3383 		ahc->msgout_index = 0;
   3384 		ahc->msgout_len = 1;
   3385 		ahc->msgout_buf[0] = MSG_MESSAGE_REJECT;
   3386 		done = MSGLOOP_MSGCOMPLETE;
   3387 		response = TRUE;
   3388 	}
   3389 
   3390 	if (done != MSGLOOP_IN_PROG && !response)
   3391 		/* Clear the outgoing message buffer */
   3392 		ahc->msgout_len = 0;
   3393 
   3394 	return (done);
   3395 }
   3396 
   3397 /*
   3398  * Process a message reject message.
   3399  */
   3400 static int
   3401 ahc_handle_msg_reject(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   3402 {
   3403 	/*
   3404 	 * What we care about here is if we had an
   3405 	 * outstanding SDTR or WDTR message for this
   3406 	 * target.  If we did, this is a signal that
   3407 	 * the target is refusing negotiation.
   3408 	 */
   3409 	struct scb *scb;
   3410 	struct ahc_initiator_tinfo *tinfo;
   3411 	struct ahc_tmode_tstate *tstate;
   3412 	u_int scb_index;
   3413 	u_int last_msg;
   3414 	int   response = 0;
   3415 
   3416 	scb_index = ahc_inb(ahc, SCB_TAG);
   3417 	scb = ahc_lookup_scb(ahc, scb_index);
   3418 	tinfo = ahc_fetch_transinfo(ahc, devinfo->channel,
   3419 				    devinfo->our_scsiid,
   3420 				    devinfo->target, &tstate);
   3421 	/* Might be necessary */
   3422 	last_msg = ahc_inb(ahc, LAST_MSG);
   3423 
   3424 	if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_PPR, /*full*/FALSE)) {
   3425 		/*
   3426 		 * Target does not support the PPR message.
   3427 		 * Attempt to negotiate SPI-2 style.
   3428 		 */
   3429 		if (bootverbose) {
   3430 			printf("(%s:%c:%d:%d): PPR Rejected. "
   3431 			       "Trying WDTR/SDTR\n",
   3432 			       ahc_name(ahc), devinfo->channel,
   3433 			       devinfo->target, devinfo->lun);
   3434 		}
   3435 		tinfo->goal.ppr_options = 0;
   3436 		tinfo->curr.transport_version = 2;
   3437 		tinfo->goal.transport_version = 2;
   3438 		ahc->msgout_index = 0;
   3439 		ahc->msgout_len = 0;
   3440 		ahc_build_transfer_msg(ahc, devinfo);
   3441 		ahc->msgout_index = 0;
   3442 		response = 1;
   3443 	} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_WDTR, /*full*/FALSE)) {
   3444 
   3445 		/* note 8bit xfers */
   3446 		if (bootverbose)
   3447 			printf("(%s:%c:%d:%d): refuses WIDE negotiation. Using "
   3448 			       "8bit transfers\n", ahc_name(ahc),
   3449 			       devinfo->channel, devinfo->target, devinfo->lun);
   3450 		ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
   3451 			      AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3452 			      /*paused*/TRUE);
   3453 		/*
   3454 		 * No need to clear the sync rate.  If the target
   3455 		 * did not accept the command, our syncrate is
   3456 		 * unaffected.  If the target started the negotiation,
   3457 		 * but rejected our response, we already cleared the
   3458 		 * sync rate before sending our WDTR.
   3459 		 */
   3460 		if (tinfo->goal.offset != tinfo->curr.offset) {
   3461 
   3462 			/* Start the sync negotiation */
   3463 			ahc->msgout_index = 0;
   3464 			ahc->msgout_len = 0;
   3465 			ahc_build_transfer_msg(ahc, devinfo);
   3466 			ahc->msgout_index = 0;
   3467 			response = 1;
   3468 		}
   3469 	} else if (ahc_sent_msg(ahc, AHCMSG_EXT, MSG_EXT_SDTR, /*full*/FALSE)) {
   3470 		/* note asynch xfers and clear flag */
   3471 		ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL, /*period*/0,
   3472 				 /*offset*/0, /*ppr_options*/0,
   3473 				 AHC_TRANS_ACTIVE|AHC_TRANS_GOAL,
   3474 				 /*paused*/TRUE);
   3475 		if (bootverbose)
   3476 			printf("(%s:%c:%d:%d): refuses synchronous negotiation."
   3477 			       " Using asynchronous transfers\n",
   3478 			       ahc_name(ahc), devinfo->channel,
   3479 			       devinfo->target, devinfo->lun);
   3480 	} else if ((scb->hscb->control & MSG_SIMPLE_TASK) != 0) {
   3481 		int tag_type;
   3482 		int mask;
   3483 
   3484 		tag_type = (scb->hscb->control & MSG_SIMPLE_TASK);
   3485 
   3486 		if (tag_type == MSG_SIMPLE_TASK) {
   3487 			if (bootverbose)
   3488 				printf("(%s:%c:%d:%d): refuses tagged commands."
   3489 				       " Performing non-tagged I/O\n",
   3490 					ahc_name(ahc), devinfo->channel,
   3491 					devinfo->target, devinfo->lun);
   3492 			ahc_set_tags(ahc, devinfo, AHC_QUEUE_NONE);
   3493 			mask = ~0x23;
   3494 		} else {
   3495 			if (bootverbose)
   3496 				printf("(%s:%c:%d:%d): refuses %s tagged "
   3497 				       "commands. Performing simple queue "
   3498 				       "tagged I/O only\n",
   3499 				       ahc_name(ahc), devinfo->channel,
   3500 				       devinfo->target, devinfo->lun,
   3501 				       tag_type == MSG_ORDERED_TASK
   3502 				         ? "ordered" : "head of queue");
   3503 			ahc_set_tags(ahc, devinfo, AHC_QUEUE_BASIC);
   3504 			mask = ~0x03;
   3505 		}
   3506 
   3507 		/*
   3508 		 * Resend the identify for this CCB as the target
   3509 		 * may believe that the selection is invalid otherwise.
   3510 		 */
   3511 		ahc_outb(ahc, SCB_CONTROL,
   3512 			 ahc_inb(ahc, SCB_CONTROL) & mask);
   3513 	 	scb->hscb->control &= mask;
   3514 		ahc_set_transaction_tag(scb, /*enabled*/FALSE,
   3515 					/*type*/MSG_SIMPLE_TASK);
   3516 		ahc_outb(ahc, MSG_OUT, MSG_IDENTIFYFLAG);
   3517 		ahc_assert_atn(ahc);
   3518 
   3519 		/*
   3520 		 * This transaction is now at the head of
   3521 		 * the untagged queue for this target.
   3522 		 */
   3523 		if ((ahc->flags & AHC_SCB_BTT) == 0) {
   3524 			struct scb_tailq *untagged_q;
   3525 
   3526 			untagged_q =
   3527 			    &(ahc->untagged_queues[devinfo->target_offset]);
   3528 			TAILQ_INSERT_HEAD(untagged_q, scb, links.tqe);
   3529 			scb->flags |= SCB_UNTAGGEDQ;
   3530 		}
   3531 		ahc_busy_tcl(ahc, BUILD_TCL(scb->hscb->scsiid, devinfo->lun),
   3532 			     scb->hscb->tag);
   3533 
   3534 		/*
   3535 		 * Requeue all tagged commands for this target
   3536 		 * currently in our possession so they can be
   3537 		 * converted to untagged commands.
   3538 		 */
   3539 		ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
   3540 				   SCB_GET_CHANNEL(ahc, scb),
   3541 				   SCB_GET_LUN(scb), /*tag*/SCB_LIST_NULL,
   3542 				   ROLE_INITIATOR, CAM_REQUEUE_REQ,
   3543 				   SEARCH_COMPLETE);
   3544 	} else {
   3545 		/*
   3546 		 * Otherwise, we ignore it.
   3547 		 */
   3548 		if (bootverbose)
   3549 			printf("%s:%c:%d: Message reject for %x -- ignored\n",
   3550 			       ahc_name(ahc), devinfo->channel, devinfo->target,
   3551 			       last_msg);
   3552 	}
   3553 	return (response);
   3554 }
   3555 
   3556 /*
   3557  * Process an ingnore wide residue message.
   3558  */
   3559 static void
   3560 ahc_handle_ign_wide_residue(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
   3561 {
   3562 	u_int scb_index;
   3563 	struct scb *scb;
   3564 
   3565 	scb_index = ahc_inb(ahc, SCB_TAG);
   3566 	scb = ahc_lookup_scb(ahc, scb_index);
   3567 	/*
   3568 	 * XXX Actually check data direction in the sequencer?
   3569 	 * Perhaps add datadir to some spare bits in the hscb?
   3570 	 */
   3571 	if ((ahc_inb(ahc, SEQ_FLAGS) & DPHASE) == 0
   3572 	 || ahc_get_transfer_dir(scb) != CAM_DIR_IN) {
   3573 		/*
   3574 		 * Ignore the message if we haven't
   3575 		 * seen an appropriate data phase yet.
   3576 		 */
   3577 	} else {
   3578 		/*
   3579 		 * If the residual occurred on the last
   3580 		 * transfer and the transfer request was
   3581 		 * expected to end on an odd count, do
   3582 		 * nothing.  Otherwise, subtract a byte
   3583 		 * and update the residual count accordingly.
   3584 		 */
   3585 		uint32_t sgptr;
   3586 
   3587 		sgptr = ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
   3588 		if ((sgptr & SG_LIST_NULL) != 0
   3589 		 && ahc_inb(ahc, DATA_COUNT_ODD) == 1) {
   3590 			/*
   3591 			 * If the residual occurred on the last
   3592 			 * transfer and the transfer request was
   3593 			 * expected to end on an odd count, do
   3594 			 * nothing.
   3595 			 */
   3596 		} else {
   3597 			struct ahc_dma_seg *sg;
   3598 			uint32_t data_cnt;
   3599 			uint32_t data_addr;
   3600 			uint32_t sglen;
   3601 
   3602 			/* Pull in the rest of the sgptr */
   3603 			sgptr |= (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 3) << 24)
   3604 			      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 2) << 16)
   3605 			      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 1) << 8);
   3606 			sgptr &= SG_PTR_MASK;
   3607 			data_cnt = (ahc_inb(ahc, SCB_RESIDUAL_DATACNT+3) << 24)
   3608 				 | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT+2) << 16)
   3609 				 | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT+1) << 8)
   3610 				 | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT));
   3611 
   3612 			data_addr = (ahc_inb(ahc, SHADDR + 3) << 24)
   3613 				  | (ahc_inb(ahc, SHADDR + 2) << 16)
   3614 				  | (ahc_inb(ahc, SHADDR + 1) << 8)
   3615 				  | (ahc_inb(ahc, SHADDR));
   3616 
   3617 			data_cnt += 1;
   3618 			data_addr -= 1;
   3619 
   3620 			sg = ahc_sg_bus_to_virt(scb, sgptr);
   3621 			/*
   3622 			 * The residual sg ptr points to the next S/G
   3623 			 * to load so we must go back one.
   3624 			 */
   3625 			sg--;
   3626 			sglen = ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
   3627 			if (sg != scb->sg_list
   3628 			 && sglen < (data_cnt & AHC_SG_LEN_MASK)) {
   3629 
   3630 				sg--;
   3631 				sglen = ahc_le32toh(sg->len);
   3632 				/*
   3633 				 * Preserve High Address and SG_LIST bits
   3634 				 * while setting the count to 1.
   3635 				 */
   3636 				data_cnt = 1 | (sglen & (~AHC_SG_LEN_MASK));
   3637 				data_addr = ahc_le32toh(sg->addr)
   3638 					  + (sglen & AHC_SG_LEN_MASK) - 1;
   3639 
   3640 				/*
   3641 				 * Increment sg so it points to the
   3642 				 * "next" sg.
   3643 				 */
   3644 				sg++;
   3645 				sgptr = ahc_sg_virt_to_bus(scb, sg);
   3646 				ahc_outb(ahc, SCB_RESIDUAL_SGPTR + 3,
   3647 					 sgptr >> 24);
   3648 				ahc_outb(ahc, SCB_RESIDUAL_SGPTR + 2,
   3649 					 sgptr >> 16);
   3650 				ahc_outb(ahc, SCB_RESIDUAL_SGPTR + 1,
   3651 					 sgptr >> 8);
   3652 				ahc_outb(ahc, SCB_RESIDUAL_SGPTR, sgptr);
   3653 			}
   3654 
   3655 			ahc_outb(ahc, SCB_RESIDUAL_DATACNT + 3, data_cnt >> 24);
   3656 			ahc_outb(ahc, SCB_RESIDUAL_DATACNT + 2, data_cnt >> 16);
   3657 			ahc_outb(ahc, SCB_RESIDUAL_DATACNT + 1, data_cnt >> 8);
   3658 			ahc_outb(ahc, SCB_RESIDUAL_DATACNT, data_cnt);
   3659 		}
   3660 	}
   3661 }
   3662 
   3663 
   3664 /*
   3665  * Reinitialize the data pointers for the active transfer
   3666  * based on its current residual.
   3667  */
   3668 static void
   3669 ahc_reinitialize_dataptrs(struct ahc_softc *ahc)
   3670 {
   3671 	struct	 scb *scb;
   3672 	struct	 ahc_dma_seg *sg;
   3673 	u_int	 scb_index;
   3674 	uint32_t sgptr;
   3675 	uint32_t resid;
   3676 	uint32_t dataptr;
   3677 
   3678 	scb_index = ahc_inb(ahc, SCB_TAG);
   3679 	scb = ahc_lookup_scb(ahc, scb_index);
   3680 	sgptr = (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 3) << 24)
   3681 	      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 2) << 16)
   3682 	      | (ahc_inb(ahc, SCB_RESIDUAL_SGPTR + 1) << 8)
   3683 	      |	ahc_inb(ahc, SCB_RESIDUAL_SGPTR);
   3684 
   3685 	sgptr &= SG_PTR_MASK;
   3686 	sg = ahc_sg_bus_to_virt(scb, sgptr);
   3687 
   3688 	/* The residual sg_ptr always points to the next sg */
   3689 	sg--;
   3690 
   3691 	resid = (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 2) << 16)
   3692 	      | (ahc_inb(ahc, SCB_RESIDUAL_DATACNT + 1) << 8)
   3693 	      | ahc_inb(ahc, SCB_RESIDUAL_DATACNT);
   3694 
   3695 	dataptr = ahc_le32toh(sg->addr)
   3696 		+ (ahc_le32toh(sg->len) & AHC_SG_LEN_MASK)
   3697 		- resid;
   3698 	if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
   3699 		u_int dscommand1;
   3700 
   3701 		dscommand1 = ahc_inb(ahc, DSCOMMAND1);
   3702 		ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
   3703 		ahc_outb(ahc, HADDR,
   3704 			 (ahc_le32toh(sg->len) >> 24) & SG_HIGH_ADDR_BITS);
   3705 		ahc_outb(ahc, DSCOMMAND1, dscommand1);
   3706 	}
   3707 	ahc_outb(ahc, HADDR + 3, dataptr >> 24);
   3708 	ahc_outb(ahc, HADDR + 2, dataptr >> 16);
   3709 	ahc_outb(ahc, HADDR + 1, dataptr >> 8);
   3710 	ahc_outb(ahc, HADDR, dataptr);
   3711 	ahc_outb(ahc, HCNT + 2, resid >> 16);
   3712 	ahc_outb(ahc, HCNT + 1, resid >> 8);
   3713 	ahc_outb(ahc, HCNT, resid);
   3714 	if ((ahc->features & AHC_ULTRA2) == 0) {
   3715 		ahc_outb(ahc, STCNT + 2, resid >> 16);
   3716 		ahc_outb(ahc, STCNT + 1, resid >> 8);
   3717 		ahc_outb(ahc, STCNT, resid);
   3718 	}
   3719 }
   3720 
   3721 /*
   3722  * Handle the effects of issuing a bus device reset message.
   3723  */
   3724 static void
   3725 ahc_handle_devreset(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   3726 		    cam_status status, const char *message, int verbose_level)
   3727 {
   3728 #ifdef AHC_TARGET_MODE
   3729 	struct ahc_tmode_tstate* tstate;
   3730 	u_int lun;
   3731 #endif
   3732 	int found;
   3733 
   3734 	found = ahc_abort_scbs(ahc, devinfo->target, devinfo->channel,
   3735 			       CAM_LUN_WILDCARD, SCB_LIST_NULL, devinfo->role,
   3736 			       status);
   3737 
   3738 #ifdef AHC_TARGET_MODE
   3739 	/*
   3740 	 * Send an immediate notify ccb to all target mord peripheral
   3741 	 * drivers affected by this action.
   3742 	 */
   3743 	tstate = ahc->enabled_targets[devinfo->our_scsiid];
   3744 	if (tstate != NULL) {
   3745 		for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
   3746 			struct ahc_tmode_lstate* lstate;
   3747 
   3748 			lstate = tstate->enabled_luns[lun];
   3749 			if (lstate == NULL)
   3750 				continue;
   3751 
   3752 			ahc_queue_lstate_event(ahc, lstate, devinfo->our_scsiid,
   3753 					       MSG_BUS_DEV_RESET, /*arg*/0);
   3754 			ahc_send_lstate_events(ahc, lstate);
   3755 		}
   3756 	}
   3757 #endif
   3758 
   3759 	/*
   3760 	 * Go back to async/narrow transfers and renegotiate.
   3761 	 */
   3762 	ahc_set_width(ahc, devinfo, MSG_EXT_WDTR_BUS_8_BIT,
   3763 		      AHC_TRANS_CUR, /*paused*/TRUE);
   3764 	ahc_set_syncrate(ahc, devinfo, /*syncrate*/NULL,
   3765 			 /*period*/0, /*offset*/0, /*ppr_options*/0,
   3766 			 AHC_TRANS_CUR, /*paused*/TRUE);
   3767 
   3768 	ahc_send_async(ahc, devinfo->channel, devinfo->target,
   3769 	  CAM_LUN_WILDCARD, AC_SENT_BDR, NULL);
   3770 
   3771 	if (message != NULL
   3772 	 && (verbose_level <= bootverbose))
   3773 		printf("%s: %s on %c:%d. %d SCBs aborted\n", ahc_name(ahc),
   3774 		       message, devinfo->channel, devinfo->target, found);
   3775 }
   3776 
   3777 #ifdef AHC_TARGET_MODE
   3778 static void
   3779 ahc_setup_target_msgin(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
   3780 		       struct scb *scb)
   3781 {
   3782 
   3783 	/*
   3784 	 * To facilitate adding multiple messages together,
   3785 	 * each routine should increment the index and len
   3786 	 * variables instead of setting them explicitly.
   3787 	 */
   3788 	ahc->msgout_index = 0;
   3789 	ahc->msgout_len = 0;
   3790 
   3791 	if (scb != NULL && (scb->flags & SCB_AUTO_NEGOTIATE) != 0)
   3792 		ahc_build_transfer_msg(ahc, devinfo);
   3793 	else
   3794 		panic("ahc_intr: AWAITING target message with no message");
   3795 
   3796 	ahc->msgout_index = 0;
   3797 	ahc->msg_type = MSG_TYPE_TARGET_MSGIN;
   3798 }
   3799 #endif
   3800 
   3801 int
   3802 ahc_softc_init(struct ahc_softc *ahc)
   3803 {
   3804 
   3805 	/* The IRQMS bit is only valid on VL and EISA chips */
   3806 	if ((ahc->chip & AHC_PCI) == 0)
   3807 		ahc->unpause = ahc_inb(ahc, HCNTRL) & IRQMS;
   3808 	else
   3809 		ahc->unpause = 0;
   3810 	ahc->pause = ahc->unpause | PAUSE;
   3811 	/* XXX The shared scb data stuff should be deprecated */
   3812 	if (ahc->scb_data == NULL) {
   3813 		ahc->scb_data = malloc(sizeof(*ahc->scb_data),
   3814 				       M_DEVBUF, M_NOWAIT);
   3815 		if (ahc->scb_data == NULL)
   3816 			return (ENOMEM);
   3817 		memset(ahc->scb_data, 0, sizeof(*ahc->scb_data));
   3818 	}
   3819 
   3820 	return (0);
   3821 }
   3822 
   3823 void
   3824 ahc_softc_insert(struct ahc_softc *ahc)
   3825 {
   3826 	struct ahc_softc *list_ahc;
   3827 
   3828 #if AHC_PCI_CONFIG > 0
   3829 	/*
   3830 	 * Second Function PCI devices need to inherit some
   3831 	 * settings from function 0.
   3832 	 */
   3833 	if ((ahc->chip & AHC_BUS_MASK) == AHC_PCI
   3834 	 && (ahc->features & AHC_MULTI_FUNC) != 0) {
   3835 		TAILQ_FOREACH(list_ahc, &ahc_tailq, links) {
   3836 			ahc_dev_softc_t list_pci;
   3837 			ahc_dev_softc_t pci;
   3838 
   3839 			list_pci = list_ahc->dev_softc;
   3840 			pci = ahc->dev_softc;
   3841 			if (ahc_get_pci_slot(list_pci) == ahc_get_pci_slot(pci)
   3842 			 && ahc_get_pci_bus(list_pci) == ahc_get_pci_bus(pci)) {
   3843 				struct ahc_softc *master;
   3844 				struct ahc_softc *slave;
   3845 
   3846 				if (ahc_get_pci_function(list_pci) == 0) {
   3847 					master = list_ahc;
   3848 					slave = ahc;
   3849 				} else {
   3850 					master = ahc;
   3851 					slave = list_ahc;
   3852 				}
   3853 				slave->flags &= ~AHC_BIOS_ENABLED;
   3854 				slave->flags |=
   3855 				    master->flags & AHC_BIOS_ENABLED;
   3856 				slave->flags &= ~AHC_PRIMARY_CHANNEL;
   3857 				slave->flags |=
   3858 				    master->flags & AHC_PRIMARY_CHANNEL;
   3859 				break;
   3860 			}
   3861 		}
   3862 	}
   3863 #endif
   3864 
   3865 	/*
   3866 	 * Insertion sort into our list of softcs.
   3867 	 */
   3868 	list_ahc = TAILQ_FIRST(&ahc_tailq);
   3869 	while (list_ahc != NULL
   3870 	    && ahc_softc_comp(list_ahc, ahc) <= 0)
   3871 		list_ahc = TAILQ_NEXT(list_ahc, links);
   3872 	if (list_ahc != NULL)
   3873 		TAILQ_INSERT_BEFORE(list_ahc, ahc, links);
   3874 	else
   3875 		TAILQ_INSERT_TAIL(&ahc_tailq, ahc, links);
   3876 	ahc->init_level++;
   3877 }
   3878 
   3879 /*
   3880  * Verify that the passed in softc pointer is for a
   3881  * controller that is still configured.
   3882  */
   3883 struct ahc_softc *
   3884 ahc_find_softc(struct ahc_softc *ahc)
   3885 {
   3886 	struct ahc_softc *list_ahc;
   3887 
   3888 	TAILQ_FOREACH(list_ahc, &ahc_tailq, links) {
   3889 		if (list_ahc == ahc)
   3890 			return (ahc);
   3891 	}
   3892 	return (NULL);
   3893 }
   3894 
   3895 void
   3896 ahc_set_unit(struct ahc_softc *ahc, int unit)
   3897 {
   3898 	ahc->unit = unit;
   3899 }
   3900 
   3901 void
   3902 ahc_set_name(struct ahc_softc *ahc, char *name)
   3903 {
   3904 	if (ahc->name != NULL)
   3905 		free(ahc->name, M_DEVBUF);
   3906 	ahc->name = name;
   3907 }
   3908 
   3909 void
   3910 ahc_free(struct ahc_softc *ahc)
   3911 {
   3912 	int i;
   3913 
   3914 	ahc_fini_scbdata(ahc);
   3915 	switch (ahc->init_level) {
   3916 	default:
   3917 	case 2:
   3918 		ahc_shutdown(ahc);
   3919 		/* TAILQ_REMOVE(&ahc_tailq, ahc, links); XXX */
   3920 		/* FALLTHROUGH */
   3921 	case 1:
   3922 		bus_dmamap_unload(ahc->parent_dmat, ahc->shared_data_dmamap);
   3923 		bus_dmamap_destroy(ahc->parent_dmat, ahc->shared_data_dmamap);
   3924 		bus_dmamem_unmap(ahc->parent_dmat, (caddr_t)ahc->qoutfifo, ahc->shared_data_size);
   3925 		bus_dmamem_free(ahc->parent_dmat, &ahc->shared_data_seg, ahc->shared_data_nseg);
   3926 		break;
   3927 	case 0:
   3928 		break;
   3929 	}
   3930 
   3931 	ahc_platform_free(ahc);
   3932 	for (i = 0; i < AHC_NUM_TARGETS; i++) {
   3933 		struct ahc_tmode_tstate *tstate;
   3934 
   3935 		tstate = ahc->enabled_targets[i];
   3936 		if (tstate != NULL) {
   3937 #if AHC_TARGET_MODE
   3938 			int j;
   3939 
   3940 			for (j = 0; j < AHC_NUM_LUNS; j++) {
   3941 				struct ahc_tmode_lstate *lstate;
   3942 
   3943 				lstate = tstate->enabled_luns[j];
   3944 				if (lstate != NULL) {
   3945 					  /*xpt_free_path(lstate->path);*/
   3946 					free(lstate, M_DEVBUF);
   3947 				}
   3948 			}
   3949 #endif
   3950 			free(tstate, M_DEVBUF);
   3951 		}
   3952 	}
   3953 #if AHC_TARGET_MODE
   3954 	if (ahc->black_hole != NULL) {
   3955 	  /*xpt_free_path(ahc->black_hole->path);*/
   3956 		free(ahc->black_hole, M_DEVBUF);
   3957 	}
   3958 #endif
   3959 #ifndef __NetBSD__
   3960 	if (ahc->name != NULL)
   3961 		free(ahc->name, M_DEVBUF);
   3962 #endif
   3963 	if (ahc->seep_config != NULL)
   3964 		free(ahc->seep_config, M_DEVBUF);
   3965 #if !defined(__FreeBSD__) && !defined(__NetBSD__)
   3966 	free(ahc, M_DEVBUF);
   3967 #endif
   3968 	return;
   3969 }
   3970 
   3971 void
   3972 ahc_shutdown(void *arg)
   3973 {
   3974 	struct	ahc_softc *ahc;
   3975 	int	i;
   3976 
   3977 	ahc = (struct ahc_softc *)arg;
   3978 
   3979 	/* This will reset most registers to 0, but not all */
   3980 	ahc_reset(ahc);
   3981 	ahc_outb(ahc, SCSISEQ, 0);
   3982 	ahc_outb(ahc, SXFRCTL0, 0);
   3983 	ahc_outb(ahc, DSPCISTATUS, 0);
   3984 
   3985 	for (i = TARG_SCSIRATE; i < SCSICONF; i++)
   3986 		ahc_outb(ahc, i, 0);
   3987 }
   3988 
   3989 /*
   3990  * Reset the controller and record some information about it
   3991  * that is only available just after a reset.
   3992  */
   3993 int
   3994 ahc_reset(struct ahc_softc *ahc)
   3995 {
   3996 	u_int	sblkctl;
   3997 	u_int	sxfrctl1_a, sxfrctl1_b;
   3998 	int	wait;
   3999 
   4000 	/*
   4001 	 * Preserve the value of the SXFRCTL1 register for all channels.
   4002 	 * It contains settings that affect termination and we don't want
   4003 	 * to disturb the integrity of the bus.
   4004 	 */
   4005 	ahc_pause(ahc);
   4006 	if ((ahc_inb(ahc, HCNTRL) & CHIPRST) != 0) {
   4007 		/*
   4008 		 * The chip has not been initialized since
   4009 		 * PCI/EISA/VLB bus reset.  Don't trust
   4010 		 * "left over BIOS data".
   4011 		 */
   4012 		ahc->flags |= AHC_NO_BIOS_INIT;
   4013 	}
   4014 	sxfrctl1_b = 0;
   4015 	if ((ahc->chip & AHC_CHIPID_MASK) == AHC_AIC7770) {
   4016 		u_int sblkctl1;
   4017 
   4018 		/*
   4019 		 * Save channel B's settings in case this chip
   4020 		 * is setup for TWIN channel operation.
   4021 		 */
   4022 		sblkctl1 = ahc_inb(ahc, SBLKCTL);
   4023 		ahc_outb(ahc, SBLKCTL, sblkctl1 | SELBUSB);
   4024 		sxfrctl1_b = ahc_inb(ahc, SXFRCTL1);
   4025 		ahc_outb(ahc, SBLKCTL, sblkctl1 & ~SELBUSB);
   4026 	}
   4027 	sxfrctl1_a = ahc_inb(ahc, SXFRCTL1);
   4028 
   4029 	ahc_outb(ahc, HCNTRL, CHIPRST | ahc->pause);
   4030 
   4031 	/*
   4032 	 * Ensure that the reset has finished.  We delay 1000us
   4033 	 * prior to reading the register to make sure the chip
   4034 	 * has sufficiently completed its reset to handle register
   4035 	 * accesses.
   4036 	 */
   4037 	wait = 1000;
   4038 	do {
   4039 		ahc_delay(1000);
   4040 	} while (--wait && !(ahc_inb(ahc, HCNTRL) & CHIPRSTACK));
   4041 
   4042 	if (wait == 0) {
   4043 		printf("%s: WARNING - Failed chip reset!  "
   4044 		       "Trying to initialize anyway.\n", ahc_name(ahc));
   4045 	}
   4046 	ahc_outb(ahc, HCNTRL, ahc->pause);
   4047 
   4048 	/* Determine channel configuration */
   4049 	sblkctl = ahc_inb(ahc, SBLKCTL) & (SELBUSB|SELWIDE);
   4050 	/* No Twin Channel PCI cards */
   4051 	if ((ahc->chip & AHC_PCI) != 0)
   4052 		sblkctl &= ~SELBUSB;
   4053 	switch (sblkctl) {
   4054 	case 0:
   4055 		/* Single Narrow Channel */
   4056 		break;
   4057 	case 2:
   4058 		/* Wide Channel */
   4059 		ahc->features |= AHC_WIDE;
   4060 		break;
   4061 	case 8:
   4062 		/* Twin Channel */
   4063 		ahc->features |= AHC_TWIN;
   4064 		break;
   4065 	default:
   4066 		printf(" Unsupported adapter type (0x%x).  Ignoring\n", sblkctl);
   4067 		return(-1);
   4068 	}
   4069 
   4070 	/*
   4071 	 * Reload sxfrctl1.
   4072 	 *
   4073 	 * We must always initialize STPWEN to 1 before we
   4074 	 * restore the saved values.  STPWEN is initialized
   4075 	 * to a tri-state condition which can only be cleared
   4076 	 * by turning it on.
   4077 	 */
   4078 	if ((ahc->features & AHC_TWIN) != 0) {
   4079 		u_int sblkctl1;
   4080 
   4081 		sblkctl1 = ahc_inb(ahc, SBLKCTL);
   4082 		ahc_outb(ahc, SBLKCTL, sblkctl1 | SELBUSB);
   4083 		ahc_outb(ahc, SXFRCTL1, sxfrctl1_b);
   4084 		ahc_outb(ahc, SBLKCTL, sblkctl1 & ~SELBUSB);
   4085 	}
   4086 	ahc_outb(ahc, SXFRCTL1, sxfrctl1_a);
   4087 
   4088 #ifdef AHC_DUMP_SEQ
   4089 	if (ahc->init_level == 0)
   4090 		ahc_dumpseq(ahc);
   4091 #endif
   4092 
   4093 	return (0);
   4094 }
   4095 
   4096 /*
   4097  * Determine the number of SCBs available on the controller
   4098  */
   4099 int
   4100 ahc_probe_scbs(struct ahc_softc *ahc) {
   4101 	int i;
   4102 
   4103 	for (i = 0; i < AHC_SCB_MAX; i++) {
   4104 
   4105 		ahc_outb(ahc, SCBPTR, i);
   4106 		ahc_outb(ahc, SCB_BASE, i);
   4107 		if (ahc_inb(ahc, SCB_BASE) != i)
   4108 			break;
   4109 		ahc_outb(ahc, SCBPTR, 0);
   4110 		if (ahc_inb(ahc, SCB_BASE) != 0)
   4111 			break;
   4112 	}
   4113 	return (i);
   4114 }
   4115 
   4116 #if 0
   4117 static void
   4118 ahc_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
   4119 {
   4120 	bus_addr_t *baddr;
   4121 
   4122 	baddr = (bus_addr_t *)arg;
   4123 	*baddr = segs->ds_addr;
   4124 }
   4125 #endif
   4126 
   4127 static void
   4128 ahc_build_free_scb_list(struct ahc_softc *ahc)
   4129 {
   4130 	int scbsize;
   4131 	int i;
   4132 
   4133 	scbsize = 32;
   4134 	if ((ahc->flags & AHC_LSCBS_ENABLED) != 0)
   4135 		scbsize = 64;
   4136 
   4137 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
   4138 		int j;
   4139 
   4140 		ahc_outb(ahc, SCBPTR, i);
   4141 
   4142 		/*
   4143 		 * Touch all SCB bytes to avoid parity errors
   4144 		 * should one of our debugging routines read
   4145 		 * an otherwise uninitiatlized byte.
   4146 		 */
   4147 		for (j = 0; j < scbsize; j++)
   4148 			ahc_outb(ahc, SCB_BASE+j, 0xFF);
   4149 
   4150 		/* Clear the control byte. */
   4151 		ahc_outb(ahc, SCB_CONTROL, 0);
   4152 
   4153 		/* Set the next pointer */
   4154 		if ((ahc->flags & AHC_PAGESCBS) != 0)
   4155 			ahc_outb(ahc, SCB_NEXT, i+1);
   4156 		else
   4157 			ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
   4158 
   4159 		/* Make the tag number, SCSIID, and lun invalid */
   4160 		ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
   4161 		ahc_outb(ahc, SCB_SCSIID, 0xFF);
   4162 		ahc_outb(ahc, SCB_LUN, 0xFF);
   4163 	}
   4164 
   4165 	/* Make sure that the last SCB terminates the free list */
   4166 	ahc_outb(ahc, SCBPTR, i-1);
   4167 	ahc_outb(ahc, SCB_NEXT, SCB_LIST_NULL);
   4168 }
   4169 
   4170 static int
   4171 ahc_init_scbdata(struct ahc_softc *ahc)
   4172 {
   4173 	struct scb_data *scb_data;
   4174 
   4175 	scb_data = ahc->scb_data;
   4176 	SLIST_INIT(&scb_data->free_scbs);
   4177 	SLIST_INIT(&scb_data->sg_maps);
   4178 
   4179 	/* Allocate SCB resources */
   4180 	scb_data->scbarray =
   4181 	    (struct scb *)malloc(sizeof(struct scb) * AHC_SCB_MAX_ALLOC,
   4182 				 M_DEVBUF, M_NOWAIT);
   4183 	if (scb_data->scbarray == NULL)
   4184 		return (ENOMEM);
   4185 	memset(scb_data->scbarray, 0, sizeof(struct scb) * AHC_SCB_MAX_ALLOC);
   4186 
   4187 	/* Determine the number of hardware SCBs and initialize them */
   4188 
   4189 	scb_data->maxhscbs = ahc_probe_scbs(ahc);
   4190 	if ((ahc->flags & AHC_PAGESCBS) != 0) {
   4191 		/* SCB 0 heads the free list */
   4192 		ahc_outb(ahc, FREE_SCBH, 0);
   4193 	} else {
   4194 		ahc_outb(ahc, FREE_SCBH, SCB_LIST_NULL);
   4195 	}
   4196 
   4197 	if (ahc->scb_data->maxhscbs == 0) {
   4198 		printf("%s: No SCB space found\n", ahc_name(ahc));
   4199 		return (ENXIO);
   4200 	}
   4201 
   4202 	ahc_build_free_scb_list(ahc);
   4203 
   4204 	/*
   4205 	 * Create our DMA tags.  These tags define the kinds of device
   4206 	 * accessible memory allocations and memory mappings we will
   4207 	 * need to perform during normal operation.
   4208 	 *
   4209 	 * Unless we need to further restrict the allocation, we rely
   4210 	 * on the restrictions of the parent dmat, hence the common
   4211 	 * use of MAXADDR and MAXSIZE.
   4212 	 */
   4213 
   4214 	if (ahc_createdmamem(ahc->parent_dmat,
   4215 	     AHC_SCB_MAX * sizeof(struct hardware_scb), ahc->sc_dmaflags,
   4216 	     &scb_data->hscb_dmamap,
   4217 	     (caddr_t *)&scb_data->hscbs, &scb_data->hscb_busaddr,
   4218 	     &scb_data->hscb_seg, &scb_data->hscb_nseg, ahc_name(ahc),
   4219 	     "hardware SCB structures") < 0)
   4220 		goto error_exit;
   4221 
   4222 	scb_data->init_level++;
   4223 
   4224 	if (ahc_createdmamem(ahc->parent_dmat,
   4225 	     AHC_SCB_MAX * sizeof(struct scsi_sense_data), ahc->sc_dmaflags,
   4226 	     &scb_data->sense_dmamap, (caddr_t *)&scb_data->sense,
   4227 	     &scb_data->sense_busaddr, &scb_data->sense_seg,
   4228 	     &scb_data->sense_nseg, ahc_name(ahc), "sense buffers") < 0)
   4229 		goto error_exit;
   4230 
   4231 	scb_data->init_level++;
   4232 
   4233 	/* Perform initial CCB allocation */
   4234 	memset(scb_data->hscbs, 0,
   4235 	       AHC_SCB_MAX_ALLOC * sizeof(struct hardware_scb));
   4236 	ahc_alloc_scbs(ahc);
   4237 	scb_data->init_level++;
   4238 
   4239 	if (scb_data->numscbs == 0) {
   4240 		printf("%s: ahc_init_scbdata - "
   4241 		       "Unable to allocate initial scbs\n",
   4242 		       ahc_name(ahc));
   4243 		goto error_exit;
   4244 	}
   4245 
   4246 	/*
   4247 	 * Tell the sequencer which SCB will be the next one it receives.
   4248 	 */
   4249 	ahc->next_queued_scb = ahc_get_scb(ahc);
   4250 	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
   4251 
   4252 	/*
   4253 	 * Note that we were successfull
   4254 	 */
   4255 	return (0);
   4256 
   4257 error_exit:
   4258 
   4259 	return (ENOMEM);
   4260 }
   4261 
   4262 static void
   4263 ahc_fini_scbdata(struct ahc_softc *ahc)
   4264 {
   4265 	struct scb_data *scb_data;
   4266 
   4267 	scb_data = ahc->scb_data;
   4268 	if (scb_data == NULL)
   4269 		return;
   4270 
   4271 	switch (scb_data->init_level) {
   4272 	default:
   4273 	case 5:
   4274 	{
   4275 		struct sg_map_node *sg_map;
   4276 
   4277 		while ((sg_map = SLIST_FIRST(&scb_data->sg_maps))!= NULL) {
   4278 			SLIST_REMOVE_HEAD(&scb_data->sg_maps, links);
   4279 			ahc_freedmamem(ahc->parent_dmat, PAGE_SIZE,
   4280 			    sg_map->sg_dmamap, (caddr_t)sg_map->sg_vaddr,
   4281 			    &sg_map->sg_dmasegs, sg_map->sg_nseg);
   4282 			free(sg_map, M_DEVBUF);
   4283 		}
   4284 	}
   4285 	/*FALLTHROUGH*/
   4286 	case 4:
   4287 		ahc_freedmamem(ahc->parent_dmat,
   4288 		    AHC_SCB_MAX * sizeof(struct scsi_sense_data),
   4289 		    scb_data->sense_dmamap, (caddr_t)scb_data->sense,
   4290 		    &scb_data->sense_seg, scb_data->sense_nseg);
   4291 	/*FALLTHROUGH*/
   4292 	case 3:
   4293 		ahc_freedmamem(ahc->parent_dmat,
   4294 		    AHC_SCB_MAX * sizeof(struct hardware_scb),
   4295 		    scb_data->hscb_dmamap, (caddr_t)scb_data->hscbs,
   4296 		    &scb_data->hscb_seg, scb_data->hscb_nseg);
   4297 	/*FALLTHROUGH*/
   4298 	case 2:
   4299 	case 1:
   4300 	case 0:
   4301 		break;
   4302 	}
   4303 	if (scb_data->scbarray != NULL)
   4304 		free(scb_data->scbarray, M_DEVBUF);
   4305 }
   4306 
   4307 void
   4308 ahc_alloc_scbs(struct ahc_softc *ahc)
   4309 {
   4310 	struct scb_data *scb_data;
   4311 	struct scb *next_scb;
   4312 	struct sg_map_node *sg_map;
   4313 	bus_addr_t physaddr;
   4314 	struct ahc_dma_seg *segs;
   4315 	int newcount;
   4316 	int i;
   4317 
   4318 	scb_data = ahc->scb_data;
   4319 	if (scb_data->numscbs >= AHC_SCB_MAX_ALLOC)
   4320 		/* Can't allocate any more */
   4321 		return;
   4322 
   4323 	next_scb = &scb_data->scbarray[scb_data->numscbs];
   4324 
   4325 	sg_map = malloc(sizeof(*sg_map), M_DEVBUF, M_NOWAIT);
   4326 
   4327 	if (sg_map == NULL)
   4328 		return;
   4329 
   4330 	/* Allocate S/G space for the next batch of SCBS */
   4331 	if (ahc_createdmamem(ahc->parent_dmat, PAGE_SIZE, ahc->sc_dmaflags,
   4332 			     &sg_map->sg_dmamap,
   4333 			     (caddr_t *)&sg_map->sg_vaddr, &sg_map->sg_physaddr,
   4334 			     &sg_map->sg_dmasegs, &sg_map->sg_nseg, ahc_name(ahc),
   4335 			     "SG space") < 0) {
   4336 		free(sg_map, M_DEVBUF);
   4337 		return;
   4338 	}
   4339 
   4340 	SLIST_INSERT_HEAD(&scb_data->sg_maps, sg_map, links);
   4341 
   4342 	segs = sg_map->sg_vaddr;
   4343 	physaddr = sg_map->sg_physaddr;
   4344 
   4345 	newcount = (PAGE_SIZE / (AHC_NSEG * sizeof(struct ahc_dma_seg)));
   4346 	newcount = MIN(newcount, (AHC_SCB_MAX_ALLOC - scb_data->numscbs));
   4347 	for (i = 0; i < newcount; i++) {
   4348 		struct scb_platform_data *pdata;
   4349 		int error;
   4350 
   4351 		pdata = (struct scb_platform_data *)malloc(sizeof(*pdata),
   4352 							   M_DEVBUF, M_NOWAIT);
   4353 		if (pdata == NULL)
   4354 			break;
   4355 		next_scb->platform_data = pdata;
   4356 		next_scb->sg_map = sg_map;
   4357 		next_scb->sg_list = segs;
   4358 		/*
   4359 		 * The sequencer always starts with the second entry.
   4360 		 * The first entry is embedded in the scb.
   4361 		 */
   4362 		next_scb->sg_list_phys = physaddr + sizeof(struct ahc_dma_seg);
   4363 		next_scb->ahc_softc = ahc;
   4364 		next_scb->flags = SCB_FREE;
   4365 
   4366 		error = bus_dmamap_create(ahc->parent_dmat,
   4367 			  AHC_MAXTRANSFER_SIZE, AHC_NSEG, MAXPHYS, 0,
   4368 			  BUS_DMA_NOWAIT|BUS_DMA_ALLOCNOW|ahc->sc_dmaflags,
   4369 			  &next_scb->dmamap);
   4370 		if (error != 0)
   4371 			break;
   4372 
   4373 		next_scb->hscb = &scb_data->hscbs[scb_data->numscbs];
   4374 		next_scb->hscb->tag = ahc->scb_data->numscbs;
   4375 		SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs,
   4376 				  next_scb, links.sle);
   4377 		segs += AHC_NSEG;
   4378 		physaddr += (AHC_NSEG * sizeof(struct ahc_dma_seg));
   4379 		next_scb++;
   4380 		ahc->scb_data->numscbs++;
   4381 	}
   4382 }
   4383 
   4384 void
   4385 ahc_controller_info(struct ahc_softc *ahc, char *tbuf, size_t l)
   4386 {
   4387 	int len;
   4388 	char *ep;
   4389 
   4390 	ep = tbuf + l;
   4391 
   4392 	len = snprintf(tbuf, ep - tbuf, "%s: ",
   4393 	    ahc_chip_names[ahc->chip & AHC_CHIPID_MASK]);
   4394 	tbuf += len;
   4395 	if ((ahc->features & AHC_TWIN) != 0)
   4396  		len = snprintf(tbuf, ep - tbuf, "Twin Channel, A SCSI Id=%d, "
   4397 			      "B SCSI Id=%d, primary %c, ",
   4398 			      ahc->our_id, ahc->our_id_b,
   4399 			      (ahc->flags & AHC_PRIMARY_CHANNEL) + 'A');
   4400 	else {
   4401 		const char *speed;
   4402 		const char *type;
   4403 
   4404 		speed = "";
   4405 		if ((ahc->features & AHC_ULTRA) != 0) {
   4406 			speed = "Ultra ";
   4407 		} else if ((ahc->features & AHC_DT) != 0) {
   4408 			speed = "Ultra160 ";
   4409 		} else if ((ahc->features & AHC_ULTRA2) != 0) {
   4410 			speed = "Ultra2 ";
   4411 		}
   4412 		if ((ahc->features & AHC_WIDE) != 0) {
   4413 			type = "Wide";
   4414 		} else {
   4415 			type = "Single";
   4416 		}
   4417 		len = snprintf(tbuf, ep - tbuf, "%s%s Channel %c, SCSI Id=%d, ",
   4418 			      speed, type, ahc->channel, ahc->our_id);
   4419 	}
   4420 	tbuf += len;
   4421 
   4422 	if ((ahc->flags & AHC_PAGESCBS) != 0)
   4423 		snprintf(tbuf, ep - tbuf, "%d/%d SCBs",
   4424 			ahc->scb_data->maxhscbs, AHC_MAX_QUEUE);
   4425 	else
   4426 		snprintf(tbuf, ep - tbuf, "%d SCBs", ahc->scb_data->maxhscbs);
   4427 }
   4428 
   4429 /*
   4430  * Start the board, ready for normal operation
   4431  */
   4432 int
   4433 ahc_init(struct ahc_softc *ahc)
   4434 {
   4435 	int	 max_targ;
   4436 	int	 i;
   4437 	int	 term;
   4438 	u_int	 scsi_conf;
   4439 	u_int	 scsiseq_template;
   4440 	u_int	 ultraenb;
   4441 	u_int	 discenable;
   4442 	u_int	 tagenable;
   4443 	size_t	 driver_data_size;
   4444 	uint32_t physaddr;
   4445 
   4446 #ifdef AHC_DEBUG
   4447 	if ((ahc_debug & AHC_DEBUG_SEQUENCER) != 0)
   4448 		ahc->flags |= AHC_SEQUENCER_DEBUG;
   4449 #endif
   4450 
   4451 #ifdef AHC_PRINT_SRAM
   4452 	printf("Scratch Ram:");
   4453 	for (i = 0x20; i < 0x5f; i++) {
   4454 		if (((i % 8) == 0) && (i != 0)) {
   4455 			printf ("\n              ");
   4456 		}
   4457 		printf (" 0x%x", ahc_inb(ahc, i));
   4458 	}
   4459 	if ((ahc->features & AHC_MORE_SRAM) != 0) {
   4460 		for (i = 0x70; i < 0x7f; i++) {
   4461 			if (((i % 8) == 0) && (i != 0)) {
   4462 				printf ("\n              ");
   4463 			}
   4464 			printf (" 0x%x", ahc_inb(ahc, i));
   4465 		}
   4466 	}
   4467 	printf ("\n");
   4468 	/*
   4469 	 * Reading uninitialized scratch ram may
   4470 	 * generate parity errors.
   4471 	 */
   4472 	ahc_outb(ahc, CLRINT, CLRPARERR);
   4473 	ahc_outb(ahc, CLRINT, CLRBRKADRINT);
   4474 #endif
   4475 	max_targ = 15;
   4476 
   4477 	/*
   4478 	 * Assume we have a board at this stage and it has been reset.
   4479 	 */
   4480 	if ((ahc->flags & AHC_USEDEFAULTS) != 0)
   4481 		ahc->our_id = ahc->our_id_b = 7;
   4482 
   4483 	/*
   4484 	 * Default to allowing initiator operations.
   4485 	 */
   4486 	ahc->flags |= AHC_INITIATORROLE;
   4487 
   4488 	/*
   4489 	 * Only allow target mode features if this unit has them enabled.
   4490 	 */
   4491 	//if ((AHC_TMODE_ENABLE & (0x1 << ahc->unit)) == 0)
   4492 		ahc->features &= ~AHC_TARGETMODE;
   4493 
   4494 	/*
   4495 	 * DMA tag for our command fifos and other data in system memory
   4496 	 * the card's sequencer must be able to access.  For initiator
   4497 	 * roles, we need to allocate space for the qinfifo and qoutfifo.
   4498 	 * The qinfifo and qoutfifo are composed of 256 1 byte elements.
   4499 	 * When providing for the target mode role, we must additionally
   4500 	 * provide space for the incoming target command fifo and an extra
   4501 	 * byte to deal with a DMA bug in some chip versions.
   4502 	 */
   4503 	driver_data_size = 2 * 256 * sizeof(uint8_t);
   4504 	if ((ahc->features & AHC_TARGETMODE) != 0)
   4505 		driver_data_size += AHC_TMODE_CMDS * sizeof(struct target_cmd)
   4506 				 + /*DMA WideOdd Bug Buffer*/1;
   4507 
   4508 	if (ahc_createdmamem(ahc->parent_dmat, driver_data_size,
   4509 			     ahc->sc_dmaflags,
   4510 			     &ahc->shared_data_dmamap, (caddr_t *)&ahc->qoutfifo,
   4511 			     &ahc->shared_data_busaddr, &ahc->shared_data_seg,
   4512 			     &ahc->shared_data_nseg, ahc_name(ahc), "shared data") < 0)
   4513 		return (ENOMEM);
   4514 
   4515 	ahc->init_level++;
   4516 
   4517 	if ((ahc->features & AHC_TARGETMODE) != 0) {
   4518 		ahc->targetcmds = (struct target_cmd *)ahc->qoutfifo;
   4519 		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[AHC_TMODE_CMDS];
   4520 		ahc->dma_bug_buf = ahc->shared_data_busaddr
   4521 				 + driver_data_size - 1;
   4522 		/* All target command blocks start out invalid. */
   4523 		for (i = 0; i < AHC_TMODE_CMDS; i++)
   4524 			ahc->targetcmds[i].cmd_valid = 0;
   4525 		ahc_sync_tqinfifo(ahc, BUS_DMASYNC_PREREAD);
   4526 		ahc->tqinfifonext = 1;
   4527 		ahc_outb(ahc, KERNEL_TQINPOS, ahc->tqinfifonext - 1);
   4528 		ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
   4529 		ahc->qoutfifo = (uint8_t *)&ahc->targetcmds[256];
   4530 	}
   4531 	ahc->qinfifo = &ahc->qoutfifo[256];
   4532 
   4533 	ahc->init_level++;
   4534 
   4535 	/* Allocate SCB data now that buffer_dmat is initialized */
   4536 	if (ahc->scb_data->maxhscbs == 0)
   4537 		if (ahc_init_scbdata(ahc) != 0)
   4538 		  return (ENOMEM);
   4539 
   4540 	if (bootverbose)
   4541 		printf("%s: found %d SCBs\n", ahc_name(ahc),
   4542 		    ahc->scb_data->maxhscbs);
   4543 
   4544 	/*
   4545 	 * Allocate a tstate to house information for our
   4546 	 * initiator presence on the bus as well as the user
   4547 	 * data for any target mode initiator.
   4548 	 */
   4549 	if (ahc_alloc_tstate(ahc, ahc->our_id, 'A') == NULL) {
   4550 		printf("%s: unable to allocate ahc_tmode_tstate.  "
   4551 		       "Failing attach\n", ahc_name(ahc));
   4552 		return (ENOMEM);
   4553 	}
   4554 
   4555 	if ((ahc->features & AHC_TWIN) != 0) {
   4556 		if (ahc_alloc_tstate(ahc, ahc->our_id_b, 'B') == NULL) {
   4557 			printf("%s: unable to allocate ahc_tmode_tstate.  "
   4558 			       "Failing attach\n", ahc_name(ahc));
   4559 			return (ENOMEM);
   4560 		}
   4561 	}
   4562 
   4563 	ahc_outb(ahc, SEQ_FLAGS, 0);
   4564 	ahc_outb(ahc, SEQ_FLAGS2, 0);
   4565 
   4566 	if (ahc->scb_data->maxhscbs < AHC_SCB_MAX_ALLOC) {
   4567 		ahc->flags |= AHC_PAGESCBS;
   4568 	} else {
   4569 		ahc->flags &= ~AHC_PAGESCBS;
   4570 	}
   4571 
   4572 #ifdef AHC_DEBUG
   4573 	if (ahc_debug & AHC_SHOW_MISC) {
   4574 		printf("%s: hardware scb %lu bytes; kernel scb %lu bytes; "
   4575 		       "ahc_dma %lu bytes\n",
   4576 			ahc_name(ahc),
   4577 			(u_long)sizeof(struct hardware_scb),
   4578 			(u_long)sizeof(struct scb),
   4579 			(u_long)sizeof(struct ahc_dma_seg));
   4580 	}
   4581 #endif /* AHC_DEBUG */
   4582 
   4583 	/* Set the SCSI Id, SXFRCTL0, SXFRCTL1, and SIMODE1, for both channels*/
   4584 	if (ahc->features & AHC_TWIN) {
   4585 
   4586 		/*
   4587 		 * The device is gated to channel B after a chip reset,
   4588 		 * so set those values first
   4589 		 */
   4590 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
   4591 		term = (ahc->flags & AHC_TERM_ENB_B) != 0 ? STPWEN : 0;
   4592 		ahc_outb(ahc, SCSIID, ahc->our_id_b);
   4593 		scsi_conf = ahc_inb(ahc, SCSICONF + 1);
   4594 		ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
   4595 					|term|ahc->seltime_b|ENSTIMER|ACTNEGEN);
   4596 		if ((ahc->features & AHC_ULTRA2) != 0)
   4597 			ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
   4598 		ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
   4599 		ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
   4600 
   4601 		if ((scsi_conf & RESET_SCSI) != 0
   4602 		 && (ahc->flags & AHC_INITIATORROLE) != 0)
   4603 			ahc->flags |= AHC_RESET_BUS_B;
   4604 
   4605 		/* Select Channel A */
   4606 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
   4607 	}
   4608 
   4609 	term = (ahc->flags & AHC_TERM_ENB_A) != 0 ? STPWEN : 0;
   4610 	if ((ahc->features & AHC_ULTRA2) != 0)
   4611 		ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
   4612 	else
   4613 		ahc_outb(ahc, SCSIID, ahc->our_id);
   4614 	scsi_conf = ahc_inb(ahc, SCSICONF);
   4615 	ahc_outb(ahc, SXFRCTL1, (scsi_conf & (ENSPCHK|STIMESEL))
   4616 				|term|ahc->seltime
   4617 				|ENSTIMER|ACTNEGEN);
   4618 	if ((ahc->features & AHC_ULTRA2) != 0)
   4619 		ahc_outb(ahc, SIMODE0, ahc_inb(ahc, SIMODE0)|ENIOERR);
   4620 	ahc_outb(ahc, SIMODE1, ENSELTIMO|ENSCSIRST|ENSCSIPERR);
   4621 	ahc_outb(ahc, SXFRCTL0, DFON|SPIOEN);
   4622 
   4623 	if ((scsi_conf & RESET_SCSI) != 0
   4624 	 && (ahc->flags & AHC_INITIATORROLE) != 0)
   4625 		ahc->flags |= AHC_RESET_BUS_A;
   4626 
   4627 	/*
   4628 	 * Look at the information that board initialization or
   4629 	 * the board bios has left us.
   4630 	 */
   4631 	ultraenb = 0;
   4632 	tagenable = ALL_TARGETS_MASK;
   4633 
   4634 	/* Grab the disconnection disable table and invert it for our needs */
   4635 	if ((ahc->flags & AHC_USEDEFAULTS) != 0) {
   4636 		printf("%s: Host Adapter Bios disabled.  Using default SCSI "
   4637 			"device parameters\n", ahc_name(ahc));
   4638 		ahc->flags |= AHC_EXTENDED_TRANS_A|AHC_EXTENDED_TRANS_B|
   4639 			      AHC_TERM_ENB_A|AHC_TERM_ENB_B;
   4640 		discenable = ALL_TARGETS_MASK;
   4641 		if ((ahc->features & AHC_ULTRA) != 0)
   4642 			ultraenb = ALL_TARGETS_MASK;
   4643 	} else {
   4644 		discenable = ~((ahc_inb(ahc, DISC_DSB + 1) << 8)
   4645 			   | ahc_inb(ahc, DISC_DSB));
   4646 		if ((ahc->features & (AHC_ULTRA|AHC_ULTRA2)) != 0)
   4647 			ultraenb = (ahc_inb(ahc, ULTRA_ENB + 1) << 8)
   4648 				      | ahc_inb(ahc, ULTRA_ENB);
   4649 	}
   4650 
   4651 	if ((ahc->features & (AHC_WIDE|AHC_TWIN)) == 0)
   4652 		max_targ = 7;
   4653 
   4654 	for (i = 0; i <= max_targ; i++) {
   4655 		struct ahc_initiator_tinfo *tinfo;
   4656 		struct ahc_tmode_tstate *tstate;
   4657 		u_int our_id;
   4658 		u_int target_id;
   4659 		char channel;
   4660 
   4661 		channel = 'A';
   4662 		our_id = ahc->our_id;
   4663 		target_id = i;
   4664 		if (i > 7 && (ahc->features & AHC_TWIN) != 0) {
   4665 			channel = 'B';
   4666 			our_id = ahc->our_id_b;
   4667 			target_id = i % 8;
   4668 		}
   4669 		tinfo = ahc_fetch_transinfo(ahc, channel, our_id,
   4670 					    target_id, &tstate);
   4671 		/* Default to async narrow across the board */
   4672 		memset(tinfo, 0, sizeof(*tinfo));
   4673 		if (ahc->flags & AHC_USEDEFAULTS) {
   4674 			if ((ahc->features & AHC_WIDE) != 0)
   4675 				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
   4676 
   4677 			/*
   4678 			 * These will be truncated when we determine the
   4679 			 * connection type we have with the target.
   4680 			 */
   4681 			tinfo->user.period = ahc_syncrates->period;
   4682 			tinfo->user.offset = ~0;
   4683 		} else {
   4684 			u_int scsirate;
   4685 			uint16_t mask;
   4686 
   4687 			/* Take the settings leftover in scratch RAM. */
   4688 			scsirate = ahc_inb(ahc, TARG_SCSIRATE + i);
   4689 			mask = (0x01 << i);
   4690 			if ((ahc->features & AHC_ULTRA2) != 0) {
   4691 				u_int offset;
   4692 				u_int maxsync;
   4693 
   4694 				if ((scsirate & SOFS) == 0x0F) {
   4695 					/*
   4696 					 * Haven't negotiated yet,
   4697 					 * so the format is different.
   4698 					 */
   4699 					scsirate = (scsirate & SXFR) >> 4
   4700 						 | (ultraenb & mask)
   4701 						  ? 0x08 : 0x0
   4702 						 | (scsirate & WIDEXFER);
   4703 					offset = MAX_OFFSET_ULTRA2;
   4704 				} else
   4705 					offset = ahc_inb(ahc, TARG_OFFSET + i);
   4706 				if ((scsirate & ~WIDEXFER) == 0 && offset != 0)
   4707 					/* Set to the lowest sync rate, 5MHz */
   4708 					scsirate |= 0x1c;
   4709 				maxsync = AHC_SYNCRATE_ULTRA2;
   4710 				if ((ahc->features & AHC_DT) != 0)
   4711 					maxsync = AHC_SYNCRATE_DT;
   4712 				tinfo->user.period =
   4713 				    ahc_find_period(ahc, scsirate, maxsync);
   4714 				if (offset == 0)
   4715 					tinfo->user.period = 0;
   4716 				else
   4717 					tinfo->user.offset = ~0;
   4718 				if ((scsirate & SXFR_ULTRA2) <= 8/*10MHz*/
   4719 				 && (ahc->features & AHC_DT) != 0)
   4720 					tinfo->user.ppr_options =
   4721 					    MSG_EXT_PPR_DT_REQ;
   4722 			} else if ((scsirate & SOFS) != 0) {
   4723 				if ((scsirate & SXFR) == 0x40
   4724 				 && (ultraenb & mask) != 0) {
   4725 					/* Treat 10MHz as a non-ultra speed */
   4726 					scsirate &= ~SXFR;
   4727 				 	ultraenb &= ~mask;
   4728 				}
   4729 				tinfo->user.period =
   4730 				    ahc_find_period(ahc, scsirate,
   4731 						    (ultraenb & mask)
   4732 						   ? AHC_SYNCRATE_ULTRA
   4733 						   : AHC_SYNCRATE_FAST);
   4734 				if (tinfo->user.period != 0)
   4735 					tinfo->user.offset = ~0;
   4736 			}
   4737 			if (tinfo->user.period == 0)
   4738 				tinfo->user.offset = 0;
   4739 			if ((scsirate & WIDEXFER) != 0
   4740 			 && (ahc->features & AHC_WIDE) != 0)
   4741 				tinfo->user.width = MSG_EXT_WDTR_BUS_16_BIT;
   4742 			tinfo->user.protocol_version = 4;
   4743 			if ((ahc->features & AHC_DT) != 0)
   4744 				tinfo->user.transport_version = 3;
   4745 			else
   4746 				tinfo->user.transport_version = 2;
   4747 			tinfo->goal.protocol_version = 2;
   4748 			tinfo->goal.transport_version = 2;
   4749 			tinfo->curr.protocol_version = 2;
   4750 			tinfo->curr.transport_version = 2;
   4751 		}
   4752 		tstate->ultraenb = 0;
   4753 		tstate->discenable = discenable;
   4754 	}
   4755 	ahc->user_discenable = discenable;
   4756 	ahc->user_tagenable = tagenable;
   4757 
   4758 	/* There are no untagged SCBs active yet. */
   4759 	for (i = 0; i < 16; i++) {
   4760 		ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, 0));
   4761 		if ((ahc->flags & AHC_SCB_BTT) != 0) {
   4762 			int lun;
   4763 
   4764 			/*
   4765 			 * The SCB based BTT allows an entry per
   4766 			 * target and lun pair.
   4767 			 */
   4768 			for (lun = 1; lun < AHC_NUM_LUNS; lun++)
   4769 				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, lun));
   4770 		}
   4771 	}
   4772 
   4773 	/* All of our queues are empty */
   4774 	for (i = 0; i < 256; i++)
   4775 		ahc->qoutfifo[i] = SCB_LIST_NULL;
   4776 
   4777 	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_PREREAD);
   4778 
   4779 	for (i = 0; i < 256; i++)
   4780 		ahc->qinfifo[i] = SCB_LIST_NULL;
   4781 
   4782 	if ((ahc->features & AHC_MULTI_TID) != 0) {
   4783 		ahc_outb(ahc, TARGID, 0);
   4784 		ahc_outb(ahc, TARGID + 1, 0);
   4785 	}
   4786 
   4787 	/*
   4788 	 * Tell the sequencer where it can find our arrays in memory.
   4789 	 */
   4790 	physaddr = ahc->scb_data->hscb_busaddr;
   4791 	ahc_outb(ahc, HSCB_ADDR, physaddr & 0xFF);
   4792 	ahc_outb(ahc, HSCB_ADDR + 1, (physaddr >> 8) & 0xFF);
   4793 	ahc_outb(ahc, HSCB_ADDR + 2, (physaddr >> 16) & 0xFF);
   4794 	ahc_outb(ahc, HSCB_ADDR + 3, (physaddr >> 24) & 0xFF);
   4795 
   4796 	physaddr = ahc->shared_data_busaddr;
   4797 	ahc_outb(ahc, SHARED_DATA_ADDR, physaddr & 0xFF);
   4798 	ahc_outb(ahc, SHARED_DATA_ADDR + 1, (physaddr >> 8) & 0xFF);
   4799 	ahc_outb(ahc, SHARED_DATA_ADDR + 2, (physaddr >> 16) & 0xFF);
   4800 	ahc_outb(ahc, SHARED_DATA_ADDR + 3, (physaddr >> 24) & 0xFF);
   4801 
   4802 	/*
   4803 	 * Initialize the group code to command length table.
   4804 	 * This overrides the values in TARG_SCSIRATE, so only
   4805 	 * setup the table after we have processed that information.
   4806 	 */
   4807 	ahc_outb(ahc, CMDSIZE_TABLE, 5);
   4808 	ahc_outb(ahc, CMDSIZE_TABLE + 1, 9);
   4809 	ahc_outb(ahc, CMDSIZE_TABLE + 2, 9);
   4810 	ahc_outb(ahc, CMDSIZE_TABLE + 3, 0);
   4811 	ahc_outb(ahc, CMDSIZE_TABLE + 4, 15);
   4812 	ahc_outb(ahc, CMDSIZE_TABLE + 5, 11);
   4813 	ahc_outb(ahc, CMDSIZE_TABLE + 6, 0);
   4814 	ahc_outb(ahc, CMDSIZE_TABLE + 7, 0);
   4815 
   4816 	/* Tell the sequencer of our initial queue positions */
   4817 	ahc_outb(ahc, KERNEL_QINPOS, 0);
   4818 	ahc_outb(ahc, QINPOS, 0);
   4819 	ahc_outb(ahc, QOUTPOS, 0);
   4820 
   4821 	/*
   4822 	 * Use the built in queue management registers
   4823 	 * if they are available.
   4824 	 */
   4825 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
   4826 		ahc_outb(ahc, QOFF_CTLSTA, SCB_QSIZE_256);
   4827 		ahc_outb(ahc, SDSCB_QOFF, 0);
   4828 		ahc_outb(ahc, SNSCB_QOFF, 0);
   4829 		ahc_outb(ahc, HNSCB_QOFF, 0);
   4830 	}
   4831 
   4832 
   4833 	/* We don't have any waiting selections */
   4834 	ahc_outb(ahc, WAITING_SCBH, SCB_LIST_NULL);
   4835 
   4836 	/* Our disconnection list is empty too */
   4837 	ahc_outb(ahc, DISCONNECTED_SCBH, SCB_LIST_NULL);
   4838 
   4839 	/* Message out buffer starts empty */
   4840 	ahc_outb(ahc, MSG_OUT, MSG_NOOP);
   4841 
   4842 	/*
   4843 	 * Setup the allowed SCSI Sequences based on operational mode.
   4844 	 * If we are a target, we'll enalbe select in operations once
   4845 	 * we've had a lun enabled.
   4846 	 */
   4847 	scsiseq_template = ENSELO|ENAUTOATNO|ENAUTOATNP;
   4848 	if ((ahc->flags & AHC_INITIATORROLE) != 0)
   4849 		scsiseq_template |= ENRSELI;
   4850 	ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq_template);
   4851 
   4852 	/*
   4853 	 * Load the Sequencer program and Enable the adapter
   4854 	 * in "fast" mode.
   4855 	 */
   4856 	if (bootverbose)
   4857 		printf("%s: Downloading Sequencer Program...",
   4858 		       ahc_name(ahc));
   4859 
   4860 	ahc_loadseq(ahc);
   4861 
   4862 	if ((ahc->features & AHC_ULTRA2) != 0) {
   4863 		int wait;
   4864 
   4865 		/*
   4866 		 * Wait for up to 500ms for our transceivers
   4867 		 * to settle.  If the adapter does not have
   4868 		 * a cable attached, the transceivers may
   4869 		 * never settle, so don't complain if we
   4870 		 * fail here.
   4871 		 */
   4872 		ahc_pause(ahc);
   4873 		for (wait = 5000;
   4874 		     (ahc_inb(ahc, SBLKCTL) & (ENAB40|ENAB20)) == 0 && wait;
   4875 		     wait--)
   4876 			ahc_delay(100);
   4877 		ahc_unpause(ahc);
   4878 	}
   4879 
   4880 	/* We have to wait until after any system dumps... */
   4881 	ahc->shutdown_hook = shutdownhook_establish(ahc_shutdown, ahc);
   4882 
   4883 	return (0);
   4884 }
   4885 
   4886 void
   4887 ahc_intr_enable(struct ahc_softc *ahc, int enable)
   4888 {
   4889 	u_int hcntrl;
   4890 
   4891 	hcntrl = ahc_inb(ahc, HCNTRL);
   4892 	hcntrl &= ~INTEN;
   4893 	ahc->pause &= ~INTEN;
   4894 	ahc->unpause &= ~INTEN;
   4895 	if (enable) {
   4896 		hcntrl |= INTEN;
   4897 		ahc->pause |= INTEN;
   4898 		ahc->unpause |= INTEN;
   4899 	}
   4900 	ahc_outb(ahc, HCNTRL, hcntrl);
   4901 }
   4902 
   4903 /*
   4904  * Ensure that the card is paused in a location
   4905  * outside of all critical sections and that all
   4906  * pending work is completed prior to returning.
   4907  * This routine should only be called from outside
   4908  * an interrupt context.
   4909  */
   4910 void
   4911 ahc_pause_and_flushwork(struct ahc_softc *ahc)
   4912 {
   4913 	int intstat;
   4914 	int maxloops;
   4915 	int paused;
   4916 
   4917 	maxloops = 1000;
   4918 	ahc->flags |= AHC_ALL_INTERRUPTS;
   4919 	intstat = 0;
   4920 	paused = FALSE;
   4921 	do {
   4922 		if (paused)
   4923 			ahc_unpause(ahc);
   4924 		ahc_intr(ahc);
   4925 		ahc_pause(ahc);
   4926 		paused = TRUE;
   4927 		ahc_outb(ahc, SCSISEQ, ahc_inb(ahc, SCSISEQ) & ~ENSELO);
   4928 		ahc_clear_critical_section(ahc);
   4929 		if (intstat == 0xFF && (ahc->features & AHC_REMOVABLE) != 0)
   4930 			break;
   4931 	} while (--maxloops
   4932 	      && (((intstat = ahc_inb(ahc, INTSTAT)) & INT_PEND) != 0
   4933 	       || (ahc_inb(ahc, SSTAT0) & (SELDO|SELINGO))));
   4934 	if (maxloops == 0) {
   4935 		printf("Infinite interrupt loop, INTSTAT = %x",
   4936 		       ahc_inb(ahc, INTSTAT));
   4937 	}
   4938 	ahc_platform_flushwork(ahc);
   4939 	ahc->flags &= ~AHC_ALL_INTERRUPTS;
   4940 }
   4941 
   4942 int
   4943 ahc_suspend(struct ahc_softc *ahc)
   4944 {
   4945 	uint8_t *ptr;
   4946 	int	 i;
   4947 
   4948 	ahc_pause_and_flushwork(ahc);
   4949 
   4950 	if (LIST_FIRST(&ahc->pending_scbs) != NULL)
   4951 		return (EBUSY);
   4952 
   4953 #if AHC_TARGET_MODE
   4954 	/*
   4955 	 * XXX What about ATIOs that have not yet been serviced?
   4956 	 * Perhaps we should just refuse to be suspended if we
   4957 	 * are acting in a target role.
   4958 	 */
   4959 	if (ahc->pending_device != NULL)
   4960 		return (EBUSY);
   4961 #endif
   4962 
   4963 	/* Save volatile registers */
   4964 	if ((ahc->features & AHC_TWIN) != 0) {
   4965 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
   4966 		ahc->suspend_state.channel[1].scsiseq = ahc_inb(ahc, SCSISEQ);
   4967 		ahc->suspend_state.channel[1].sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
   4968 		ahc->suspend_state.channel[1].sxfrctl1 = ahc_inb(ahc, SXFRCTL1);
   4969 		ahc->suspend_state.channel[1].simode0 = ahc_inb(ahc, SIMODE0);
   4970 		ahc->suspend_state.channel[1].simode1 = ahc_inb(ahc, SIMODE1);
   4971 		ahc->suspend_state.channel[1].seltimer = ahc_inb(ahc, SELTIMER);
   4972 		ahc->suspend_state.channel[1].seqctl = ahc_inb(ahc, SEQCTL);
   4973 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
   4974 	}
   4975 	ahc->suspend_state.channel[0].scsiseq = ahc_inb(ahc, SCSISEQ);
   4976 	ahc->suspend_state.channel[0].sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
   4977 	ahc->suspend_state.channel[0].sxfrctl1 = ahc_inb(ahc, SXFRCTL1);
   4978 	ahc->suspend_state.channel[0].simode0 = ahc_inb(ahc, SIMODE0);
   4979 	ahc->suspend_state.channel[0].simode1 = ahc_inb(ahc, SIMODE1);
   4980 	ahc->suspend_state.channel[0].seltimer = ahc_inb(ahc, SELTIMER);
   4981 	ahc->suspend_state.channel[0].seqctl = ahc_inb(ahc, SEQCTL);
   4982 
   4983 	if ((ahc->chip & AHC_PCI) != 0) {
   4984 		ahc->suspend_state.dscommand0 = ahc_inb(ahc, DSCOMMAND0);
   4985 		ahc->suspend_state.dspcistatus = ahc_inb(ahc, DSPCISTATUS);
   4986 	}
   4987 
   4988 	if ((ahc->features & AHC_DT) != 0) {
   4989 		u_int sfunct;
   4990 
   4991 		sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE;
   4992 		ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE);
   4993 		ahc->suspend_state.optionmode = ahc_inb(ahc, OPTIONMODE);
   4994 		ahc_outb(ahc, SFUNCT, sfunct);
   4995 		ahc->suspend_state.crccontrol1 = ahc_inb(ahc, CRCCONTROL1);
   4996 	}
   4997 
   4998 	if ((ahc->features & AHC_MULTI_FUNC) != 0)
   4999 		ahc->suspend_state.scbbaddr = ahc_inb(ahc, SCBBADDR);
   5000 
   5001 	if ((ahc->features & AHC_ULTRA2) != 0)
   5002 		ahc->suspend_state.dff_thrsh = ahc_inb(ahc, DFF_THRSH);
   5003 
   5004 	ptr = ahc->suspend_state.scratch_ram;
   5005 	for (i = 0; i < 64; i++)
   5006 		*ptr++ = ahc_inb(ahc, SRAM_BASE + i);
   5007 
   5008 	if ((ahc->features & AHC_MORE_SRAM) != 0) {
   5009 		for (i = 0; i < 16; i++)
   5010 			*ptr++ = ahc_inb(ahc, TARG_OFFSET + i);
   5011 	}
   5012 
   5013 	ptr = ahc->suspend_state.btt;
   5014 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
   5015 		for (i = 0;i < AHC_NUM_TARGETS; i++) {
   5016 			int j;
   5017 
   5018 			for (j = 0;j < AHC_NUM_LUNS; j++) {
   5019 				u_int tcl;
   5020 
   5021 				tcl = BUILD_TCL(i << 4, j);
   5022 				*ptr = ahc_index_busy_tcl(ahc, tcl);
   5023 			}
   5024 		}
   5025 	}
   5026 	ahc_shutdown(ahc);
   5027 	return (0);
   5028 }
   5029 
   5030 int
   5031 ahc_resume(struct ahc_softc *ahc)
   5032 {
   5033 	uint8_t *ptr;
   5034 	int	 i;
   5035 
   5036 	ahc_reset(ahc);
   5037 
   5038 	ahc_build_free_scb_list(ahc);
   5039 
   5040 	/* Restore volatile registers */
   5041 	if ((ahc->features & AHC_TWIN) != 0) {
   5042 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) | SELBUSB);
   5043 		ahc_outb(ahc, SCSIID, ahc->our_id);
   5044 		ahc_outb(ahc, SCSISEQ, ahc->suspend_state.channel[1].scsiseq);
   5045 		ahc_outb(ahc, SXFRCTL0, ahc->suspend_state.channel[1].sxfrctl0);
   5046 		ahc_outb(ahc, SXFRCTL1, ahc->suspend_state.channel[1].sxfrctl1);
   5047 		ahc_outb(ahc, SIMODE0, ahc->suspend_state.channel[1].simode0);
   5048 		ahc_outb(ahc, SIMODE1, ahc->suspend_state.channel[1].simode1);
   5049 		ahc_outb(ahc, SELTIMER, ahc->suspend_state.channel[1].seltimer);
   5050 		ahc_outb(ahc, SEQCTL, ahc->suspend_state.channel[1].seqctl);
   5051 		ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) & ~SELBUSB);
   5052 	}
   5053 	ahc_outb(ahc, SCSISEQ, ahc->suspend_state.channel[0].scsiseq);
   5054 	ahc_outb(ahc, SXFRCTL0, ahc->suspend_state.channel[0].sxfrctl0);
   5055 	ahc_outb(ahc, SXFRCTL1, ahc->suspend_state.channel[0].sxfrctl1);
   5056 	ahc_outb(ahc, SIMODE0, ahc->suspend_state.channel[0].simode0);
   5057 	ahc_outb(ahc, SIMODE1, ahc->suspend_state.channel[0].simode1);
   5058 	ahc_outb(ahc, SELTIMER, ahc->suspend_state.channel[0].seltimer);
   5059 	ahc_outb(ahc, SEQCTL, ahc->suspend_state.channel[0].seqctl);
   5060 	if ((ahc->features & AHC_ULTRA2) != 0)
   5061 		ahc_outb(ahc, SCSIID_ULTRA2, ahc->our_id);
   5062 	else
   5063 		ahc_outb(ahc, SCSIID, ahc->our_id);
   5064 
   5065 	if ((ahc->chip & AHC_PCI) != 0) {
   5066 		ahc_outb(ahc, DSCOMMAND0, ahc->suspend_state.dscommand0);
   5067 		ahc_outb(ahc, DSPCISTATUS, ahc->suspend_state.dspcistatus);
   5068 	}
   5069 
   5070 	if ((ahc->features & AHC_DT) != 0) {
   5071 		u_int sfunct;
   5072 
   5073 		sfunct = ahc_inb(ahc, SFUNCT) & ~ALT_MODE;
   5074 		ahc_outb(ahc, SFUNCT, sfunct | ALT_MODE);
   5075 		ahc_outb(ahc, OPTIONMODE, ahc->suspend_state.optionmode);
   5076 		ahc_outb(ahc, SFUNCT, sfunct);
   5077 		ahc_outb(ahc, CRCCONTROL1, ahc->suspend_state.crccontrol1);
   5078 	}
   5079 
   5080 	if ((ahc->features & AHC_MULTI_FUNC) != 0)
   5081 		ahc_outb(ahc, SCBBADDR, ahc->suspend_state.scbbaddr);
   5082 
   5083 	if ((ahc->features & AHC_ULTRA2) != 0)
   5084 		ahc_outb(ahc, DFF_THRSH, ahc->suspend_state.dff_thrsh);
   5085 
   5086 	ptr = ahc->suspend_state.scratch_ram;
   5087 	for (i = 0; i < 64; i++)
   5088 		ahc_outb(ahc, SRAM_BASE + i, *ptr++);
   5089 
   5090 	if ((ahc->features & AHC_MORE_SRAM) != 0) {
   5091 		for (i = 0; i < 16; i++)
   5092 			ahc_outb(ahc, TARG_OFFSET + i, *ptr++);
   5093 	}
   5094 
   5095 	ptr = ahc->suspend_state.btt;
   5096 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
   5097 		for (i = 0;i < AHC_NUM_TARGETS; i++) {
   5098 			int j;
   5099 
   5100 			for (j = 0;j < AHC_NUM_LUNS; j++) {
   5101 				u_int tcl;
   5102 
   5103 				tcl = BUILD_TCL(i << 4, j);
   5104 				ahc_busy_tcl(ahc, tcl, *ptr);
   5105 			}
   5106 		}
   5107 	}
   5108 	return (0);
   5109 }
   5110 
   5111 /************************** Busy Target Table *********************************/
   5112 /*
   5113  * Return the untagged transaction id for a given target/channel lun.
   5114  * Optionally, clear the entry.
   5115  */
   5116 u_int
   5117 ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl)
   5118 {
   5119 	u_int scbid;
   5120 	u_int target_offset;
   5121 
   5122 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
   5123 		u_int saved_scbptr;
   5124 
   5125 		saved_scbptr = ahc_inb(ahc, SCBPTR);
   5126 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
   5127 		scbid = ahc_inb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl));
   5128 		ahc_outb(ahc, SCBPTR, saved_scbptr);
   5129 	} else {
   5130 		target_offset = TCL_TARGET_OFFSET(tcl);
   5131 		scbid = ahc_inb(ahc, BUSY_TARGETS + target_offset);
   5132 	}
   5133 
   5134 	return (scbid);
   5135 }
   5136 
   5137 void
   5138 ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl)
   5139 {
   5140 	u_int target_offset;
   5141 
   5142 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
   5143 		u_int saved_scbptr;
   5144 
   5145 		saved_scbptr = ahc_inb(ahc, SCBPTR);
   5146 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
   5147 		ahc_outb(ahc, SCB_64_BTT+TCL_TARGET_OFFSET(tcl), SCB_LIST_NULL);
   5148 		ahc_outb(ahc, SCBPTR, saved_scbptr);
   5149 	} else {
   5150 		target_offset = TCL_TARGET_OFFSET(tcl);
   5151 		ahc_outb(ahc, BUSY_TARGETS + target_offset, SCB_LIST_NULL);
   5152 	}
   5153 }
   5154 
   5155 void
   5156 ahc_busy_tcl(struct ahc_softc *ahc, u_int tcl, u_int scbid)
   5157 {
   5158 	u_int target_offset;
   5159 
   5160 	if ((ahc->flags & AHC_SCB_BTT) != 0) {
   5161 		u_int saved_scbptr;
   5162 
   5163 		saved_scbptr = ahc_inb(ahc, SCBPTR);
   5164 		ahc_outb(ahc, SCBPTR, TCL_LUN(tcl));
   5165 		ahc_outb(ahc, SCB_64_BTT + TCL_TARGET_OFFSET(tcl), scbid);
   5166 		ahc_outb(ahc, SCBPTR, saved_scbptr);
   5167 	} else {
   5168 		target_offset = TCL_TARGET_OFFSET(tcl);
   5169 		ahc_outb(ahc, BUSY_TARGETS + target_offset, scbid);
   5170 	}
   5171 }
   5172 
   5173 /************************** SCB and SCB queue management **********************/
   5174 int
   5175 ahc_match_scb(struct ahc_softc *ahc, struct scb *scb, int target,
   5176 	      char channel, int lun, u_int tag, role_t role)
   5177 {
   5178 	int targ = SCB_GET_TARGET(ahc, scb);
   5179 	char chan = SCB_GET_CHANNEL(ahc, scb);
   5180 	int slun = SCB_GET_LUN(scb);
   5181 	int match;
   5182 
   5183 	match = ((chan == channel) || (channel == ALL_CHANNELS));
   5184 	if (match != 0)
   5185 		match = ((targ == target) || (target == CAM_TARGET_WILDCARD));
   5186 	if (match != 0)
   5187 		match = ((lun == slun) || (lun == CAM_LUN_WILDCARD));
   5188 	if (match != 0) {
   5189 #if 0
   5190 #if AHC_TARGET_MODE
   5191 		int group;
   5192 
   5193 		group = XPT_FC_GROUP(scb->io_ctx->ccb_h.func_code);
   5194 		if (role == ROLE_INITIATOR) {
   5195 			match = (group != XPT_FC_GROUP_TMODE)
   5196 			      && ((tag == scb->hscb->tag)
   5197 			       || (tag == SCB_LIST_NULL));
   5198 		} else if (role == ROLE_TARGET) {
   5199 			match = (group == XPT_FC_GROUP_TMODE)
   5200 			      && ((tag == scb->io_ctx->csio.tag_id)
   5201 			       || (tag == SCB_LIST_NULL));
   5202 		}
   5203 #else /* !AHC_TARGET_MODE */
   5204 		match = ((tag == scb->hscb->tag) || (tag == SCB_LIST_NULL));
   5205 #endif /* AHC_TARGET_MODE */
   5206 #endif
   5207 	}
   5208 
   5209 	return match;
   5210 }
   5211 
   5212 void
   5213 ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb)
   5214 {
   5215 	int	target;
   5216 	char	channel;
   5217 	int	lun;
   5218 
   5219 	target = SCB_GET_TARGET(ahc, scb);
   5220 	lun = SCB_GET_LUN(scb);
   5221 	channel = SCB_GET_CHANNEL(ahc, scb);
   5222 
   5223 	ahc_search_qinfifo(ahc, target, channel, lun,
   5224 			   /*tag*/SCB_LIST_NULL, ROLE_UNKNOWN,
   5225 			   CAM_REQUEUE_REQ, SEARCH_COMPLETE);
   5226 
   5227 	ahc_platform_freeze_devq(ahc, scb);
   5228 }
   5229 
   5230 void
   5231 ahc_qinfifo_requeue_tail(struct ahc_softc *ahc, struct scb *scb)
   5232 {
   5233 	struct scb *prev_scb;
   5234 
   5235 	prev_scb = NULL;
   5236 	if (ahc_qinfifo_count(ahc) != 0) {
   5237 		u_int prev_tag;
   5238 		uint8_t prev_pos;
   5239 
   5240 		prev_pos = ahc->qinfifonext - 1;
   5241 		prev_tag = ahc->qinfifo[prev_pos];
   5242 		prev_scb = ahc_lookup_scb(ahc, prev_tag);
   5243 	}
   5244 	ahc_qinfifo_requeue(ahc, prev_scb, scb);
   5245 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
   5246 		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
   5247 	} else {
   5248 		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
   5249 	}
   5250 }
   5251 
   5252 static void
   5253 ahc_qinfifo_requeue(struct ahc_softc *ahc, struct scb *prev_scb,
   5254 		    struct scb *scb)
   5255 {
   5256 	if (prev_scb == NULL) {
   5257 		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
   5258 	} else {
   5259 		prev_scb->hscb->next = scb->hscb->tag;
   5260 		ahc_sync_scb(ahc, prev_scb,
   5261 			     BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
   5262 	}
   5263 	ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
   5264 	scb->hscb->next = ahc->next_queued_scb->hscb->tag;
   5265 	ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
   5266 }
   5267 
   5268 static int
   5269 ahc_qinfifo_count(struct ahc_softc *ahc)
   5270 {
   5271 	uint8_t qinpos;
   5272 	uint8_t diff;
   5273 
   5274 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
   5275 		qinpos = ahc_inb(ahc, SNSCB_QOFF);
   5276 		ahc_outb(ahc, SNSCB_QOFF, qinpos);
   5277 	} else
   5278 		qinpos = ahc_inb(ahc, QINPOS);
   5279 	diff = ahc->qinfifonext - qinpos;
   5280 	return (diff);
   5281 }
   5282 
   5283 int
   5284 ahc_search_qinfifo(struct ahc_softc *ahc, int target, char channel,
   5285 		   int lun, u_int tag, role_t role, uint32_t status,
   5286 		   ahc_search_action action)
   5287 {
   5288 	struct	scb *scb;
   5289 	struct	scb *prev_scb;
   5290 	uint8_t qinstart;
   5291 	uint8_t qinpos;
   5292 	uint8_t qintail;
   5293 	uint8_t next;
   5294 	uint8_t prev;
   5295 	uint8_t curscbptr;
   5296 	int	found;
   5297 	int	have_qregs;
   5298 
   5299 	qintail = ahc->qinfifonext;
   5300 	have_qregs = (ahc->features & AHC_QUEUE_REGS) != 0;
   5301 	if (have_qregs) {
   5302 		qinstart = ahc_inb(ahc, SNSCB_QOFF);
   5303 		ahc_outb(ahc, SNSCB_QOFF, qinstart);
   5304 	} else
   5305 		qinstart = ahc_inb(ahc, QINPOS);
   5306 	qinpos = qinstart;
   5307 	found = 0;
   5308 	prev_scb = NULL;
   5309 
   5310 	if (action == SEARCH_COMPLETE) {
   5311 		/*
   5312 		 * Don't attempt to run any queued untagged transactions
   5313 		 * until we are done with the abort process.
   5314 		 */
   5315 		ahc_freeze_untagged_queues(ahc);
   5316 	}
   5317 
   5318 	/*
   5319 	 * Start with an empty queue.  Entries that are not chosen
   5320 	 * for removal will be re-added to the queue as we go.
   5321 	 */
   5322 	ahc->qinfifonext = qinpos;
   5323 	ahc_outb(ahc, NEXT_QUEUED_SCB, ahc->next_queued_scb->hscb->tag);
   5324 
   5325 	while (qinpos != qintail) {
   5326 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinpos]);
   5327 		if (scb == NULL) {
   5328 			printf("qinpos = %d, SCB index = %d\n",
   5329 				qinpos, ahc->qinfifo[qinpos]);
   5330 			panic("Loop 1\n");
   5331 		}
   5332 
   5333 		if (ahc_match_scb(ahc, scb, target, channel, lun, tag, role)) {
   5334 			/*
   5335 			 * We found an scb that needs to be acted on.
   5336 			 */
   5337 			found++;
   5338 			switch (action) {
   5339 			case SEARCH_COMPLETE:
   5340 			{
   5341 				cam_status ostat;
   5342 				cam_status cstat;
   5343 
   5344 				ostat = ahc_get_transaction_status(scb);
   5345 				if (ostat == CAM_REQ_INPROG)
   5346 					ahc_set_transaction_status(scb, status);
   5347 				cstat = ahc_get_transaction_status(scb);
   5348 				if (cstat != CAM_REQ_CMP)
   5349 					ahc_freeze_scb(scb);
   5350 				if ((scb->flags & SCB_ACTIVE) == 0)
   5351 					printf("Inactive SCB in qinfifo\n");
   5352 				ahc_done(ahc, scb);
   5353 
   5354 				/* FALLTHROUGH */
   5355 			}
   5356 			case SEARCH_REMOVE:
   5357 				break;
   5358 			case SEARCH_COUNT:
   5359 				ahc_qinfifo_requeue(ahc, prev_scb, scb);
   5360 				prev_scb = scb;
   5361 				break;
   5362 			}
   5363 		} else {
   5364 			ahc_qinfifo_requeue(ahc, prev_scb, scb);
   5365 			prev_scb = scb;
   5366 		}
   5367 		qinpos++;
   5368 	}
   5369 
   5370 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
   5371 		ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
   5372 	} else {
   5373 		ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
   5374 	}
   5375 
   5376 	if (action != SEARCH_COUNT
   5377 	 && (found != 0)
   5378 	 && (qinstart != ahc->qinfifonext)) {
   5379 		/*
   5380 		 * The sequencer may be in the process of DMA'ing
   5381 		 * down the SCB at the beginning of the queue.
   5382 		 * This could be problematic if either the first,
   5383 		 * or the second SCB is removed from the queue
   5384 		 * (the first SCB includes a pointer to the "next"
   5385 		 * SCB to DMA). If we have removed any entries, swap
   5386 		 * the first element in the queue with the next HSCB
   5387 		 * so the sequencer will notice that NEXT_QUEUED_SCB
   5388 		 * has changed during its DMA attempt and will retry
   5389 		 * the DMA.
   5390 		 */
   5391 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qinstart]);
   5392 
   5393 		if (scb == NULL) {
   5394 			printf("found = %d, qinstart = %d, qinfifionext = %d\n",
   5395 				found, qinstart, ahc->qinfifonext);
   5396 			panic("First/Second Qinfifo fixup\n");
   5397 		}
   5398 		/*
   5399 		 * ahc_swap_with_next_hscb forces our next pointer to
   5400 		 * point to the reserved SCB for future commands.  Save
   5401 		 * and restore our original next pointer to maintain
   5402 		 * queue integrity.
   5403 		 */
   5404 		next = scb->hscb->next;
   5405 		ahc->scb_data->scbindex[scb->hscb->tag] = NULL;
   5406 		ahc_swap_with_next_hscb(ahc, scb);
   5407 		scb->hscb->next = next;
   5408 		ahc->qinfifo[qinstart] = scb->hscb->tag;
   5409 
   5410 		/* Tell the card about the new head of the qinfifo. */
   5411 		ahc_outb(ahc, NEXT_QUEUED_SCB, scb->hscb->tag);
   5412 
   5413 		/* Fixup the tail "next" pointer. */
   5414 		qintail = ahc->qinfifonext - 1;
   5415 		scb = ahc_lookup_scb(ahc, ahc->qinfifo[qintail]);
   5416 		scb->hscb->next = ahc->next_queued_scb->hscb->tag;
   5417 	}
   5418 
   5419 	/*
   5420 	 * Search waiting for selection list.
   5421 	 */
   5422 	curscbptr = ahc_inb(ahc, SCBPTR);
   5423 	next = ahc_inb(ahc, WAITING_SCBH);  /* Start at head of list. */
   5424 	prev = SCB_LIST_NULL;
   5425 
   5426 	while (next != SCB_LIST_NULL) {
   5427 		uint8_t scb_index;
   5428 
   5429 		ahc_outb(ahc, SCBPTR, next);
   5430 		scb_index = ahc_inb(ahc, SCB_TAG);
   5431 		if (scb_index >= ahc->scb_data->numscbs) {
   5432 			printf("Waiting List inconsistency. "
   5433 			       "SCB index == %d, yet numscbs == %d.",
   5434 			       scb_index, ahc->scb_data->numscbs);
   5435 			ahc_dump_card_state(ahc);
   5436 			panic("for safety");
   5437 		}
   5438 		scb = ahc_lookup_scb(ahc, scb_index);
   5439 		if (scb == NULL) {
   5440 			printf("scb_index = %d, next = %d\n",
   5441 				scb_index, next);
   5442 			panic("Waiting List traversal\n");
   5443 		}
   5444 		if (ahc_match_scb(ahc, scb, target, channel,
   5445 				  lun, SCB_LIST_NULL, role)) {
   5446 			/*
   5447 			 * We found an scb that needs to be acted on.
   5448 			 */
   5449 			found++;
   5450 			switch (action) {
   5451 			case SEARCH_COMPLETE:
   5452 			{
   5453 				cam_status ostat;
   5454 				cam_status cstat;
   5455 
   5456 				ostat = ahc_get_transaction_status(scb);
   5457 				if (ostat == CAM_REQ_INPROG)
   5458 					ahc_set_transaction_status(scb, status);
   5459 				cstat = ahc_get_transaction_status(scb);
   5460 				if (cstat != CAM_REQ_CMP)
   5461 					ahc_freeze_scb(scb);
   5462 				if ((scb->flags & SCB_ACTIVE) == 0)
   5463 					printf("Inactive SCB in Waiting List\n");
   5464 				ahc_done(ahc, scb);
   5465 				/* FALLTHROUGH */
   5466 			}
   5467 			case SEARCH_REMOVE:
   5468 				next = ahc_rem_wscb(ahc, next, prev);
   5469 				break;
   5470 			case SEARCH_COUNT:
   5471 				prev = next;
   5472 				next = ahc_inb(ahc, SCB_NEXT);
   5473 				break;
   5474 			}
   5475 		} else {
   5476 
   5477 			prev = next;
   5478 			next = ahc_inb(ahc, SCB_NEXT);
   5479 		}
   5480 	}
   5481 	ahc_outb(ahc, SCBPTR, curscbptr);
   5482 
   5483 	found += ahc_search_untagged_queues(ahc, /*ahc_io_ctx_t*/NULL, target,
   5484 					    channel, lun, status, action);
   5485 
   5486 	if (action == SEARCH_COMPLETE)
   5487 		ahc_release_untagged_queues(ahc);
   5488 	return (found);
   5489 }
   5490 
   5491 int
   5492 ahc_search_untagged_queues(struct ahc_softc *ahc, struct scsipi_xfer *xs, /*ahc_io_ctx_t ctx,*/
   5493 			   int target, char channel, int lun, uint32_t status,
   5494 			   ahc_search_action action)
   5495 {
   5496 	struct	scb *scb;
   5497 	int	maxtarget;
   5498 	int	found;
   5499 	int	i;
   5500 
   5501 	if (action == SEARCH_COMPLETE) {
   5502 		/*
   5503 		 * Don't attempt to run any queued untagged transactions
   5504 		 * until we are done with the abort process.
   5505 		 */
   5506 		ahc_freeze_untagged_queues(ahc);
   5507 	}
   5508 
   5509 	found = 0;
   5510 	i = 0;
   5511 	if ((ahc->flags & AHC_SCB_BTT) == 0) {
   5512 
   5513 		maxtarget = 16;
   5514 		if (target != CAM_TARGET_WILDCARD) {
   5515 
   5516 			i = target;
   5517 			if (channel == 'B')
   5518 				i += 8;
   5519 			maxtarget = i + 1;
   5520 		}
   5521 	} else {
   5522 		maxtarget = 0;
   5523 	}
   5524 
   5525 	for (; i < maxtarget; i++) {
   5526 		struct scb_tailq *untagged_q;
   5527 		struct scb *next_scb;
   5528 
   5529 		untagged_q = &(ahc->untagged_queues[i]);
   5530 		next_scb = TAILQ_FIRST(untagged_q);
   5531 		while (next_scb != NULL) {
   5532 
   5533 			scb = next_scb;
   5534 			next_scb = TAILQ_NEXT(scb, links.tqe);
   5535 
   5536 			/*
   5537 			 * The head of the list may be the currently
   5538 			 * active untagged command for a device.
   5539 			 * We're only searching for commands that
   5540 			 * have not been started.  A transaction
   5541 			 * marked active but still in the qinfifo
   5542 			 * is removed by the qinfifo scanning code
   5543 			 * above.
   5544 			 */
   5545 			if ((scb->flags & SCB_ACTIVE) != 0)
   5546 				continue;
   5547 
   5548 			if (ahc_match_scb(ahc, scb, target, channel, lun,
   5549 					  SCB_LIST_NULL, ROLE_INITIATOR) == 0
   5550 			    /*|| (ctx != NULL && ctx != scb->io_ctx)*/)
   5551 				continue;
   5552 
   5553 			/*
   5554 			 * We found an scb that needs to be acted on.
   5555 			 */
   5556 			found++;
   5557 			switch (action) {
   5558 			case SEARCH_COMPLETE:
   5559 			{
   5560 				cam_status ostat;
   5561 				cam_status cstat;
   5562 
   5563 				ostat = ahc_get_transaction_status(scb);
   5564 				if (ostat == CAM_REQ_INPROG)
   5565 					ahc_set_transaction_status(scb, status);
   5566 				cstat = ahc_get_transaction_status(scb);
   5567 				if (cstat != CAM_REQ_CMP)
   5568 					ahc_freeze_scb(scb);
   5569 				if ((scb->flags & SCB_ACTIVE) == 0)
   5570 					printf("Inactive SCB in untaggedQ\n");
   5571 				ahc_done(ahc, scb);
   5572 				break;
   5573 			}
   5574 			case SEARCH_REMOVE:
   5575 				scb->flags &= ~SCB_UNTAGGEDQ;
   5576 				TAILQ_REMOVE(untagged_q, scb, links.tqe);
   5577 				break;
   5578 			case SEARCH_COUNT:
   5579 				break;
   5580 			}
   5581 		}
   5582 	}
   5583 
   5584 	if (action == SEARCH_COMPLETE)
   5585 		ahc_release_untagged_queues(ahc);
   5586 	return (found);
   5587 }
   5588 
   5589 int
   5590 ahc_search_disc_list(struct ahc_softc *ahc, int target, char channel,
   5591 		     int lun, u_int tag, int stop_on_first, int remove,
   5592 		     int save_state)
   5593 {
   5594 	struct	scb *scbp;
   5595 	u_int	next;
   5596 	u_int	prev;
   5597 	u_int	count;
   5598 	u_int	active_scb;
   5599 
   5600 	count = 0;
   5601 	next = ahc_inb(ahc, DISCONNECTED_SCBH);
   5602 	prev = SCB_LIST_NULL;
   5603 
   5604 	if (save_state) {
   5605 		/* restore this when we're done */
   5606 		active_scb = ahc_inb(ahc, SCBPTR);
   5607 	} else
   5608 		/* Silence compiler */
   5609 		active_scb = SCB_LIST_NULL;
   5610 
   5611 	while (next != SCB_LIST_NULL) {
   5612 		u_int scb_index;
   5613 
   5614 		ahc_outb(ahc, SCBPTR, next);
   5615 		scb_index = ahc_inb(ahc, SCB_TAG);
   5616 		if (scb_index >= ahc->scb_data->numscbs) {
   5617 			printf("Disconnected List inconsistency. "
   5618 			       "SCB index == %d, yet numscbs == %d.",
   5619 			       scb_index, ahc->scb_data->numscbs);
   5620 			ahc_dump_card_state(ahc);
   5621 			panic("for safety");
   5622 		}
   5623 
   5624 		if (next == prev) {
   5625 			panic("Disconnected List Loop. "
   5626 			      "cur SCBPTR == %x, prev SCBPTR == %x.",
   5627 			      next, prev);
   5628 		}
   5629 		scbp = ahc_lookup_scb(ahc, scb_index);
   5630 		if (ahc_match_scb(ahc, scbp, target, channel, lun,
   5631 				  tag, ROLE_INITIATOR)) {
   5632 			count++;
   5633 			if (remove) {
   5634 				next =
   5635 				    ahc_rem_scb_from_disc_list(ahc, prev, next);
   5636 			} else {
   5637 				prev = next;
   5638 				next = ahc_inb(ahc, SCB_NEXT);
   5639 			}
   5640 			if (stop_on_first)
   5641 				break;
   5642 		} else {
   5643 			prev = next;
   5644 			next = ahc_inb(ahc, SCB_NEXT);
   5645 		}
   5646 	}
   5647 	if (save_state)
   5648 		ahc_outb(ahc, SCBPTR, active_scb);
   5649 	return (count);
   5650 }
   5651 
   5652 /*
   5653  * Remove an SCB from the on chip list of disconnected transactions.
   5654  * This is empty/unused if we are not performing SCB paging.
   5655  */
   5656 static u_int
   5657 ahc_rem_scb_from_disc_list(struct ahc_softc *ahc, u_int prev, u_int scbptr)
   5658 {
   5659 	u_int next;
   5660 
   5661 	ahc_outb(ahc, SCBPTR, scbptr);
   5662 	next = ahc_inb(ahc, SCB_NEXT);
   5663 
   5664 	ahc_outb(ahc, SCB_CONTROL, 0);
   5665 
   5666 	ahc_add_curscb_to_free_list(ahc);
   5667 
   5668 	if (prev != SCB_LIST_NULL) {
   5669 		ahc_outb(ahc, SCBPTR, prev);
   5670 		ahc_outb(ahc, SCB_NEXT, next);
   5671 	} else
   5672 		ahc_outb(ahc, DISCONNECTED_SCBH, next);
   5673 
   5674 	return (next);
   5675 }
   5676 
   5677 /*
   5678  * Add the SCB as selected by SCBPTR onto the on chip list of
   5679  * free hardware SCBs.  This list is empty/unused if we are not
   5680  * performing SCB paging.
   5681  */
   5682 static void
   5683 ahc_add_curscb_to_free_list(struct ahc_softc *ahc)
   5684 {
   5685 	/*
   5686 	 * Invalidate the tag so that our abort
   5687 	 * routines don't think it's active.
   5688 	 */
   5689 	ahc_outb(ahc, SCB_TAG, SCB_LIST_NULL);
   5690 
   5691 	if ((ahc->flags & AHC_PAGESCBS) != 0) {
   5692 		ahc_outb(ahc, SCB_NEXT, ahc_inb(ahc, FREE_SCBH));
   5693 		ahc_outb(ahc, FREE_SCBH, ahc_inb(ahc, SCBPTR));
   5694 	}
   5695 }
   5696 
   5697 /*
   5698  * Manipulate the waiting for selection list and return the
   5699  * scb that follows the one that we remove.
   5700  */
   5701 static u_int
   5702 ahc_rem_wscb(struct ahc_softc *ahc, u_int scbpos, u_int prev)
   5703 {
   5704 	u_int curscb, next;
   5705 
   5706 	/*
   5707 	 * Select the SCB we want to abort and
   5708 	 * pull the next pointer out of it.
   5709 	 */
   5710 	curscb = ahc_inb(ahc, SCBPTR);
   5711 	ahc_outb(ahc, SCBPTR, scbpos);
   5712 	next = ahc_inb(ahc, SCB_NEXT);
   5713 
   5714 	/* Clear the necessary fields */
   5715 	ahc_outb(ahc, SCB_CONTROL, 0);
   5716 
   5717 	ahc_add_curscb_to_free_list(ahc);
   5718 
   5719 	/* update the waiting list */
   5720 	if (prev == SCB_LIST_NULL) {
   5721 		/* First in the list */
   5722 		ahc_outb(ahc, WAITING_SCBH, next);
   5723 
   5724 		/*
   5725 		 * Ensure we aren't attempting to perform
   5726 		 * selection for this entry.
   5727 		 */
   5728 		ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
   5729 	} else {
   5730 		/*
   5731 		 * Select the scb that pointed to us
   5732 		 * and update its next pointer.
   5733 		 */
   5734 		ahc_outb(ahc, SCBPTR, prev);
   5735 		ahc_outb(ahc, SCB_NEXT, next);
   5736 	}
   5737 
   5738 	/*
   5739 	 * Point us back at the original scb position.
   5740 	 */
   5741 	ahc_outb(ahc, SCBPTR, curscb);
   5742 	return next;
   5743 }
   5744 
   5745 /******************************** Error Handling ******************************/
   5746 /*
   5747  * Abort all SCBs that match the given description (target/channel/lun/tag),
   5748  * setting their status to the passed in status if the status has not already
   5749  * been modified from CAM_REQ_INPROG.  This routine assumes that the sequencer
   5750  * is paused before it is called.
   5751  */
   5752 int
   5753 ahc_abort_scbs(struct ahc_softc *ahc, int target, char channel,
   5754 	       int lun, u_int tag, role_t role, uint32_t status)
   5755 {
   5756 	struct	scb *scbp;
   5757 	struct	scb *scbp_next;
   5758 	u_int	active_scb;
   5759 	int	i, j;
   5760 	int	maxtarget;
   5761 	int	minlun;
   5762 	int	maxlun;
   5763 
   5764 	int	found;
   5765 
   5766 	/*
   5767 	 * Don't attempt to run any queued untagged transactions
   5768 	 * until we are done with the abort process.
   5769 	 */
   5770 	ahc_freeze_untagged_queues(ahc);
   5771 
   5772 	/* restore this when we're done */
   5773 	active_scb = ahc_inb(ahc, SCBPTR);
   5774 
   5775 	found = ahc_search_qinfifo(ahc, target, channel, lun, SCB_LIST_NULL,
   5776 				   role, CAM_REQUEUE_REQ, SEARCH_COMPLETE);
   5777 
   5778 	/*
   5779 	 * Clean out the busy target table for any untagged commands.
   5780 	 */
   5781 	i = 0;
   5782 	maxtarget = 16;
   5783 	if (target != CAM_TARGET_WILDCARD) {
   5784 		i = target;
   5785 		if (channel == 'B')
   5786 			i += 8;
   5787 		maxtarget = i + 1;
   5788 	}
   5789 
   5790 	if (lun == CAM_LUN_WILDCARD) {
   5791 
   5792 		/*
   5793 		 * Unless we are using an SCB based
   5794 		 * busy targets table, there is only
   5795 		 * one table entry for all luns of
   5796 		 * a target.
   5797 		 */
   5798 		minlun = 0;
   5799 		maxlun = 1;
   5800 		if ((ahc->flags & AHC_SCB_BTT) != 0)
   5801 			maxlun = AHC_NUM_LUNS;
   5802 	} else {
   5803 		minlun = lun;
   5804 		maxlun = lun + 1;
   5805 	}
   5806 
   5807 	if (role != ROLE_TARGET) {
   5808 		for (;i < maxtarget; i++) {
   5809 			for (j = minlun;j < maxlun; j++) {
   5810 				u_int scbid;
   5811 				u_int tcl;
   5812 
   5813 				tcl = BUILD_TCL(i << 4, j);
   5814 				scbid = ahc_index_busy_tcl(ahc, tcl);
   5815 				scbp = ahc_lookup_scb(ahc, scbid);
   5816 				if (scbp == NULL
   5817 				 || ahc_match_scb(ahc, scbp, target, channel,
   5818 						  lun, tag, role) == 0)
   5819 					continue;
   5820 				ahc_unbusy_tcl(ahc, BUILD_TCL(i << 4, j));
   5821 			}
   5822 		}
   5823 
   5824 		/*
   5825 		 * Go through the disconnected list and remove any entries we
   5826 		 * have queued for completion, 0'ing their control byte too.
   5827 		 * We save the active SCB and restore it ourselves, so there
   5828 		 * is no reason for this search to restore it too.
   5829 		 */
   5830 		ahc_search_disc_list(ahc, target, channel, lun, tag,
   5831 				     /*stop_on_first*/FALSE, /*remove*/TRUE,
   5832 				     /*save_state*/FALSE);
   5833 	}
   5834 
   5835 	/*
   5836 	 * Go through the hardware SCB array looking for commands that
   5837 	 * were active but not on any list.  In some cases, these remnants
   5838 	 * might not still have mappings in the scbindex array (e.g. unexpected
   5839 	 * bus free with the same scb queued for an abort).  Don't hold this
   5840 	 * against them.
   5841 	 */
   5842 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
   5843 		u_int scbid;
   5844 
   5845 		ahc_outb(ahc, SCBPTR, i);
   5846 		scbid = ahc_inb(ahc, SCB_TAG);
   5847 		scbp = ahc_lookup_scb(ahc, scbid);
   5848 		if ((scbp == NULL && scbid != SCB_LIST_NULL)
   5849 		 || (scbp != NULL
   5850 		  && ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)))
   5851 			ahc_add_curscb_to_free_list(ahc);
   5852 	}
   5853 
   5854 	/*
   5855 	 * Go through the pending CCB list and look for
   5856 	 * commands for this target that are still active.
   5857 	 * These are other tagged commands that were
   5858 	 * disconnected when the reset occurred.
   5859 	 */
   5860 	scbp_next = LIST_FIRST(&ahc->pending_scbs);
   5861 	while (scbp_next != NULL) {
   5862 		scbp = scbp_next;
   5863 		scbp_next = LIST_NEXT(scbp, pending_links);
   5864 		if (ahc_match_scb(ahc, scbp, target, channel, lun, tag, role)) {
   5865 			cam_status ostat;
   5866 
   5867 			ostat = ahc_get_transaction_status(scbp);
   5868 			if (ostat == CAM_REQ_INPROG)
   5869 				ahc_set_transaction_status(scbp, status);
   5870 			if (ahc_get_transaction_status(scbp) != CAM_REQ_CMP)
   5871 				ahc_freeze_scb(scbp);
   5872 			if ((scbp->flags & SCB_ACTIVE) == 0)
   5873 				printf("Inactive SCB on pending list\n");
   5874 			ahc_done(ahc, scbp);
   5875 			found++;
   5876 		}
   5877 	}
   5878 	ahc_outb(ahc, SCBPTR, active_scb);
   5879 	ahc_platform_abort_scbs(ahc, target, channel, lun, tag, role, status);
   5880 	ahc_release_untagged_queues(ahc);
   5881 	return found;
   5882 }
   5883 
   5884 static void
   5885 ahc_reset_current_bus(struct ahc_softc *ahc)
   5886 {
   5887 	uint8_t scsiseq;
   5888 
   5889 	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENSCSIRST);
   5890 	scsiseq = ahc_inb(ahc, SCSISEQ);
   5891 	ahc_outb(ahc, SCSISEQ, scsiseq | SCSIRSTO);
   5892 	ahc_flush_device_writes(ahc);
   5893 	ahc_delay(AHC_BUSRESET_DELAY);
   5894 	/* Turn off the bus reset */
   5895 	ahc_outb(ahc, SCSISEQ, scsiseq & ~SCSIRSTO);
   5896 
   5897 	ahc_clear_intstat(ahc);
   5898 
   5899 	/* Re-enable reset interrupts */
   5900 	ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) | ENSCSIRST);
   5901 }
   5902 
   5903 int
   5904 ahc_reset_channel(struct ahc_softc *ahc, char channel, int initiate_reset)
   5905 {
   5906 	struct	ahc_devinfo dinfo;
   5907 	u_int	initiator, target, max_scsiid;
   5908 	u_int	sblkctl;
   5909 	u_int	scsiseq;
   5910 	u_int	simode1;
   5911 	int	found;
   5912 	int	restart_needed;
   5913 	char	cur_channel;
   5914 
   5915 	ahc->pending_device = NULL;
   5916 
   5917 	ahc_compile_devinfo(&dinfo,
   5918 			    CAM_TARGET_WILDCARD,
   5919 			    CAM_TARGET_WILDCARD,
   5920 			    CAM_LUN_WILDCARD,
   5921 			    channel, ROLE_UNKNOWN);
   5922 	ahc_pause(ahc);
   5923 
   5924 	/* Make sure the sequencer is in a safe location. */
   5925 	ahc_clear_critical_section(ahc);
   5926 
   5927 	/*
   5928 	 * Run our command complete fifos to ensure that we perform
   5929 	 * completion processing on any commands that 'completed'
   5930 	 * before the reset occurred.
   5931 	 */
   5932 	ahc_run_qoutfifo(ahc);
   5933 #if AHC_TARGET_MODE
   5934 	/*
   5935 	 * XXX - In Twin mode, the tqinfifo may have commands
   5936 	 *	 for an unaffected channel in it.  However, if
   5937 	 *	 we have run out of ATIO resources to drain that
   5938 	 *	 queue, we may not get them all out here.  Further,
   5939 	 *	 the blocked transactions for the reset channel
   5940 	 *	 should just be killed off, irrespecitve of whether
   5941 	 *	 we are blocked on ATIO resources.  Write a routine
   5942 	 *	 to compact the tqinfifo appropriately.
   5943 	 */
   5944 	if ((ahc->flags & AHC_TARGETROLE) != 0) {
   5945 		ahc_run_tqinfifo(ahc, /*paused*/TRUE);
   5946 	}
   5947 #endif
   5948 
   5949 	/*
   5950 	 * Reset the bus if we are initiating this reset
   5951 	 */
   5952 	sblkctl = ahc_inb(ahc, SBLKCTL);
   5953 	cur_channel = 'A';
   5954 	if ((ahc->features & AHC_TWIN) != 0
   5955 	 && ((sblkctl & SELBUSB) != 0))
   5956 	    cur_channel = 'B';
   5957 	scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
   5958 	if (cur_channel != channel) {
   5959 		/* Case 1: Command for another bus is active
   5960 		 * Stealthily reset the other bus without
   5961 		 * upsetting the current bus.
   5962 		 */
   5963 		ahc_outb(ahc, SBLKCTL, sblkctl ^ SELBUSB);
   5964 		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
   5965 #if AHC_TARGET_MODE
   5966 		/*
   5967 		 * Bus resets clear ENSELI, so we cannot
   5968 		 * defer re-enabling bus reset interrupts
   5969 		 * if we are in target mode.
   5970 		 */
   5971 		if ((ahc->flags & AHC_TARGETROLE) != 0)
   5972 			simode1 |= ENSCSIRST;
   5973 #endif
   5974 		ahc_outb(ahc, SIMODE1, simode1);
   5975 		if (initiate_reset)
   5976 			ahc_reset_current_bus(ahc);
   5977 		ahc_clear_intstat(ahc);
   5978 		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
   5979 		ahc_outb(ahc, SBLKCTL, sblkctl);
   5980 		restart_needed = FALSE;
   5981 	} else {
   5982 		/* Case 2: A command from this bus is active or we're idle */
   5983 		simode1 = ahc_inb(ahc, SIMODE1) & ~(ENBUSFREE|ENSCSIRST);
   5984 #if AHC_TARGET_MODE
   5985 		/*
   5986 		 * Bus resets clear ENSELI, so we cannot
   5987 		 * defer re-enabling bus reset interrupts
   5988 		 * if we are in target mode.
   5989 		 */
   5990 		if ((ahc->flags & AHC_TARGETROLE) != 0)
   5991 			simode1 |= ENSCSIRST;
   5992 #endif
   5993 		ahc_outb(ahc, SIMODE1, simode1);
   5994 		if (initiate_reset)
   5995 			ahc_reset_current_bus(ahc);
   5996 		ahc_clear_intstat(ahc);
   5997 		ahc_outb(ahc, SCSISEQ, scsiseq & (ENSELI|ENRSELI|ENAUTOATNP));
   5998 		restart_needed = TRUE;
   5999 	}
   6000 
   6001 	/*
   6002 	 * Clean up all the state information for the
   6003 	 * pending transactions on this bus.
   6004 	 */
   6005 	found = ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, channel,
   6006 			       CAM_LUN_WILDCARD, SCB_LIST_NULL,
   6007 			       ROLE_UNKNOWN, CAM_SCSI_BUS_RESET);
   6008 
   6009 	max_scsiid = (ahc->features & AHC_WIDE) ? 15 : 7;
   6010 
   6011 #ifdef AHC_TARGET_MODE
   6012 	/*
   6013 	 * Send an immediate notify ccb to all target more peripheral
   6014 	 * drivers affected by this action.
   6015 	 */
   6016 	for (target = 0; target <= max_scsiid; target++) {
   6017 		struct ahc_tmode_tstate* tstate;
   6018 		u_int lun;
   6019 
   6020 		tstate = ahc->enabled_targets[target];
   6021 		if (tstate == NULL)
   6022 			continue;
   6023 		for (lun = 0; lun < AHC_NUM_LUNS; lun++) {
   6024 			struct ahc_tmode_lstate* lstate;
   6025 
   6026 			lstate = tstate->enabled_luns[lun];
   6027 			if (lstate == NULL)
   6028 				continue;
   6029 
   6030 			ahc_queue_lstate_event(ahc, lstate, CAM_TARGET_WILDCARD,
   6031 					       EVENT_TYPE_BUS_RESET, /*arg*/0);
   6032 			ahc_send_lstate_events(ahc, lstate);
   6033 		}
   6034 	}
   6035 #endif
   6036 	/*
   6037 	 * Revert to async/narrow transfers until we renegotiate.
   6038 	 */
   6039 	for (target = 0; target <= max_scsiid; target++) {
   6040 
   6041 		if (ahc->enabled_targets[target] == NULL)
   6042 			continue;
   6043 		for (initiator = 0; initiator <= max_scsiid; initiator++) {
   6044 			struct ahc_devinfo devinfo;
   6045 
   6046 			ahc_compile_devinfo(&devinfo, target, initiator,
   6047 					    CAM_LUN_WILDCARD,
   6048 					    channel, ROLE_UNKNOWN);
   6049 			ahc_set_width(ahc, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
   6050 				      AHC_TRANS_CUR, /*paused*/TRUE);
   6051 			ahc_set_syncrate(ahc, &devinfo, /*syncrate*/NULL,
   6052 					 /*period*/0, /*offset*/0,
   6053 					 /*ppr_options*/0, AHC_TRANS_CUR,
   6054 					 /*paused*/TRUE);
   6055 		}
   6056 	}
   6057 
   6058 	if (restart_needed)
   6059 		ahc_restart(ahc);
   6060 	else
   6061 		ahc_unpause(ahc);
   6062 	return found;
   6063 }
   6064 
   6065 
   6066 /***************************** Residual Processing ****************************/
   6067 /*
   6068  * Calculate the residual for a just completed SCB.
   6069  */
   6070 void
   6071 ahc_calc_residual(struct ahc_softc *ahc, struct scb *scb)
   6072 {
   6073 	struct hardware_scb *hscb;
   6074 	struct status_pkt *spkt;
   6075 	uint32_t sgptr;
   6076 	uint32_t resid_sgptr;
   6077 	uint32_t resid;
   6078 
   6079 	/*
   6080 	 * 5 cases.
   6081 	 * 1) No residual.
   6082 	 *    SG_RESID_VALID clear in sgptr.
   6083 	 * 2) Transferless command
   6084 	 * 3) Never performed any transfers.
   6085 	 *    sgptr has SG_FULL_RESID set.
   6086 	 * 4) No residual but target did not
   6087 	 *    save data pointers after the
   6088 	 *    last transfer, so sgptr was
   6089 	 *    never updated.
   6090 	 * 5) We have a partial residual.
   6091 	 *    Use residual_sgptr to determine
   6092 	 *    where we are.
   6093 	 */
   6094 
   6095 	hscb = scb->hscb;
   6096 	sgptr = ahc_le32toh(hscb->sgptr);
   6097 	if ((sgptr & SG_RESID_VALID) == 0)
   6098 		/* Case 1 */
   6099 		return;
   6100 	sgptr &= ~SG_RESID_VALID;
   6101 
   6102 	if ((sgptr & SG_LIST_NULL) != 0)
   6103 		/* Case 2 */
   6104 		return;
   6105 
   6106 	spkt = &hscb->shared_data.status;
   6107 	resid_sgptr = ahc_le32toh(spkt->residual_sg_ptr);
   6108 	if ((sgptr & SG_FULL_RESID) != 0) {
   6109 		/* Case 3 */
   6110 		resid = ahc_get_transfer_length(scb);
   6111 	} else if ((resid_sgptr & SG_LIST_NULL) != 0) {
   6112 		/* Case 4 */
   6113 		return;
   6114 	} else if ((resid_sgptr & ~SG_PTR_MASK) != 0) {
   6115 		panic("Bogus resid sgptr value 0x%x\n", resid_sgptr);
   6116 	} else {
   6117 		struct ahc_dma_seg *sg;
   6118 
   6119 		/*
   6120 		 * Remainder of the SG where the transfer
   6121 		 * stopped.
   6122 		 */
   6123 		resid = ahc_le32toh(spkt->residual_datacnt) & AHC_SG_LEN_MASK;
   6124 		sg = ahc_sg_bus_to_virt(scb, resid_sgptr & SG_PTR_MASK);
   6125 
   6126 		/* The residual sg_ptr always points to the next sg */
   6127 		sg--;
   6128 
   6129 		/*
   6130 		 * Add up the contents of all residual
   6131 		 * SG segments that are after the SG where
   6132 		 * the transfer stopped.
   6133 		 */
   6134 		while ((ahc_le32toh(sg->len) & AHC_DMA_LAST_SEG) == 0) {
   6135 			sg++;
   6136 			resid += ahc_le32toh(sg->len) & AHC_SG_LEN_MASK;
   6137 		}
   6138 	}
   6139 	if ((scb->flags & SCB_SENSE) == 0)
   6140 		ahc_set_residual(scb, resid);
   6141 	else
   6142 		ahc_set_sense_residual(scb, resid);
   6143 
   6144 #ifdef AHC_DEBUG
   6145 	if ((ahc_debug & AHC_SHOW_MISC) != 0) {
   6146 		ahc_print_path(ahc, scb);
   6147 		printf("Handled %sResidual of %d bytes\n",
   6148 		       (scb->flags & SCB_SENSE) ? "Sense " : "", resid);
   6149 	}
   6150 #endif
   6151 }
   6152 
   6153 /******************************* Target Mode **********************************/
   6154 #ifdef AHC_TARGET_MODE
   6155 /*
   6156  * Add a target mode event to this lun's queue
   6157  */
   6158 static void
   6159 ahc_queue_lstate_event(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate,
   6160 		       u_int initiator_id, u_int event_type, u_int event_arg)
   6161 {
   6162 	struct ahc_tmode_event *event;
   6163 	int pending;
   6164 
   6165 	xpt_freeze_devq(lstate->path, /*count*/1);
   6166 	if (lstate->event_w_idx >= lstate->event_r_idx)
   6167 		pending = lstate->event_w_idx - lstate->event_r_idx;
   6168 	else
   6169 		pending = AHC_TMODE_EVENT_BUFFER_SIZE + 1
   6170 			- (lstate->event_r_idx - lstate->event_w_idx);
   6171 
   6172 	if (event_type == EVENT_TYPE_BUS_RESET
   6173 	 || event_type == MSG_BUS_DEV_RESET) {
   6174 		/*
   6175 		 * Any earlier events are irrelevant, so reset our buffer.
   6176 		 * This has the effect of allowing us to deal with reset
   6177 		 * floods (an external device holding down the reset line)
   6178 		 * without losing the event that is really interesting.
   6179 		 */
   6180 		lstate->event_r_idx = 0;
   6181 		lstate->event_w_idx = 0;
   6182 		xpt_release_devq(lstate->path, pending, /*runqueue*/FALSE);
   6183 	}
   6184 
   6185 	if (pending == AHC_TMODE_EVENT_BUFFER_SIZE) {
   6186 		xpt_print_path(lstate->path);
   6187 		printf("immediate event %x:%x lost\n",
   6188 		       lstate->event_buffer[lstate->event_r_idx].event_type,
   6189 		       lstate->event_buffer[lstate->event_r_idx].event_arg);
   6190 		lstate->event_r_idx++;
   6191 		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
   6192 			lstate->event_r_idx = 0;
   6193 		xpt_release_devq(lstate->path, /*count*/1, /*runqueue*/FALSE);
   6194 	}
   6195 
   6196 	event = &lstate->event_buffer[lstate->event_w_idx];
   6197 	event->initiator_id = initiator_id;
   6198 	event->event_type = event_type;
   6199 	event->event_arg = event_arg;
   6200 	lstate->event_w_idx++;
   6201 	if (lstate->event_w_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
   6202 		lstate->event_w_idx = 0;
   6203 }
   6204 
   6205 /*
   6206  * Send any target mode events queued up waiting
   6207  * for immediate notify resources.
   6208  */
   6209 void
   6210 ahc_send_lstate_events(struct ahc_softc *ahc, struct ahc_tmode_lstate *lstate)
   6211 {
   6212 	struct ccb_hdr *ccbh;
   6213 	struct ccb_immed_notify *inot;
   6214 
   6215 	while (lstate->event_r_idx != lstate->event_w_idx
   6216 	    && (ccbh = SLIST_FIRST(&lstate->immed_notifies)) != NULL) {
   6217 		struct ahc_tmode_event *event;
   6218 
   6219 		event = &lstate->event_buffer[lstate->event_r_idx];
   6220 		SLIST_REMOVE_HEAD(&lstate->immed_notifies, sim_links.sle);
   6221 		inot = (struct ccb_immed_notify *)ccbh;
   6222 		switch (event->event_type) {
   6223 		case EVENT_TYPE_BUS_RESET:
   6224 			ccbh->status = CAM_SCSI_BUS_RESET|CAM_DEV_QFRZN;
   6225 			break;
   6226 		default:
   6227 			ccbh->status = CAM_MESSAGE_RECV|CAM_DEV_QFRZN;
   6228 			inot->message_args[0] = event->event_type;
   6229 			inot->message_args[1] = event->event_arg;
   6230 			break;
   6231 		}
   6232 		inot->initiator_id = event->initiator_id;
   6233 		inot->sense_len = 0;
   6234 		xpt_done((union ccb *)inot);
   6235 		lstate->event_r_idx++;
   6236 		if (lstate->event_r_idx == AHC_TMODE_EVENT_BUFFER_SIZE)
   6237 			lstate->event_r_idx = 0;
   6238 	}
   6239 }
   6240 #endif
   6241 
   6242 /******************** Sequencer Program Patching/Download *********************/
   6243 
   6244 #ifdef AHC_DUMP_SEQ
   6245 void
   6246 ahc_dumpseq(struct ahc_softc* ahc)
   6247 {
   6248 	int i;
   6249 	int max_prog;
   6250 
   6251 	if ((ahc->chip & AHC_BUS_MASK) < AHC_PCI)
   6252 		max_prog = 448;
   6253 	else if ((ahc->features & AHC_ULTRA2) != 0)
   6254 		max_prog = 768;
   6255 	else
   6256 		max_prog = 512;
   6257 
   6258 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
   6259 	ahc_outb(ahc, SEQADDR0, 0);
   6260 	ahc_outb(ahc, SEQADDR1, 0);
   6261 	for (i = 0; i < max_prog; i++) {
   6262 		uint8_t ins_bytes[4];
   6263 
   6264 		ahc_insb(ahc, SEQRAM, ins_bytes, 4);
   6265 		printf("0x%08x\n", ins_bytes[0] << 24
   6266 				 | ins_bytes[1] << 16
   6267 				 | ins_bytes[2] << 8
   6268 				 | ins_bytes[3]);
   6269 	}
   6270 }
   6271 #endif
   6272 
   6273 static void
   6274 ahc_loadseq(struct ahc_softc *ahc)
   6275 {
   6276 	struct	cs cs_table[num_critical_sections];
   6277 	u_int	begin_set[num_critical_sections];
   6278 	u_int	end_set[num_critical_sections];
   6279 	struct	patch *cur_patch;
   6280 	u_int	cs_count;
   6281 	u_int	cur_cs;
   6282 	u_int	i;
   6283 	int	downloaded;
   6284 	u_int	skip_addr;
   6285 	u_int	sg_prefetch_cnt;
   6286 	uint8_t	download_consts[7];
   6287 
   6288 	/*
   6289 	 * Start out with 0 critical sections
   6290 	 * that apply to this firmware load.
   6291 	 */
   6292 	cs_count = 0;
   6293 	cur_cs = 0;
   6294 	memset(begin_set, 0, sizeof(begin_set));
   6295 	memset(end_set, 0, sizeof(end_set));
   6296 
   6297 	/* Setup downloadable constant table */
   6298 	download_consts[QOUTFIFO_OFFSET] = 0;
   6299 	if (ahc->targetcmds != NULL)
   6300 		download_consts[QOUTFIFO_OFFSET] += 32;
   6301 	download_consts[QINFIFO_OFFSET] = download_consts[QOUTFIFO_OFFSET] + 1;
   6302 	download_consts[CACHESIZE_MASK] = ahc->pci_cachesize - 1;
   6303 	download_consts[INVERTED_CACHESIZE_MASK] = ~(ahc->pci_cachesize - 1);
   6304 	sg_prefetch_cnt = ahc->pci_cachesize;
   6305 	if (sg_prefetch_cnt < (2 * sizeof(struct ahc_dma_seg)))
   6306 		sg_prefetch_cnt = 2 * sizeof(struct ahc_dma_seg);
   6307 	download_consts[SG_PREFETCH_CNT] = sg_prefetch_cnt;
   6308 	download_consts[SG_PREFETCH_ALIGN_MASK] = ~(sg_prefetch_cnt - 1);
   6309 	download_consts[SG_PREFETCH_ADDR_MASK] = (sg_prefetch_cnt - 1);
   6310 
   6311 	cur_patch = patches;
   6312 	downloaded = 0;
   6313 	skip_addr = 0;
   6314 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE|LOADRAM);
   6315 	ahc_outb(ahc, SEQADDR0, 0);
   6316 	ahc_outb(ahc, SEQADDR1, 0);
   6317 
   6318 	for (i = 0; i < sizeof(seqprog)/4; i++) {
   6319 		if (ahc_check_patch(ahc, &cur_patch, i, &skip_addr) == 0) {
   6320 			/*
   6321 			 * Don't download this instruction as it
   6322 			 * is in a patch that was removed.
   6323 			 */
   6324 			continue;
   6325 		}
   6326 		/*
   6327 		 * Move through the CS table until we find a CS
   6328 		 * that might apply to this instruction.
   6329 		 */
   6330 		for (; cur_cs < num_critical_sections; cur_cs++) {
   6331 			if (critical_sections[cur_cs].end <= i) {
   6332 				if (begin_set[cs_count] == TRUE
   6333 				 && end_set[cs_count] == FALSE) {
   6334 					cs_table[cs_count].end = downloaded;
   6335 				 	end_set[cs_count] = TRUE;
   6336 					cs_count++;
   6337 				}
   6338 				continue;
   6339 			}
   6340 			if (critical_sections[cur_cs].begin <= i
   6341 			 && begin_set[cs_count] == FALSE) {
   6342 				cs_table[cs_count].begin = downloaded;
   6343 				begin_set[cs_count] = TRUE;
   6344 			}
   6345 			break;
   6346 		}
   6347 		ahc_download_instr(ahc, i, download_consts);
   6348 		downloaded++;
   6349 	}
   6350 
   6351 	ahc->num_critical_sections = cs_count;
   6352 	if (cs_count != 0) {
   6353 
   6354 		cs_count *= sizeof(struct cs);
   6355 		ahc->critical_sections = malloc(cs_count, M_DEVBUF, M_NOWAIT);
   6356 		if (ahc->critical_sections == NULL)
   6357 			panic("ahc_loadseq: Could not malloc");
   6358 		memcpy(ahc->critical_sections, cs_table, cs_count);
   6359 	}
   6360 	ahc_outb(ahc, SEQCTL, PERRORDIS|FAILDIS|FASTMODE);
   6361 	ahc_restart(ahc);
   6362 
   6363 	if (bootverbose) {
   6364 		printf(" %d instructions downloaded\n", downloaded);
   6365 		printf("%s: Features 0x%x, Bugs 0x%x, Flags 0x%x\n",
   6366 		       ahc_name(ahc), ahc->features, ahc->bugs, ahc->flags);
   6367 	}
   6368 }
   6369 
   6370 static int
   6371 ahc_check_patch(struct ahc_softc *ahc, struct patch **start_patch,
   6372 		u_int start_instr, u_int *skip_addr)
   6373 {
   6374 	struct	patch *cur_patch;
   6375 	struct	patch *last_patch;
   6376 	u_int	num_patches;
   6377 
   6378 	num_patches = sizeof(patches)/sizeof(struct patch);
   6379 	last_patch = &patches[num_patches];
   6380 	cur_patch = *start_patch;
   6381 
   6382 	while (cur_patch < last_patch && start_instr == cur_patch->begin) {
   6383 
   6384 		if (cur_patch->patch_func(ahc) == 0) {
   6385 
   6386 			/* Start rejecting code */
   6387 			*skip_addr = start_instr + cur_patch->skip_instr;
   6388 			cur_patch += cur_patch->skip_patch;
   6389 		} else {
   6390 			/* Accepted this patch.  Advance to the next
   6391 			 * one and wait for our intruction pointer to
   6392 			 * hit this point.
   6393 			 */
   6394 			cur_patch++;
   6395 		}
   6396 	}
   6397 
   6398 	*start_patch = cur_patch;
   6399 	if (start_instr < *skip_addr)
   6400 		/* Still skipping */
   6401 		return (0);
   6402 
   6403 	return (1);
   6404 }
   6405 
   6406 static void
   6407 ahc_download_instr(struct ahc_softc *ahc, u_int instrptr, uint8_t *dconsts)
   6408 {
   6409 	union	ins_formats instr;
   6410 	struct	ins_format1 *fmt1_ins;
   6411 	struct	ins_format3 *fmt3_ins;
   6412 	u_int	opcode;
   6413 
   6414 	/*
   6415 	 * The firmware is always compiled into a little endian format.
   6416 	 */
   6417 	instr.integer = ahc_le32toh(*(uint32_t*)&seqprog[instrptr * 4]);
   6418 
   6419 	fmt1_ins = &instr.format1;
   6420 	fmt3_ins = NULL;
   6421 
   6422 	/* Pull the opcode */
   6423 	opcode = instr.format1.opcode;
   6424 	switch (opcode) {
   6425 	case AIC_OP_JMP:
   6426 	case AIC_OP_JC:
   6427 	case AIC_OP_JNC:
   6428 	case AIC_OP_CALL:
   6429 	case AIC_OP_JNE:
   6430 	case AIC_OP_JNZ:
   6431 	case AIC_OP_JE:
   6432 	case AIC_OP_JZ:
   6433 	{
   6434 		struct patch *cur_patch;
   6435 		int address_offset;
   6436 		u_int address;
   6437 		u_int skip_addr;
   6438 		u_int i;
   6439 
   6440 		fmt3_ins = &instr.format3;
   6441 		address_offset = 0;
   6442 		address = fmt3_ins->address;
   6443 		cur_patch = patches;
   6444 		skip_addr = 0;
   6445 		for (i = 0; i < address;) {
   6446 			ahc_check_patch(ahc, &cur_patch, i, &skip_addr);
   6447 
   6448 			if (skip_addr > i) {
   6449 				int end_addr;
   6450 
   6451 				end_addr = MIN(address, skip_addr);
   6452 				address_offset += end_addr - i;
   6453 				i = skip_addr;
   6454 			} else {
   6455 				i++;
   6456 			}
   6457 		}
   6458 		address -= address_offset;
   6459 		fmt3_ins->address = address;
   6460 		/* FALLTHROUGH */
   6461 	}
   6462 	case AIC_OP_OR:
   6463 	case AIC_OP_AND:
   6464 	case AIC_OP_XOR:
   6465 	case AIC_OP_ADD:
   6466 	case AIC_OP_ADC:
   6467 	case AIC_OP_BMOV:
   6468 		if (fmt1_ins->parity != 0) {
   6469 			fmt1_ins->immediate = dconsts[fmt1_ins->immediate];
   6470 		}
   6471 		fmt1_ins->parity = 0;
   6472 		if ((ahc->features & AHC_CMD_CHAN) == 0
   6473 		 && opcode == AIC_OP_BMOV) {
   6474 			/*
   6475 			 * Block move was added at the same time
   6476 			 * as the command channel.  Verify that
   6477 			 * this is only a move of a single element
   6478 			 * and convert the BMOV to a MOV
   6479 			 * (AND with an immediate of FF).
   6480 			 */
   6481 			if (fmt1_ins->immediate != 1)
   6482 				panic("%s: BMOV not supported\n",
   6483 				      ahc_name(ahc));
   6484 			fmt1_ins->opcode = AIC_OP_AND;
   6485 			fmt1_ins->immediate = 0xff;
   6486 		}
   6487 		/* FALLTHROUGH */
   6488 	case AIC_OP_ROL:
   6489 		if ((ahc->features & AHC_ULTRA2) != 0) {
   6490 			int i, count;
   6491 
   6492 			/* Calculate odd parity for the instruction */
   6493 			for (i = 0, count = 0; i < 31; i++) {
   6494 				uint32_t mask;
   6495 
   6496 				mask = 0x01 << i;
   6497 				if ((instr.integer & mask) != 0)
   6498 					count++;
   6499 			}
   6500 			if ((count & 0x01) == 0)
   6501 				instr.format1.parity = 1;
   6502 		} else {
   6503 			/* Compress the instruction for older sequencers */
   6504 			if (fmt3_ins != NULL) {
   6505 				instr.integer =
   6506 					fmt3_ins->immediate
   6507 				      | (fmt3_ins->source << 8)
   6508 				      | (fmt3_ins->address << 16)
   6509 				      |	(fmt3_ins->opcode << 25);
   6510 			} else {
   6511 				instr.integer =
   6512 					fmt1_ins->immediate
   6513 				      | (fmt1_ins->source << 8)
   6514 				      | (fmt1_ins->destination << 16)
   6515 				      |	(fmt1_ins->ret << 24)
   6516 				      |	(fmt1_ins->opcode << 25);
   6517 			}
   6518 		}
   6519 		/* The sequencer is a little endian CPU */
   6520 		instr.integer = ahc_htole32(instr.integer);
   6521 		ahc_outsb(ahc, SEQRAM, instr.bytes, 4);
   6522 		break;
   6523 	default:
   6524 		panic("Unknown opcode encountered in seq program");
   6525 		break;
   6526 	}
   6527 }
   6528 
   6529 int
   6530 ahc_print_register(ahc_reg_parse_entry_t *table, u_int num_entries,
   6531 		   const char *name, u_int address, u_int value,
   6532 		   u_int *cur_column, u_int wrap_point)
   6533 {
   6534 	int	printed;
   6535 	u_int	printed_mask;
   6536 	char    line[1024];
   6537 
   6538 	line[0] = 0;
   6539 
   6540 	if (cur_column != NULL && *cur_column >= wrap_point) {
   6541 		printf("\n");
   6542 		*cur_column = 0;
   6543 	}
   6544 	printed = snprintf(line, sizeof(line), "%s[0x%x]", name, value);
   6545 	if (table == NULL) {
   6546 		printed += snprintf(&line[printed], (sizeof line) - printed,
   6547 		    " ");
   6548 		printf("%s", line);
   6549 		if (cur_column != NULL)
   6550 			*cur_column += printed;
   6551 		return (printed);
   6552 	}
   6553 	printed_mask = 0;
   6554 	while (printed_mask != 0xFF) {
   6555 		int entry;
   6556 
   6557 		for (entry = 0; entry < num_entries; entry++) {
   6558 			if (((value & table[entry].mask)
   6559 			  != table[entry].value)
   6560 			 || ((printed_mask & table[entry].mask)
   6561 			  == table[entry].mask))
   6562 				continue;
   6563 			printed += snprintf(&line[printed],
   6564 			    (sizeof line) - printed, "%s%s",
   6565 				printed_mask == 0 ? ":(" : "|",
   6566 				table[entry].name);
   6567 			printed_mask |= table[entry].mask;
   6568 
   6569 			break;
   6570 		}
   6571 		if (entry >= num_entries)
   6572 			break;
   6573 	}
   6574 	if (printed_mask != 0)
   6575 		printed += snprintf(&line[printed],
   6576 		    (sizeof line) - printed, ") ");
   6577 	else
   6578 		printed += snprintf(&line[printed],
   6579 		    (sizeof line) - printed, " ");
   6580 	if (cur_column != NULL)
   6581 		*cur_column += printed;
   6582 	printf("%s", line);
   6583 
   6584 	return (printed);
   6585 }
   6586 
   6587 void
   6588 ahc_dump_card_state(struct ahc_softc *ahc)
   6589 {
   6590 	struct	scb *scb;
   6591 	struct	scb_tailq *untagged_q;
   6592 	u_int	cur_col;
   6593 	int	paused;
   6594 	int	target;
   6595 	int	maxtarget;
   6596 	int	i;
   6597 	uint8_t last_phase;
   6598 	uint8_t qinpos;
   6599 	uint8_t qintail;
   6600 	uint8_t qoutpos;
   6601 	uint8_t scb_index;
   6602 	uint8_t saved_scbptr;
   6603 
   6604 	if (ahc_is_paused(ahc)) {
   6605 		paused = 1;
   6606 	} else {
   6607 		paused = 0;
   6608 		ahc_pause(ahc);
   6609 	}
   6610 
   6611 	saved_scbptr = ahc_inb(ahc, SCBPTR);
   6612 	last_phase = ahc_inb(ahc, LASTPHASE);
   6613 	printf(">>>>>>>>>>>>>>>>>> Dump Card State Begins <<<<<<<<<<<<<<<<<\n"
   6614 	       "%s: Dumping Card State %s, at SEQADDR 0x%x\n",
   6615 	       ahc_name(ahc), ahc_lookup_phase_entry(last_phase)->phasemsg,
   6616 	       ahc_inb(ahc, SEQADDR0) | (ahc_inb(ahc, SEQADDR1) << 8));
   6617 	if (paused)
   6618 		printf("Card was paused\n");
   6619 	printf("ACCUM = 0x%x, SINDEX = 0x%x, DINDEX = 0x%x, ARG_2 = 0x%x\n",
   6620 	       ahc_inb(ahc, ACCUM), ahc_inb(ahc, SINDEX), ahc_inb(ahc, DINDEX),
   6621 	       ahc_inb(ahc, ARG_2));
   6622 	printf("HCNT = 0x%x SCBPTR = 0x%x\n", ahc_inb(ahc, HCNT),
   6623 	       ahc_inb(ahc, SCBPTR));
   6624 	cur_col = 0;
   6625 	if ((ahc->features & AHC_DT) != 0)
   6626 		ahc_scsiphase_print(ahc_inb(ahc, SCSIPHASE), &cur_col, 50);
   6627 	ahc_scsisigi_print(ahc_inb(ahc, SCSISIGI), &cur_col, 50);
   6628 	ahc_error_print(ahc_inb(ahc, ERROR), &cur_col, 50);
   6629 	ahc_scsibusl_print(ahc_inb(ahc, SCSIBUSL), &cur_col, 50);
   6630 	ahc_lastphase_print(ahc_inb(ahc, LASTPHASE), &cur_col, 50);
   6631 	ahc_scsiseq_print(ahc_inb(ahc, SCSISEQ), &cur_col, 50);
   6632 	ahc_sblkctl_print(ahc_inb(ahc, SBLKCTL), &cur_col, 50);
   6633 	ahc_scsirate_print(ahc_inb(ahc, SCSIRATE), &cur_col, 50);
   6634 	ahc_seqctl_print(ahc_inb(ahc, SEQCTL), &cur_col, 50);
   6635 	ahc_seq_flags_print(ahc_inb(ahc, SEQ_FLAGS), &cur_col, 50);
   6636 	ahc_sstat0_print(ahc_inb(ahc, SSTAT0), &cur_col, 50);
   6637 	ahc_sstat1_print(ahc_inb(ahc, SSTAT1), &cur_col, 50);
   6638 	ahc_sstat2_print(ahc_inb(ahc, SSTAT2), &cur_col, 50);
   6639 	ahc_sstat3_print(ahc_inb(ahc, SSTAT3), &cur_col, 50);
   6640 	ahc_simode0_print(ahc_inb(ahc, SIMODE0), &cur_col, 50);
   6641 	ahc_simode1_print(ahc_inb(ahc, SIMODE1), &cur_col, 50);
   6642 	ahc_sxfrctl0_print(ahc_inb(ahc, SXFRCTL0), &cur_col, 50);
   6643 	ahc_dfcntrl_print(ahc_inb(ahc, DFCNTRL), &cur_col, 50);
   6644 	ahc_dfstatus_print(ahc_inb(ahc, DFSTATUS), &cur_col, 50);
   6645 	if (cur_col != 0)
   6646 		printf("\n");
   6647 	printf("STACK:");
   6648 	for (i = 0; i < STACK_SIZE; i++)
   6649 	       printf(" 0x%x", ahc_inb(ahc, STACK)|(ahc_inb(ahc, STACK) << 8));
   6650 	printf("\nSCB count = %d\n", ahc->scb_data->numscbs);
   6651 	printf("Kernel NEXTQSCB = %d\n", ahc->next_queued_scb->hscb->tag);
   6652 	printf("Card NEXTQSCB = %d\n", ahc_inb(ahc, NEXT_QUEUED_SCB));
   6653 	/* QINFIFO */
   6654 	printf("QINFIFO entries: ");
   6655 	if ((ahc->features & AHC_QUEUE_REGS) != 0) {
   6656 		qinpos = ahc_inb(ahc, SNSCB_QOFF);
   6657 		ahc_outb(ahc, SNSCB_QOFF, qinpos);
   6658 	} else
   6659 		qinpos = ahc_inb(ahc, QINPOS);
   6660 	qintail = ahc->qinfifonext;
   6661 	while (qinpos != qintail) {
   6662 		printf("%d ", ahc->qinfifo[qinpos]);
   6663 		qinpos++;
   6664 	}
   6665 	printf("\n");
   6666 
   6667 	printf("Waiting Queue entries: ");
   6668 	scb_index = ahc_inb(ahc, WAITING_SCBH);
   6669 	i = 0;
   6670 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
   6671 		ahc_outb(ahc, SCBPTR, scb_index);
   6672 		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
   6673 		scb_index = ahc_inb(ahc, SCB_NEXT);
   6674 	}
   6675 	printf("\n");
   6676 
   6677 	printf("Disconnected Queue entries: ");
   6678 	scb_index = ahc_inb(ahc, DISCONNECTED_SCBH);
   6679 	i = 0;
   6680 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
   6681 		ahc_outb(ahc, SCBPTR, scb_index);
   6682 		printf("%d:%d ", scb_index, ahc_inb(ahc, SCB_TAG));
   6683 		scb_index = ahc_inb(ahc, SCB_NEXT);
   6684 	}
   6685 	printf("\n");
   6686 
   6687 	ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
   6688 	printf("QOUTFIFO entries: ");
   6689 	qoutpos = ahc->qoutfifonext;
   6690 	i = 0;
   6691 	while (ahc->qoutfifo[qoutpos] != SCB_LIST_NULL && i++ < 256) {
   6692 		printf("%d ", ahc->qoutfifo[qoutpos]);
   6693 		qoutpos++;
   6694 	}
   6695 	printf("\n");
   6696 
   6697 	printf("Sequencer Free SCB List: ");
   6698 	scb_index = ahc_inb(ahc, FREE_SCBH);
   6699 	i = 0;
   6700 	while (scb_index != SCB_LIST_NULL && i++ < 256) {
   6701 		ahc_outb(ahc, SCBPTR, scb_index);
   6702 		printf("%d ", scb_index);
   6703 		scb_index = ahc_inb(ahc, SCB_NEXT);
   6704 	}
   6705 	printf("\n");
   6706 
   6707 	printf("Sequencer SCB Info: ");
   6708 	for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
   6709 		ahc_outb(ahc, SCBPTR, i);
   6710 		/*cur_col =*/ printf("\n%3d ", i);
   6711 
   6712 		ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL), &cur_col, 60);
   6713 		ahc_scb_scsiid_print(ahc_inb(ahc, SCB_SCSIID), &cur_col, 60);
   6714 		ahc_scb_lun_print(ahc_inb(ahc, SCB_LUN), &cur_col, 60);
   6715 		ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
   6716 	}
   6717 	printf("\n");
   6718 
   6719 	printf("Pending list: ");
   6720 	i = 0;
   6721 	LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
   6722 		if (i++ > 256)
   6723 			break;
   6724 		/*cur_col =*/ printf("\n%3d ", scb->hscb->tag);
   6725 		ahc_scb_control_print(scb->hscb->control, &cur_col, 60);
   6726 		ahc_scb_scsiid_print(scb->hscb->scsiid, &cur_col, 60);
   6727 		ahc_scb_lun_print(scb->hscb->lun, &cur_col, 60);
   6728 		if ((ahc->flags & AHC_PAGESCBS) == 0) {
   6729 			ahc_outb(ahc, SCBPTR, scb->hscb->tag);
   6730 			printf("(");
   6731 			ahc_scb_control_print(ahc_inb(ahc, SCB_CONTROL),
   6732 					      &cur_col, 60);
   6733 			ahc_scb_tag_print(ahc_inb(ahc, SCB_TAG), &cur_col, 60);
   6734 			printf(")");
   6735 		}
   6736 	}
   6737 	printf("\n");
   6738 
   6739 	printf("Kernel Free SCB list: ");
   6740 	i = 0;
   6741 	SLIST_FOREACH(scb, &ahc->scb_data->free_scbs, links.sle) {
   6742 		if (i++ > 256)
   6743 			break;
   6744 		printf("%d ", scb->hscb->tag);
   6745 	}
   6746 	printf("\n");
   6747 
   6748 	maxtarget = (ahc->features & (AHC_WIDE|AHC_TWIN)) ? 15 : 7;
   6749 	for (target = 0; target <= maxtarget; target++) {
   6750 		untagged_q = &ahc->untagged_queues[target];
   6751 		if (TAILQ_FIRST(untagged_q) == NULL)
   6752 			continue;
   6753 		printf("Untagged Q(%d): ", target);
   6754 		i = 0;
   6755 		TAILQ_FOREACH(scb, untagged_q, links.tqe) {
   6756 			if (i++ > 256)
   6757 				break;
   6758 			printf("%d ", scb->hscb->tag);
   6759 		}
   6760 		printf("\n");
   6761 	}
   6762 
   6763 	ahc_platform_dump_card_state(ahc);
   6764 	printf("\n<<<<<<<<<<<<<<<<< Dump Card State Ends >>>>>>>>>>>>>>>>>>\n");
   6765 	ahc_outb(ahc, SCBPTR, saved_scbptr);
   6766 	if (paused == 0)
   6767 		ahc_unpause(ahc);
   6768 }
   6769 
   6770 /************************* Target Mode ****************************************/
   6771 #ifdef AHC_TARGET_MODE
   6772 cam_status
   6773 ahc_find_tmode_devs(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb,
   6774 		    struct ahc_tmode_tstate **tstate,
   6775 		    struct ahc_tmode_lstate **lstate,
   6776 		    int notfound_failure)
   6777 {
   6778 
   6779 	if ((ahc->features & AHC_TARGETMODE) == 0)
   6780 		return (CAM_REQ_INVALID);
   6781 
   6782 	/*
   6783 	 * Handle the 'black hole' device that sucks up
   6784 	 * requests to unattached luns on enabled targets.
   6785 	 */
   6786 	if (ccb->ccb_h.target_id == CAM_TARGET_WILDCARD
   6787 	 && ccb->ccb_h.target_lun == CAM_LUN_WILDCARD) {
   6788 		*tstate = NULL;
   6789 		*lstate = ahc->black_hole;
   6790 	} else {
   6791 		u_int max_id;
   6792 
   6793 		max_id = (ahc->features & AHC_WIDE) ? 15 : 7;
   6794 		if (ccb->ccb_h.target_id > max_id)
   6795 			return (CAM_TID_INVALID);
   6796 
   6797 		if (ccb->ccb_h.target_lun >= AHC_NUM_LUNS)
   6798 			return (CAM_LUN_INVALID);
   6799 
   6800 		*tstate = ahc->enabled_targets[ccb->ccb_h.target_id];
   6801 		*lstate = NULL;
   6802 		if (*tstate != NULL)
   6803 			*lstate =
   6804 			    (*tstate)->enabled_luns[ccb->ccb_h.target_lun];
   6805 	}
   6806 
   6807 	if (notfound_failure != 0 && *lstate == NULL)
   6808 		return (CAM_PATH_INVALID);
   6809 
   6810 	return (CAM_REQ_CMP);
   6811 }
   6812 
   6813 void
   6814 ahc_handle_en_lun(struct ahc_softc *ahc, struct cam_sim *sim, union ccb *ccb)
   6815 {
   6816 	struct	   ahc_tmode_tstate *tstate;
   6817 	struct	   ahc_tmode_lstate *lstate;
   6818 	struct	   ccb_en_lun *cel;
   6819 	cam_status status;
   6820 	u_int	   target;
   6821 	u_int	   lun;
   6822 	u_int	   target_mask;
   6823 	u_int	   our_id;
   6824 	u_long	   s;
   6825 	char	   channel;
   6826 
   6827 	status = ahc_find_tmode_devs(ahc, sim, ccb, &tstate, &lstate,
   6828 				     /*notfound_failure*/FALSE);
   6829 
   6830 	if (status != CAM_REQ_CMP) {
   6831 		ccb->ccb_h.status = status;
   6832 		return;
   6833 	}
   6834 
   6835 	if (cam_sim_bus(sim) == 0)
   6836 		our_id = ahc->our_id;
   6837 	else
   6838 		our_id = ahc->our_id_b;
   6839 
   6840 	if (ccb->ccb_h.target_id != our_id) {
   6841 		/*
   6842 		 * our_id represents our initiator ID, or
   6843 		 * the ID of the first target to have an
   6844 		 * enabled lun in target mode.  There are
   6845 		 * two cases that may preclude enabling a
   6846 		 * target id other than our_id.
   6847 		 *
   6848 		 *   o our_id is for an active initiator role.
   6849 		 *     Since the hardware does not support
   6850 		 *     reselections to the initiator role at
   6851 		 *     anything other than our_id, and our_id
   6852 		 *     is used by the hardware to indicate the
   6853 		 *     ID to use for both select-out and
   6854 		 *     reselect-out operations, the only target
   6855 		 *     ID we can support in this mode is our_id.
   6856 		 *
   6857 		 *   o The MULTARGID feature is not available and
   6858 		 *     a previous target mode ID has been enabled.
   6859 		 */
   6860 		if ((ahc->features & AHC_MULTIROLE) != 0) {
   6861 
   6862 			if ((ahc->features & AHC_MULTI_TID) != 0
   6863 		   	 && (ahc->flags & AHC_INITIATORROLE) != 0) {
   6864 				/*
   6865 				 * Only allow additional targets if
   6866 				 * the initiator role is disabled.
   6867 				 * The hardware cannot handle a re-select-in
   6868 				 * on the initiator id during a re-select-out
   6869 				 * on a different target id.
   6870 				 */
   6871 				status = CAM_TID_INVALID;
   6872 			} else if ((ahc->flags & AHC_INITIATORROLE) != 0
   6873 				|| ahc->enabled_luns > 0) {
   6874 				/*
   6875 				 * Only allow our target id to change
   6876 				 * if the initiator role is not configured
   6877 				 * and there are no enabled luns which
   6878 				 * are attached to the currently registered
   6879 				 * scsi id.
   6880 				 */
   6881 				status = CAM_TID_INVALID;
   6882 			}
   6883 		} else if ((ahc->features & AHC_MULTI_TID) == 0
   6884 			&& ahc->enabled_luns > 0) {
   6885 
   6886 			status = CAM_TID_INVALID;
   6887 		}
   6888 	}
   6889 
   6890 	if (status != CAM_REQ_CMP) {
   6891 		ccb->ccb_h.status = status;
   6892 		return;
   6893 	}
   6894 
   6895 	/*
   6896 	 * We now have an id that is valid.
   6897 	 * If we aren't in target mode, switch modes.
   6898 	 */
   6899 	if ((ahc->flags & AHC_TARGETROLE) == 0
   6900 	 && ccb->ccb_h.target_id != CAM_TARGET_WILDCARD) {
   6901 		u_long	s;
   6902 
   6903 		printf("Configuring Target Mode\n");
   6904 		ahc_lock(ahc, &s);
   6905 		if (LIST_FIRST(&ahc->pending_scbs) != NULL) {
   6906 			ccb->ccb_h.status = CAM_BUSY;
   6907 			ahc_unlock(ahc, &s);
   6908 			return;
   6909 		}
   6910 		ahc->flags |= AHC_TARGETROLE;
   6911 		if ((ahc->features & AHC_MULTIROLE) == 0)
   6912 			ahc->flags &= ~AHC_INITIATORROLE;
   6913 		ahc_pause(ahc);
   6914 		ahc_loadseq(ahc);
   6915 		ahc_unlock(ahc, &s);
   6916 	}
   6917 	cel = &ccb->cel;
   6918 	target = ccb->ccb_h.target_id;
   6919 	lun = ccb->ccb_h.target_lun;
   6920 	channel = SIM_CHANNEL(ahc, sim);
   6921 	target_mask = 0x01 << target;
   6922 	if (channel == 'B')
   6923 		target_mask <<= 8;
   6924 
   6925 	if (cel->enable != 0) {
   6926 		u_int scsiseq;
   6927 
   6928 		/* Are we already enabled?? */
   6929 		if (lstate != NULL) {
   6930 			xpt_print_path(ccb->ccb_h.path);
   6931 			printf("Lun already enabled\n");
   6932 			ccb->ccb_h.status = CAM_LUN_ALRDY_ENA;
   6933 			return;
   6934 		}
   6935 
   6936 		if (cel->grp6_len != 0
   6937 		 || cel->grp7_len != 0) {
   6938 			/*
   6939 			 * Don't (yet?) support vendor
   6940 			 * specific commands.
   6941 			 */
   6942 			ccb->ccb_h.status = CAM_REQ_INVALID;
   6943 			printf("Non-zero Group Codes\n");
   6944 			return;
   6945 		}
   6946 
   6947 		/*
   6948 		 * Seems to be okay.
   6949 		 * Setup our data structures.
   6950 		 */
   6951 		if (target != CAM_TARGET_WILDCARD && tstate == NULL) {
   6952 			tstate = ahc_alloc_tstate(ahc, target, channel);
   6953 			if (tstate == NULL) {
   6954 				xpt_print_path(ccb->ccb_h.path);
   6955 				printf("Couldn't allocate tstate\n");
   6956 				ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
   6957 				return;
   6958 			}
   6959 		}
   6960 		lstate = malloc(sizeof(*lstate), M_DEVBUF, M_NOWAIT);
   6961 		if (lstate == NULL) {
   6962 			xpt_print_path(ccb->ccb_h.path);
   6963 			printf("Couldn't allocate lstate\n");
   6964 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
   6965 			return;
   6966 		}
   6967 		memset(lstate, 0, sizeof(*lstate));
   6968 		status = xpt_create_path(&lstate->path, /*periph*/NULL,
   6969 					 xpt_path_path_id(ccb->ccb_h.path),
   6970 					 xpt_path_target_id(ccb->ccb_h.path),
   6971 					 xpt_path_lun_id(ccb->ccb_h.path));
   6972 		if (status != CAM_REQ_CMP) {
   6973 			free(lstate, M_DEVBUF);
   6974 			xpt_print_path(ccb->ccb_h.path);
   6975 			printf("Couldn't allocate path\n");
   6976 			ccb->ccb_h.status = CAM_RESRC_UNAVAIL;
   6977 			return;
   6978 		}
   6979 		SLIST_INIT(&lstate->accept_tios);
   6980 		SLIST_INIT(&lstate->immed_notifies);
   6981 		ahc_lock(ahc, &s);
   6982 		ahc_pause(ahc);
   6983 		if (target != CAM_TARGET_WILDCARD) {
   6984 			tstate->enabled_luns[lun] = lstate;
   6985 			ahc->enabled_luns++;
   6986 
   6987 			if ((ahc->features & AHC_MULTI_TID) != 0) {
   6988 				u_int targid_mask;
   6989 
   6990 				targid_mask = ahc_inb(ahc, TARGID)
   6991 					    | (ahc_inb(ahc, TARGID + 1) << 8);
   6992 
   6993 				targid_mask |= target_mask;
   6994 				ahc_outb(ahc, TARGID, targid_mask);
   6995 				ahc_outb(ahc, TARGID+1, (targid_mask >> 8));
   6996 
   6997 				ahc_update_scsiid(ahc, targid_mask);
   6998 			} else {
   6999 				u_int our_id;
   7000 				char  channel;
   7001 
   7002 				channel = SIM_CHANNEL(ahc, sim);
   7003 				our_id = SIM_SCSI_ID(ahc, sim);
   7004 
   7005 				/*
   7006 				 * This can only happen if selections
   7007 				 * are not enabled
   7008 				 */
   7009 				if (target != our_id) {
   7010 					u_int sblkctl;
   7011 					char  cur_channel;
   7012 					int   swap;
   7013 
   7014 					sblkctl = ahc_inb(ahc, SBLKCTL);
   7015 					cur_channel = (sblkctl & SELBUSB)
   7016 						    ? 'B' : 'A';
   7017 					if ((ahc->features & AHC_TWIN) == 0)
   7018 						cur_channel = 'A';
   7019 					swap = cur_channel != channel;
   7020 					if (channel == 'A')
   7021 						ahc->our_id = target;
   7022 					else
   7023 						ahc->our_id_b = target;
   7024 
   7025 					if (swap)
   7026 						ahc_outb(ahc, SBLKCTL,
   7027 							 sblkctl ^ SELBUSB);
   7028 
   7029 					ahc_outb(ahc, SCSIID, target);
   7030 
   7031 					if (swap)
   7032 						ahc_outb(ahc, SBLKCTL, sblkctl);
   7033 				}
   7034 			}
   7035 		} else
   7036 			ahc->black_hole = lstate;
   7037 		/* Allow select-in operations */
   7038 		if (ahc->black_hole != NULL && ahc->enabled_luns > 0) {
   7039 			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
   7040 			scsiseq |= ENSELI;
   7041 			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
   7042 			scsiseq = ahc_inb(ahc, SCSISEQ);
   7043 			scsiseq |= ENSELI;
   7044 			ahc_outb(ahc, SCSISEQ, scsiseq);
   7045 		}
   7046 		ahc_unpause(ahc);
   7047 		ahc_unlock(ahc, &s);
   7048 		ccb->ccb_h.status = CAM_REQ_CMP;
   7049 		xpt_print_path(ccb->ccb_h.path);
   7050 		printf("Lun now enabled for target mode\n");
   7051 	} else {
   7052 		struct scb *scb;
   7053 		int i, empty;
   7054 
   7055 		if (lstate == NULL) {
   7056 			ccb->ccb_h.status = CAM_LUN_INVALID;
   7057 			return;
   7058 		}
   7059 
   7060 		ahc_lock(ahc, &s);
   7061 
   7062 		ccb->ccb_h.status = CAM_REQ_CMP;
   7063 		LIST_FOREACH(scb, &ahc->pending_scbs, pending_links) {
   7064 			struct ccb_hdr *ccbh;
   7065 
   7066 			ccbh = &scb->io_ctx->ccb_h;
   7067 			if (ccbh->func_code == XPT_CONT_TARGET_IO
   7068 			 && !xpt_path_comp(ccbh->path, ccb->ccb_h.path)){
   7069 				printf("CTIO pending\n");
   7070 				ccb->ccb_h.status = CAM_REQ_INVALID;
   7071 				ahc_unlock(ahc, &s);
   7072 				return;
   7073 			}
   7074 		}
   7075 
   7076 		if (SLIST_FIRST(&lstate->accept_tios) != NULL) {
   7077 			printf("ATIOs pending\n");
   7078 			ccb->ccb_h.status = CAM_REQ_INVALID;
   7079 		}
   7080 
   7081 		if (SLIST_FIRST(&lstate->immed_notifies) != NULL) {
   7082 			printf("INOTs pending\n");
   7083 			ccb->ccb_h.status = CAM_REQ_INVALID;
   7084 		}
   7085 
   7086 		if (ccb->ccb_h.status != CAM_REQ_CMP) {
   7087 			ahc_unlock(ahc, &s);
   7088 			return;
   7089 		}
   7090 
   7091 		xpt_print_path(ccb->ccb_h.path);
   7092 		printf("Target mode disabled\n");
   7093 		xpt_free_path(lstate->path);
   7094 		free(lstate, M_DEVBUF);
   7095 
   7096 		ahc_pause(ahc);
   7097 		/* Can we clean up the target too? */
   7098 		if (target != CAM_TARGET_WILDCARD) {
   7099 			tstate->enabled_luns[lun] = NULL;
   7100 			ahc->enabled_luns--;
   7101 			for (empty = 1, i = 0; i < 8; i++)
   7102 				if (tstate->enabled_luns[i] != NULL) {
   7103 					empty = 0;
   7104 					break;
   7105 				}
   7106 
   7107 			if (empty) {
   7108 				ahc_free_tstate(ahc, target, channel,
   7109 						/*force*/FALSE);
   7110 				if (ahc->features & AHC_MULTI_TID) {
   7111 					u_int targid_mask;
   7112 
   7113 					targid_mask = ahc_inb(ahc, TARGID)
   7114 						    | (ahc_inb(ahc, TARGID + 1)
   7115 						       << 8);
   7116 
   7117 					targid_mask &= ~target_mask;
   7118 					ahc_outb(ahc, TARGID, targid_mask);
   7119 					ahc_outb(ahc, TARGID+1,
   7120 					 	 (targid_mask >> 8));
   7121 					ahc_update_scsiid(ahc, targid_mask);
   7122 				}
   7123 			}
   7124 		} else {
   7125 
   7126 			ahc->black_hole = NULL;
   7127 
   7128 			/*
   7129 			 * We can't allow selections without
   7130 			 * our black hole device.
   7131 			 */
   7132 			empty = TRUE;
   7133 		}
   7134 		if (ahc->enabled_luns == 0) {
   7135 			/* Disallow select-in */
   7136 			u_int scsiseq;
   7137 
   7138 			scsiseq = ahc_inb(ahc, SCSISEQ_TEMPLATE);
   7139 			scsiseq &= ~ENSELI;
   7140 			ahc_outb(ahc, SCSISEQ_TEMPLATE, scsiseq);
   7141 			scsiseq = ahc_inb(ahc, SCSISEQ);
   7142 			scsiseq &= ~ENSELI;
   7143 			ahc_outb(ahc, SCSISEQ, scsiseq);
   7144 
   7145 			if ((ahc->features & AHC_MULTIROLE) == 0) {
   7146 				printf("Configuring Initiator Mode\n");
   7147 				ahc->flags &= ~AHC_TARGETROLE;
   7148 				ahc->flags |= AHC_INITIATORROLE;
   7149 				ahc_pause(ahc);
   7150 				ahc_loadseq(ahc);
   7151 			}
   7152 		}
   7153 		ahc_unpause(ahc);
   7154 		ahc_unlock(ahc, &s);
   7155 	}
   7156 }
   7157 
   7158 static void
   7159 ahc_update_scsiid(struct ahc_softc *ahc, u_int targid_mask)
   7160 {
   7161 	u_int scsiid_mask;
   7162 	u_int scsiid;
   7163 
   7164 	if ((ahc->features & AHC_MULTI_TID) == 0)
   7165 		panic("ahc_update_scsiid called on non-multitid unit\n");
   7166 
   7167 	/*
   7168 	 * Since we will rely on the TARGID mask
   7169 	 * for selection enables, ensure that OID
   7170 	 * in SCSIID is not set to some other ID
   7171 	 * that we don't want to allow selections on.
   7172 	 */
   7173 	if ((ahc->features & AHC_ULTRA2) != 0)
   7174 		scsiid = ahc_inb(ahc, SCSIID_ULTRA2);
   7175 	else
   7176 		scsiid = ahc_inb(ahc, SCSIID);
   7177 	scsiid_mask = 0x1 << (scsiid & OID);
   7178 	if ((targid_mask & scsiid_mask) == 0) {
   7179 		u_int our_id;
   7180 
   7181 		/* ffs counts from 1 */
   7182 		our_id = ffs(targid_mask);
   7183 		if (our_id == 0)
   7184 			our_id = ahc->our_id;
   7185 		else
   7186 			our_id--;
   7187 		scsiid &= TID;
   7188 		scsiid |= our_id;
   7189 	}
   7190 	if ((ahc->features & AHC_ULTRA2) != 0)
   7191 		ahc_outb(ahc, SCSIID_ULTRA2, scsiid);
   7192 	else
   7193 		ahc_outb(ahc, SCSIID, scsiid);
   7194 }
   7195 
   7196 void
   7197 ahc_run_tqinfifo(struct ahc_softc *ahc, int paused)
   7198 {
   7199 	struct target_cmd *cmd;
   7200 
   7201 	/*
   7202 	 * If the card supports auto-access pause,
   7203 	 * we can access the card directly regardless
   7204 	 * of whether it is paused or not.
   7205 	 */
   7206 	if ((ahc->features & AHC_AUTOPAUSE) != 0)
   7207 		paused = TRUE;
   7208 
   7209 	ahc_sync_tqinfifo(ahc, BUS_DMASYNC_POSTREAD);
   7210 	while ((cmd = &ahc->targetcmds[ahc->tqinfifonext])->cmd_valid != 0) {
   7211 
   7212 		/*
   7213 		 * Only advance through the queue if we
   7214 		 * have the resources to process the command.
   7215 		 */
   7216 		if (ahc_handle_target_cmd(ahc, cmd) != 0)
   7217 			break;
   7218 
   7219 		cmd->cmd_valid = 0;
   7220 		ahc_dmamap_sync(ahc, ahc->parent_dmat/*shared_data_dmat*/,
   7221 				ahc->shared_data_dmamap,
   7222 				ahc_targetcmd_offset(ahc, ahc->tqinfifonext),
   7223 				sizeof(struct target_cmd),
   7224 				BUS_DMASYNC_PREREAD);
   7225 		ahc->tqinfifonext++;
   7226 
   7227 		/*
   7228 		 * Lazily update our position in the target mode incoming
   7229 		 * command queue as seen by the sequencer.
   7230 		 */
   7231 		if ((ahc->tqinfifonext & (HOST_TQINPOS - 1)) == 1) {
   7232 			if ((ahc->features & AHC_HS_MAILBOX) != 0) {
   7233 				u_int hs_mailbox;
   7234 
   7235 				hs_mailbox = ahc_inb(ahc, HS_MAILBOX);
   7236 				hs_mailbox &= ~HOST_TQINPOS;
   7237 				hs_mailbox |= ahc->tqinfifonext & HOST_TQINPOS;
   7238 				ahc_outb(ahc, HS_MAILBOX, hs_mailbox);
   7239 			} else {
   7240 				if (!paused)
   7241 					ahc_pause(ahc);
   7242 				ahc_outb(ahc, KERNEL_TQINPOS,
   7243 					 ahc->tqinfifonext & HOST_TQINPOS);
   7244 				if (!paused)
   7245 					ahc_unpause(ahc);
   7246 			}
   7247 		}
   7248 	}
   7249 }
   7250 
   7251 static int
   7252 ahc_handle_target_cmd(struct ahc_softc *ahc, struct target_cmd *cmd)
   7253 {
   7254 	struct	  ahc_tmode_tstate *tstate;
   7255 	struct	  ahc_tmode_lstate *lstate;
   7256 	struct	  ccb_accept_tio *atio;
   7257 	uint8_t *byte;
   7258 	int	  initiator;
   7259 	int	  target;
   7260 	int	  lun;
   7261 
   7262 	initiator = SCSIID_TARGET(ahc, cmd->scsiid);
   7263 	target = SCSIID_OUR_ID(cmd->scsiid);
   7264 	lun    = (cmd->identify & MSG_IDENTIFY_LUNMASK);
   7265 
   7266 	byte = cmd->bytes;
   7267 	tstate = ahc->enabled_targets[target];
   7268 	lstate = NULL;
   7269 	if (tstate != NULL)
   7270 		lstate = tstate->enabled_luns[lun];
   7271 
   7272 	/*
   7273 	 * Commands for disabled luns go to the black hole driver.
   7274 	 */
   7275 	if (lstate == NULL)
   7276 		lstate = ahc->black_hole;
   7277 
   7278 	atio = (struct ccb_accept_tio*)SLIST_FIRST(&lstate->accept_tios);
   7279 	if (atio == NULL) {
   7280 		ahc->flags |= AHC_TQINFIFO_BLOCKED;
   7281 		/*
   7282 		 * Wait for more ATIOs from the peripheral driver for this lun.
   7283 		 */
   7284 		if (bootverbose)
   7285 			printf("%s: ATIOs exhausted\n", ahc_name(ahc));
   7286 		return (1);
   7287 	} else
   7288 		ahc->flags &= ~AHC_TQINFIFO_BLOCKED;
   7289 #if 0
   7290 	printf("Incoming command from %d for %d:%d%s\n",
   7291 	       initiator, target, lun,
   7292 	       lstate == ahc->black_hole ? "(Black Holed)" : "");
   7293 #endif
   7294 	SLIST_REMOVE_HEAD(&lstate->accept_tios, sim_links.sle);
   7295 
   7296 	if (lstate == ahc->black_hole) {
   7297 		/* Fill in the wildcards */
   7298 		atio->ccb_h.target_id = target;
   7299 		atio->ccb_h.target_lun = lun;
   7300 	}
   7301 
   7302 	/*
   7303 	 * Package it up and send it off to
   7304 	 * whomever has this lun enabled.
   7305 	 */
   7306 	atio->sense_len = 0;
   7307 	atio->init_id = initiator;
   7308 	if (byte[0] != 0xFF) {
   7309 		/* Tag was included */
   7310 		atio->tag_action = *byte++;
   7311 		atio->tag_id = *byte++;
   7312 		atio->ccb_h.flags = CAM_TAG_ACTION_VALID;
   7313 	} else {
   7314 		atio->ccb_h.flags = 0;
   7315 	}
   7316 	byte++;
   7317 
   7318 	/* Okay.  Now determine the cdb size based on the command code */
   7319 	switch (*byte >> CMD_GROUP_CODE_SHIFT) {
   7320 	case 0:
   7321 		atio->cdb_len = 6;
   7322 		break;
   7323 	case 1:
   7324 	case 2:
   7325 		atio->cdb_len = 10;
   7326 		break;
   7327 	case 4:
   7328 		atio->cdb_len = 16;
   7329 		break;
   7330 	case 5:
   7331 		atio->cdb_len = 12;
   7332 		break;
   7333 	case 3:
   7334 	default:
   7335 		/* Only copy the opcode. */
   7336 		atio->cdb_len = 1;
   7337 		printf("Reserved or VU command code type encountered\n");
   7338 		break;
   7339 	}
   7340 
   7341 	memcpy(atio->cdb_io.cdb_bytes, byte, atio->cdb_len);
   7342 
   7343 	atio->ccb_h.status |= CAM_CDB_RECVD;
   7344 
   7345 	if ((cmd->identify & MSG_IDENTIFY_DISCFLAG) == 0) {
   7346 		/*
   7347 		 * We weren't allowed to disconnect.
   7348 		 * We're hanging on the bus until a
   7349 		 * continue target I/O comes in response
   7350 		 * to this accept tio.
   7351 		 */
   7352 #if 0
   7353 		printf("Received Immediate Command %d:%d:%d - %p\n",
   7354 		       initiator, target, lun, ahc->pending_device);
   7355 #endif
   7356 		ahc->pending_device = lstate;
   7357 		ahc_freeze_ccb((union ccb *)atio);
   7358 		atio->ccb_h.flags |= CAM_DIS_DISCONNECT;
   7359 	}
   7360 	xpt_done((union ccb*)atio);
   7361 	return (0);
   7362 }
   7363 #endif
   7364 
   7365 static int
   7366 ahc_createdmamem(tag, size, flags, mapp, vaddr, baddr, seg, nseg, myname, what)
   7367 	bus_dma_tag_t tag;
   7368 	int size;
   7369 	int flags;
   7370 	bus_dmamap_t *mapp;
   7371 	caddr_t *vaddr;
   7372 	bus_addr_t *baddr;
   7373 	bus_dma_segment_t *seg;
   7374 	int *nseg;
   7375 	const char *myname, *what;
   7376 {
   7377 	int error, level = 0;
   7378 
   7379 	if ((error = bus_dmamem_alloc(tag, size, PAGE_SIZE, 0,
   7380 				      seg, 1, nseg, BUS_DMA_NOWAIT)) != 0) {
   7381 		printf("%s: failed to allocate DMA mem for %s, error = %d\n",
   7382 			myname, what, error);
   7383 		goto out;
   7384 	}
   7385 	level++;
   7386 
   7387 	if ((error = bus_dmamem_map(tag, seg, *nseg, size, vaddr,
   7388 				    BUS_DMA_NOWAIT|BUS_DMA_COHERENT)) != 0) {
   7389 		printf("%s: failed to map DMA mem for %s, error = %d\n",
   7390 			myname, what, error);
   7391 		goto out;
   7392 	}
   7393 	level++;
   7394 
   7395 	if ((error = bus_dmamap_create(tag, size, 1, size, 0,
   7396 				       BUS_DMA_NOWAIT | flags, mapp)) != 0) {
   7397                 printf("%s: failed to create DMA map for %s, error = %d\n",
   7398 			myname, what, error);
   7399 		goto out;
   7400         }
   7401 	level++;
   7402 
   7403 
   7404 	if ((error = bus_dmamap_load(tag, *mapp, *vaddr, size, NULL,
   7405 				     BUS_DMA_NOWAIT)) != 0) {
   7406                 printf("%s: failed to load DMA map for %s, error = %d\n",
   7407 			myname, what, error);
   7408 		goto out;
   7409         }
   7410 
   7411 	*baddr = (*mapp)->dm_segs[0].ds_addr;
   7412 
   7413 	return 0;
   7414 out:
   7415 	printf("ahc_createdmamem error (%d)\n", level);
   7416 	switch (level) {
   7417 	case 3:
   7418 		bus_dmamap_destroy(tag, *mapp);
   7419 		/* FALLTHROUGH */
   7420 	case 2:
   7421 		bus_dmamem_unmap(tag, *vaddr, size);
   7422 		/* FALLTHROUGH */
   7423 	case 1:
   7424 		bus_dmamem_free(tag, seg, *nseg);
   7425 		break;
   7426 	default:
   7427 		break;
   7428 	}
   7429 
   7430 	return -1;
   7431 }
   7432 
   7433 static void
   7434 ahc_freedmamem(tag, size, map, vaddr, seg, nseg)
   7435 	bus_dma_tag_t tag;
   7436 	int size;
   7437 	bus_dmamap_t map;
   7438 	caddr_t vaddr;
   7439 	bus_dma_segment_t *seg;
   7440 	int nseg;
   7441 {
   7442 
   7443 	bus_dmamap_unload(tag, map);
   7444 	bus_dmamap_destroy(tag, map);
   7445 	bus_dmamem_unmap(tag, vaddr, size);
   7446 	bus_dmamem_free(tag, seg, nseg);
   7447 }
   7448