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