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