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