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