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