Merge master.kernel.org:/pub/scm/linux/kernel/git/jejb/scsi-rc-fixes-2.6
[linux-2.6.git] / drivers / scsi / aic7xxx / aic79xx_core.c
1 /*
2  * Core routines and tables shareable across OS platforms.
3  *
4  * Copyright (c) 1994-2002 Justin T. Gibbs.
5  * Copyright (c) 2000-2003 Adaptec Inc.
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions, and the following disclaimer,
13  *    without modification.
14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
15  *    substantially similar to the "NO WARRANTY" disclaimer below
16  *    ("Disclaimer") and any redistribution must be conditioned upon
17  *    including a substantially similar Disclaimer requirement for further
18  *    binary redistribution.
19  * 3. Neither the names of the above-listed copyright holders nor the names
20  *    of any contributors may be used to endorse or promote products derived
21  *    from this software without specific prior written permission.
22  *
23  * Alternatively, this software may be distributed under the terms of the
24  * GNU General Public License ("GPL") version 2 as published by the Free
25  * Software Foundation.
26  *
27  * NO WARRANTY
28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
32  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
36  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
37  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGES.
39  *
40  * $Id: //depot/aic7xxx/aic7xxx/aic79xx.c#250 $
41  */
42
43 #ifdef __linux__
44 #include "aic79xx_osm.h"
45 #include "aic79xx_inline.h"
46 #include "aicasm/aicasm_insformat.h"
47 #else
48 #include <dev/aic7xxx/aic79xx_osm.h>
49 #include <dev/aic7xxx/aic79xx_inline.h>
50 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
51 #endif
52
53
54 /***************************** Lookup Tables **********************************/
55 char *ahd_chip_names[] =
56 {
57         "NONE",
58         "aic7901",
59         "aic7902",
60         "aic7901A"
61 };
62 static const u_int num_chip_names = NUM_ELEMENTS(ahd_chip_names);
63
64 /*
65  * Hardware error codes.
66  */
67 struct ahd_hard_error_entry {
68         uint8_t errno;
69         char *errmesg;
70 };
71
72 static struct ahd_hard_error_entry ahd_hard_errors[] = {
73         { DSCTMOUT,     "Discard Timer has timed out" },
74         { ILLOPCODE,    "Illegal Opcode in sequencer program" },
75         { SQPARERR,     "Sequencer Parity Error" },
76         { DPARERR,      "Data-path Parity Error" },
77         { MPARERR,      "Scratch or SCB Memory Parity Error" },
78         { CIOPARERR,    "CIOBUS Parity Error" },
79 };
80 static const u_int num_errors = NUM_ELEMENTS(ahd_hard_errors);
81
82 static struct ahd_phase_table_entry ahd_phase_table[] =
83 {
84         { P_DATAOUT,    MSG_NOOP,               "in Data-out phase"     },
85         { P_DATAIN,     MSG_INITIATOR_DET_ERR,  "in Data-in phase"      },
86         { P_DATAOUT_DT, MSG_NOOP,               "in DT Data-out phase"  },
87         { P_DATAIN_DT,  MSG_INITIATOR_DET_ERR,  "in DT Data-in phase"   },
88         { P_COMMAND,    MSG_NOOP,               "in Command phase"      },
89         { P_MESGOUT,    MSG_NOOP,               "in Message-out phase"  },
90         { P_STATUS,     MSG_INITIATOR_DET_ERR,  "in Status phase"       },
91         { P_MESGIN,     MSG_PARITY_ERROR,       "in Message-in phase"   },
92         { P_BUSFREE,    MSG_NOOP,               "while idle"            },
93         { 0,            MSG_NOOP,               "in unknown phase"      }
94 };
95
96 /*
97  * In most cases we only wish to itterate over real phases, so
98  * exclude the last element from the count.
99  */
100 static const u_int num_phases = NUM_ELEMENTS(ahd_phase_table) - 1;
101
102 /* Our Sequencer Program */
103 #include "aic79xx_seq.h"
104
105 /**************************** Function Declarations ***************************/
106 static void             ahd_handle_transmission_error(struct ahd_softc *ahd);
107 static void             ahd_handle_lqiphase_error(struct ahd_softc *ahd,
108                                                   u_int lqistat1);
109 static int              ahd_handle_pkt_busfree(struct ahd_softc *ahd,
110                                                u_int busfreetime);
111 static int              ahd_handle_nonpkt_busfree(struct ahd_softc *ahd);
112 static void             ahd_handle_proto_violation(struct ahd_softc *ahd);
113 static void             ahd_force_renegotiation(struct ahd_softc *ahd,
114                                                 struct ahd_devinfo *devinfo);
115
116 static struct ahd_tmode_tstate*
117                         ahd_alloc_tstate(struct ahd_softc *ahd,
118                                          u_int scsi_id, char channel);
119 #ifdef AHD_TARGET_MODE
120 static void             ahd_free_tstate(struct ahd_softc *ahd,
121                                         u_int scsi_id, char channel, int force);
122 #endif
123 static void             ahd_devlimited_syncrate(struct ahd_softc *ahd,
124                                                 struct ahd_initiator_tinfo *,
125                                                 u_int *period,
126                                                 u_int *ppr_options,
127                                                 role_t role);
128 static void             ahd_update_neg_table(struct ahd_softc *ahd,
129                                              struct ahd_devinfo *devinfo,
130                                              struct ahd_transinfo *tinfo);
131 static void             ahd_update_pending_scbs(struct ahd_softc *ahd);
132 static void             ahd_fetch_devinfo(struct ahd_softc *ahd,
133                                           struct ahd_devinfo *devinfo);
134 static void             ahd_scb_devinfo(struct ahd_softc *ahd,
135                                         struct ahd_devinfo *devinfo,
136                                         struct scb *scb);
137 static void             ahd_setup_initiator_msgout(struct ahd_softc *ahd,
138                                                    struct ahd_devinfo *devinfo,
139                                                    struct scb *scb);
140 static void             ahd_build_transfer_msg(struct ahd_softc *ahd,
141                                                struct ahd_devinfo *devinfo);
142 static void             ahd_construct_sdtr(struct ahd_softc *ahd,
143                                            struct ahd_devinfo *devinfo,
144                                            u_int period, u_int offset);
145 static void             ahd_construct_wdtr(struct ahd_softc *ahd,
146                                            struct ahd_devinfo *devinfo,
147                                            u_int bus_width);
148 static void             ahd_construct_ppr(struct ahd_softc *ahd,
149                                           struct ahd_devinfo *devinfo,
150                                           u_int period, u_int offset,
151                                           u_int bus_width, u_int ppr_options);
152 static void             ahd_clear_msg_state(struct ahd_softc *ahd);
153 static void             ahd_handle_message_phase(struct ahd_softc *ahd);
154 typedef enum {
155         AHDMSG_1B,
156         AHDMSG_2B,
157         AHDMSG_EXT
158 } ahd_msgtype;
159 static int              ahd_sent_msg(struct ahd_softc *ahd, ahd_msgtype type,
160                                      u_int msgval, int full);
161 static int              ahd_parse_msg(struct ahd_softc *ahd,
162                                       struct ahd_devinfo *devinfo);
163 static int              ahd_handle_msg_reject(struct ahd_softc *ahd,
164                                               struct ahd_devinfo *devinfo);
165 static void             ahd_handle_ign_wide_residue(struct ahd_softc *ahd,
166                                                 struct ahd_devinfo *devinfo);
167 static void             ahd_reinitialize_dataptrs(struct ahd_softc *ahd);
168 static void             ahd_handle_devreset(struct ahd_softc *ahd,
169                                             struct ahd_devinfo *devinfo,
170                                             u_int lun, cam_status status,
171                                             char *message, int verbose_level);
172 #ifdef AHD_TARGET_MODE
173 static void             ahd_setup_target_msgin(struct ahd_softc *ahd,
174                                                struct ahd_devinfo *devinfo,
175                                                struct scb *scb);
176 #endif
177
178 static u_int            ahd_sglist_size(struct ahd_softc *ahd);
179 static u_int            ahd_sglist_allocsize(struct ahd_softc *ahd);
180 static bus_dmamap_callback_t
181                         ahd_dmamap_cb; 
182 static void             ahd_initialize_hscbs(struct ahd_softc *ahd);
183 static int              ahd_init_scbdata(struct ahd_softc *ahd);
184 static void             ahd_fini_scbdata(struct ahd_softc *ahd);
185 static void             ahd_setup_iocell_workaround(struct ahd_softc *ahd);
186 static void             ahd_iocell_first_selection(struct ahd_softc *ahd);
187 static void             ahd_add_col_list(struct ahd_softc *ahd,
188                                          struct scb *scb, u_int col_idx);
189 static void             ahd_rem_col_list(struct ahd_softc *ahd,
190                                          struct scb *scb);
191 static void             ahd_chip_init(struct ahd_softc *ahd);
192 static void             ahd_qinfifo_requeue(struct ahd_softc *ahd,
193                                             struct scb *prev_scb,
194                                             struct scb *scb);
195 static int              ahd_qinfifo_count(struct ahd_softc *ahd);
196 static int              ahd_search_scb_list(struct ahd_softc *ahd, int target,
197                                             char channel, int lun, u_int tag,
198                                             role_t role, uint32_t status,
199                                             ahd_search_action action,
200                                             u_int *list_head, u_int *list_tail,
201                                             u_int tid);
202 static void             ahd_stitch_tid_list(struct ahd_softc *ahd,
203                                             u_int tid_prev, u_int tid_cur,
204                                             u_int tid_next);
205 static void             ahd_add_scb_to_free_list(struct ahd_softc *ahd,
206                                                  u_int scbid);
207 static u_int            ahd_rem_wscb(struct ahd_softc *ahd, u_int scbid,
208                                      u_int prev, u_int next, u_int tid);
209 static void             ahd_reset_current_bus(struct ahd_softc *ahd);
210 static ahd_callback_t   ahd_reset_poll;
211 static ahd_callback_t   ahd_stat_timer;
212 #ifdef AHD_DUMP_SEQ
213 static void             ahd_dumpseq(struct ahd_softc *ahd);
214 #endif
215 static void             ahd_loadseq(struct ahd_softc *ahd);
216 static int              ahd_check_patch(struct ahd_softc *ahd,
217                                         struct patch **start_patch,
218                                         u_int start_instr, u_int *skip_addr);
219 static u_int            ahd_resolve_seqaddr(struct ahd_softc *ahd,
220                                             u_int address);
221 static void             ahd_download_instr(struct ahd_softc *ahd,
222                                            u_int instrptr, uint8_t *dconsts);
223 static int              ahd_probe_stack_size(struct ahd_softc *ahd);
224 static int              ahd_scb_active_in_fifo(struct ahd_softc *ahd,
225                                                struct scb *scb);
226 static void             ahd_run_data_fifo(struct ahd_softc *ahd,
227                                           struct scb *scb);
228
229 #ifdef AHD_TARGET_MODE
230 static void             ahd_queue_lstate_event(struct ahd_softc *ahd,
231                                                struct ahd_tmode_lstate *lstate,
232                                                u_int initiator_id,
233                                                u_int event_type,
234                                                u_int event_arg);
235 static void             ahd_update_scsiid(struct ahd_softc *ahd,
236                                           u_int targid_mask);
237 static int              ahd_handle_target_cmd(struct ahd_softc *ahd,
238                                               struct target_cmd *cmd);
239 #endif
240
241 /******************************** Private Inlines *****************************/
242 static __inline void    ahd_assert_atn(struct ahd_softc *ahd);
243 static __inline int     ahd_currently_packetized(struct ahd_softc *ahd);
244 static __inline int     ahd_set_active_fifo(struct ahd_softc *ahd);
245
246 static __inline void
247 ahd_assert_atn(struct ahd_softc *ahd)
248 {
249         ahd_outb(ahd, SCSISIGO, ATNO);
250 }
251
252 /*
253  * Determine if the current connection has a packetized
254  * agreement.  This does not necessarily mean that we
255  * are currently in a packetized transfer.  We could
256  * just as easily be sending or receiving a message.
257  */
258 static __inline int
259 ahd_currently_packetized(struct ahd_softc *ahd)
260 {
261         ahd_mode_state   saved_modes;
262         int              packetized;
263
264         saved_modes = ahd_save_modes(ahd);
265         if ((ahd->bugs & AHD_PKTIZED_STATUS_BUG) != 0) {
266                 /*
267                  * The packetized bit refers to the last
268                  * connection, not the current one.  Check
269                  * for non-zero LQISTATE instead.
270                  */
271                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
272                 packetized = ahd_inb(ahd, LQISTATE) != 0;
273         } else {
274                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
275                 packetized = ahd_inb(ahd, LQISTAT2) & PACKETIZED;
276         }
277         ahd_restore_modes(ahd, saved_modes);
278         return (packetized);
279 }
280
281 static __inline int
282 ahd_set_active_fifo(struct ahd_softc *ahd)
283 {
284         u_int active_fifo;
285
286         AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
287         active_fifo = ahd_inb(ahd, DFFSTAT) & CURRFIFO;
288         switch (active_fifo) {
289         case 0:
290         case 1:
291                 ahd_set_modes(ahd, active_fifo, active_fifo);
292                 return (1);
293         default:
294                 return (0);
295         }
296 }
297
298 /************************* Sequencer Execution Control ************************/
299 /*
300  * Restart the sequencer program from address zero
301  */
302 void
303 ahd_restart(struct ahd_softc *ahd)
304 {
305
306         ahd_pause(ahd);
307
308         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
309
310         /* No more pending messages */
311         ahd_clear_msg_state(ahd);
312         ahd_outb(ahd, SCSISIGO, 0);             /* De-assert BSY */
313         ahd_outb(ahd, MSG_OUT, MSG_NOOP);       /* No message to send */
314         ahd_outb(ahd, SXFRCTL1, ahd_inb(ahd, SXFRCTL1) & ~BITBUCKET);
315         ahd_outb(ahd, SEQINTCTL, 0);
316         ahd_outb(ahd, LASTPHASE, P_BUSFREE);
317         ahd_outb(ahd, SEQ_FLAGS, 0);
318         ahd_outb(ahd, SAVED_SCSIID, 0xFF);
319         ahd_outb(ahd, SAVED_LUN, 0xFF);
320
321         /*
322          * Ensure that the sequencer's idea of TQINPOS
323          * matches our own.  The sequencer increments TQINPOS
324          * only after it sees a DMA complete and a reset could
325          * occur before the increment leaving the kernel to believe
326          * the command arrived but the sequencer to not.
327          */
328         ahd_outb(ahd, TQINPOS, ahd->tqinfifonext);
329
330         /* Always allow reselection */
331         ahd_outb(ahd, SCSISEQ1,
332                  ahd_inb(ahd, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
333         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
334
335         /*
336          * Clear any pending sequencer interrupt.  It is no
337          * longer relevant since we're resetting the Program
338          * Counter.
339          */
340         ahd_outb(ahd, CLRINT, CLRSEQINT);
341
342         ahd_outb(ahd, SEQCTL0, FASTMODE|SEQRESET);
343         ahd_unpause(ahd);
344 }
345
346 void
347 ahd_clear_fifo(struct ahd_softc *ahd, u_int fifo)
348 {
349         ahd_mode_state   saved_modes;
350
351 #ifdef AHD_DEBUG
352         if ((ahd_debug & AHD_SHOW_FIFOS) != 0)
353                 printf("%s: Clearing FIFO %d\n", ahd_name(ahd), fifo);
354 #endif
355         saved_modes = ahd_save_modes(ahd);
356         ahd_set_modes(ahd, fifo, fifo);
357         ahd_outb(ahd, DFFSXFRCTL, RSTCHN|CLRSHCNT);
358         if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
359                 ahd_outb(ahd, CCSGCTL, CCSGRESET);
360         ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
361         ahd_outb(ahd, SG_STATE, 0);
362         ahd_restore_modes(ahd, saved_modes);
363 }
364
365 /************************* Input/Output Queues ********************************/
366 /*
367  * Flush and completed commands that are sitting in the command
368  * complete queues down on the chip but have yet to be dma'ed back up.
369  */
370 void
371 ahd_flush_qoutfifo(struct ahd_softc *ahd)
372 {
373         struct          scb *scb;
374         ahd_mode_state  saved_modes;
375         u_int           saved_scbptr;
376         u_int           ccscbctl;
377         u_int           scbid;
378         u_int           next_scbid;
379
380         saved_modes = ahd_save_modes(ahd);
381
382         /*
383          * Flush the good status FIFO for completed packetized commands.
384          */
385         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
386         saved_scbptr = ahd_get_scbptr(ahd);
387         while ((ahd_inb(ahd, LQISTAT2) & LQIGSAVAIL) != 0) {
388                 u_int fifo_mode;
389                 u_int i;
390                 
391                 scbid = ahd_inw(ahd, GSFIFO);
392                 scb = ahd_lookup_scb(ahd, scbid);
393                 if (scb == NULL) {
394                         printf("%s: Warning - GSFIFO SCB %d invalid\n",
395                                ahd_name(ahd), scbid);
396                         continue;
397                 }
398                 /*
399                  * Determine if this transaction is still active in
400                  * any FIFO.  If it is, we must flush that FIFO to
401                  * the host before completing the  command.
402                  */
403                 fifo_mode = 0;
404 rescan_fifos:
405                 for (i = 0; i < 2; i++) {
406                         /* Toggle to the other mode. */
407                         fifo_mode ^= 1;
408                         ahd_set_modes(ahd, fifo_mode, fifo_mode);
409
410                         if (ahd_scb_active_in_fifo(ahd, scb) == 0)
411                                 continue;
412
413                         ahd_run_data_fifo(ahd, scb);
414
415                         /*
416                          * Running this FIFO may cause a CFG4DATA for
417                          * this same transaction to assert in the other
418                          * FIFO or a new snapshot SAVEPTRS interrupt
419                          * in this FIFO.  Even running a FIFO may not
420                          * clear the transaction if we are still waiting
421                          * for data to drain to the host. We must loop
422                          * until the transaction is not active in either
423                          * FIFO just to be sure.  Reset our loop counter
424                          * so we will visit both FIFOs again before
425                          * declaring this transaction finished.  We
426                          * also delay a bit so that status has a chance
427                          * to change before we look at this FIFO again.
428                          */
429                         ahd_delay(200);
430                         goto rescan_fifos;
431                 }
432                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
433                 ahd_set_scbptr(ahd, scbid);
434                 if ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_LIST_NULL) == 0
435                  && ((ahd_inb_scbram(ahd, SCB_SGPTR) & SG_FULL_RESID) != 0
436                   || (ahd_inb_scbram(ahd, SCB_RESIDUAL_SGPTR)
437                       & SG_LIST_NULL) != 0)) {
438                         u_int comp_head;
439
440                         /*
441                          * The transfer completed with a residual.
442                          * Place this SCB on the complete DMA list
443                          * so that we update our in-core copy of the
444                          * SCB before completing the command.
445                          */
446                         ahd_outb(ahd, SCB_SCSI_STATUS, 0);
447                         ahd_outb(ahd, SCB_SGPTR,
448                                  ahd_inb_scbram(ahd, SCB_SGPTR)
449                                  | SG_STATUS_VALID);
450                         ahd_outw(ahd, SCB_TAG, scbid);
451                         ahd_outw(ahd, SCB_NEXT_COMPLETE, SCB_LIST_NULL);
452                         comp_head = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
453                         if (SCBID_IS_NULL(comp_head)) {
454                                 ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, scbid);
455                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
456                         } else {
457                                 u_int tail;
458
459                                 tail = ahd_inw(ahd, COMPLETE_DMA_SCB_TAIL);
460                                 ahd_set_scbptr(ahd, tail);
461                                 ahd_outw(ahd, SCB_NEXT_COMPLETE, scbid);
462                                 ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, scbid);
463                                 ahd_set_scbptr(ahd, scbid);
464                         }
465                 } else
466                         ahd_complete_scb(ahd, scb);
467         }
468         ahd_set_scbptr(ahd, saved_scbptr);
469
470         /*
471          * Setup for command channel portion of flush.
472          */
473         ahd_set_modes(ahd, AHD_MODE_CCHAN, AHD_MODE_CCHAN);
474
475         /*
476          * Wait for any inprogress DMA to complete and clear DMA state
477          * if this if for an SCB in the qinfifo.
478          */
479         while (((ccscbctl = ahd_inb(ahd, CCSCBCTL)) & (CCARREN|CCSCBEN)) != 0) {
480
481                 if ((ccscbctl & (CCSCBDIR|CCARREN)) == (CCSCBDIR|CCARREN)) {
482                         if ((ccscbctl & ARRDONE) != 0)
483                                 break;
484                 } else if ((ccscbctl & CCSCBDONE) != 0)
485                         break;
486                 ahd_delay(200);
487         }
488         /*
489          * We leave the sequencer to cleanup in the case of DMA's to
490          * update the qoutfifo.  In all other cases (DMA's to the
491          * chip or a push of an SCB from the COMPLETE_DMA_SCB list),
492          * we disable the DMA engine so that the sequencer will not
493          * attempt to handle the DMA completion.
494          */
495         if ((ccscbctl & CCSCBDIR) != 0 || (ccscbctl & ARRDONE) != 0)
496                 ahd_outb(ahd, CCSCBCTL, ccscbctl & ~(CCARREN|CCSCBEN));
497
498         /*
499          * Complete any SCBs that just finished
500          * being DMA'ed into the qoutfifo.
501          */
502         ahd_run_qoutfifo(ahd);
503
504         saved_scbptr = ahd_get_scbptr(ahd);
505         /*
506          * Manually update/complete any completed SCBs that are waiting to be
507          * DMA'ed back up to the host.
508          */
509         scbid = ahd_inw(ahd, COMPLETE_DMA_SCB_HEAD);
510         while (!SCBID_IS_NULL(scbid)) {
511                 uint8_t *hscb_ptr;
512                 u_int    i;
513                 
514                 ahd_set_scbptr(ahd, scbid);
515                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
516                 scb = ahd_lookup_scb(ahd, scbid);
517                 if (scb == NULL) {
518                         printf("%s: Warning - DMA-up and complete "
519                                "SCB %d invalid\n", ahd_name(ahd), scbid);
520                         continue;
521                 }
522                 hscb_ptr = (uint8_t *)scb->hscb;
523                 for (i = 0; i < sizeof(struct hardware_scb); i++)
524                         *hscb_ptr++ = ahd_inb_scbram(ahd, SCB_BASE + i);
525
526                 ahd_complete_scb(ahd, scb);
527                 scbid = next_scbid;
528         }
529         ahd_outw(ahd, COMPLETE_DMA_SCB_HEAD, SCB_LIST_NULL);
530         ahd_outw(ahd, COMPLETE_DMA_SCB_TAIL, SCB_LIST_NULL);
531
532         scbid = ahd_inw(ahd, COMPLETE_ON_QFREEZE_HEAD);
533         while (!SCBID_IS_NULL(scbid)) {
534
535                 ahd_set_scbptr(ahd, scbid);
536                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
537                 scb = ahd_lookup_scb(ahd, scbid);
538                 if (scb == NULL) {
539                         printf("%s: Warning - Complete Qfrz SCB %d invalid\n",
540                                ahd_name(ahd), scbid);
541                         continue;
542                 }
543
544                 ahd_complete_scb(ahd, scb);
545                 scbid = next_scbid;
546         }
547         ahd_outw(ahd, COMPLETE_ON_QFREEZE_HEAD, SCB_LIST_NULL);
548
549         scbid = ahd_inw(ahd, COMPLETE_SCB_HEAD);
550         while (!SCBID_IS_NULL(scbid)) {
551
552                 ahd_set_scbptr(ahd, scbid);
553                 next_scbid = ahd_inw_scbram(ahd, SCB_NEXT_COMPLETE);
554                 scb = ahd_lookup_scb(ahd, scbid);
555                 if (scb == NULL) {
556                         printf("%s: Warning - Complete SCB %d invalid\n",
557                                ahd_name(ahd), scbid);
558                         continue;
559                 }
560
561                 ahd_complete_scb(ahd, scb);
562                 scbid = next_scbid;
563         }
564         ahd_outw(ahd, COMPLETE_SCB_HEAD, SCB_LIST_NULL);
565
566         /*
567          * Restore state.
568          */
569         ahd_set_scbptr(ahd, saved_scbptr);
570         ahd_restore_modes(ahd, saved_modes);
571         ahd->flags |= AHD_UPDATE_PEND_CMDS;
572 }
573
574 /*
575  * Determine if an SCB for a packetized transaction
576  * is active in a FIFO.
577  */
578 static int
579 ahd_scb_active_in_fifo(struct ahd_softc *ahd, struct scb *scb)
580 {
581
582         /*
583          * The FIFO is only active for our transaction if
584          * the SCBPTR matches the SCB's ID and the firmware
585          * has installed a handler for the FIFO or we have
586          * a pending SAVEPTRS or CFG4DATA interrupt.
587          */
588         if (ahd_get_scbptr(ahd) != SCB_GET_TAG(scb)
589          || ((ahd_inb(ahd, LONGJMP_ADDR+1) & INVALID_ADDR) != 0
590           && (ahd_inb(ahd, SEQINTSRC) & (CFG4DATA|SAVEPTRS)) == 0))
591                 return (0);
592
593         return (1);
594 }
595
596 /*
597  * Run a data fifo to completion for a transaction we know
598  * has completed across the SCSI bus (good status has been
599  * received).  We are already set to the correct FIFO mode
600  * on entry to this routine.
601  *
602  * This function attempts to operate exactly as the firmware
603  * would when running this FIFO.  Care must be taken to update
604  * this routine any time the firmware's FIFO algorithm is
605  * changed.
606  */
607 static void
608 ahd_run_data_fifo(struct ahd_softc *ahd, struct scb *scb)
609 {
610         u_int seqintsrc;
611
612         seqintsrc = ahd_inb(ahd, SEQINTSRC);
613         if ((seqintsrc & CFG4DATA) != 0) {
614                 uint32_t datacnt;
615                 uint32_t sgptr;
616
617                 /*
618                  * Clear full residual flag.
619                  */
620                 sgptr = ahd_inl_scbram(ahd, SCB_SGPTR) & ~SG_FULL_RESID;
621                 ahd_outb(ahd, SCB_SGPTR, sgptr);
622
623                 /*
624                  * Load datacnt and address.
625                  */
626                 datacnt = ahd_inl_scbram(ahd, SCB_DATACNT);
627                 if ((datacnt & AHD_DMA_LAST_SEG) != 0) {
628                         sgptr |= LAST_SEG;
629                         ahd_outb(ahd, SG_STATE, 0);
630                 } else
631                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
632                 ahd_outq(ahd, HADDR, ahd_inq_scbram(ahd, SCB_DATAPTR));
633                 ahd_outl(ahd, HCNT, datacnt & AHD_SG_LEN_MASK);
634                 ahd_outb(ahd, SG_CACHE_PRE, sgptr);
635                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
636
637                 /*
638                  * Initialize Residual Fields.
639                  */
640                 ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, datacnt >> 24);
641                 ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr & SG_PTR_MASK);
642
643                 /*
644                  * Mark the SCB as having a FIFO in use.
645                  */
646                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
647                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) + 1);
648
649                 /*
650                  * Install a "fake" handler for this FIFO.
651                  */
652                 ahd_outw(ahd, LONGJMP_ADDR, 0);
653
654                 /*
655                  * Notify the hardware that we have satisfied
656                  * this sequencer interrupt.
657                  */
658                 ahd_outb(ahd, CLRSEQINTSRC, CLRCFG4DATA);
659         } else if ((seqintsrc & SAVEPTRS) != 0) {
660                 uint32_t sgptr;
661                 uint32_t resid;
662
663                 if ((ahd_inb(ahd, LONGJMP_ADDR+1)&INVALID_ADDR) != 0) {
664                         /*
665                          * Snapshot Save Pointers.  All that
666                          * is necessary to clear the snapshot
667                          * is a CLRCHN.
668                          */
669                         goto clrchn;
670                 }
671
672                 /*
673                  * Disable S/G fetch so the DMA engine
674                  * is available to future users.
675                  */
676                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0)
677                         ahd_outb(ahd, CCSGCTL, 0);
678                 ahd_outb(ahd, SG_STATE, 0);
679
680                 /*
681                  * Flush the data FIFO.  Strickly only
682                  * necessary for Rev A parts.
683                  */
684                 ahd_outb(ahd, DFCNTRL, ahd_inb(ahd, DFCNTRL) | FIFOFLUSH);
685
686                 /*
687                  * Calculate residual.
688                  */
689                 sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
690                 resid = ahd_inl(ahd, SHCNT);
691                 resid |= ahd_inb_scbram(ahd, SCB_RESIDUAL_DATACNT+3) << 24;
692                 ahd_outl(ahd, SCB_RESIDUAL_DATACNT, resid);
693                 if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG) == 0) {
694                         /*
695                          * Must back up to the correct S/G element.
696                          * Typically this just means resetting our
697                          * low byte to the offset in the SG_CACHE,
698                          * but if we wrapped, we have to correct
699                          * the other bytes of the sgptr too.
700                          */
701                         if ((ahd_inb(ahd, SG_CACHE_SHADOW) & 0x80) != 0
702                          && (sgptr & 0x80) == 0)
703                                 sgptr -= 0x100;
704                         sgptr &= ~0xFF;
705                         sgptr |= ahd_inb(ahd, SG_CACHE_SHADOW)
706                                & SG_ADDR_MASK;
707                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
708                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT + 3, 0);
709                 } else if ((resid & AHD_SG_LEN_MASK) == 0) {
710                         ahd_outb(ahd, SCB_RESIDUAL_SGPTR,
711                                  sgptr | SG_LIST_NULL);
712                 }
713                 /*
714                  * Save Pointers.
715                  */
716                 ahd_outq(ahd, SCB_DATAPTR, ahd_inq(ahd, SHADDR));
717                 ahd_outl(ahd, SCB_DATACNT, resid);
718                 ahd_outl(ahd, SCB_SGPTR, sgptr);
719                 ahd_outb(ahd, CLRSEQINTSRC, CLRSAVEPTRS);
720                 ahd_outb(ahd, SEQIMODE,
721                          ahd_inb(ahd, SEQIMODE) | ENSAVEPTRS);
722                 /*
723                  * If the data is to the SCSI bus, we are
724                  * done, otherwise wait for FIFOEMP.
725                  */
726                 if ((ahd_inb(ahd, DFCNTRL) & DIRECTION) != 0)
727                         goto clrchn;
728         } else if ((ahd_inb(ahd, SG_STATE) & LOADING_NEEDED) != 0) {
729                 uint32_t sgptr;
730                 uint64_t data_addr;
731                 uint32_t data_len;
732                 u_int    dfcntrl;
733
734                 /*
735                  * Disable S/G fetch so the DMA engine
736                  * is available to future users.  We won't
737                  * be using the DMA engine to load segments.
738                  */
739                 if ((ahd_inb(ahd, SG_STATE) & FETCH_INPROG) != 0) {
740                         ahd_outb(ahd, CCSGCTL, 0);
741                         ahd_outb(ahd, SG_STATE, LOADING_NEEDED);
742                 }
743
744                 /*
745                  * Wait for the DMA engine to notice that the
746                  * host transfer is enabled and that there is
747                  * space in the S/G FIFO for new segments before
748                  * loading more segments.
749                  */
750                 if ((ahd_inb(ahd, DFSTATUS) & PRELOAD_AVAIL) != 0
751                  && (ahd_inb(ahd, DFCNTRL) & HDMAENACK) != 0) {
752
753                         /*
754                          * Determine the offset of the next S/G
755                          * element to load.
756                          */
757                         sgptr = ahd_inl_scbram(ahd, SCB_RESIDUAL_SGPTR);
758                         sgptr &= SG_PTR_MASK;
759                         if ((ahd->flags & AHD_64BIT_ADDRESSING) != 0) {
760                                 struct ahd_dma64_seg *sg;
761
762                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
763                                 data_addr = sg->addr;
764                                 data_len = sg->len;
765                                 sgptr += sizeof(*sg);
766                         } else {
767                                 struct  ahd_dma_seg *sg;
768
769                                 sg = ahd_sg_bus_to_virt(ahd, scb, sgptr);
770                                 data_addr = sg->len & AHD_SG_HIGH_ADDR_MASK;
771                                 data_addr <<= 8;
772                                 data_addr |= sg->addr;
773                                 data_len = sg->len;
774                                 sgptr += sizeof(*sg);
775                         }
776
777                         /*
778                          * Update residual information.
779                          */
780                         ahd_outb(ahd, SCB_RESIDUAL_DATACNT+3, data_len >> 24);
781                         ahd_outl(ahd, SCB_RESIDUAL_SGPTR, sgptr);
782
783                         /*
784                          * Load the S/G.
785                          */
786                         if (data_len & AHD_DMA_LAST_SEG) {
787                                 sgptr |= LAST_SEG;
788                                 ahd_outb(ahd, SG_STATE, 0);
789                         }
790                         ahd_outq(ahd, HADDR, data_addr);
791                         ahd_outl(ahd, HCNT, data_len & AHD_SG_LEN_MASK);
792                         ahd_outb(ahd, SG_CACHE_PRE, sgptr & 0xFF);
793
794                         /*
795                          * Advertise the segment to the hardware.
796                          */
797                         dfcntrl = ahd_inb(ahd, DFCNTRL)|PRELOADEN|HDMAEN;
798                         if ((ahd->features & AHD_NEW_DFCNTRL_OPTS) != 0) {
799                                 /*
800                                  * Use SCSIENWRDIS so that SCSIEN
801                                  * is never modified by this
802                                  * operation.
803                                  */
804                                 dfcntrl |= SCSIENWRDIS;
805                         }
806                         ahd_outb(ahd, DFCNTRL, dfcntrl);
807                 }
808         } else if ((ahd_inb(ahd, SG_CACHE_SHADOW) & LAST_SEG_DONE) != 0) {
809
810                 /*
811                  * Transfer completed to the end of SG list
812                  * and has flushed to the host.
813                  */
814                 ahd_outb(ahd, SCB_SGPTR,
815                          ahd_inb_scbram(ahd, SCB_SGPTR) | SG_LIST_NULL);
816                 goto clrchn;
817         } else if ((ahd_inb(ahd, DFSTATUS) & FIFOEMP) != 0) {
818 clrchn:
819                 /*
820                  * Clear any handler for this FIFO, decrement
821                  * the FIFO use count for the SCB, and release
822                  * the FIFO.
823                  */
824                 ahd_outb(ahd, LONGJMP_ADDR + 1, INVALID_ADDR);
825                 ahd_outb(ahd, SCB_FIFO_USE_COUNT,
826                          ahd_inb_scbram(ahd, SCB_FIFO_USE_COUNT) - 1);
827                 ahd_outb(ahd, DFFSXFRCTL, CLRCHN);
828         }
829 }
830
831 /*
832  * Look for entries in the QoutFIFO that have completed.
833  * The valid_tag completion field indicates the validity
834  * of the entry - the valid value toggles each time through
835  * the queue. We use the sg_status field in the completion
836  * entry to avoid referencing the hscb if the completion
837  * occurred with no errors and no residual.  sg_status is
838  * a copy of the first byte (little endian) of the sgptr
839  * hscb field.
840  */
841 void
842 ahd_run_qoutfifo(struct ahd_softc *ahd)
843 {
844         struct ahd_completion *completion;
845         struct scb *scb;
846         u_int  scb_index;
847
848         if ((ahd->flags & AHD_RUNNING_QOUTFIFO) != 0)
849                 panic("ahd_run_qoutfifo recursion");
850         ahd->flags |= AHD_RUNNING_QOUTFIFO;
851         ahd_sync_qoutfifo(ahd, BUS_DMASYNC_POSTREAD);
852         for (;;) {
853                 completion = &ahd->qoutfifo[ahd->qoutfifonext];
854
855                 if (completion->valid_tag != ahd->qoutfifonext_valid_tag)
856                         break;
857
858                 scb_index = ahd_le16toh(completion->tag);
859                 scb = ahd_lookup_scb(ahd, scb_index);
860                 if (scb == NULL) {
861                         printf("%s: WARNING no command for scb %d "
862                                "(cmdcmplt)\nQOUTPOS = %d\n",
863                                ahd_name(ahd), scb_index,
864                                ahd->qoutfifonext);
865                         ahd_dump_card_state(ahd);
866                 } else if ((completion->sg_status & SG_STATUS_VALID) != 0) {
867                         ahd_handle_scb_status(ahd, scb);
868                 } else {
869                         ahd_done(ahd, scb);
870                 }
871
872                 ahd->qoutfifonext = (ahd->qoutfifonext+1) & (AHD_QOUT_SIZE-1);
873                 if (ahd->qoutfifonext == 0)
874                         ahd->qoutfifonext_valid_tag ^= QOUTFIFO_ENTRY_VALID;
875         }
876         ahd->flags &= ~AHD_RUNNING_QOUTFIFO;
877 }
878
879 /************************* Interrupt Handling *********************************/
880 void
881 ahd_handle_hwerrint(struct ahd_softc *ahd)
882 {
883         /*
884          * Some catastrophic hardware error has occurred.
885          * Print it for the user and disable the controller.
886          */
887         int i;
888         int error;
889
890         error = ahd_inb(ahd, ERROR);
891         for (i = 0; i < num_errors; i++) {
892                 if ((error & ahd_hard_errors[i].errno) != 0)
893                         printf("%s: hwerrint, %s\n",
894                                ahd_name(ahd), ahd_hard_errors[i].errmesg);
895         }
896
897         ahd_dump_card_state(ahd);
898         panic("BRKADRINT");
899
900         /* Tell everyone that this HBA is no longer available */
901         ahd_abort_scbs(ahd, CAM_TARGET_WILDCARD, ALL_CHANNELS,
902                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
903                        CAM_NO_HBA);
904
905         /* Tell the system that this controller has gone away. */
906         ahd_free(ahd);
907 }
908
909 void
910 ahd_handle_seqint(struct ahd_softc *ahd, u_int intstat)
911 {
912         u_int seqintcode;
913
914         /*
915          * Save the sequencer interrupt code and clear the SEQINT
916          * bit. We will unpause the sequencer, if appropriate,
917          * after servicing the request.
918          */
919         seqintcode = ahd_inb(ahd, SEQINTCODE);
920         ahd_outb(ahd, CLRINT, CLRSEQINT);
921         if ((ahd->bugs & AHD_INTCOLLISION_BUG) != 0) {
922                 /*
923                  * Unpause the sequencer and let it clear
924                  * SEQINT by writing NO_SEQINT to it.  This
925                  * will cause the sequencer to be paused again,
926                  * which is the expected state of this routine.
927                  */
928                 ahd_unpause(ahd);
929                 while (!ahd_is_paused(ahd))
930                         ;
931                 ahd_outb(ahd, CLRINT, CLRSEQINT);
932         }
933         ahd_update_modes(ahd);
934 #ifdef AHD_DEBUG
935         if ((ahd_debug & AHD_SHOW_MISC) != 0)
936                 printf("%s: Handle Seqint Called for code %d\n",
937                        ahd_name(ahd), seqintcode);
938 #endif
939         switch (seqintcode) {
940         case ENTERING_NONPACK:
941         {
942                 struct  scb *scb;
943                 u_int   scbid;
944
945                 AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
946                                  ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
947                 scbid = ahd_get_scbptr(ahd);
948                 scb = ahd_lookup_scb(ahd, scbid);
949                 if (scb == NULL) {
950                         /*
951                          * Somehow need to know if this
952                          * is from a selection or reselection.
953                          * From that, we can determine target
954                          * ID so we at least have an I_T nexus.
955                          */
956                 } else {
957                         ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
958                         ahd_outb(ahd, SAVED_LUN, scb->hscb->lun);
959                         ahd_outb(ahd, SEQ_FLAGS, 0x0);
960                 }
961                 if ((ahd_inb(ahd, LQISTAT2) & LQIPHASE_OUTPKT) != 0
962                  && (ahd_inb(ahd, SCSISIGO) & ATNO) != 0) {
963                         /*
964                          * Phase change after read stream with
965                          * CRC error with P0 asserted on last
966                          * packet.
967                          */
968 #ifdef AHD_DEBUG
969                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
970                                 printf("%s: Assuming LQIPHASE_NLQ with "
971                                        "P0 assertion\n", ahd_name(ahd));
972 #endif
973                 }
974 #ifdef AHD_DEBUG
975                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0)
976                         printf("%s: Entering NONPACK\n", ahd_name(ahd));
977 #endif
978                 break;
979         }
980         case INVALID_SEQINT:
981                 printf("%s: Invalid Sequencer interrupt occurred.\n",
982                        ahd_name(ahd));
983                 ahd_dump_card_state(ahd);
984                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
985                 break;
986         case STATUS_OVERRUN:
987         {
988                 struct  scb *scb;
989                 u_int   scbid;
990
991                 scbid = ahd_get_scbptr(ahd);
992                 scb = ahd_lookup_scb(ahd, scbid);
993                 if (scb != NULL)
994                         ahd_print_path(ahd, scb);
995                 else
996                         printf("%s: ", ahd_name(ahd));
997                 printf("SCB %d Packetized Status Overrun", scbid);
998                 ahd_dump_card_state(ahd);
999                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1000                 break;
1001         }
1002         case CFG4ISTAT_INTR:
1003         {
1004                 struct  scb *scb;
1005                 u_int   scbid;
1006
1007                 scbid = ahd_get_scbptr(ahd);
1008                 scb = ahd_lookup_scb(ahd, scbid);
1009                 if (scb == NULL) {
1010                         ahd_dump_card_state(ahd);
1011                         printf("CFG4ISTAT: Free SCB %d referenced", scbid);
1012                         panic("For safety");
1013                 }
1014                 ahd_outq(ahd, HADDR, scb->sense_busaddr);
1015                 ahd_outw(ahd, HCNT, AHD_SENSE_BUFSIZE);
1016                 ahd_outb(ahd, HCNT + 2, 0);
1017                 ahd_outb(ahd, SG_CACHE_PRE, SG_LAST_SEG);
1018                 ahd_outb(ahd, DFCNTRL, PRELOADEN|SCSIEN|HDMAEN);
1019                 break;
1020         }
1021         case ILLEGAL_PHASE:
1022         {
1023                 u_int bus_phase;
1024
1025                 bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1026                 printf("%s: ILLEGAL_PHASE 0x%x\n",
1027                        ahd_name(ahd), bus_phase);
1028
1029                 switch (bus_phase) {
1030                 case P_DATAOUT:
1031                 case P_DATAIN:
1032                 case P_DATAOUT_DT:
1033                 case P_DATAIN_DT:
1034                 case P_MESGOUT:
1035                 case P_STATUS:
1036                 case P_MESGIN:
1037                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1038                         printf("%s: Issued Bus Reset.\n", ahd_name(ahd));
1039                         break;
1040                 case P_COMMAND:
1041                 {
1042                         struct  ahd_devinfo devinfo;
1043                         struct  scb *scb;
1044                         struct  ahd_initiator_tinfo *targ_info;
1045                         struct  ahd_tmode_tstate *tstate;
1046                         struct  ahd_transinfo *tinfo;
1047                         u_int   scbid;
1048
1049                         /*
1050                          * If a target takes us into the command phase
1051                          * assume that it has been externally reset and
1052                          * has thus lost our previous packetized negotiation
1053                          * agreement.  Since we have not sent an identify
1054                          * message and may not have fully qualified the
1055                          * connection, we change our command to TUR, assert
1056                          * ATN and ABORT the task when we go to message in
1057                          * phase.  The OSM will see the REQUEUE_REQUEST
1058                          * status and retry the command.
1059                          */
1060                         scbid = ahd_get_scbptr(ahd);
1061                         scb = ahd_lookup_scb(ahd, scbid);
1062                         if (scb == NULL) {
1063                                 printf("Invalid phase with no valid SCB.  "
1064                                        "Resetting bus.\n");
1065                                 ahd_reset_channel(ahd, 'A',
1066                                                   /*Initiate Reset*/TRUE);
1067                                 break;
1068                         }
1069                         ahd_compile_devinfo(&devinfo, SCB_GET_OUR_ID(scb),
1070                                             SCB_GET_TARGET(ahd, scb),
1071                                             SCB_GET_LUN(scb),
1072                                             SCB_GET_CHANNEL(ahd, scb),
1073                                             ROLE_INITIATOR);
1074                         targ_info = ahd_fetch_transinfo(ahd,
1075                                                         devinfo.channel,
1076                                                         devinfo.our_scsiid,
1077                                                         devinfo.target,
1078                                                         &tstate);
1079                         tinfo = &targ_info->curr;
1080                         ahd_set_width(ahd, &devinfo, MSG_EXT_WDTR_BUS_8_BIT,
1081                                       AHD_TRANS_ACTIVE, /*paused*/TRUE);
1082                         ahd_set_syncrate(ahd, &devinfo, /*period*/0,
1083                                          /*offset*/0, /*ppr_options*/0,
1084                                          AHD_TRANS_ACTIVE, /*paused*/TRUE);
1085                         ahd_outb(ahd, SCB_CDB_STORE, 0);
1086                         ahd_outb(ahd, SCB_CDB_STORE+1, 0);
1087                         ahd_outb(ahd, SCB_CDB_STORE+2, 0);
1088                         ahd_outb(ahd, SCB_CDB_STORE+3, 0);
1089                         ahd_outb(ahd, SCB_CDB_STORE+4, 0);
1090                         ahd_outb(ahd, SCB_CDB_STORE+5, 0);
1091                         ahd_outb(ahd, SCB_CDB_LEN, 6);
1092                         scb->hscb->control &= ~(TAG_ENB|SCB_TAG_TYPE);
1093                         scb->hscb->control |= MK_MESSAGE;
1094                         ahd_outb(ahd, SCB_CONTROL, scb->hscb->control);
1095                         ahd_outb(ahd, MSG_OUT, HOST_MSG);
1096                         ahd_outb(ahd, SAVED_SCSIID, scb->hscb->scsiid);
1097                         /*
1098                          * The lun is 0, regardless of the SCB's lun
1099                          * as we have not sent an identify message.
1100                          */
1101                         ahd_outb(ahd, SAVED_LUN, 0);
1102                         ahd_outb(ahd, SEQ_FLAGS, 0);
1103                         ahd_assert_atn(ahd);
1104                         scb->flags &= ~SCB_PACKETIZED;
1105                         scb->flags |= SCB_ABORT|SCB_CMDPHASE_ABORT;
1106                         ahd_freeze_devq(ahd, scb);
1107                         ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
1108                         ahd_freeze_scb(scb);
1109
1110                         /*
1111                          * Allow the sequencer to continue with
1112                          * non-pack processing.
1113                          */
1114                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1115                         ahd_outb(ahd, CLRLQOINT1, CLRLQOPHACHGINPKT);
1116                         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
1117                                 ahd_outb(ahd, CLRLQOINT1, 0);
1118                         }
1119 #ifdef AHD_DEBUG
1120                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1121                                 ahd_print_path(ahd, scb);
1122                                 printf("Unexpected command phase from "
1123                                        "packetized target\n");
1124                         }
1125 #endif
1126                         break;
1127                 }
1128                 }
1129                 break;
1130         }
1131         case CFG4OVERRUN:
1132         {
1133                 struct  scb *scb;
1134                 u_int   scb_index;
1135                 
1136 #ifdef AHD_DEBUG
1137                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1138                         printf("%s: CFG4OVERRUN mode = %x\n", ahd_name(ahd),
1139                                ahd_inb(ahd, MODE_PTR));
1140                 }
1141 #endif
1142                 scb_index = ahd_get_scbptr(ahd);
1143                 scb = ahd_lookup_scb(ahd, scb_index);
1144                 if (scb == NULL) {
1145                         /*
1146                          * Attempt to transfer to an SCB that is
1147                          * not outstanding.
1148                          */
1149                         ahd_assert_atn(ahd);
1150                         ahd_outb(ahd, MSG_OUT, HOST_MSG);
1151                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
1152                         ahd->msgout_len = 1;
1153                         ahd->msgout_index = 0;
1154                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1155                         /*
1156                          * Clear status received flag to prevent any
1157                          * attempt to complete this bogus SCB.
1158                          */
1159                         ahd_outb(ahd, SCB_CONTROL,
1160                                  ahd_inb_scbram(ahd, SCB_CONTROL)
1161                                  & ~STATUS_RCVD);
1162                 }
1163                 break;
1164         }
1165         case DUMP_CARD_STATE:
1166         {
1167                 ahd_dump_card_state(ahd);
1168                 break;
1169         }
1170         case PDATA_REINIT:
1171         {
1172 #ifdef AHD_DEBUG
1173                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1174                         printf("%s: PDATA_REINIT - DFCNTRL = 0x%x "
1175                                "SG_CACHE_SHADOW = 0x%x\n",
1176                                ahd_name(ahd), ahd_inb(ahd, DFCNTRL),
1177                                ahd_inb(ahd, SG_CACHE_SHADOW));
1178                 }
1179 #endif
1180                 ahd_reinitialize_dataptrs(ahd);
1181                 break;
1182         }
1183         case HOST_MSG_LOOP:
1184         {
1185                 struct ahd_devinfo devinfo;
1186
1187                 /*
1188                  * The sequencer has encountered a message phase
1189                  * that requires host assistance for completion.
1190                  * While handling the message phase(s), we will be
1191                  * notified by the sequencer after each byte is
1192                  * transfered so we can track bus phase changes.
1193                  *
1194                  * If this is the first time we've seen a HOST_MSG_LOOP
1195                  * interrupt, initialize the state of the host message
1196                  * loop.
1197                  */
1198                 ahd_fetch_devinfo(ahd, &devinfo);
1199                 if (ahd->msg_type == MSG_TYPE_NONE) {
1200                         struct scb *scb;
1201                         u_int scb_index;
1202                         u_int bus_phase;
1203
1204                         bus_phase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1205                         if (bus_phase != P_MESGIN
1206                          && bus_phase != P_MESGOUT) {
1207                                 printf("ahd_intr: HOST_MSG_LOOP bad "
1208                                        "phase 0x%x\n", bus_phase);
1209                                 /*
1210                                  * Probably transitioned to bus free before
1211                                  * we got here.  Just punt the message.
1212                                  */
1213                                 ahd_dump_card_state(ahd);
1214                                 ahd_clear_intstat(ahd);
1215                                 ahd_restart(ahd);
1216                                 return;
1217                         }
1218
1219                         scb_index = ahd_get_scbptr(ahd);
1220                         scb = ahd_lookup_scb(ahd, scb_index);
1221                         if (devinfo.role == ROLE_INITIATOR) {
1222                                 if (bus_phase == P_MESGOUT)
1223                                         ahd_setup_initiator_msgout(ahd,
1224                                                                    &devinfo,
1225                                                                    scb);
1226                                 else {
1227                                         ahd->msg_type =
1228                                             MSG_TYPE_INITIATOR_MSGIN;
1229                                         ahd->msgin_index = 0;
1230                                 }
1231                         }
1232 #ifdef AHD_TARGET_MODE
1233                         else {
1234                                 if (bus_phase == P_MESGOUT) {
1235                                         ahd->msg_type =
1236                                             MSG_TYPE_TARGET_MSGOUT;
1237                                         ahd->msgin_index = 0;
1238                                 }
1239                                 else 
1240                                         ahd_setup_target_msgin(ahd,
1241                                                                &devinfo,
1242                                                                scb);
1243                         }
1244 #endif
1245                 }
1246
1247                 ahd_handle_message_phase(ahd);
1248                 break;
1249         }
1250         case NO_MATCH:
1251         {
1252                 /* Ensure we don't leave the selection hardware on */
1253                 AHD_ASSERT_MODES(ahd, AHD_MODE_SCSI_MSK, AHD_MODE_SCSI_MSK);
1254                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
1255
1256                 printf("%s:%c:%d: no active SCB for reconnecting "
1257                        "target - issuing BUS DEVICE RESET\n",
1258                        ahd_name(ahd), 'A', ahd_inb(ahd, SELID) >> 4);
1259                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
1260                        "REG0 == 0x%x ACCUM = 0x%x\n",
1261                        ahd_inb(ahd, SAVED_SCSIID), ahd_inb(ahd, SAVED_LUN),
1262                        ahd_inw(ahd, REG0), ahd_inb(ahd, ACCUM));
1263                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
1264                        "SINDEX == 0x%x\n",
1265                        ahd_inb(ahd, SEQ_FLAGS), ahd_get_scbptr(ahd),
1266                        ahd_find_busy_tcl(ahd,
1267                                          BUILD_TCL(ahd_inb(ahd, SAVED_SCSIID),
1268                                                    ahd_inb(ahd, SAVED_LUN))),
1269                        ahd_inw(ahd, SINDEX));
1270                 printf("SELID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
1271                        "SCB_CONTROL == 0x%x\n",
1272                        ahd_inb(ahd, SELID), ahd_inb_scbram(ahd, SCB_SCSIID),
1273                        ahd_inb_scbram(ahd, SCB_LUN),
1274                        ahd_inb_scbram(ahd, SCB_CONTROL));
1275                 printf("SCSIBUS[0] == 0x%x, SCSISIGI == 0x%x\n",
1276                        ahd_inb(ahd, SCSIBUS), ahd_inb(ahd, SCSISIGI));
1277                 printf("SXFRCTL0 == 0x%x\n", ahd_inb(ahd, SXFRCTL0));
1278                 printf("SEQCTL0 == 0x%x\n", ahd_inb(ahd, SEQCTL0));
1279                 ahd_dump_card_state(ahd);
1280                 ahd->msgout_buf[0] = MSG_BUS_DEV_RESET;
1281                 ahd->msgout_len = 1;
1282                 ahd->msgout_index = 0;
1283                 ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1284                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
1285                 ahd_assert_atn(ahd);
1286                 break;
1287         }
1288         case PROTO_VIOLATION:
1289         {
1290                 ahd_handle_proto_violation(ahd);
1291                 break;
1292         }
1293         case IGN_WIDE_RES:
1294         {
1295                 struct ahd_devinfo devinfo;
1296
1297                 ahd_fetch_devinfo(ahd, &devinfo);
1298                 ahd_handle_ign_wide_residue(ahd, &devinfo);
1299                 break;
1300         }
1301         case BAD_PHASE:
1302         {
1303                 u_int lastphase;
1304
1305                 lastphase = ahd_inb(ahd, LASTPHASE);
1306                 printf("%s:%c:%d: unknown scsi bus phase %x, "
1307                        "lastphase = 0x%x.  Attempting to continue\n",
1308                        ahd_name(ahd), 'A',
1309                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1310                        lastphase, ahd_inb(ahd, SCSISIGI));
1311                 break;
1312         }
1313         case MISSED_BUSFREE:
1314         {
1315                 u_int lastphase;
1316
1317                 lastphase = ahd_inb(ahd, LASTPHASE);
1318                 printf("%s:%c:%d: Missed busfree. "
1319                        "Lastphase = 0x%x, Curphase = 0x%x\n",
1320                        ahd_name(ahd), 'A',
1321                        SCSIID_TARGET(ahd, ahd_inb(ahd, SAVED_SCSIID)),
1322                        lastphase, ahd_inb(ahd, SCSISIGI));
1323                 ahd_restart(ahd);
1324                 return;
1325         }
1326         case DATA_OVERRUN:
1327         {
1328                 /*
1329                  * When the sequencer detects an overrun, it
1330                  * places the controller in "BITBUCKET" mode
1331                  * and allows the target to complete its transfer.
1332                  * Unfortunately, none of the counters get updated
1333                  * when the controller is in this mode, so we have
1334                  * no way of knowing how large the overrun was.
1335                  */
1336                 struct  scb *scb;
1337                 u_int   scbindex;
1338 #ifdef AHD_DEBUG
1339                 u_int   lastphase;
1340 #endif
1341
1342                 scbindex = ahd_get_scbptr(ahd);
1343                 scb = ahd_lookup_scb(ahd, scbindex);
1344 #ifdef AHD_DEBUG
1345                 lastphase = ahd_inb(ahd, LASTPHASE);
1346                 if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1347                         ahd_print_path(ahd, scb);
1348                         printf("data overrun detected %s.  Tag == 0x%x.\n",
1349                                ahd_lookup_phase_entry(lastphase)->phasemsg,
1350                                SCB_GET_TAG(scb));
1351                         ahd_print_path(ahd, scb);
1352                         printf("%s seen Data Phase.  Length = %ld.  "
1353                                "NumSGs = %d.\n",
1354                                ahd_inb(ahd, SEQ_FLAGS) & DPHASE
1355                                ? "Have" : "Haven't",
1356                                ahd_get_transfer_length(scb), scb->sg_count);
1357                         ahd_dump_sglist(scb);
1358                 }
1359 #endif
1360
1361                 /*
1362                  * Set this and it will take effect when the
1363                  * target does a command complete.
1364                  */
1365                 ahd_freeze_devq(ahd, scb);
1366                 ahd_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1367                 ahd_freeze_scb(scb);
1368                 break;
1369         }
1370         case MKMSG_FAILED:
1371         {
1372                 struct ahd_devinfo devinfo;
1373                 struct scb *scb;
1374                 u_int scbid;
1375
1376                 ahd_fetch_devinfo(ahd, &devinfo);
1377                 printf("%s:%c:%d:%d: Attempt to issue message failed\n",
1378                        ahd_name(ahd), devinfo.channel, devinfo.target,
1379                        devinfo.lun);
1380                 scbid = ahd_get_scbptr(ahd);
1381                 scb = ahd_lookup_scb(ahd, scbid);
1382                 if (scb != NULL
1383                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
1384                         /*
1385                          * Ensure that we didn't put a second instance of this
1386                          * SCB into the QINFIFO.
1387                          */
1388                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1389                                            SCB_GET_CHANNEL(ahd, scb),
1390                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb),
1391                                            ROLE_INITIATOR, /*status*/0,
1392                                            SEARCH_REMOVE);
1393                 ahd_outb(ahd, SCB_CONTROL,
1394                          ahd_inb_scbram(ahd, SCB_CONTROL) & ~MK_MESSAGE);
1395                 break;
1396         }
1397         case TASKMGMT_FUNC_COMPLETE:
1398         {
1399                 u_int   scbid;
1400                 struct  scb *scb;
1401
1402                 scbid = ahd_get_scbptr(ahd);
1403                 scb = ahd_lookup_scb(ahd, scbid);
1404                 if (scb != NULL) {
1405                         u_int      lun;
1406                         u_int      tag;
1407                         cam_status error;
1408
1409                         ahd_print_path(ahd, scb);
1410                         printf("Task Management Func 0x%x Complete\n",
1411                                scb->hscb->task_management);
1412                         lun = CAM_LUN_WILDCARD;
1413                         tag = SCB_LIST_NULL;
1414
1415                         switch (scb->hscb->task_management) {
1416                         case SIU_TASKMGMT_ABORT_TASK:
1417                                 tag = SCB_GET_TAG(scb);
1418                         case SIU_TASKMGMT_ABORT_TASK_SET:
1419                         case SIU_TASKMGMT_CLEAR_TASK_SET:
1420                                 lun = scb->hscb->lun;
1421                                 error = CAM_REQ_ABORTED;
1422                                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
1423                                                'A', lun, tag, ROLE_INITIATOR,
1424                                                error);
1425                                 break;
1426                         case SIU_TASKMGMT_LUN_RESET:
1427                                 lun = scb->hscb->lun;
1428                         case SIU_TASKMGMT_TARGET_RESET:
1429                         {
1430                                 struct ahd_devinfo devinfo;
1431
1432                                 ahd_scb_devinfo(ahd, &devinfo, scb);
1433                                 error = CAM_BDR_SENT;
1434                                 ahd_handle_devreset(ahd, &devinfo, lun,
1435                                                     CAM_BDR_SENT,
1436                                                     lun != CAM_LUN_WILDCARD
1437                                                     ? "Lun Reset"
1438                                                     : "Target Reset",
1439                                                     /*verbose_level*/0);
1440                                 break;
1441                         }
1442                         default:
1443                                 panic("Unexpected TaskMgmt Func\n");
1444                                 break;
1445                         }
1446                 }
1447                 break;
1448         }
1449         case TASKMGMT_CMD_CMPLT_OKAY:
1450         {
1451                 u_int   scbid;
1452                 struct  scb *scb;
1453
1454                 /*
1455                  * An ABORT TASK TMF failed to be delivered before
1456                  * the targeted command completed normally.
1457                  */
1458                 scbid = ahd_get_scbptr(ahd);
1459                 scb = ahd_lookup_scb(ahd, scbid);
1460                 if (scb != NULL) {
1461                         /*
1462                          * Remove the second instance of this SCB from
1463                          * the QINFIFO if it is still there.
1464                          */
1465                         ahd_print_path(ahd, scb);
1466                         printf("SCB completes before TMF\n");
1467                         /*
1468                          * Handle losing the race.  Wait until any
1469                          * current selection completes.  We will then
1470                          * set the TMF back to zero in this SCB so that
1471                          * the sequencer doesn't bother to issue another
1472                          * sequencer interrupt for its completion.
1473                          */
1474                         while ((ahd_inb(ahd, SCSISEQ0) & ENSELO) != 0
1475                             && (ahd_inb(ahd, SSTAT0) & SELDO) == 0
1476                             && (ahd_inb(ahd, SSTAT1) & SELTO) == 0)
1477                                 ;
1478                         ahd_outb(ahd, SCB_TASK_MANAGEMENT, 0);
1479                         ahd_search_qinfifo(ahd, SCB_GET_TARGET(ahd, scb),
1480                                            SCB_GET_CHANNEL(ahd, scb),  
1481                                            SCB_GET_LUN(scb), SCB_GET_TAG(scb), 
1482                                            ROLE_INITIATOR, /*status*/0,   
1483                                            SEARCH_REMOVE);
1484                 }
1485                 break;
1486         }
1487         case TRACEPOINT0:
1488         case TRACEPOINT1:
1489         case TRACEPOINT2:
1490         case TRACEPOINT3:
1491                 printf("%s: Tracepoint %d\n", ahd_name(ahd),
1492                        seqintcode - TRACEPOINT0);
1493                 break;
1494         case NO_SEQINT:
1495                 break;
1496         case SAW_HWERR:
1497                 ahd_handle_hwerrint(ahd);
1498                 break;
1499         default:
1500                 printf("%s: Unexpected SEQINTCODE %d\n", ahd_name(ahd),
1501                        seqintcode);
1502                 break;
1503         }
1504         /*
1505          *  The sequencer is paused immediately on
1506          *  a SEQINT, so we should restart it when
1507          *  we're done.
1508          */
1509         ahd_unpause(ahd);
1510 }
1511
1512 void
1513 ahd_handle_scsiint(struct ahd_softc *ahd, u_int intstat)
1514 {
1515         struct scb      *scb;
1516         u_int            status0;
1517         u_int            status3;
1518         u_int            status;
1519         u_int            lqistat1;
1520         u_int            lqostat0;
1521         u_int            scbid;
1522         u_int            busfreetime;
1523
1524         ahd_update_modes(ahd);
1525         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1526
1527         status3 = ahd_inb(ahd, SSTAT3) & (NTRAMPERR|OSRAMPERR);
1528         status0 = ahd_inb(ahd, SSTAT0) & (IOERR|OVERRUN|SELDI|SELDO);
1529         status = ahd_inb(ahd, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1530         lqistat1 = ahd_inb(ahd, LQISTAT1);
1531         lqostat0 = ahd_inb(ahd, LQOSTAT0);
1532         busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1533         if ((status0 & (SELDI|SELDO)) != 0) {
1534                 u_int simode0;
1535
1536                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1537                 simode0 = ahd_inb(ahd, SIMODE0);
1538                 status0 &= simode0 & (IOERR|OVERRUN|SELDI|SELDO);
1539                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1540         }
1541         scbid = ahd_get_scbptr(ahd);
1542         scb = ahd_lookup_scb(ahd, scbid);
1543         if (scb != NULL
1544          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1545                 scb = NULL;
1546
1547         if ((status0 & IOERR) != 0) {
1548                 u_int now_lvd;
1549
1550                 now_lvd = ahd_inb(ahd, SBLKCTL) & ENAB40;
1551                 printf("%s: Transceiver State Has Changed to %s mode\n",
1552                        ahd_name(ahd), now_lvd ? "LVD" : "SE");
1553                 ahd_outb(ahd, CLRSINT0, CLRIOERR);
1554                 /*
1555                  * A change in I/O mode is equivalent to a bus reset.
1556                  */
1557                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1558                 ahd_pause(ahd);
1559                 ahd_setup_iocell_workaround(ahd);
1560                 ahd_unpause(ahd);
1561         } else if ((status0 & OVERRUN) != 0) {
1562
1563                 printf("%s: SCSI offset overrun detected.  Resetting bus.\n",
1564                        ahd_name(ahd));
1565                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1566         } else if ((status & SCSIRSTI) != 0) {
1567
1568                 printf("%s: Someone reset channel A\n", ahd_name(ahd));
1569                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/FALSE);
1570         } else if ((status & SCSIPERR) != 0) {
1571
1572                 /* Make sure the sequencer is in a safe location. */
1573                 ahd_clear_critical_section(ahd);
1574
1575                 ahd_handle_transmission_error(ahd);
1576         } else if (lqostat0 != 0) {
1577
1578                 printf("%s: lqostat0 == 0x%x!\n", ahd_name(ahd), lqostat0);
1579                 ahd_outb(ahd, CLRLQOINT0, lqostat0);
1580                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
1581                         ahd_outb(ahd, CLRLQOINT1, 0);
1582         } else if ((status & SELTO) != 0) {
1583                 u_int  scbid;
1584
1585                 /* Stop the selection */
1586                 ahd_outb(ahd, SCSISEQ0, 0);
1587
1588                 /* Make sure the sequencer is in a safe location. */
1589                 ahd_clear_critical_section(ahd);
1590
1591                 /* No more pending messages */
1592                 ahd_clear_msg_state(ahd);
1593
1594                 /* Clear interrupt state */
1595                 ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1596
1597                 /*
1598                  * Although the driver does not care about the
1599                  * 'Selection in Progress' status bit, the busy
1600                  * LED does.  SELINGO is only cleared by a sucessfull
1601                  * selection, so we must manually clear it to insure
1602                  * the LED turns off just incase no future successful
1603                  * selections occur (e.g. no devices on the bus).
1604                  */
1605                 ahd_outb(ahd, CLRSINT0, CLRSELINGO);
1606
1607                 scbid = ahd_inw(ahd, WAITING_TID_HEAD);
1608                 scb = ahd_lookup_scb(ahd, scbid);
1609                 if (scb == NULL) {
1610                         printf("%s: ahd_intr - referenced scb not "
1611                                "valid during SELTO scb(0x%x)\n",
1612                                ahd_name(ahd), scbid);
1613                         ahd_dump_card_state(ahd);
1614                 } else {
1615                         struct ahd_devinfo devinfo;
1616 #ifdef AHD_DEBUG
1617                         if ((ahd_debug & AHD_SHOW_SELTO) != 0) {
1618                                 ahd_print_path(ahd, scb);
1619                                 printf("Saw Selection Timeout for SCB 0x%x\n",
1620                                        scbid);
1621                         }
1622 #endif
1623                         ahd_scb_devinfo(ahd, &devinfo, scb);
1624                         ahd_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1625                         ahd_freeze_devq(ahd, scb);
1626
1627                         /*
1628                          * Cancel any pending transactions on the device
1629                          * now that it seems to be missing.  This will
1630                          * also revert us to async/narrow transfers until
1631                          * we can renegotiate with the device.
1632                          */
1633                         ahd_handle_devreset(ahd, &devinfo,
1634                                             CAM_LUN_WILDCARD,
1635                                             CAM_SEL_TIMEOUT,
1636                                             "Selection Timeout",
1637                                             /*verbose_level*/1);
1638                 }
1639                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
1640                 ahd_iocell_first_selection(ahd);
1641                 ahd_unpause(ahd);
1642         } else if ((status0 & (SELDI|SELDO)) != 0) {
1643
1644                 ahd_iocell_first_selection(ahd);
1645                 ahd_unpause(ahd);
1646         } else if (status3 != 0) {
1647                 printf("%s: SCSI Cell parity error SSTAT3 == 0x%x\n",
1648                        ahd_name(ahd), status3);
1649                 ahd_outb(ahd, CLRSINT3, status3);
1650         } else if ((lqistat1 & (LQIPHASE_LQ|LQIPHASE_NLQ)) != 0) {
1651
1652                 /* Make sure the sequencer is in a safe location. */
1653                 ahd_clear_critical_section(ahd);
1654
1655                 ahd_handle_lqiphase_error(ahd, lqistat1);
1656         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1657                 /*
1658                  * This status can be delayed during some
1659                  * streaming operations.  The SCSIPHASE
1660                  * handler has already dealt with this case
1661                  * so just clear the error.
1662                  */
1663                 ahd_outb(ahd, CLRLQIINT1, CLRLQICRCI_NLQ);
1664         } else if ((status & BUSFREE) != 0
1665                 || (lqistat1 & LQOBUSFREE) != 0) {
1666                 u_int lqostat1;
1667                 int   restart;
1668                 int   clear_fifo;
1669                 int   packetized;
1670                 u_int mode;
1671
1672                 /*
1673                  * Clear our selection hardware as soon as possible.
1674                  * We may have an entry in the waiting Q for this target,
1675                  * that is affected by this busfree and we don't want to
1676                  * go about selecting the target while we handle the event.
1677                  */
1678                 ahd_outb(ahd, SCSISEQ0, 0);
1679
1680                 /* Make sure the sequencer is in a safe location. */
1681                 ahd_clear_critical_section(ahd);
1682
1683                 /*
1684                  * Determine what we were up to at the time of
1685                  * the busfree.
1686                  */
1687                 mode = AHD_MODE_SCSI;
1688                 busfreetime = ahd_inb(ahd, SSTAT2) & BUSFREETIME;
1689                 lqostat1 = ahd_inb(ahd, LQOSTAT1);
1690                 switch (busfreetime) {
1691                 case BUSFREE_DFF0:
1692                 case BUSFREE_DFF1:
1693                 {
1694                         u_int   scbid;
1695                         struct  scb *scb;
1696
1697                         mode = busfreetime == BUSFREE_DFF0
1698                              ? AHD_MODE_DFF0 : AHD_MODE_DFF1;
1699                         ahd_set_modes(ahd, mode, mode);
1700                         scbid = ahd_get_scbptr(ahd);
1701                         scb = ahd_lookup_scb(ahd, scbid);
1702                         if (scb == NULL) {
1703                                 printf("%s: Invalid SCB %d in DFF%d "
1704                                        "during unexpected busfree\n",
1705                                        ahd_name(ahd), scbid, mode);
1706                                 packetized = 0;
1707                         } else
1708                                 packetized = (scb->flags & SCB_PACKETIZED) != 0;
1709                         clear_fifo = 1;
1710                         break;
1711                 }
1712                 case BUSFREE_LQO:
1713                         clear_fifo = 0;
1714                         packetized = 1;
1715                         break;
1716                 default:
1717                         clear_fifo = 0;
1718                         packetized =  (lqostat1 & LQOBUSFREE) != 0;
1719                         if (!packetized
1720                          && ahd_inb(ahd, LASTPHASE) == P_BUSFREE
1721                          && (ahd_inb(ahd, SSTAT0) & SELDI) == 0
1722                          && ((ahd_inb(ahd, SSTAT0) & SELDO) == 0
1723                           || (ahd_inb(ahd, SCSISEQ0) & ENSELO) == 0))
1724                                 /*
1725                                  * Assume packetized if we are not
1726                                  * on the bus in a non-packetized
1727                                  * capacity and any pending selection
1728                                  * was a packetized selection.
1729                                  */
1730                                 packetized = 1;
1731                         break;
1732                 }
1733
1734 #ifdef AHD_DEBUG
1735                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
1736                         printf("Saw Busfree.  Busfreetime = 0x%x.\n",
1737                                busfreetime);
1738 #endif
1739                 /*
1740                  * Busfrees that occur in non-packetized phases are
1741                  * handled by the nonpkt_busfree handler.
1742                  */
1743                 if (packetized && ahd_inb(ahd, LASTPHASE) == P_BUSFREE) {
1744                         restart = ahd_handle_pkt_busfree(ahd, busfreetime);
1745                 } else {
1746                         packetized = 0;
1747                         restart = ahd_handle_nonpkt_busfree(ahd);
1748                 }
1749                 /*
1750                  * Clear the busfree interrupt status.  The setting of
1751                  * the interrupt is a pulse, so in a perfect world, we
1752                  * would not need to muck with the ENBUSFREE logic.  This
1753                  * would ensure that if the bus moves on to another
1754                  * connection, busfree protection is still in force.  If
1755                  * BUSFREEREV is broken, however, we must manually clear
1756                  * the ENBUSFREE if the busfree occurred during a non-pack
1757                  * connection so that we don't get false positives during
1758                  * future, packetized, connections.
1759                  */
1760                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
1761                 if (packetized == 0
1762                  && (ahd->bugs & AHD_BUSFREEREV_BUG) != 0)
1763                         ahd_outb(ahd, SIMODE1,
1764                                  ahd_inb(ahd, SIMODE1) & ~ENBUSFREE);
1765
1766                 if (clear_fifo)
1767                         ahd_clear_fifo(ahd, mode);
1768
1769                 ahd_clear_msg_state(ahd);
1770                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
1771                 if (restart) {
1772                         ahd_restart(ahd);
1773                 } else {
1774                         ahd_unpause(ahd);
1775                 }
1776         } else {
1777                 printf("%s: Missing case in ahd_handle_scsiint. status = %x\n",
1778                        ahd_name(ahd), status);
1779                 ahd_dump_card_state(ahd);
1780                 ahd_clear_intstat(ahd);
1781                 ahd_unpause(ahd);
1782         }
1783 }
1784
1785 static void
1786 ahd_handle_transmission_error(struct ahd_softc *ahd)
1787 {
1788         struct  scb *scb;
1789         u_int   scbid;
1790         u_int   lqistat1;
1791         u_int   lqistat2;
1792         u_int   msg_out;
1793         u_int   curphase;
1794         u_int   lastphase;
1795         u_int   perrdiag;
1796         u_int   cur_col;
1797         int     silent;
1798
1799         scb = NULL;
1800         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1801         lqistat1 = ahd_inb(ahd, LQISTAT1) & ~(LQIPHASE_LQ|LQIPHASE_NLQ);
1802         lqistat2 = ahd_inb(ahd, LQISTAT2);
1803         if ((lqistat1 & (LQICRCI_NLQ|LQICRCI_LQ)) == 0
1804          && (ahd->bugs & AHD_NLQICRC_DELAYED_BUG) != 0) {
1805                 u_int lqistate;
1806
1807                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
1808                 lqistate = ahd_inb(ahd, LQISTATE);
1809                 if ((lqistate >= 0x1E && lqistate <= 0x24)
1810                  || (lqistate == 0x29)) {
1811 #ifdef AHD_DEBUG
1812                         if ((ahd_debug & AHD_SHOW_RECOVERY) != 0) {
1813                                 printf("%s: NLQCRC found via LQISTATE\n",
1814                                        ahd_name(ahd));
1815                         }
1816 #endif
1817                         lqistat1 |= LQICRCI_NLQ;
1818                 }
1819                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1820         }
1821
1822         ahd_outb(ahd, CLRLQIINT1, lqistat1);
1823         lastphase = ahd_inb(ahd, LASTPHASE);
1824         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
1825         perrdiag = ahd_inb(ahd, PERRDIAG);
1826         msg_out = MSG_INITIATOR_DET_ERR;
1827         ahd_outb(ahd, CLRSINT1, CLRSCSIPERR);
1828         
1829         /*
1830          * Try to find the SCB associated with this error.
1831          */
1832         silent = FALSE;
1833         if (lqistat1 == 0
1834          || (lqistat1 & LQICRCI_NLQ) != 0) {
1835                 if ((lqistat1 & (LQICRCI_NLQ|LQIOVERI_NLQ)) != 0)
1836                         ahd_set_active_fifo(ahd);
1837                 scbid = ahd_get_scbptr(ahd);
1838                 scb = ahd_lookup_scb(ahd, scbid);
1839                 if (scb != NULL && SCB_IS_SILENT(scb))
1840                         silent = TRUE;
1841         }
1842
1843         cur_col = 0;
1844         if (silent == FALSE) {
1845                 printf("%s: Transmission error detected\n", ahd_name(ahd));
1846                 ahd_lqistat1_print(lqistat1, &cur_col, 50);
1847                 ahd_lastphase_print(lastphase, &cur_col, 50);
1848                 ahd_scsisigi_print(curphase, &cur_col, 50);
1849                 ahd_perrdiag_print(perrdiag, &cur_col, 50);
1850                 printf("\n");
1851                 ahd_dump_card_state(ahd);
1852         }
1853
1854         if ((lqistat1 & (LQIOVERI_LQ|LQIOVERI_NLQ)) != 0) {
1855                 if (silent == FALSE) {
1856                         printf("%s: Gross protocol error during incoming "
1857                                "packet.  lqistat1 == 0x%x.  Resetting bus.\n",
1858                                ahd_name(ahd), lqistat1);
1859                 }
1860                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1861                 return;
1862         } else if ((lqistat1 & LQICRCI_LQ) != 0) {
1863                 /*
1864                  * A CRC error has been detected on an incoming LQ.
1865                  * The bus is currently hung on the last ACK.
1866                  * Hit LQIRETRY to release the last ack, and
1867                  * wait for the sequencer to determine that ATNO
1868                  * is asserted while in message out to take us
1869                  * to our host message loop.  No NONPACKREQ or
1870                  * LQIPHASE type errors will occur in this
1871                  * scenario.  After this first LQIRETRY, the LQI
1872                  * manager will be in ISELO where it will
1873                  * happily sit until another packet phase begins.
1874                  * Unexpected bus free detection is enabled
1875                  * through any phases that occur after we release
1876                  * this last ack until the LQI manager sees a
1877                  * packet phase.  This implies we may have to
1878                  * ignore a perfectly valid "unexected busfree"
1879                  * after our "initiator detected error" message is
1880                  * sent.  A busfree is the expected response after
1881                  * we tell the target that it's L_Q was corrupted.
1882                  * (SPI4R09 10.7.3.3.3)
1883                  */
1884                 ahd_outb(ahd, LQCTL2, LQIRETRY);
1885                 printf("LQIRetry for LQICRCI_LQ to release ACK\n");
1886         } else if ((lqistat1 & LQICRCI_NLQ) != 0) {
1887                 /*
1888                  * We detected a CRC error in a NON-LQ packet.
1889                  * The hardware has varying behavior in this situation
1890                  * depending on whether this packet was part of a
1891                  * stream or not.
1892                  *
1893                  * PKT by PKT mode:
1894                  * The hardware has already acked the complete packet.
1895                  * If the target honors our outstanding ATN condition,
1896                  * we should be (or soon will be) in MSGOUT phase.
1897                  * This will trigger the LQIPHASE_LQ status bit as the
1898                  * hardware was expecting another LQ.  Unexpected
1899                  * busfree detection is enabled.  Once LQIPHASE_LQ is
1900                  * true (first entry into host message loop is much
1901                  * the same), we must clear LQIPHASE_LQ and hit
1902                  * LQIRETRY so the hardware is ready to handle
1903                  * a future LQ.  NONPACKREQ will not be asserted again
1904                  * once we hit LQIRETRY until another packet is
1905                  * processed.  The target may either go busfree
1906                  * or start another packet in response to our message.
1907                  *
1908                  * Read Streaming P0 asserted:
1909                  * If we raise ATN and the target completes the entire
1910                  * stream (P0 asserted during the last packet), the
1911                  * hardware will ack all data and return to the ISTART
1912                  * state.  When the target reponds to our ATN condition,
1913                  * LQIPHASE_LQ will be asserted.  We should respond to
1914                  * this with an LQIRETRY to prepare for any future
1915                  * packets.  NONPACKREQ will not be asserted again
1916                  * once we hit LQIRETRY until another packet is
1917                  * processed.  The target may either go busfree or
1918                  * start another packet in response to our message.
1919                  * Busfree detection is enabled.
1920                  *
1921                  * Read Streaming P0 not asserted:
1922                  * If we raise ATN and the target transitions to
1923                  * MSGOUT in or after a packet where P0 is not
1924                  * asserted, the hardware will assert LQIPHASE_NLQ.
1925                  * We should respond to the LQIPHASE_NLQ with an
1926                  * LQIRETRY.  Should the target stay in a non-pkt
1927                  * phase after we send our message, the hardware
1928                  * will assert LQIPHASE_LQ.  Recovery is then just as
1929                  * listed above for the read streaming with P0 asserted.
1930                  * Busfree detection is enabled.
1931                  */
1932                 if (silent == FALSE)
1933                         printf("LQICRC_NLQ\n");
1934                 if (scb == NULL) {
1935                         printf("%s: No SCB valid for LQICRC_NLQ.  "
1936                                "Resetting bus\n", ahd_name(ahd));
1937                         ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1938                         return;
1939                 }
1940         } else if ((lqistat1 & LQIBADLQI) != 0) {
1941                 printf("Need to handle BADLQI!\n");
1942                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
1943                 return;
1944         } else if ((perrdiag & (PARITYERR|PREVPHASE)) == PARITYERR) {
1945                 if ((curphase & ~P_DATAIN_DT) != 0) {
1946                         /* Ack the byte.  So we can continue. */
1947                         if (silent == FALSE)
1948                                 printf("Acking %s to clear perror\n",
1949                                     ahd_lookup_phase_entry(curphase)->phasemsg);
1950                         ahd_inb(ahd, SCSIDAT);
1951                 }
1952         
1953                 if (curphase == P_MESGIN)
1954                         msg_out = MSG_PARITY_ERROR;
1955         }
1956
1957         /*
1958          * We've set the hardware to assert ATN if we 
1959          * get a parity error on "in" phases, so all we
1960          * need to do is stuff the message buffer with
1961          * the appropriate message.  "In" phases have set
1962          * mesg_out to something other than MSG_NOP.
1963          */
1964         ahd->send_msg_perror = msg_out;
1965         if (scb != NULL && msg_out == MSG_INITIATOR_DET_ERR)
1966                 scb->flags |= SCB_TRANSMISSION_ERROR;
1967         ahd_outb(ahd, MSG_OUT, HOST_MSG);
1968         ahd_outb(ahd, CLRINT, CLRSCSIINT);
1969         ahd_unpause(ahd);
1970 }
1971
1972 static void
1973 ahd_handle_lqiphase_error(struct ahd_softc *ahd, u_int lqistat1)
1974 {
1975         /*
1976          * Clear the sources of the interrupts.
1977          */
1978         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
1979         ahd_outb(ahd, CLRLQIINT1, lqistat1);
1980
1981         /*
1982          * If the "illegal" phase changes were in response
1983          * to our ATN to flag a CRC error, AND we ended up
1984          * on packet boundaries, clear the error, restart the
1985          * LQI manager as appropriate, and go on our merry
1986          * way toward sending the message.  Otherwise, reset
1987          * the bus to clear the error.
1988          */
1989         ahd_set_active_fifo(ahd);
1990         if ((ahd_inb(ahd, SCSISIGO) & ATNO) != 0
1991          && (ahd_inb(ahd, MDFFSTAT) & DLZERO) != 0) {
1992                 if ((lqistat1 & LQIPHASE_LQ) != 0) {
1993                         printf("LQIRETRY for LQIPHASE_LQ\n");
1994                         ahd_outb(ahd, LQCTL2, LQIRETRY);
1995                 } else if ((lqistat1 & LQIPHASE_NLQ) != 0) {
1996                         printf("LQIRETRY for LQIPHASE_NLQ\n");
1997                         ahd_outb(ahd, LQCTL2, LQIRETRY);
1998                 } else
1999                         panic("ahd_handle_lqiphase_error: No phase errors\n");
2000                 ahd_dump_card_state(ahd);
2001                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2002                 ahd_unpause(ahd);
2003         } else {
2004                 printf("Reseting Channel for LQI Phase error\n");
2005                 ahd_dump_card_state(ahd);
2006                 ahd_reset_channel(ahd, 'A', /*Initiate Reset*/TRUE);
2007         }
2008 }
2009
2010 /*
2011  * Packetized unexpected or expected busfree.
2012  * Entered in mode based on busfreetime.
2013  */
2014 static int
2015 ahd_handle_pkt_busfree(struct ahd_softc *ahd, u_int busfreetime)
2016 {
2017         u_int lqostat1;
2018
2019         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2020                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2021         lqostat1 = ahd_inb(ahd, LQOSTAT1);
2022         if ((lqostat1 & LQOBUSFREE) != 0) {
2023                 struct scb *scb;
2024                 u_int scbid;
2025                 u_int saved_scbptr;
2026                 u_int waiting_h;
2027                 u_int waiting_t;
2028                 u_int next;
2029
2030                 /*
2031                  * The LQO manager detected an unexpected busfree
2032                  * either:
2033                  *
2034                  * 1) During an outgoing LQ.
2035                  * 2) After an outgoing LQ but before the first
2036                  *    REQ of the command packet.
2037                  * 3) During an outgoing command packet.
2038                  *
2039                  * In all cases, CURRSCB is pointing to the
2040                  * SCB that encountered the failure.  Clean
2041                  * up the queue, clear SELDO and LQOBUSFREE,
2042                  * and allow the sequencer to restart the select
2043                  * out at its lesure.
2044                  */
2045                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2046                 scbid = ahd_inw(ahd, CURRSCB);
2047                 scb = ahd_lookup_scb(ahd, scbid);
2048                 if (scb == NULL)
2049                        panic("SCB not valid during LQOBUSFREE");
2050                 /*
2051                  * Clear the status.
2052                  */
2053                 ahd_outb(ahd, CLRLQOINT1, CLRLQOBUSFREE);
2054                 if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0)
2055                         ahd_outb(ahd, CLRLQOINT1, 0);
2056                 ahd_outb(ahd, SCSISEQ0, ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2057                 ahd_flush_device_writes(ahd);
2058                 ahd_outb(ahd, CLRSINT0, CLRSELDO);
2059
2060                 /*
2061                  * Return the LQO manager to its idle loop.  It will
2062                  * not do this automatically if the busfree occurs
2063                  * after the first REQ of either the LQ or command
2064                  * packet or between the LQ and command packet.
2065                  */
2066                 ahd_outb(ahd, LQCTL2, ahd_inb(ahd, LQCTL2) | LQOTOIDLE);
2067
2068                 /*
2069                  * Update the waiting for selection queue so
2070                  * we restart on the correct SCB.
2071                  */
2072                 waiting_h = ahd_inw(ahd, WAITING_TID_HEAD);
2073                 saved_scbptr = ahd_get_scbptr(ahd);
2074                 if (waiting_h != scbid) {
2075
2076                         ahd_outw(ahd, WAITING_TID_HEAD, scbid);
2077                         waiting_t = ahd_inw(ahd, WAITING_TID_TAIL);
2078                         if (waiting_t == waiting_h) {
2079                                 ahd_outw(ahd, WAITING_TID_TAIL, scbid);
2080                                 next = SCB_LIST_NULL;
2081                         } else {
2082                                 ahd_set_scbptr(ahd, waiting_h);
2083                                 next = ahd_inw_scbram(ahd, SCB_NEXT2);
2084                         }
2085                         ahd_set_scbptr(ahd, scbid);
2086                         ahd_outw(ahd, SCB_NEXT2, next);
2087                 }
2088                 ahd_set_scbptr(ahd, saved_scbptr);
2089                 if (scb->crc_retry_count < AHD_MAX_LQ_CRC_ERRORS) {
2090                         if (SCB_IS_SILENT(scb) == FALSE) {
2091                                 ahd_print_path(ahd, scb);
2092                                 printf("Probable outgoing LQ CRC error.  "
2093                                        "Retrying command\n");
2094                         }
2095                         scb->crc_retry_count++;
2096                 } else {
2097                         ahd_set_transaction_status(scb, CAM_UNCOR_PARITY);
2098                         ahd_freeze_scb(scb);
2099                         ahd_freeze_devq(ahd, scb);
2100                 }
2101                 /* Return unpausing the sequencer. */
2102                 return (0);
2103         } else if ((ahd_inb(ahd, PERRDIAG) & PARITYERR) != 0) {
2104                 /*
2105                  * Ignore what are really parity errors that
2106                  * occur on the last REQ of a free running
2107                  * clock prior to going busfree.  Some drives
2108                  * do not properly active negate just before
2109                  * going busfree resulting in a parity glitch.
2110                  */
2111                 ahd_outb(ahd, CLRSINT1, CLRSCSIPERR|CLRBUSFREE);
2112 #ifdef AHD_DEBUG
2113                 if ((ahd_debug & AHD_SHOW_MASKED_ERRORS) != 0)
2114                         printf("%s: Parity on last REQ detected "
2115                                "during busfree phase.\n",
2116                                ahd_name(ahd));
2117 #endif
2118                 /* Return unpausing the sequencer. */
2119                 return (0);
2120         }
2121         if (ahd->src_mode != AHD_MODE_SCSI) {
2122                 u_int   scbid;
2123                 struct  scb *scb;
2124
2125                 scbid = ahd_get_scbptr(ahd);
2126                 scb = ahd_lookup_scb(ahd, scbid);
2127                 ahd_print_path(ahd, scb);
2128                 printf("Unexpected PKT busfree condition\n");
2129                 ahd_dump_card_state(ahd);
2130                 ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb), 'A',
2131                                SCB_GET_LUN(scb), SCB_GET_TAG(scb),
2132                                ROLE_INITIATOR, CAM_UNEXP_BUSFREE);
2133
2134                 /* Return restarting the sequencer. */
2135                 return (1);
2136         }
2137         printf("%s: Unexpected PKT busfree condition\n", ahd_name(ahd));
2138         ahd_dump_card_state(ahd);
2139         /* Restart the sequencer. */
2140         return (1);
2141 }
2142
2143 /*
2144  * Non-packetized unexpected or expected busfree.
2145  */
2146 static int
2147 ahd_handle_nonpkt_busfree(struct ahd_softc *ahd)
2148 {
2149         struct  ahd_devinfo devinfo;
2150         struct  scb *scb;
2151         u_int   lastphase;
2152         u_int   saved_scsiid;
2153         u_int   saved_lun;
2154         u_int   target;
2155         u_int   initiator_role_id;
2156         u_int   scbid;
2157         u_int   ppr_busfree;
2158         int     printerror;
2159
2160         /*
2161          * Look at what phase we were last in.  If its message out,
2162          * chances are pretty good that the busfree was in response
2163          * to one of our abort requests.
2164          */
2165         lastphase = ahd_inb(ahd, LASTPHASE);
2166         saved_scsiid = ahd_inb(ahd, SAVED_SCSIID);
2167         saved_lun = ahd_inb(ahd, SAVED_LUN);
2168         target = SCSIID_TARGET(ahd, saved_scsiid);
2169         initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
2170         ahd_compile_devinfo(&devinfo, initiator_role_id,
2171                             target, saved_lun, 'A', ROLE_INITIATOR);
2172         printerror = 1;
2173
2174         scbid = ahd_get_scbptr(ahd);
2175         scb = ahd_lookup_scb(ahd, scbid);
2176         if (scb != NULL
2177          && (ahd_inb(ahd, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
2178                 scb = NULL;
2179
2180         ppr_busfree = (ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0;
2181         if (lastphase == P_MESGOUT) {
2182                 u_int tag;
2183
2184                 tag = SCB_LIST_NULL;
2185                 if (ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT_TAG, TRUE)
2186                  || ahd_sent_msg(ahd, AHDMSG_1B, MSG_ABORT, TRUE)) {
2187                         int found;
2188                         int sent_msg;
2189
2190                         if (scb == NULL) {
2191                                 ahd_print_devinfo(ahd, &devinfo);
2192                                 printf("Abort for unidentified "
2193                                        "connection completed.\n");
2194                                 /* restart the sequencer. */
2195                                 return (1);
2196                         }
2197                         sent_msg = ahd->msgout_buf[ahd->msgout_index - 1];
2198                         ahd_print_path(ahd, scb);
2199                         printf("SCB %d - Abort%s Completed.\n",
2200                                SCB_GET_TAG(scb),
2201                                sent_msg == MSG_ABORT_TAG ? "" : " Tag");
2202
2203                         if (sent_msg == MSG_ABORT_TAG)
2204                                 tag = SCB_GET_TAG(scb);
2205
2206                         if ((scb->flags & SCB_CMDPHASE_ABORT) != 0) {
2207                                 /*
2208                                  * This abort is in response to an
2209                                  * unexpected switch to command phase
2210                                  * for a packetized connection.  Since
2211                                  * the identify message was never sent,
2212                                  * "saved lun" is 0.  We really want to
2213                                  * abort only the SCB that encountered
2214                                  * this error, which could have a different
2215                                  * lun.  The SCB will be retried so the OS
2216                                  * will see the UA after renegotiating to
2217                                  * packetized.
2218                                  */
2219                                 tag = SCB_GET_TAG(scb);
2220                                 saved_lun = scb->hscb->lun;
2221                         }
2222                         found = ahd_abort_scbs(ahd, target, 'A', saved_lun,
2223                                                tag, ROLE_INITIATOR,
2224                                                CAM_REQ_ABORTED);
2225                         printf("found == 0x%x\n", found);
2226                         printerror = 0;
2227                 } else if (ahd_sent_msg(ahd, AHDMSG_1B,
2228                                         MSG_BUS_DEV_RESET, TRUE)) {
2229 #ifdef __FreeBSD__
2230                         /*
2231                          * Don't mark the user's request for this BDR
2232                          * as completing with CAM_BDR_SENT.  CAM3
2233                          * specifies CAM_REQ_CMP.
2234                          */
2235                         if (scb != NULL
2236                          && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
2237                          && ahd_match_scb(ahd, scb, target, 'A',
2238                                           CAM_LUN_WILDCARD, SCB_LIST_NULL,
2239                                           ROLE_INITIATOR))
2240                                 ahd_set_transaction_status(scb, CAM_REQ_CMP);
2241 #endif
2242                         ahd_handle_devreset(ahd, &devinfo, CAM_LUN_WILDCARD,
2243                                             CAM_BDR_SENT, "Bus Device Reset",
2244                                             /*verbose_level*/0);
2245                         printerror = 0;
2246                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_PPR, FALSE)
2247                         && ppr_busfree == 0) {
2248                         struct ahd_initiator_tinfo *tinfo;
2249                         struct ahd_tmode_tstate *tstate;
2250
2251                         /*
2252                          * PPR Rejected.
2253                          *
2254                          * If the previous negotiation was packetized,
2255                          * this could be because the device has been
2256                          * reset without our knowledge.  Force our
2257                          * current negotiation to async and retry the
2258                          * negotiation.  Otherwise retry the command
2259                          * with non-ppr negotiation.
2260                          */
2261 #ifdef AHD_DEBUG
2262                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2263                                 printf("PPR negotiation rejected busfree.\n");
2264 #endif
2265                         tinfo = ahd_fetch_transinfo(ahd, devinfo.channel,
2266                                                     devinfo.our_scsiid,
2267                                                     devinfo.target, &tstate);
2268                         if ((tinfo->curr.ppr_options & MSG_EXT_PPR_IU_REQ)!=0) {
2269                                 ahd_set_width(ahd, &devinfo,
2270                                               MSG_EXT_WDTR_BUS_8_BIT,
2271                                               AHD_TRANS_CUR,
2272                                               /*paused*/TRUE);
2273                                 ahd_set_syncrate(ahd, &devinfo,
2274                                                 /*period*/0, /*offset*/0,
2275                                                 /*ppr_options*/0,
2276                                                 AHD_TRANS_CUR,
2277                                                 /*paused*/TRUE);
2278                                 /*
2279                                  * The expect PPR busfree handler below
2280                                  * will effect the retry and necessary
2281                                  * abort.
2282                                  */
2283                         } else {
2284                                 tinfo->curr.transport_version = 2;
2285                                 tinfo->goal.transport_version = 2;
2286                                 tinfo->goal.ppr_options = 0;
2287                                 /*
2288                                  * Remove any SCBs in the waiting for selection
2289                                  * queue that may also be for this target so
2290                                  * that command ordering is preserved.
2291                                  */
2292                                 ahd_freeze_devq(ahd, scb);
2293                                 ahd_qinfifo_requeue_tail(ahd, scb);
2294                                 printerror = 0;
2295                         }
2296                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_WDTR, FALSE)
2297                         && ppr_busfree == 0) {
2298                         /*
2299                          * Negotiation Rejected.  Go-narrow and
2300                          * retry command.
2301                          */
2302 #ifdef AHD_DEBUG
2303                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2304                                 printf("WDTR negotiation rejected busfree.\n");
2305 #endif
2306                         ahd_set_width(ahd, &devinfo,
2307                                       MSG_EXT_WDTR_BUS_8_BIT,
2308                                       AHD_TRANS_CUR|AHD_TRANS_GOAL,
2309                                       /*paused*/TRUE);
2310                         /*
2311                          * Remove any SCBs in the waiting for selection
2312                          * queue that may also be for this target so that
2313                          * command ordering is preserved.
2314                          */
2315                         ahd_freeze_devq(ahd, scb);
2316                         ahd_qinfifo_requeue_tail(ahd, scb);
2317                         printerror = 0;
2318                 } else if (ahd_sent_msg(ahd, AHDMSG_EXT, MSG_EXT_SDTR, FALSE)
2319                         && ppr_busfree == 0) {
2320                         /*
2321                          * Negotiation Rejected.  Go-async and
2322                          * retry command.
2323                          */
2324 #ifdef AHD_DEBUG
2325                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2326                                 printf("SDTR negotiation rejected busfree.\n");
2327 #endif
2328                         ahd_set_syncrate(ahd, &devinfo,
2329                                         /*period*/0, /*offset*/0,
2330                                         /*ppr_options*/0,
2331                                         AHD_TRANS_CUR|AHD_TRANS_GOAL,
2332                                         /*paused*/TRUE);
2333                         /*
2334                          * Remove any SCBs in the waiting for selection
2335                          * queue that may also be for this target so that
2336                          * command ordering is preserved.
2337                          */
2338                         ahd_freeze_devq(ahd, scb);
2339                         ahd_qinfifo_requeue_tail(ahd, scb);
2340                         printerror = 0;
2341                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_IDE_BUSFREE) != 0
2342                         && ahd_sent_msg(ahd, AHDMSG_1B,
2343                                          MSG_INITIATOR_DET_ERR, TRUE)) {
2344
2345 #ifdef AHD_DEBUG
2346                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2347                                 printf("Expected IDE Busfree\n");
2348 #endif
2349                         printerror = 0;
2350                 } else if ((ahd->msg_flags & MSG_FLAG_EXPECT_QASREJ_BUSFREE)
2351                         && ahd_sent_msg(ahd, AHDMSG_1B,
2352                                         MSG_MESSAGE_REJECT, TRUE)) {
2353
2354 #ifdef AHD_DEBUG
2355                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2356                                 printf("Expected QAS Reject Busfree\n");
2357 #endif
2358                         printerror = 0;
2359                 }
2360         }
2361
2362         /*
2363          * The busfree required flag is honored at the end of
2364          * the message phases.  We check it last in case we
2365          * had to send some other message that caused a busfree.
2366          */
2367         if (printerror != 0
2368          && (lastphase == P_MESGIN || lastphase == P_MESGOUT)
2369          && ((ahd->msg_flags & MSG_FLAG_EXPECT_PPR_BUSFREE) != 0)) {
2370
2371                 ahd_freeze_devq(ahd, scb);
2372                 ahd_set_transaction_status(scb, CAM_REQUEUE_REQ);
2373                 ahd_freeze_scb(scb);
2374                 if ((ahd->msg_flags & MSG_FLAG_IU_REQ_CHANGED) != 0) {
2375                         ahd_abort_scbs(ahd, SCB_GET_TARGET(ahd, scb),
2376                                        SCB_GET_CHANNEL(ahd, scb),
2377                                        SCB_GET_LUN(scb), SCB_LIST_NULL,
2378                                        ROLE_INITIATOR, CAM_REQ_ABORTED);
2379                 } else {
2380 #ifdef AHD_DEBUG
2381                         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0)
2382                                 printf("PPR Negotiation Busfree.\n");
2383 #endif
2384                         ahd_done(ahd, scb);
2385                 }
2386                 printerror = 0;
2387         }
2388         if (printerror != 0) {
2389                 int aborted;
2390
2391                 aborted = 0;
2392                 if (scb != NULL) {
2393                         u_int tag;
2394
2395                         if ((scb->hscb->control & TAG_ENB) != 0)
2396                                 tag = SCB_GET_TAG(scb);
2397                         else
2398                                 tag = SCB_LIST_NULL;
2399                         ahd_print_path(ahd, scb);
2400                         aborted = ahd_abort_scbs(ahd, target, 'A',
2401                                        SCB_GET_LUN(scb), tag,
2402                                        ROLE_INITIATOR,
2403                                        CAM_UNEXP_BUSFREE);
2404                 } else {
2405                         /*
2406                          * We had not fully identified this connection,
2407                          * so we cannot abort anything.
2408                          */
2409                         printf("%s: ", ahd_name(ahd));
2410                 }
2411                 printf("Unexpected busfree %s, %d SCBs aborted, "
2412                        "PRGMCNT == 0x%x\n",
2413                        ahd_lookup_phase_entry(lastphase)->phasemsg,
2414                        aborted,
2415                        ahd_inw(ahd, PRGMCNT));
2416                 ahd_dump_card_state(ahd);
2417                 if (lastphase != P_BUSFREE)
2418                         ahd_force_renegotiation(ahd, &devinfo);
2419         }
2420         /* Always restart the sequencer. */
2421         return (1);
2422 }
2423
2424 static void
2425 ahd_handle_proto_violation(struct ahd_softc *ahd)
2426 {
2427         struct  ahd_devinfo devinfo;
2428         struct  scb *scb;
2429         u_int   scbid;
2430         u_int   seq_flags;
2431         u_int   curphase;
2432         u_int   lastphase;
2433         int     found;
2434
2435         ahd_fetch_devinfo(ahd, &devinfo);
2436         scbid = ahd_get_scbptr(ahd);
2437         scb = ahd_lookup_scb(ahd, scbid);
2438         seq_flags = ahd_inb(ahd, SEQ_FLAGS);
2439         curphase = ahd_inb(ahd, SCSISIGI) & PHASE_MASK;
2440         lastphase = ahd_inb(ahd, LASTPHASE);
2441         if ((seq_flags & NOT_IDENTIFIED) != 0) {
2442
2443                 /*
2444                  * The reconnecting target either did not send an
2445                  * identify message, or did, but we didn't find an SCB
2446                  * to match.
2447                  */
2448                 ahd_print_devinfo(ahd, &devinfo);
2449                 printf("Target did not send an IDENTIFY message. "
2450                        "LASTPHASE = 0x%x.\n", lastphase);
2451                 scb = NULL;
2452         } else if (scb == NULL) {
2453                 /*
2454                  * We don't seem to have an SCB active for this
2455                  * transaction.  Print an error and reset the bus.
2456                  */
2457                 ahd_print_devinfo(ahd, &devinfo);
2458                 printf("No SCB found during protocol violation\n");
2459                 goto proto_violation_reset;
2460         } else {
2461                 ahd_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
2462                 if ((seq_flags & NO_CDB_SENT) != 0) {
2463                         ahd_print_path(ahd, scb);
2464                         printf("No or incomplete CDB sent to device.\n");
2465                 } else if ((ahd_inb_scbram(ahd, SCB_CONTROL)
2466                           & STATUS_RCVD) == 0) {
2467                         /*
2468                          * The target never bothered to provide status to
2469                          * us prior to completing the command.  Since we don't
2470                          * know the disposition of this command, we must attempt
2471                          * to abort it.  Assert ATN and prepare to send an abort
2472                          * message.
2473                          */
2474                         ahd_print_path(ahd, scb);
2475                         printf("Completed command without status.\n");
2476                 } else {
2477                         ahd_print_path(ahd, scb);
2478                         printf("Unknown protocol violation.\n");
2479                         ahd_dump_card_state(ahd);
2480                 }
2481         }
2482         if ((lastphase & ~P_DATAIN_DT) == 0
2483          || lastphase == P_COMMAND) {
2484 proto_violation_reset:
2485                 /*
2486                  * Target either went directly to data
2487                  * phase or didn't respond to our ATN.
2488                  * The only safe thing to do is to blow
2489                  * it away with a bus reset.
2490                  */
2491                 found = ahd_reset_channel(ahd, 'A', TRUE);
2492                 printf("%s: Issued Channel %c Bus Reset. "
2493                        "%d SCBs aborted\n", ahd_name(ahd), 'A', found);
2494         } else {
2495                 /*
2496                  * Leave the selection hardware off in case
2497                  * this abort attempt will affect yet to
2498                  * be sent commands.
2499                  */
2500                 ahd_outb(ahd, SCSISEQ0,
2501                          ahd_inb(ahd, SCSISEQ0) & ~ENSELO);
2502                 ahd_assert_atn(ahd);
2503                 ahd_outb(ahd, MSG_OUT, HOST_MSG);
2504                 if (scb == NULL) {
2505                         ahd_print_devinfo(ahd, &devinfo);
2506                         ahd->msgout_buf[0] = MSG_ABORT_TASK;
2507                         ahd->msgout_len = 1;
2508                         ahd->msgout_index = 0;
2509                         ahd->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2510                 } else {
2511                         ahd_print_path(ahd, scb);
2512                         scb->flags |= SCB_ABORT;
2513                 }
2514                 printf("Protocol violation %s.  Attempting to abort.\n",
2515                        ahd_lookup_phase_entry(curphase)->phasemsg);
2516         }
2517 }
2518
2519 /*
2520  * Force renegotiation to occur the next time we initiate
2521  * a command to the current device.
2522  */
2523 static void
2524 ahd_force_renegotiation(struct ahd_softc *ahd, struct ahd_devinfo *devinfo)
2525 {
2526         struct  ahd_initiator_tinfo *targ_info;
2527         struct  ahd_tmode_tstate *tstate;
2528
2529 #ifdef AHD_DEBUG
2530         if ((ahd_debug & AHD_SHOW_MESSAGES) != 0) {
2531                 ahd_print_devinfo(ahd, devinfo);
2532                 printf("Forcing renegotiation\n");
2533         }
2534 #endif
2535         targ_info = ahd_fetch_transinfo(ahd,
2536                                         devinfo->channel,
2537                                         devinfo->our_scsiid,
2538                                         devinfo->target,
2539                                         &tstate);
2540         ahd_update_neg_request(ahd, devinfo, tstate,
2541                                targ_info, AHD_NEG_IF_NON_ASYNC);
2542 }
2543
2544 #define AHD_MAX_STEPS 2000
2545 void
2546 ahd_clear_critical_section(struct ahd_softc *ahd)
2547 {
2548         ahd_mode_state  saved_modes;
2549         int             stepping;
2550         int             steps;
2551         int             first_instr;
2552         u_int           simode0;
2553         u_int           simode1;
2554         u_int           simode3;
2555         u_int           lqimode0;
2556         u_int           lqimode1;
2557         u_int           lqomode0;
2558         u_int           lqomode1;
2559
2560         if (ahd->num_critical_sections == 0)
2561                 return;
2562
2563         stepping = FALSE;
2564         steps = 0;
2565         first_instr = 0;
2566         simode0 = 0;
2567         simode1 = 0;
2568         simode3 = 0;
2569         lqimode0 = 0;
2570         lqimode1 = 0;
2571         lqomode0 = 0;
2572         lqomode1 = 0;
2573         saved_modes = ahd_save_modes(ahd);
2574         for (;;) {
2575                 struct  cs *cs;
2576                 u_int   seqaddr;
2577                 u_int   i;
2578
2579                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2580                 seqaddr = ahd_inw(ahd, CURADDR);
2581
2582                 cs = ahd->critical_sections;
2583                 for (i = 0; i < ahd->num_critical_sections; i++, cs++) {
2584                         
2585                         if (cs->begin < seqaddr && cs->end >= seqaddr)
2586                                 break;
2587                 }
2588
2589                 if (i == ahd->num_critical_sections)
2590                         break;
2591
2592                 if (steps > AHD_MAX_STEPS) {
2593                         printf("%s: Infinite loop in critical section\n"
2594                                "%s: First Instruction 0x%x now 0x%x\n",
2595                                ahd_name(ahd), ahd_name(ahd), first_instr,
2596                                seqaddr);
2597                         ahd_dump_card_state(ahd);
2598                         panic("critical section loop");
2599                 }
2600
2601                 steps++;
2602 #ifdef AHD_DEBUG
2603                 if ((ahd_debug & AHD_SHOW_MISC) != 0)
2604                         printf("%s: Single stepping at 0x%x\n", ahd_name(ahd),
2605                                seqaddr);
2606 #endif
2607                 if (stepping == FALSE) {
2608
2609                         first_instr = seqaddr;
2610                         ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2611                         simode0 = ahd_inb(ahd, SIMODE0);
2612                         simode3 = ahd_inb(ahd, SIMODE3);
2613                         lqimode0 = ahd_inb(ahd, LQIMODE0);
2614                         lqimode1 = ahd_inb(ahd, LQIMODE1);
2615                         lqomode0 = ahd_inb(ahd, LQOMODE0);
2616                         lqomode1 = ahd_inb(ahd, LQOMODE1);
2617                         ahd_outb(ahd, SIMODE0, 0);
2618                         ahd_outb(ahd, SIMODE3, 0);
2619                         ahd_outb(ahd, LQIMODE0, 0);
2620                         ahd_outb(ahd, LQIMODE1, 0);
2621                         ahd_outb(ahd, LQOMODE0, 0);
2622                         ahd_outb(ahd, LQOMODE1, 0);
2623                         ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2624                         simode1 = ahd_inb(ahd, SIMODE1);
2625                         /*
2626                          * We don't clear ENBUSFREE.  Unfortunately
2627                          * we cannot re-enable busfree detection within
2628                          * the current connection, so we must leave it
2629                          * on while single stepping.
2630                          */
2631                         ahd_outb(ahd, SIMODE1, simode1 & ENBUSFREE);
2632                         ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) | STEP);
2633                         stepping = TRUE;
2634                 }
2635                 ahd_outb(ahd, CLRSINT1, CLRBUSFREE);
2636                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2637                 ahd_set_modes(ahd, ahd->saved_src_mode, ahd->saved_dst_mode);
2638                 ahd_outb(ahd, HCNTRL, ahd->unpause);
2639                 while (!ahd_is_paused(ahd))
2640                         ahd_delay(200);
2641                 ahd_update_modes(ahd);
2642         }
2643         if (stepping) {
2644                 ahd_set_modes(ahd, AHD_MODE_CFG, AHD_MODE_CFG);
2645                 ahd_outb(ahd, SIMODE0, simode0);
2646                 ahd_outb(ahd, SIMODE3, simode3);
2647                 ahd_outb(ahd, LQIMODE0, lqimode0);
2648                 ahd_outb(ahd, LQIMODE1, lqimode1);
2649                 ahd_outb(ahd, LQOMODE0, lqomode0);
2650                 ahd_outb(ahd, LQOMODE1, lqomode1);
2651                 ahd_set_modes(ahd, AHD_MODE_SCSI, AHD_MODE_SCSI);
2652                 ahd_outb(ahd, SEQCTL0, ahd_inb(ahd, SEQCTL0) & ~STEP);
2653                 ahd_outb(ahd, SIMODE1, simode1);
2654                 /*
2655                  * SCSIINT seems to glitch occassionally when
2656                  * the interrupt masks are restored.  Clear SCSIINT
2657                  * one more time so that only persistent errors
2658                  * are seen as a real interrupt.
2659                  */
2660                 ahd_outb(ahd, CLRINT, CLRSCSIINT);
2661         }
2662         ahd_restore_modes(ahd, saved_modes);
2663 }
2664
2665 /*
2666  * Clear any pending interrupt status.
2667  */
2668 void
2669 ahd_clear_intstat(struct ahd_softc *ahd)
2670 {
2671         AHD_ASSERT_MODES(ahd, ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK),
2672                          ~(AHD_MODE_UNKNOWN_MSK|AHD_MODE_CFG_MSK));
2673         /* Clear any interrupt conditions this may have caused */
2674         ahd_outb(ahd, CLRLQIINT0, CLRLQIATNQAS|CLRLQICRCT1|CLRLQICRCT2
2675                                  |CLRLQIBADLQT|CLRLQIATNLQ|CLRLQIATNCMD);
2676         ahd_outb(ahd, CLRLQIINT1, CLRLQIPHASE_LQ|CLRLQIPHASE_NLQ|CLRLIQABORT
2677                                  |CLRLQICRCI_LQ|CLRLQICRCI_NLQ|CLRLQIBADLQI
2678                                  |CLRLQIOVERI_LQ|CLRLQIOVERI_NLQ|CLRNONPACKREQ);
2679         ahd_outb(ahd, CLRLQOINT0, CLRLQOTARGSCBPERR|CLRLQOSTOPT2|CLRLQOATNLQ
2680                                  |CLRLQOATNPKT|CLRLQOTCRC);
2681         ahd_outb(ahd, CLRLQOINT1, CLRLQOINITSCBPERR|CLRLQOSTOPI2|CLRLQOBADQAS
2682                                  |CLRLQOBUSFREE|CLRLQOPHACHGINPKT);
2683         if ((ahd->bugs & AHD_CLRLQO_AUTOCLR_BUG) != 0) {
2684                 ahd_outb(ahd, CLRLQOINT0, 0);
2685                 ahd_outb(ahd, CLRLQOINT1, 0);
2686         }
2687         ahd_outb(ahd, CLRSINT3, CLRNTRAMPERR|CLROSRAMPERR);
2688         ahd_outb(ahd, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
2689                                 |CLRBUSFREE|CLRSCSIPERR|CLRREQINIT);
2690         ahd_outb(ahd, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO
2691                                 |CLRIOERR|CLROVERRUN);
2692         ahd_outb(ahd, CLRINT, CLRSCSIINT);
2693 }
2694
2695 /**************************** Debugging Routines ******************************/
2696 #ifdef AHD_DEBUG
2697 uint32_t ahd_debug = AHD_DEBUG_OPTS;
2698 #endif
2699 void
2700 ahd_print_scb(struct scb *scb)
2701 {
2702         struct hardware_scb *hscb;
2703         int i;
2704
2705         hscb = scb->hscb;
2706         printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
2707                (void *)scb,
2708                hscb->control,
2709                hscb->scsiid,
2710                hscb->lun,
2711                hscb->cdb_len);
2712         printf("Shared Data: ");
2713         for (i = 0; i < sizeof(hscb->shared_data.idata.cdb); i++)
2714                 printf("%#02x", hscb->shared_data.idata.cdb[i]);
2715         printf("        dataptr:%#x%x datacnt:%#x sgptr:%#x tag:%#x\n",
2716                (uint32_t)((ahd_le64toh(hscb->dataptr) >> 32) & 0xFFFFFFFF),
2717                (uint32_t)(ahd_le64toh(hscb->dataptr) & 0xFFFFFFFF),
2718                ahd_le32toh(hscb->datacnt),
2719                ahd_le32toh(hscb->sgptr),
2720                SCB_GET_TAG(scb));
2721         ahd_dump_sglist(scb);
2722 }
2723
2724 void
2725 ahd_dump_sglist(struct scb *scb)
2726 {
2727         int i;
2728
2729         if (scb->sg_count > 0) {
2730                 if ((scb->ahd_softc->flags & AHD_64BIT_ADDRESSING) != 0) {
2731                         struct ahd_dma64_seg *sg_list;
2732
2733                         sg_list = (struct ahd_dma64_seg*)scb->sg_list;
2734                         for (i = 0; i < scb->sg_count; i++) {
2735                                 uint64_t addr;
2736                                 uint32_t len;
2737
2738                                 addr = ahd_le64toh(sg_list[i].addr);
2739                                 len = ahd_le32toh(sg_list[i].len);
2740                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
2741                                        i,
2742                                        (uint32_t)((addr >> 32) & 0xFFFFFFFF),
2743                                        (uint32_t)(addr & 0xFFFFFFFF),
2744                                        sg_list[i].len & AHD_SG_LEN_MASK,
2745                                        (sg_list[i].len & AHD_DMA_LAST_SEG)
2746                                      ? " Last" : "");
2747                         }
2748                 } else {
2749                         struct ahd_dma_seg *sg_list;
2750
2751                         sg_list = (struct ahd_dma_seg*)scb->sg_list;
2752                         for (i = 0; i < scb->sg_count; i++) {
2753                                 uint32_t len;
2754
2755                                 len = ahd_le32toh(sg_list[i].len);
2756                                 printf("sg[%d] - Addr 0x%x%x : Length %d%s\n",
2757                                        i,
2758                                        (len & AHD_SG_HIGH_ADDR_MASK) >> 24,
2759                                        ahd_le32toh(sg_list[i].addr),
2760                                        len & AHD_SG_LEN_MASK,
2761                                        len & AHD_DMA_LAST_SEG ? " Last" : "");
2762                         }
2763                 }
2764         }
2765 }
2766
2767 /************************* Transfer Negotiation *******************************/
2768 /*
2769  * Allocate per target mode instance (ID we respond to as a target)
2770  * transfer negotiation data structures.
2771  */
2772 static struct ahd_tmode_tstate *
2773 ahd_alloc_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel)
2774 {
2775         struct ahd_tmode_tstate *master_tstate;
2776         struct ahd_tmode_tstate *tstate;
2777         int i;
2778
2779         master_tstate = ahd->enabled_targets[ahd->our_id];
2780         if (ahd->enabled_targets[scsi_id] != NULL
2781          && ahd->enabled_targets[scsi_id] != master_tstate)
2782                 panic("%s: ahd_alloc_tstate - Target already allocated",
2783                       ahd_name(ahd));
2784         tstate = malloc(sizeof(*tstate), M_DEVBUF, M_NOWAIT);
2785         if (tstate == NULL)
2786                 return (NULL);
2787
2788         /*
2789          * If we have allocated a master tstate, copy user settings from
2790          * the master tstate (taken from SRAM or the EEPROM) for this
2791          * channel, but reset our current and goal settings to async/narrow
2792          * until an initiator talks to us.
2793          */
2794         if (master_tstate != NULL) {
2795                 memcpy(tstate, master_tstate, sizeof(*tstate));
2796                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
2797                 for (i = 0; i < 16; i++) {
2798                         memset(&tstate->transinfo[i].curr, 0,
2799                               sizeof(tstate->transinfo[i].curr));
2800                         memset(&tstate->transinfo[i].goal, 0,
2801                               sizeof(tstate->transinfo[i].goal));
2802                 }
2803         } else
2804                 memset(tstate, 0, sizeof(*tstate));
2805         ahd->enabled_targets[scsi_id] = tstate;
2806         return (tstate);
2807 }
2808
2809 #ifdef AHD_TARGET_MODE
2810 /*
2811  * Free per target mode instance (ID we respond to as a target)
2812  * transfer negotiation data structures.
2813  */
2814 static void
2815 ahd_free_tstate(struct ahd_softc *ahd, u_int scsi_id, char channel, int force)
2816 {
2817         struct ahd_tmode_tstate *tstate;
2818
2819