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