Linux kernel & device driver programming

Cross-Referenced Linux and Device Driver Code

[ source navigation ] [ diff markup ] [ identifier search ] [ freetext search ] [ file search ]
Version: [ 2.6.11.8 ] [ 2.6.25 ] [ 2.6.25.8 ] [ 2.6.31.13 ] Architecture: [ i386 ]
  1 /*
  2  * Core routines and tables shareable across OS platforms.
  3  *
  4  * Copyright (c) 1994-2002 Justin T. Gibbs.
  5  * Copyright (c) 2000-2002 Adaptec Inc.
  6  * All rights reserved.
  7  *
  8  * Redistribution and use in source and binary forms, with or without
  9  * modification, are permitted provided that the following conditions
 10  * are met:
 11  * 1. Redistributions of source code must retain the above copyright
 12  *    notice, this list of conditions, and the following disclaimer,
 13  *    without modification.
 14  * 2. Redistributions in binary form must reproduce at minimum a disclaimer
 15  *    substantially similar to the "NO WARRANTY" disclaimer below
 16  *    ("Disclaimer") and any redistribution must be conditioned upon
 17  *    including a substantially similar Disclaimer requirement for further
 18  *    binary redistribution.
 19  * 3. Neither the names of the above-listed copyright holders nor the names
 20  *    of any contributors may be used to endorse or promote products derived
 21  *    from this software without specific prior written permission.
 22  *
 23  * Alternatively, this software may be distributed under the terms of the
 24  * GNU General Public License ("GPL") version 2 as published by the Free
 25  * Software Foundation.
 26  *
 27  * NO WARRANTY
 28  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 29  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 30  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR
 31  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 32  * HOLDERS OR CONTRIBUTORS BE LIABLE FOR SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 36  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
 37  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 38  * POSSIBILITY OF SUCH DAMAGES.
 39  *
 40  * $Id: //depot/aic7xxx/aic7xxx/aic7xxx.c#155 $
 41  */
 42 
 43 #ifdef __linux__
 44 #include "aic7xxx_osm.h"
 45 #include "aic7xxx_inline.h"
 46 #include "aicasm/aicasm_insformat.h"
 47 #else
 48 #include <dev/aic7xxx/aic7xxx_osm.h>
 49 #include <dev/aic7xxx/aic7xxx_inline.h>
 50 #include <dev/aic7xxx/aicasm/aicasm_insformat.h>
 51 #endif
 52 
 53 /***************************** Lookup Tables **********************************/
 54 static const char *const ahc_chip_names[] = {
 55         "NONE",
 56         "aic7770",
 57         "aic7850",
 58         "aic7855",
 59         "aic7859",
 60         "aic7860",
 61         "aic7870",
 62         "aic7880",
 63         "aic7895",
 64         "aic7895C",
 65         "aic7890/91",
 66         "aic7896/97",
 67         "aic7892",
 68         "aic7899"
 69 };
 70 static const u_int num_chip_names = ARRAY_SIZE(ahc_chip_names);
 71 
 72 /*
 73  * Hardware error codes.
 74  */
 75 struct ahc_hard_error_entry {
 76         uint8_t errno;
 77         const char *errmesg;
 78 };
 79 
 80 static const struct ahc_hard_error_entry ahc_hard_errors[] = {
 81         { ILLHADDR,     "Illegal Host Access" },
 82         { ILLSADDR,     "Illegal Sequencer Address referrenced" },
 83         { ILLOPCODE,    "Illegal Opcode in sequencer program" },
 84         { SQPARERR,     "Sequencer Parity Error" },
 85         { DPARERR,      "Data-path Parity Error" },
 86         { MPARERR,      "Scratch or SCB Memory Parity Error" },
 87         { PCIERRSTAT,   "PCI Error detected" },
 88         { CIOPARERR,    "CIOBUS Parity Error" },
 89 };
 90 static const u_int num_errors = ARRAY_SIZE(ahc_hard_errors);
 91 
 92 static const struct ahc_phase_table_entry ahc_phase_table[] =
 93 {
 94         { P_DATAOUT,    MSG_NOOP,               "in Data-out phase"     },
 95         { P_DATAIN,     MSG_INITIATOR_DET_ERR,  "in Data-in phase"      },
 96         { P_DATAOUT_DT, MSG_NOOP,               "in DT Data-out phase"  },
 97         { P_DATAIN_DT,  MSG_INITIATOR_DET_ERR,  "in DT Data-in phase"   },
 98         { P_COMMAND,    MSG_NOOP,               "in Command phase"      },
 99         { P_MESGOUT,    MSG_NOOP,               "in Message-out phase"  },
100         { P_STATUS,     MSG_INITIATOR_DET_ERR,  "in Status phase"       },
101         { P_MESGIN,     MSG_PARITY_ERROR,       "in Message-in phase"   },
102         { P_BUSFREE,    MSG_NOOP,               "while idle"            },
103         { 0,            MSG_NOOP,               "in unknown phase"      }
104 };
105 
106 /*
107  * In most cases we only wish to itterate over real phases, so
108  * exclude the last element from the count.
109  */
110 static const u_int num_phases = ARRAY_SIZE(ahc_phase_table) - 1;
111 
112 /*
113  * Valid SCSIRATE values.  (p. 3-17)
114  * Provides a mapping of tranfer periods in ns to the proper value to
115  * stick in the scsixfer reg.
116  */
117 static const struct ahc_syncrate ahc_syncrates[] =
118 {
119       /* ultra2    fast/ultra  period     rate */
120         { 0x42,      0x000,      9,      "80.0" },
121         { 0x03,      0x000,     10,      "40.0" },
122         { 0x04,      0x000,     11,      "33.0" },
123         { 0x05,      0x100,     12,      "20.0" },
124         { 0x06,      0x110,     15,      "16.0" },
125         { 0x07,      0x120,     18,      "13.4" },
126         { 0x08,      0x000,     25,      "10.0" },
127         { 0x19,      0x010,     31,      "8.0"  },
128         { 0x1a,      0x020,     37,      "6.67" },
129         { 0x1b,      0x030,     43,      "5.7"  },
130         { 0x1c,      0x040,     50,      "5.0"  },
131         { 0x00,      0x050,     56,      "4.4"  },
132         { 0x00,      0x060,     62,      "4.0"  },
133         { 0x00,      0x070,     68,      "3.6"  },
134         { 0x00,      0x000,      0,      NULL   }
135 };
136 
137 /* Our Sequencer Program */
138 #include "aic7xxx_seq.h"
139 
140 /**************************** Function Declarations ***************************/
141 static void             ahc_force_renegotiation(struct ahc_softc *ahc,
142                                                 struct ahc_devinfo *devinfo);
143 static struct ahc_tmode_tstate*
144                         ahc_alloc_tstate(struct ahc_softc *ahc,
145                                          u_int scsi_id, char channel);
146 #ifdef AHC_TARGET_MODE
147 static void             ahc_free_tstate(struct ahc_softc *ahc,
148                                         u_int scsi_id, char channel, int force);
149 #endif
150 static const struct ahc_syncrate*
151                         ahc_devlimited_syncrate(struct ahc_softc *ahc,
152                                                 struct ahc_initiator_tinfo *,
153                                                 u_int *period,
154                                                 u_int *ppr_options,
155                                                 role_t role);
156 static void             ahc_update_pending_scbs(struct ahc_softc *ahc);
157 static void             ahc_fetch_devinfo(struct ahc_softc *ahc,
158                                           struct ahc_devinfo *devinfo);
159 static void             ahc_scb_devinfo(struct ahc_softc *ahc,
160                                         struct ahc_devinfo *devinfo,
161                                         struct scb *scb);
162 static void             ahc_assert_atn(struct ahc_softc *ahc);
163 static void             ahc_setup_initiator_msgout(struct ahc_softc *ahc,
164                                                    struct ahc_devinfo *devinfo,
165                                                    struct scb *scb);
166 static void             ahc_build_transfer_msg(struct ahc_softc *ahc,
167                                                struct ahc_devinfo *devinfo);
168 static void             ahc_construct_sdtr(struct ahc_softc *ahc,
169                                            struct ahc_devinfo *devinfo,
170                                            u_int period, u_int offset);
171 static void             ahc_construct_wdtr(struct ahc_softc *ahc,
172                                            struct ahc_devinfo *devinfo,
173                                            u_int bus_width);
174 static void             ahc_construct_ppr(struct ahc_softc *ahc,
175                                           struct ahc_devinfo *devinfo,
176                                           u_int period, u_int offset,
177                                           u_int bus_width, u_int ppr_options);
178 static void             ahc_clear_msg_state(struct ahc_softc *ahc);
179 static void             ahc_handle_proto_violation(struct ahc_softc *ahc);
180 static void             ahc_handle_message_phase(struct ahc_softc *ahc);
181 typedef enum {
182         AHCMSG_1B,
183         AHCMSG_2B,
184         AHCMSG_EXT
185 } ahc_msgtype;
186 static int              ahc_sent_msg(struct ahc_softc *ahc, ahc_msgtype type,
187                                      u_int msgval, int full);
188 static int              ahc_parse_msg(struct ahc_softc *ahc,
189                                       struct ahc_devinfo *devinfo);
190 static int              ahc_handle_msg_reject(struct ahc_softc *ahc,
191                                               struct ahc_devinfo *devinfo);
192 static void             ahc_handle_ign_wide_residue(struct ahc_softc *ahc,
193                                                 struct ahc_devinfo *devinfo);
194 static void             ahc_reinitialize_dataptrs(struct ahc_softc *ahc);
195 static void             ahc_handle_devreset(struct ahc_softc *ahc,
196                                             struct ahc_devinfo *devinfo,
197                                             cam_status status, char *message,
198                                             int verbose_level);
199 #ifdef AHC_TARGET_MODE
200 static void             ahc_setup_target_msgin(struct ahc_softc *ahc,
201                                                struct ahc_devinfo *devinfo,
202                                                struct scb *scb);
203 #endif
204 
205 static bus_dmamap_callback_t    ahc_dmamap_cb; 
206 static void             ahc_build_free_scb_list(struct ahc_softc *ahc);
207 static int              ahc_init_scbdata(struct ahc_softc *ahc);
208 static void             ahc_fini_scbdata(struct ahc_softc *ahc);
209 static void             ahc_qinfifo_requeue(struct ahc_softc *ahc,
210                                             struct scb *prev_scb,
211                                             struct scb *scb);
212 static int              ahc_qinfifo_count(struct ahc_softc *ahc);
213 static u_int            ahc_rem_scb_from_disc_list(struct ahc_softc *ahc,
214                                                    u_int prev, u_int scbptr);
215 static void             ahc_add_curscb_to_free_list(struct ahc_softc *ahc);
216 static u_int            ahc_rem_wscb(struct ahc_softc *ahc,
217                                      u_int scbpos, u_int prev);
218 static void             ahc_reset_current_bus(struct ahc_softc *ahc);
219 #ifdef AHC_DUMP_SEQ
220 static void             ahc_dumpseq(struct ahc_softc *ahc);
221 #endif
222 static int              ahc_loadseq(struct ahc_softc *ahc);
223 static int              ahc_check_patch(struct ahc_softc *ahc,
224                                         const struct patch **start_patch,
225                                         u_int start_instr, u_int *skip_addr);
226 static void             ahc_download_instr(struct ahc_softc *ahc,
227                                            u_int instrptr, uint8_t *dconsts);
228 #ifdef AHC_TARGET_MODE
229 static void             ahc_queue_lstate_event(struct ahc_softc *ahc,
230                                                struct ahc_tmode_lstate *lstate,
231                                                u_int initiator_id,
232                                                u_int event_type,
233                                                u_int event_arg);
234 static void             ahc_update_scsiid(struct ahc_softc *ahc,
235                                           u_int targid_mask);
236 static int              ahc_handle_target_cmd(struct ahc_softc *ahc,
237                                               struct target_cmd *cmd);
238 #endif
239 
240 static u_int            ahc_index_busy_tcl(struct ahc_softc *ahc, u_int tcl);
241 static void             ahc_unbusy_tcl(struct ahc_softc *ahc, u_int tcl);
242 static void             ahc_busy_tcl(struct ahc_softc *ahc,
243                                      u_int tcl, u_int busyid);
244 
245 /************************** SCB and SCB queue management **********************/
246 static void             ahc_run_untagged_queues(struct ahc_softc *ahc);
247 static void             ahc_run_untagged_queue(struct ahc_softc *ahc,
248                                                struct scb_tailq *queue);
249 
250 /****************************** Initialization ********************************/
251 static void              ahc_alloc_scbs(struct ahc_softc *ahc);
252 static void              ahc_shutdown(void *arg);
253 
254 /*************************** Interrupt Services *******************************/
255 static void             ahc_clear_intstat(struct ahc_softc *ahc);
256 static void             ahc_run_qoutfifo(struct ahc_softc *ahc);
257 #ifdef AHC_TARGET_MODE
258 static void             ahc_run_tqinfifo(struct ahc_softc *ahc, int paused);
259 #endif
260 static void             ahc_handle_brkadrint(struct ahc_softc *ahc);
261 static void             ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat);
262 static void             ahc_handle_scsiint(struct ahc_softc *ahc,
263                                            u_int intstat);
264 static void             ahc_clear_critical_section(struct ahc_softc *ahc);
265 
266 /***************************** Error Recovery *********************************/
267 static void             ahc_freeze_devq(struct ahc_softc *ahc, struct scb *scb);
268 static int              ahc_abort_scbs(struct ahc_softc *ahc, int target,
269                                        char channel, int lun, u_int tag,
270                                        role_t role, uint32_t status);
271 static void             ahc_calc_residual(struct ahc_softc *ahc,
272                                           struct scb *scb);
273 
274 /*********************** Untagged Transaction Routines ************************/
275 static inline void      ahc_freeze_untagged_queues(struct ahc_softc *ahc);
276 static inline void      ahc_release_untagged_queues(struct ahc_softc *ahc);
277 
278 /*
279  * Block our completion routine from starting the next untagged
280  * transaction for this target or target lun.
281  */
282 static inline void
283 ahc_freeze_untagged_queues(struct ahc_softc *ahc)
284 {
285         if ((ahc->flags & AHC_SCB_BTT) == 0)
286                 ahc->untagged_queue_lock++;
287 }
288 
289 /*
290  * Allow the next untagged transaction for this target or target lun
291  * to be executed.  We use a counting semaphore to allow the lock
292  * to be acquired recursively.  Once the count drops to zero, the
293  * transaction queues will be run.
294  */
295 static inline void
296 ahc_release_untagged_queues(struct ahc_softc *ahc)
297 {
298         if ((ahc->flags & AHC_SCB_BTT) == 0) {
299                 ahc->untagged_queue_lock--;
300                 if (ahc->untagged_queue_lock == 0)
301                         ahc_run_untagged_queues(ahc);
302         }
303 }
304 
305 /************************* Sequencer Execution Control ************************/
306 /*
307  * Work around any chip bugs related to halting sequencer execution.
308  * On Ultra2 controllers, we must clear the CIOBUS stretch signal by
309  * reading a register that will set this signal and deassert it.
310  * Without this workaround, if the chip is paused, by an interrupt or
311  * manual pause while accessing scb ram, accesses to certain registers
312  * will hang the system (infinite pci retries).
313  */
314 static void
315 ahc_pause_bug_fix(struct ahc_softc *ahc)
316 {
317         if ((ahc->features & AHC_ULTRA2) != 0)
318                 (void)ahc_inb(ahc, CCSCBCTL);
319 }
320 
321 /*
322  * Determine whether the sequencer has halted code execution.
323  * Returns non-zero status if the sequencer is stopped.
324  */
325 int
326 ahc_is_paused(struct ahc_softc *ahc)
327 {
328         return ((ahc_inb(ahc, HCNTRL) & PAUSE) != 0);
329 }
330 
331 /*
332  * Request that the sequencer stop and wait, indefinitely, for it
333  * to stop.  The sequencer will only acknowledge that it is paused
334  * once it has reached an instruction boundary and PAUSEDIS is
335  * cleared in the SEQCTL register.  The sequencer may use PAUSEDIS
336  * for critical sections.
337  */
338 void
339 ahc_pause(struct ahc_softc *ahc)
340 {
341         ahc_outb(ahc, HCNTRL, ahc->pause);
342 
343         /*
344          * Since the sequencer can disable pausing in a critical section, we
345          * must loop until it actually stops.
346          */
347         while (ahc_is_paused(ahc) == 0)
348                 ;
349 
350         ahc_pause_bug_fix(ahc);
351 }
352 
353 /*
354  * Allow the sequencer to continue program execution.
355  * We check here to ensure that no additional interrupt
356  * sources that would cause the sequencer to halt have been
357  * asserted.  If, for example, a SCSI bus reset is detected
358  * while we are fielding a different, pausing, interrupt type,
359  * we don't want to release the sequencer before going back
360  * into our interrupt handler and dealing with this new
361  * condition.
362  */
363 void
364 ahc_unpause(struct ahc_softc *ahc)
365 {
366         if ((ahc_inb(ahc, INTSTAT) & (SCSIINT | SEQINT | BRKADRINT)) == 0)
367                 ahc_outb(ahc, HCNTRL, ahc->unpause);
368 }
369 
370 /************************** Memory mapping routines ***************************/
371 static struct ahc_dma_seg *
372 ahc_sg_bus_to_virt(struct scb *scb, uint32_t sg_busaddr)
373 {
374         int sg_index;
375 
376         sg_index = (sg_busaddr - scb->sg_list_phys)/sizeof(struct ahc_dma_seg);
377         /* sg_list_phys points to entry 1, not 0 */
378         sg_index++;
379 
380         return (&scb->sg_list[sg_index]);
381 }
382 
383 static uint32_t
384 ahc_sg_virt_to_bus(struct scb *scb, struct ahc_dma_seg *sg)
385 {
386         int sg_index;
387 
388         /* sg_list_phys points to entry 1, not 0 */
389         sg_index = sg - &scb->sg_list[1];
390 
391         return (scb->sg_list_phys + (sg_index * sizeof(*scb->sg_list)));
392 }
393 
394 static uint32_t
395 ahc_hscb_busaddr(struct ahc_softc *ahc, u_int index)
396 {
397         return (ahc->scb_data->hscb_busaddr
398                 + (sizeof(struct hardware_scb) * index));
399 }
400 
401 static void
402 ahc_sync_scb(struct ahc_softc *ahc, struct scb *scb, int op)
403 {
404         ahc_dmamap_sync(ahc, ahc->scb_data->hscb_dmat,
405                         ahc->scb_data->hscb_dmamap,
406                         /*offset*/(scb->hscb - ahc->hscbs) * sizeof(*scb->hscb),
407                         /*len*/sizeof(*scb->hscb), op);
408 }
409 
410 void
411 ahc_sync_sglist(struct ahc_softc *ahc, struct scb *scb, int op)
412 {
413         if (scb->sg_count == 0)
414                 return;
415 
416         ahc_dmamap_sync(ahc, ahc->scb_data->sg_dmat, scb->sg_map->sg_dmamap,
417                         /*offset*/(scb->sg_list - scb->sg_map->sg_vaddr)
418                                 * sizeof(struct ahc_dma_seg),
419                         /*len*/sizeof(struct ahc_dma_seg) * scb->sg_count, op);
420 }
421 
422 #ifdef AHC_TARGET_MODE
423 static uint32_t
424 ahc_targetcmd_offset(struct ahc_softc *ahc, u_int index)
425 {
426         return (((uint8_t *)&ahc->targetcmds[index]) - ahc->qoutfifo);
427 }
428 #endif
429 
430 /*********************** Miscelaneous Support Functions ***********************/
431 /*
432  * Determine whether the sequencer reported a residual
433  * for this SCB/transaction.
434  */
435 static void
436 ahc_update_residual(struct ahc_softc *ahc, struct scb *scb)
437 {
438         uint32_t sgptr;
439 
440         sgptr = ahc_le32toh(scb->hscb->sgptr);
441         if ((sgptr & SG_RESID_VALID) != 0)
442                 ahc_calc_residual(ahc, scb);
443 }
444 
445 /*
446  * Return pointers to the transfer negotiation information
447  * for the specified our_id/remote_id pair.
448  */
449 struct ahc_initiator_tinfo *
450 ahc_fetch_transinfo(struct ahc_softc *ahc, char channel, u_int our_id,
451                     u_int remote_id, struct ahc_tmode_tstate **tstate)
452 {
453         /*
454          * Transfer data structures are stored from the perspective
455          * of the target role.  Since the parameters for a connection
456          * in the initiator role to a given target are the same as
457          * when the roles are reversed, we pretend we are the target.
458          */
459         if (channel == 'B')
460                 our_id += 8;
461         *tstate = ahc->enabled_targets[our_id];
462         return (&(*tstate)->transinfo[remote_id]);
463 }
464 
465 uint16_t
466 ahc_inw(struct ahc_softc *ahc, u_int port)
467 {
468         uint16_t r = ahc_inb(ahc, port+1) << 8;
469         return r | ahc_inb(ahc, port);
470 }
471 
472 void
473 ahc_outw(struct ahc_softc *ahc, u_int port, u_int value)
474 {
475         ahc_outb(ahc, port, value & 0xFF);
476         ahc_outb(ahc, port+1, (value >> 8) & 0xFF);
477 }
478 
479 uint32_t
480 ahc_inl(struct ahc_softc *ahc, u_int port)
481 {
482         return ((ahc_inb(ahc, port))
483               | (ahc_inb(ahc, port+1) << 8)
484               | (ahc_inb(ahc, port+2) << 16)
485               | (ahc_inb(ahc, port+3) << 24));
486 }
487 
488 void
489 ahc_outl(struct ahc_softc *ahc, u_int port, uint32_t value)
490 {
491         ahc_outb(ahc, port, (value) & 0xFF);
492         ahc_outb(ahc, port+1, ((value) >> 8) & 0xFF);
493         ahc_outb(ahc, port+2, ((value) >> 16) & 0xFF);
494         ahc_outb(ahc, port+3, ((value) >> 24) & 0xFF);
495 }
496 
497 uint64_t
498 ahc_inq(struct ahc_softc *ahc, u_int port)
499 {
500         return ((ahc_inb(ahc, port))
501               | (ahc_inb(ahc, port+1) << 8)
502               | (ahc_inb(ahc, port+2) << 16)
503               | (ahc_inb(ahc, port+3) << 24)
504               | (((uint64_t)ahc_inb(ahc, port+4)) << 32)
505               | (((uint64_t)ahc_inb(ahc, port+5)) << 40)
506               | (((uint64_t)ahc_inb(ahc, port+6)) << 48)
507               | (((uint64_t)ahc_inb(ahc, port+7)) << 56));
508 }
509 
510 void
511 ahc_outq(struct ahc_softc *ahc, u_int port, uint64_t value)
512 {
513         ahc_outb(ahc, port, value & 0xFF);
514         ahc_outb(ahc, port+1, (value >> 8) & 0xFF);
515         ahc_outb(ahc, port+2, (value >> 16) & 0xFF);
516         ahc_outb(ahc, port+3, (value >> 24) & 0xFF);
517         ahc_outb(ahc, port+4, (value >> 32) & 0xFF);
518         ahc_outb(ahc, port+5, (value >> 40) & 0xFF);
519         ahc_outb(ahc, port+6, (value >> 48) & 0xFF);
520         ahc_outb(ahc, port+7, (value >> 56) & 0xFF);
521 }
522 
523 /*
524  * Get a free scb. If there are none, see if we can allocate a new SCB.
525  */
526 struct scb *
527 ahc_get_scb(struct ahc_softc *ahc)
528 {
529         struct scb *scb;
530 
531         if ((scb = SLIST_FIRST(&ahc->scb_data->free_scbs)) == NULL) {
532                 ahc_alloc_scbs(ahc);
533                 scb = SLIST_FIRST(&ahc->scb_data->free_scbs);
534                 if (scb == NULL)
535                         return (NULL);
536         }
537         SLIST_REMOVE_HEAD(&ahc->scb_data->free_scbs, links.sle);
538         return (scb);
539 }
540 
541 /*
542  * Return an SCB resource to the free list.
543  */
544 void
545 ahc_free_scb(struct ahc_softc *ahc, struct scb *scb)
546 {
547         struct hardware_scb *hscb;
548 
549         hscb = scb->hscb;
550         /* Clean up for the next user */
551         ahc->scb_data->scbindex[hscb->tag] = NULL;
552         scb->flags = SCB_FREE;
553         hscb->control = 0;
554 
555         SLIST_INSERT_HEAD(&ahc->scb_data->free_scbs, scb, links.sle);
556 
557         /* Notify the OSM that a resource is now available. */
558         ahc_platform_scb_free(ahc, scb);
559 }
560 
561 struct scb *
562 ahc_lookup_scb(struct ahc_softc *ahc, u_int tag)
563 {
564         struct scb* scb;
565 
566         scb = ahc->scb_data->scbindex[tag];
567         if (scb != NULL)
568                 ahc_sync_scb(ahc, scb,
569                              BUS_DMASYNC_POSTREAD|BUS_DMASYNC_POSTWRITE);
570         return (scb);
571 }
572 
573 static void
574 ahc_swap_with_next_hscb(struct ahc_softc *ahc, struct scb *scb)
575 {
576         struct hardware_scb *q_hscb;
577         u_int  saved_tag;
578 
579         /*
580          * Our queuing method is a bit tricky.  The card
581          * knows in advance which HSCB to download, and we
582          * can't disappoint it.  To achieve this, the next
583          * SCB to download is saved off in ahc->next_queued_scb.
584          * When we are called to queue "an arbitrary scb",
585          * we copy the contents of the incoming HSCB to the one
586          * the sequencer knows about, swap HSCB pointers and
587          * finally assign the SCB to the tag indexed location
588          * in the scb_array.  This makes sure that we can still
589          * locate the correct SCB by SCB_TAG.
590          */
591         q_hscb = ahc->next_queued_scb->hscb;
592         saved_tag = q_hscb->tag;
593         memcpy(q_hscb, scb->hscb, sizeof(*scb->hscb));
594         if ((scb->flags & SCB_CDB32_PTR) != 0) {
595                 q_hscb->shared_data.cdb_ptr =
596                     ahc_htole32(ahc_hscb_busaddr(ahc, q_hscb->tag)
597                               + offsetof(struct hardware_scb, cdb32));
598         }
599         q_hscb->tag = saved_tag;
600         q_hscb->next = scb->hscb->tag;
601 
602         /* Now swap HSCB pointers. */
603         ahc->next_queued_scb->hscb = scb->hscb;
604         scb->hscb = q_hscb;
605 
606         /* Now define the mapping from tag to SCB in the scbindex */
607         ahc->scb_data->scbindex[scb->hscb->tag] = scb;
608 }
609 
610 /*
611  * Tell the sequencer about a new transaction to execute.
612  */
613 void
614 ahc_queue_scb(struct ahc_softc *ahc, struct scb *scb)
615 {
616         ahc_swap_with_next_hscb(ahc, scb);
617 
618         if (scb->hscb->tag == SCB_LIST_NULL
619          || scb->hscb->next == SCB_LIST_NULL)
620                 panic("Attempt to queue invalid SCB tag %x:%x\n",
621                       scb->hscb->tag, scb->hscb->next);
622 
623         /*
624          * Setup data "oddness".
625          */
626         scb->hscb->lun &= LID;
627         if (ahc_get_transfer_length(scb) & 0x1)
628                 scb->hscb->lun |= SCB_XFERLEN_ODD;
629 
630         /*
631          * Keep a history of SCBs we've downloaded in the qinfifo.
632          */
633         ahc->qinfifo[ahc->qinfifonext++] = scb->hscb->tag;
634 
635         /*
636          * Make sure our data is consistent from the
637          * perspective of the adapter.
638          */
639         ahc_sync_scb(ahc, scb, BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
640 
641         /* Tell the adapter about the newly queued SCB */
642         if ((ahc->features & AHC_QUEUE_REGS) != 0) {
643                 ahc_outb(ahc, HNSCB_QOFF, ahc->qinfifonext);
644         } else {
645                 if ((ahc->features & AHC_AUTOPAUSE) == 0)
646                         ahc_pause(ahc);
647                 ahc_outb(ahc, KERNEL_QINPOS, ahc->qinfifonext);
648                 if ((ahc->features & AHC_AUTOPAUSE) == 0)
649                         ahc_unpause(ahc);
650         }
651 }
652 
653 struct scsi_sense_data *
654 ahc_get_sense_buf(struct ahc_softc *ahc, struct scb *scb)
655 {
656         int offset;
657 
658         offset = scb - ahc->scb_data->scbarray;
659         return (&ahc->scb_data->sense[offset]);
660 }
661 
662 static uint32_t
663 ahc_get_sense_bufaddr(struct ahc_softc *ahc, struct scb *scb)
664 {
665         int offset;
666 
667         offset = scb - ahc->scb_data->scbarray;
668         return (ahc->scb_data->sense_busaddr
669               + (offset * sizeof(struct scsi_sense_data)));
670 }
671 
672 /************************** Interrupt Processing ******************************/
673 static void
674 ahc_sync_qoutfifo(struct ahc_softc *ahc, int op)
675 {
676         ahc_dmamap_sync(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
677                         /*offset*/0, /*len*/256, op);
678 }
679 
680 static void
681 ahc_sync_tqinfifo(struct ahc_softc *ahc, int op)
682 {
683 #ifdef AHC_TARGET_MODE
684         if ((ahc->flags & AHC_TARGETROLE) != 0) {
685                 ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
686                                 ahc->shared_data_dmamap,
687                                 ahc_targetcmd_offset(ahc, 0),
688                                 sizeof(struct target_cmd) * AHC_TMODE_CMDS,
689                                 op);
690         }
691 #endif
692 }
693 
694 /*
695  * See if the firmware has posted any completed commands
696  * into our in-core command complete fifos.
697  */
698 #define AHC_RUN_QOUTFIFO 0x1
699 #define AHC_RUN_TQINFIFO 0x2
700 static u_int
701 ahc_check_cmdcmpltqueues(struct ahc_softc *ahc)
702 {
703         u_int retval;
704 
705         retval = 0;
706         ahc_dmamap_sync(ahc, ahc->shared_data_dmat, ahc->shared_data_dmamap,
707                         /*offset*/ahc->qoutfifonext, /*len*/1,
708                         BUS_DMASYNC_POSTREAD);
709         if (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL)
710                 retval |= AHC_RUN_QOUTFIFO;
711 #ifdef AHC_TARGET_MODE
712         if ((ahc->flags & AHC_TARGETROLE) != 0
713          && (ahc->flags & AHC_TQINFIFO_BLOCKED) == 0) {
714                 ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
715                                 ahc->shared_data_dmamap,
716                                 ahc_targetcmd_offset(ahc, ahc->tqinfifofnext),
717                                 /*len*/sizeof(struct target_cmd),
718                                 BUS_DMASYNC_POSTREAD);
719                 if (ahc->targetcmds[ahc->tqinfifonext].cmd_valid != 0)
720                         retval |= AHC_RUN_TQINFIFO;
721         }
722 #endif
723         return (retval);
724 }
725 
726 /*
727  * Catch an interrupt from the adapter
728  */
729 int
730 ahc_intr(struct ahc_softc *ahc)
731 {
732         u_int   intstat;
733 
734         if ((ahc->pause & INTEN) == 0) {
735                 /*
736                  * Our interrupt is not enabled on the chip
737                  * and may be disabled for re-entrancy reasons,
738                  * so just return.  This is likely just a shared
739                  * interrupt.
740                  */
741                 return (0);
742         }
743         /*
744          * Instead of directly reading the interrupt status register,
745          * infer the cause of the interrupt by checking our in-core
746          * completion queues.  This avoids a costly PCI bus read in
747          * most cases.
748          */
749         if ((ahc->flags & (AHC_ALL_INTERRUPTS|AHC_EDGE_INTERRUPT)) == 0
750          && (ahc_check_cmdcmpltqueues(ahc) != 0))
751                 intstat = CMDCMPLT;
752         else {
753                 intstat = ahc_inb(ahc, INTSTAT);
754         }
755 
756         if ((intstat & INT_PEND) == 0) {
757 #if AHC_PCI_CONFIG > 0
758                 if (ahc->unsolicited_ints > 500) {
759                         ahc->unsolicited_ints = 0;
760                         if ((ahc->chip & AHC_PCI) != 0
761                          && (ahc_inb(ahc, ERROR) & PCIERRSTAT) != 0)
762                                 ahc->bus_intr(ahc);
763                 }
764 #endif
765                 ahc->unsolicited_ints++;
766                 return (0);
767         }
768         ahc->unsolicited_ints = 0;
769 
770         if (intstat & CMDCMPLT) {
771                 ahc_outb(ahc, CLRINT, CLRCMDINT);
772 
773                 /*
774                  * Ensure that the chip sees that we've cleared
775                  * this interrupt before we walk the output fifo.
776                  * Otherwise, we may, due to posted bus writes,
777                  * clear the interrupt after we finish the scan,
778                  * and after the sequencer has added new entries
779                  * and asserted the interrupt again.
780                  */
781                 ahc_flush_device_writes(ahc);
782                 ahc_run_qoutfifo(ahc);
783 #ifdef AHC_TARGET_MODE
784                 if ((ahc->flags & AHC_TARGETROLE) != 0)
785                         ahc_run_tqinfifo(ahc, /*paused*/FALSE);
786 #endif
787         }
788 
789         /*
790          * Handle statuses that may invalidate our cached
791          * copy of INTSTAT separately.
792          */
793         if (intstat == 0xFF && (ahc->features & AHC_REMOVABLE) != 0) {
794                 /* Hot eject.  Do nothing */
795         } else if (intstat & BRKADRINT) {
796                 ahc_handle_brkadrint(ahc);
797         } else if ((intstat & (SEQINT|SCSIINT)) != 0) {
798 
799                 ahc_pause_bug_fix(ahc);
800 
801                 if ((intstat & SEQINT) != 0)
802                         ahc_handle_seqint(ahc, intstat);
803 
804                 if ((intstat & SCSIINT) != 0)
805                         ahc_handle_scsiint(ahc, intstat);
806         }
807         return (1);
808 }
809 
810 /************************* Sequencer Execution Control ************************/
811 /*
812  * Restart the sequencer program from address zero
813  */
814 static void
815 ahc_restart(struct ahc_softc *ahc)
816 {
817         uint8_t sblkctl;
818 
819         ahc_pause(ahc);
820 
821         /* No more pending messages. */
822         ahc_clear_msg_state(ahc);
823 
824         ahc_outb(ahc, SCSISIGO, 0);             /* De-assert BSY */
825         ahc_outb(ahc, MSG_OUT, MSG_NOOP);       /* No message to send */
826         ahc_outb(ahc, SXFRCTL1, ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
827         ahc_outb(ahc, LASTPHASE, P_BUSFREE);
828         ahc_outb(ahc, SAVED_SCSIID, 0xFF);
829         ahc_outb(ahc, SAVED_LUN, 0xFF);
830 
831         /*
832          * Ensure that the sequencer's idea of TQINPOS
833          * matches our own.  The sequencer increments TQINPOS
834          * only after it sees a DMA complete and a reset could
835          * occur before the increment leaving the kernel to believe
836          * the command arrived but the sequencer to not.
837          */
838         ahc_outb(ahc, TQINPOS, ahc->tqinfifonext);
839 
840         /* Always allow reselection */
841         ahc_outb(ahc, SCSISEQ,
842                  ahc_inb(ahc, SCSISEQ_TEMPLATE) & (ENSELI|ENRSELI|ENAUTOATNP));
843         if ((ahc->features & AHC_CMD_CHAN) != 0) {
844                 /* Ensure that no DMA operations are in progress */
845                 ahc_outb(ahc, CCSCBCNT, 0);
846                 ahc_outb(ahc, CCSGCTL, 0);
847                 ahc_outb(ahc, CCSCBCTL, 0);
848         }
849         /*
850          * If we were in the process of DMA'ing SCB data into
851          * an SCB, replace that SCB on the free list.  This prevents
852          * an SCB leak.
853          */
854         if ((ahc_inb(ahc, SEQ_FLAGS2) & SCB_DMA) != 0) {
855                 ahc_add_curscb_to_free_list(ahc);
856                 ahc_outb(ahc, SEQ_FLAGS2,
857                          ahc_inb(ahc, SEQ_FLAGS2) & ~SCB_DMA);
858         }
859 
860         /*
861          * Clear any pending sequencer interrupt.  It is no
862          * longer relevant since we're resetting the Program
863          * Counter.
864          */
865         ahc_outb(ahc, CLRINT, CLRSEQINT);
866 
867         ahc_outb(ahc, MWI_RESIDUAL, 0);
868         ahc_outb(ahc, SEQCTL, ahc->seqctl);
869         ahc_outb(ahc, SEQADDR0, 0);
870         ahc_outb(ahc, SEQADDR1, 0);
871 
872         /*
873          * Take the LED out of diagnostic mode on PM resume, too
874          */
875         sblkctl = ahc_inb(ahc, SBLKCTL);
876         ahc_outb(ahc, SBLKCTL, (sblkctl & ~(DIAGLEDEN|DIAGLEDON)));
877 
878         ahc_unpause(ahc);
879 }
880 
881 /************************* Input/Output Queues ********************************/
882 static void
883 ahc_run_qoutfifo(struct ahc_softc *ahc)
884 {
885         struct scb *scb;
886         u_int  scb_index;
887 
888         ahc_sync_qoutfifo(ahc, BUS_DMASYNC_POSTREAD);
889         while (ahc->qoutfifo[ahc->qoutfifonext] != SCB_LIST_NULL) {
890 
891                 scb_index = ahc->qoutfifo[ahc->qoutfifonext];
892                 if ((ahc->qoutfifonext & 0x03) == 0x03) {
893                         u_int modnext;
894 
895                         /*
896                          * Clear 32bits of QOUTFIFO at a time
897                          * so that we don't clobber an incoming
898                          * byte DMA to the array on architectures
899                          * that only support 32bit load and store
900                          * operations.
901                          */
902                         modnext = ahc->qoutfifonext & ~0x3;
903                         *((uint32_t *)(&ahc->qoutfifo[modnext])) = 0xFFFFFFFFUL;
904                         ahc_dmamap_sync(ahc, ahc->shared_data_dmat,
905                                         ahc->shared_data_dmamap,
906                                         /*offset*/modnext, /*len*/4,
907                                         BUS_DMASYNC_PREREAD);
908                 }
909                 ahc->qoutfifonext++;
910 
911                 scb = ahc_lookup_scb(ahc, scb_index);
912                 if (scb == NULL) {
913                         printf("%s: WARNING no command for scb %d "
914                                "(cmdcmplt)\nQOUTPOS = %d\n",
915                                ahc_name(ahc), scb_index,
916                                (ahc->qoutfifonext - 1) & 0xFF);
917                         continue;
918                 }
919 
920                 /*
921                  * Save off the residual
922                  * if there is one.
923                  */
924                 ahc_update_residual(ahc, scb);
925                 ahc_done(ahc, scb);
926         }
927 }
928 
929 static void
930 ahc_run_untagged_queues(struct ahc_softc *ahc)
931 {
932         int i;
933 
934         for (i = 0; i < 16; i++)
935                 ahc_run_untagged_queue(ahc, &ahc->untagged_queues[i]);
936 }
937 
938 static void
939 ahc_run_untagged_queue(struct ahc_softc *ahc, struct scb_tailq *queue)
940 {
941         struct scb *scb;
942 
943         if (ahc->untagged_queue_lock != 0)
944                 return;
945 
946         if ((scb = TAILQ_FIRST(queue)) != NULL
947          && (scb->flags & SCB_ACTIVE) == 0) {
948                 scb->flags |= SCB_ACTIVE;
949                 ahc_queue_scb(ahc, scb);
950         }
951 }
952 
953 /************************* Interrupt Handling *********************************/
954 static void
955 ahc_handle_brkadrint(struct ahc_softc *ahc)
956 {
957         /*
958          * We upset the sequencer :-(
959          * Lookup the error message
960          */
961         int i;
962         int error;
963 
964         error = ahc_inb(ahc, ERROR);
965         for (i = 0; error != 1 && i < num_errors; i++)
966                 error >>= 1;
967         printf("%s: brkadrint, %s at seqaddr = 0x%x\n",
968                ahc_name(ahc), ahc_hard_errors[i].errmesg,
969                ahc_inb(ahc, SEQADDR0) |
970                (ahc_inb(ahc, SEQADDR1) << 8));
971 
972         ahc_dump_card_state(ahc);
973 
974         /* Tell everyone that this HBA is no longer available */
975         ahc_abort_scbs(ahc, CAM_TARGET_WILDCARD, ALL_CHANNELS,
976                        CAM_LUN_WILDCARD, SCB_LIST_NULL, ROLE_UNKNOWN,
977                        CAM_NO_HBA);
978 
979         /* Disable all interrupt sources by resetting the controller */
980         ahc_shutdown(ahc);
981 }
982 
983 static void
984 ahc_handle_seqint(struct ahc_softc *ahc, u_int intstat)
985 {
986         struct scb *scb;
987         struct ahc_devinfo devinfo;
988         
989         ahc_fetch_devinfo(ahc, &devinfo);
990 
991         /*
992          * Clear the upper byte that holds SEQINT status
993          * codes and clear the SEQINT bit. We will unpause
994          * the sequencer, if appropriate, after servicing
995          * the request.
996          */
997         ahc_outb(ahc, CLRINT, CLRSEQINT);
998         switch (intstat & SEQINT_MASK) {
999         case BAD_STATUS:
1000         {
1001                 u_int  scb_index;
1002                 struct hardware_scb *hscb;
1003 
1004                 /*
1005                  * Set the default return value to 0 (don't
1006                  * send sense).  The sense code will change
1007                  * this if needed.
1008                  */
1009                 ahc_outb(ahc, RETURN_1, 0);
1010 
1011                 /*
1012                  * The sequencer will notify us when a command
1013                  * has an error that would be of interest to
1014                  * the kernel.  This allows us to leave the sequencer
1015                  * running in the common case of command completes
1016                  * without error.  The sequencer will already have
1017                  * dma'd the SCB back up to us, so we can reference
1018                  * the in kernel copy directly.
1019                  */
1020                 scb_index = ahc_inb(ahc, SCB_TAG);
1021                 scb = ahc_lookup_scb(ahc, scb_index);
1022                 if (scb == NULL) {
1023                         ahc_print_devinfo(ahc, &devinfo);
1024                         printf("ahc_intr - referenced scb "
1025                                "not valid during seqint 0x%x scb(%d)\n",
1026                                intstat, scb_index);
1027                         ahc_dump_card_state(ahc);
1028                         panic("for safety");
1029                         goto unpause;
1030                 }
1031 
1032                 hscb = scb->hscb; 
1033 
1034                 /* Don't want to clobber the original sense code */
1035                 if ((scb->flags & SCB_SENSE) != 0) {
1036                         /*
1037                          * Clear the SCB_SENSE Flag and have
1038                          * the sequencer do a normal command
1039                          * complete.
1040                          */
1041                         scb->flags &= ~SCB_SENSE;
1042                         ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
1043                         break;
1044                 }
1045                 ahc_set_transaction_status(scb, CAM_SCSI_STATUS_ERROR);
1046                 /* Freeze the queue until the client sees the error. */
1047                 ahc_freeze_devq(ahc, scb);
1048                 ahc_freeze_scb(scb);
1049                 ahc_set_scsi_status(scb, hscb->shared_data.status.scsi_status);
1050                 switch (hscb->shared_data.status.scsi_status) {
1051                 case SCSI_STATUS_OK:
1052                         printf("%s: Interrupted for staus of 0???\n",
1053                                ahc_name(ahc));
1054                         break;
1055                 case SCSI_STATUS_CMD_TERMINATED:
1056                 case SCSI_STATUS_CHECK_COND:
1057                 {
1058                         struct ahc_dma_seg *sg;
1059                         struct scsi_sense *sc;
1060                         struct ahc_initiator_tinfo *targ_info;
1061                         struct ahc_tmode_tstate *tstate;
1062                         struct ahc_transinfo *tinfo;
1063 #ifdef AHC_DEBUG
1064                         if (ahc_debug & AHC_SHOW_SENSE) {
1065                                 ahc_print_path(ahc, scb);
1066                                 printf("SCB %d: requests Check Status\n",
1067                                        scb->hscb->tag);
1068                         }
1069 #endif
1070 
1071                         if (ahc_perform_autosense(scb) == 0)
1072                                 break;
1073 
1074                         targ_info = ahc_fetch_transinfo(ahc,
1075                                                         devinfo.channel,
1076                                                         devinfo.our_scsiid,
1077                                                         devinfo.target,
1078                                                         &tstate);
1079                         tinfo = &targ_info->curr;
1080                         sg = scb->sg_list;
1081                         sc = (struct scsi_sense *)(&hscb->shared_data.cdb); 
1082                         /*
1083                          * Save off the residual if there is one.
1084                          */
1085                         ahc_update_residual(ahc, scb);
1086 #ifdef AHC_DEBUG
1087                         if (ahc_debug & AHC_SHOW_SENSE) {
1088                                 ahc_print_path(ahc, scb);
1089                                 printf("Sending Sense\n");
1090                         }
1091 #endif
1092                         sg->addr = ahc_get_sense_bufaddr(ahc, scb);
1093                         sg->len = ahc_get_sense_bufsize(ahc, scb);
1094                         sg->len |= AHC_DMA_LAST_SEG;
1095 
1096                         /* Fixup byte order */
1097                         sg->addr = ahc_htole32(sg->addr);
1098                         sg->len = ahc_htole32(sg->len);
1099 
1100                         sc->opcode = REQUEST_SENSE;
1101                         sc->byte2 = 0;
1102                         if (tinfo->protocol_version <= SCSI_REV_2
1103                          && SCB_GET_LUN(scb) < 8)
1104                                 sc->byte2 = SCB_GET_LUN(scb) << 5;
1105                         sc->unused[0] = 0;
1106                         sc->unused[1] = 0;
1107                         sc->length = sg->len;
1108                         sc->control = 0;
1109 
1110                         /*
1111                          * We can't allow the target to disconnect.
1112                          * This will be an untagged transaction and
1113                          * having the target disconnect will make this
1114                          * transaction indestinguishable from outstanding
1115                          * tagged transactions.
1116                          */
1117                         hscb->control = 0;
1118 
1119                         /*
1120                          * This request sense could be because the
1121                          * the device lost power or in some other
1122                          * way has lost our transfer negotiations.
1123                          * Renegotiate if appropriate.  Unit attention
1124                          * errors will be reported before any data
1125                          * phases occur.
1126                          */
1127                         if (ahc_get_residual(scb) 
1128                          == ahc_get_transfer_length(scb)) {
1129                                 ahc_update_neg_request(ahc, &devinfo,
1130                                                        tstate, targ_info,
1131                                                        AHC_NEG_IF_NON_ASYNC);
1132                         }
1133                         if (tstate->auto_negotiate & devinfo.target_mask) {
1134                                 hscb->control |= MK_MESSAGE;
1135                                 scb->flags &= ~SCB_NEGOTIATE;
1136                                 scb->flags |= SCB_AUTO_NEGOTIATE;
1137                         }
1138                         hscb->cdb_len = sizeof(*sc);
1139                         hscb->dataptr = sg->addr; 
1140                         hscb->datacnt = sg->len;
1141                         hscb->sgptr = scb->sg_list_phys | SG_FULL_RESID;
1142                         hscb->sgptr = ahc_htole32(hscb->sgptr);
1143                         scb->sg_count = 1;
1144                         scb->flags |= SCB_SENSE;
1145                         ahc_qinfifo_requeue_tail(ahc, scb);
1146                         ahc_outb(ahc, RETURN_1, SEND_SENSE);
1147                         /*
1148                          * Ensure we have enough time to actually
1149                          * retrieve the sense.
1150                          */
1151                         ahc_scb_timer_reset(scb, 5 * 1000000);
1152                         break;
1153                 }
1154                 default:
1155                         break;
1156                 }
1157                 break;
1158         }
1159         case NO_MATCH:
1160         {
1161                 /* Ensure we don't leave the selection hardware on */
1162                 ahc_outb(ahc, SCSISEQ,
1163                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
1164 
1165                 printf("%s:%c:%d: no active SCB for reconnecting "
1166                        "target - issuing BUS DEVICE RESET\n",
1167                        ahc_name(ahc), devinfo.channel, devinfo.target);
1168                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
1169                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
1170                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
1171                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
1172                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
1173                        "SINDEX == 0x%x\n",
1174                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
1175                        ahc_index_busy_tcl(ahc,
1176                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
1177                                       ahc_inb(ahc, SAVED_LUN))),
1178                        ahc_inb(ahc, SINDEX));
1179                 printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
1180                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
1181                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
1182                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
1183                        ahc_inb(ahc, SCB_CONTROL));
1184                 printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
1185                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
1186                 printf("SXFRCTL0 == 0x%x\n", ahc_inb(ahc, SXFRCTL0));
1187                 printf("SEQCTL == 0x%x\n", ahc_inb(ahc, SEQCTL));
1188                 ahc_dump_card_state(ahc);
1189                 ahc->msgout_buf[0] = MSG_BUS_DEV_RESET;
1190                 ahc->msgout_len = 1;
1191                 ahc->msgout_index = 0;
1192                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
1193                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
1194                 ahc_assert_atn(ahc);
1195                 break;
1196         }
1197         case SEND_REJECT: 
1198         {
1199                 u_int rejbyte = ahc_inb(ahc, ACCUM);
1200                 printf("%s:%c:%d: Warning - unknown message received from "
1201                        "target (0x%x).  Rejecting\n", 
1202                        ahc_name(ahc), devinfo.channel, devinfo.target, rejbyte);
1203                 break; 
1204         }
1205         case PROTO_VIOLATION:
1206         {
1207                 ahc_handle_proto_violation(ahc);
1208                 break;
1209         }
1210         case IGN_WIDE_RES:
1211                 ahc_handle_ign_wide_residue(ahc, &devinfo);
1212                 break;
1213         case PDATA_REINIT:
1214                 ahc_reinitialize_dataptrs(ahc);
1215                 break;
1216         case BAD_PHASE:
1217         {
1218                 u_int lastphase;
1219 
1220                 lastphase = ahc_inb(ahc, LASTPHASE);
1221                 printf("%s:%c:%d: unknown scsi bus phase %x, "
1222                        "lastphase = 0x%x.  Attempting to continue\n",
1223                        ahc_name(ahc), devinfo.channel, devinfo.target,
1224                        lastphase, ahc_inb(ahc, SCSISIGI));
1225                 break;
1226         }
1227         case MISSED_BUSFREE:
1228         {
1229                 u_int lastphase;
1230 
1231                 lastphase = ahc_inb(ahc, LASTPHASE);
1232                 printf("%s:%c:%d: Missed busfree. "
1233                        "Lastphase = 0x%x, Curphase = 0x%x\n",
1234                        ahc_name(ahc), devinfo.channel, devinfo.target,
1235                        lastphase, ahc_inb(ahc, SCSISIGI));
1236                 ahc_restart(ahc);
1237                 return;
1238         }
1239         case HOST_MSG_LOOP:
1240         {
1241                 /*
1242                  * The sequencer has encountered a message phase
1243                  * that requires host assistance for completion.
1244                  * While handling the message phase(s), we will be
1245                  * notified by the sequencer after each byte is
1246                  * transfered so we can track bus phase changes.
1247                  *
1248                  * If this is the first time we've seen a HOST_MSG_LOOP
1249                  * interrupt, initialize the state of the host message
1250                  * loop.
1251                  */
1252                 if (ahc->msg_type == MSG_TYPE_NONE) {
1253                         struct scb *scb;
1254                         u_int scb_index;
1255                         u_int bus_phase;
1256 
1257                         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1258                         if (bus_phase != P_MESGIN
1259                          && bus_phase != P_MESGOUT) {
1260                                 printf("ahc_intr: HOST_MSG_LOOP bad "
1261                                        "phase 0x%x\n",
1262                                       bus_phase);
1263                                 /*
1264                                  * Probably transitioned to bus free before
1265                                  * we got here.  Just punt the message.
1266                                  */
1267                                 ahc_clear_intstat(ahc);
1268                                 ahc_restart(ahc);
1269                                 return;
1270                         }
1271 
1272                         scb_index = ahc_inb(ahc, SCB_TAG);
1273                         scb = ahc_lookup_scb(ahc, scb_index);
1274                         if (devinfo.role == ROLE_INITIATOR) {
1275                                 if (bus_phase == P_MESGOUT) {
1276                                         if (scb == NULL)
1277                                                 panic("HOST_MSG_LOOP with "
1278                                                       "invalid SCB %x\n",
1279                                                       scb_index);
1280 
1281                                         ahc_setup_initiator_msgout(ahc,
1282                                                                    &devinfo,
1283                                                                    scb);
1284                                 } else {
1285                                         ahc->msg_type =
1286                                             MSG_TYPE_INITIATOR_MSGIN;
1287                                         ahc->msgin_index = 0;
1288                                 }
1289                         }
1290 #ifdef AHC_TARGET_MODE
1291                         else {
1292                                 if (bus_phase == P_MESGOUT) {
1293                                         ahc->msg_type =
1294                                             MSG_TYPE_TARGET_MSGOUT;
1295                                         ahc->msgin_index = 0;
1296                                 }
1297                                 else 
1298                                         ahc_setup_target_msgin(ahc,
1299                                                                &devinfo,
1300                                                                scb);
1301                         }
1302 #endif
1303                 }
1304 
1305                 ahc_handle_message_phase(ahc);
1306                 break;
1307         }
1308         case PERR_DETECTED:
1309         {
1310                 /*
1311                  * If we've cleared the parity error interrupt
1312                  * but the sequencer still believes that SCSIPERR
1313                  * is true, it must be that the parity error is
1314                  * for the currently presented byte on the bus,
1315                  * and we are not in a phase (data-in) where we will
1316                  * eventually ack this byte.  Ack the byte and
1317                  * throw it away in the hope that the target will
1318                  * take us to message out to deliver the appropriate
1319                  * error message.
1320                  */
1321                 if ((intstat & SCSIINT) == 0
1322                  && (ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0) {
1323 
1324                         if ((ahc->features & AHC_DT) == 0) {
1325                                 u_int curphase;
1326 
1327                                 /*
1328                                  * The hardware will only let you ack bytes
1329                                  * if the expected phase in SCSISIGO matches
1330                                  * the current phase.  Make sure this is
1331                                  * currently the case.
1332                                  */
1333                                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1334                                 ahc_outb(ahc, LASTPHASE, curphase);
1335                                 ahc_outb(ahc, SCSISIGO, curphase);
1336                         }
1337                         if ((ahc_inb(ahc, SCSISIGI) & (CDI|MSGI)) == 0) {
1338                                 int wait;
1339 
1340                                 /*
1341                                  * In a data phase.  Faster to bitbucket
1342                                  * the data than to individually ack each
1343                                  * byte.  This is also the only strategy
1344                                  * that will work with AUTOACK enabled.
1345                                  */
1346                                 ahc_outb(ahc, SXFRCTL1,
1347                                          ahc_inb(ahc, SXFRCTL1) | BITBUCKET);
1348                                 wait = 5000;
1349                                 while (--wait != 0) {
1350                                         if ((ahc_inb(ahc, SCSISIGI)
1351                                           & (CDI|MSGI)) != 0)
1352                                                 break;
1353                                         ahc_delay(100);
1354                                 }
1355                                 ahc_outb(ahc, SXFRCTL1,
1356                                          ahc_inb(ahc, SXFRCTL1) & ~BITBUCKET);
1357                                 if (wait == 0) {
1358                                         struct  scb *scb;
1359                                         u_int   scb_index;
1360 
1361                                         ahc_print_devinfo(ahc, &devinfo);
1362                                         printf("Unable to clear parity error.  "
1363                                                "Resetting bus.\n");
1364                                         scb_index = ahc_inb(ahc, SCB_TAG);
1365                                         scb = ahc_lookup_scb(ahc, scb_index);
1366                                         if (scb != NULL)
1367                                                 ahc_set_transaction_status(scb,
1368                                                     CAM_UNCOR_PARITY);
1369                                         ahc_reset_channel(ahc, devinfo.channel, 
1370                                                           /*init reset*/TRUE);
1371                                 }
1372                         } else {
1373                                 ahc_inb(ahc, SCSIDATL);
1374                         }
1375                 }
1376                 break;
1377         }
1378         case DATA_OVERRUN:
1379         {
1380                 /*
1381                  * When the sequencer detects an overrun, it
1382                  * places the controller in "BITBUCKET" mode
1383                  * and allows the target to complete its transfer.
1384                  * Unfortunately, none of the counters get updated
1385                  * when the controller is in this mode, so we have
1386                  * no way of knowing how large the overrun was.
1387                  */
1388                 u_int scbindex = ahc_inb(ahc, SCB_TAG);
1389                 u_int lastphase = ahc_inb(ahc, LASTPHASE);
1390                 u_int i;
1391 
1392                 scb = ahc_lookup_scb(ahc, scbindex);
1393                 for (i = 0; i < num_phases; i++) {
1394                         if (lastphase == ahc_phase_table[i].phase)
1395                                 break;
1396                 }
1397                 ahc_print_path(ahc, scb);
1398                 printf("data overrun detected %s."
1399                        "  Tag == 0x%x.\n",
1400                        ahc_phase_table[i].phasemsg,
1401                        scb->hscb->tag);
1402                 ahc_print_path(ahc, scb);
1403                 printf("%s seen Data Phase.  Length = %ld.  NumSGs = %d.\n",
1404                        ahc_inb(ahc, SEQ_FLAGS) & DPHASE ? "Have" : "Haven't",
1405                        ahc_get_transfer_length(scb), scb->sg_count);
1406                 if (scb->sg_count > 0) {
1407                         for (i = 0; i < scb->sg_count; i++) {
1408 
1409                                 printf("sg[%d] - Addr 0x%x%x : Length %d\n",
1410                                        i,
1411                                        (ahc_le32toh(scb->sg_list[i].len) >> 24
1412                                         & SG_HIGH_ADDR_BITS),
1413                                        ahc_le32toh(scb->sg_list[i].addr),
1414                                        ahc_le32toh(scb->sg_list[i].len)
1415                                        & AHC_SG_LEN_MASK);
1416                         }
1417                 }
1418                 /*
1419                  * Set this and it will take effect when the
1420                  * target does a command complete.
1421                  */
1422                 ahc_freeze_devq(ahc, scb);
1423                 if ((scb->flags & SCB_SENSE) == 0) {
1424                         ahc_set_transaction_status(scb, CAM_DATA_RUN_ERR);
1425                 } else {
1426                         scb->flags &= ~SCB_SENSE;
1427                         ahc_set_transaction_status(scb, CAM_AUTOSENSE_FAIL);
1428                 }
1429                 ahc_freeze_scb(scb);
1430 
1431                 if ((ahc->features & AHC_ULTRA2) != 0) {
1432                         /*
1433                          * Clear the channel in case we return
1434                          * to data phase later.
1435                          */
1436                         ahc_outb(ahc, SXFRCTL0,
1437                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
1438                         ahc_outb(ahc, SXFRCTL0,
1439                                  ahc_inb(ahc, SXFRCTL0) | CLRSTCNT|CLRCHN);
1440                 }
1441                 if ((ahc->flags & AHC_39BIT_ADDRESSING) != 0) {
1442                         u_int dscommand1;
1443 
1444                         /* Ensure HHADDR is 0 for future DMA operations. */
1445                         dscommand1 = ahc_inb(ahc, DSCOMMAND1);
1446                         ahc_outb(ahc, DSCOMMAND1, dscommand1 | HADDLDSEL0);
1447                         ahc_outb(ahc, HADDR, 0);
1448                         ahc_outb(ahc, DSCOMMAND1, dscommand1);
1449                 }
1450                 break;
1451         }
1452         case MKMSG_FAILED:
1453         {
1454                 u_int scbindex;
1455 
1456                 printf("%s:%c:%d:%d: Attempt to issue message failed\n",
1457                        ahc_name(ahc), devinfo.channel, devinfo.target,
1458                        devinfo.lun);
1459                 scbindex = ahc_inb(ahc, SCB_TAG);
1460                 scb = ahc_lookup_scb(ahc, scbindex);
1461                 if (scb != NULL
1462                  && (scb->flags & SCB_RECOVERY_SCB) != 0)
1463                         /*
1464                          * Ensure that we didn't put a second instance of this
1465                          * SCB into the QINFIFO.
1466                          */
1467                         ahc_search_qinfifo(ahc, SCB_GET_TARGET(ahc, scb),
1468                                            SCB_GET_CHANNEL(ahc, scb),
1469                                            SCB_GET_LUN(scb), scb->hscb->tag,
1470                                            ROLE_INITIATOR, /*status*/0,
1471                                            SEARCH_REMOVE);
1472                 break;
1473         }
1474         case NO_FREE_SCB:
1475         {
1476                 printf("%s: No free or disconnected SCBs\n", ahc_name(ahc));
1477                 ahc_dump_card_state(ahc);
1478                 panic("for safety");
1479                 break;
1480         }
1481         case SCB_MISMATCH:
1482         {
1483                 u_int scbptr;
1484 
1485                 scbptr = ahc_inb(ahc, SCBPTR);
1486                 printf("Bogus TAG after DMA.  SCBPTR %d, tag %d, our tag %d\n",
1487                        scbptr, ahc_inb(ahc, ARG_1),
1488                        ahc->scb_data->hscbs[scbptr].tag);
1489                 ahc_dump_card_state(ahc);
1490                 panic("for saftey");
1491                 break;
1492         }
1493         case OUT_OF_RANGE:
1494         {
1495                 printf("%s: BTT calculation out of range\n", ahc_name(ahc));
1496                 printf("SAVED_SCSIID == 0x%x, SAVED_LUN == 0x%x, "
1497                        "ARG_1 == 0x%x ACCUM = 0x%x\n",
1498                        ahc_inb(ahc, SAVED_SCSIID), ahc_inb(ahc, SAVED_LUN),
1499                        ahc_inb(ahc, ARG_1), ahc_inb(ahc, ACCUM));
1500                 printf("SEQ_FLAGS == 0x%x, SCBPTR == 0x%x, BTT == 0x%x, "
1501                        "SINDEX == 0x%x\n, A == 0x%x\n",
1502                        ahc_inb(ahc, SEQ_FLAGS), ahc_inb(ahc, SCBPTR),
1503                        ahc_index_busy_tcl(ahc,
1504                             BUILD_TCL(ahc_inb(ahc, SAVED_SCSIID),
1505                                       ahc_inb(ahc, SAVED_LUN))),
1506                        ahc_inb(ahc, SINDEX),
1507                        ahc_inb(ahc, ACCUM));
1508                 printf("SCSIID == 0x%x, SCB_SCSIID == 0x%x, SCB_LUN == 0x%x, "
1509                        "SCB_TAG == 0x%x, SCB_CONTROL == 0x%x\n",
1510                        ahc_inb(ahc, SCSIID), ahc_inb(ahc, SCB_SCSIID),
1511                        ahc_inb(ahc, SCB_LUN), ahc_inb(ahc, SCB_TAG),
1512                        ahc_inb(ahc, SCB_CONTROL));
1513                 printf("SCSIBUSL == 0x%x, SCSISIGI == 0x%x\n",
1514                        ahc_inb(ahc, SCSIBUSL), ahc_inb(ahc, SCSISIGI));
1515                 ahc_dump_card_state(ahc);
1516                 panic("for safety");
1517                 break;
1518         }
1519         default:
1520                 printf("ahc_intr: seqint, "
1521                        "intstat == 0x%x, scsisigi = 0x%x\n",
1522                        intstat, ahc_inb(ahc, SCSISIGI));
1523                 break;
1524         }
1525 unpause:
1526         /*
1527          *  The sequencer is paused immediately on
1528          *  a SEQINT, so we should restart it when
1529          *  we're done.
1530          */
1531         ahc_unpause(ahc);
1532 }
1533 
1534 static void
1535 ahc_handle_scsiint(struct ahc_softc *ahc, u_int intstat)
1536 {
1537         u_int   scb_index;
1538         u_int   status0;
1539         u_int   status;
1540         struct  scb *scb;
1541         char    cur_channel;
1542         char    intr_channel;
1543 
1544         if ((ahc->features & AHC_TWIN) != 0
1545          && ((ahc_inb(ahc, SBLKCTL) & SELBUSB) != 0))
1546                 cur_channel = 'B';
1547         else
1548                 cur_channel = 'A';
1549         intr_channel = cur_channel;
1550 
1551         if ((ahc->features & AHC_ULTRA2) != 0)
1552                 status0 = ahc_inb(ahc, SSTAT0) & IOERR;
1553         else
1554                 status0 = 0;
1555         status = ahc_inb(ahc, SSTAT1) & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1556         if (status == 0 && status0 == 0) {
1557                 if ((ahc->features & AHC_TWIN) != 0) {
1558                         /* Try the other channel */
1559                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
1560                         status = ahc_inb(ahc, SSTAT1)
1561                                & (SELTO|SCSIRSTI|BUSFREE|SCSIPERR);
1562                         intr_channel = (cur_channel == 'A') ? 'B' : 'A';
1563                 }
1564                 if (status == 0) {
1565                         printf("%s: Spurious SCSI interrupt\n", ahc_name(ahc));
1566                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
1567                         ahc_unpause(ahc);
1568                         return;
1569                 }
1570         }
1571 
1572         /* Make sure the sequencer is in a safe location. */
1573         ahc_clear_critical_section(ahc);
1574 
1575         scb_index = ahc_inb(ahc, SCB_TAG);
1576         scb = ahc_lookup_scb(ahc, scb_index);
1577         if (scb != NULL
1578          && (ahc_inb(ahc, SEQ_FLAGS) & NOT_IDENTIFIED) != 0)
1579                 scb = NULL;
1580 
1581         if ((ahc->features & AHC_ULTRA2) != 0
1582          && (status0 & IOERR) != 0) {
1583                 int now_lvd;
1584 
1585                 now_lvd = ahc_inb(ahc, SBLKCTL) & ENAB40;
1586                 printf("%s: Transceiver State Has Changed to %s mode\n",
1587                        ahc_name(ahc), now_lvd ? "LVD" : "SE");
1588                 ahc_outb(ahc, CLRSINT0, CLRIOERR);
1589                 /*
1590                  * When transitioning to SE mode, the reset line
1591                  * glitches, triggering an arbitration bug in some
1592                  * Ultra2 controllers.  This bug is cleared when we
1593                  * assert the reset line.  Since a reset glitch has
1594                  * already occurred with this transition and a
1595                  * transceiver state change is handled just like
1596                  * a bus reset anyway, asserting the reset line
1597                  * ourselves is safe.
1598                  */
1599                 ahc_reset_channel(ahc, intr_channel,
1600                                  /*Initiate Reset*/now_lvd == 0);
1601         } else if ((status & SCSIRSTI) != 0) {
1602                 printf("%s: Someone reset channel %c\n",
1603                         ahc_name(ahc), intr_channel);
1604                 if (intr_channel != cur_channel)
1605                         ahc_outb(ahc, SBLKCTL, ahc_inb(ahc, SBLKCTL) ^ SELBUSB);
1606                 ahc_reset_channel(ahc, intr_channel, /*Initiate Reset*/FALSE);
1607         } else if ((status & SCSIPERR) != 0) {
1608                 /*
1609                  * Determine the bus phase and queue an appropriate message.
1610                  * SCSIPERR is latched true as soon as a parity error
1611                  * occurs.  If the sequencer acked the transfer that
1612                  * caused the parity error and the currently presented
1613                  * transfer on the bus has correct parity, SCSIPERR will
1614                  * be cleared by CLRSCSIPERR.  Use this to determine if
1615                  * we should look at the last phase the sequencer recorded,
1616                  * or the current phase presented on the bus.
1617                  */
1618                 struct  ahc_devinfo devinfo;
1619                 u_int   mesg_out;
1620                 u_int   curphase;
1621                 u_int   errorphase;
1622                 u_int   lastphase;
1623                 u_int   scsirate;
1624                 u_int   i;
1625                 u_int   sstat2;
1626                 int     silent;
1627 
1628                 lastphase = ahc_inb(ahc, LASTPHASE);
1629                 curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
1630                 sstat2 = ahc_inb(ahc, SSTAT2);
1631                 ahc_outb(ahc, CLRSINT1, CLRSCSIPERR);
1632                 /*
1633                  * For all phases save DATA, the sequencer won't
1634                  * automatically ack a byte that has a parity error
1635                  * in it.  So the only way that the current phase
1636                  * could be 'data-in' is if the parity error is for
1637                  * an already acked byte in the data phase.  During
1638                  * synchronous data-in transfers, we may actually
1639                  * ack bytes before latching the current phase in
1640                  * LASTPHASE, leading to the discrepancy between
1641                  * curphase and lastphase.
1642                  */
1643                 if ((ahc_inb(ahc, SSTAT1) & SCSIPERR) != 0
1644                  || curphase == P_DATAIN || curphase == P_DATAIN_DT)
1645                         errorphase = curphase;
1646                 else
1647                         errorphase = lastphase;
1648 
1649                 for (i = 0; i < num_phases; i++) {
1650                         if (errorphase == ahc_phase_table[i].phase)
1651                                 break;
1652                 }
1653                 mesg_out = ahc_phase_table[i].mesg_out;
1654                 silent = FALSE;
1655                 if (scb != NULL) {
1656                         if (SCB_IS_SILENT(scb))
1657                                 silent = TRUE;
1658                         else
1659                                 ahc_print_path(ahc, scb);
1660                         scb->flags |= SCB_TRANSMISSION_ERROR;
1661                 } else
1662                         printf("%s:%c:%d: ", ahc_name(ahc), intr_channel,
1663                                SCSIID_TARGET(ahc, ahc_inb(ahc, SAVED_SCSIID)));
1664                 scsirate = ahc_inb(ahc, SCSIRATE);
1665                 if (silent == FALSE) {
1666                         printf("parity error detected %s. "
1667                                "SEQADDR(0x%x) SCSIRATE(0x%x)\n",
1668                                ahc_phase_table[i].phasemsg,
1669                                ahc_inw(ahc, SEQADDR0),
1670                                scsirate);
1671                         if ((ahc->features & AHC_DT) != 0) {
1672                                 if ((sstat2 & CRCVALERR) != 0)
1673                                         printf("\tCRC Value Mismatch\n");
1674                                 if ((sstat2 & CRCENDERR) != 0)
1675                                         printf("\tNo terminal CRC packet "
1676                                                "recevied\n");
1677                                 if ((sstat2 & CRCREQERR) != 0)
1678                                         printf("\tIllegal CRC packet "
1679                                                "request\n");
1680                                 if ((sstat2 & DUAL_EDGE_ERR) != 0)
1681                                         printf("\tUnexpected %sDT Data Phase\n",
1682                                                (scsirate & SINGLE_EDGE)
1683                                              ? "" : "non-");
1684                         }
1685                 }
1686 
1687                 if ((ahc->features & AHC_DT) != 0
1688                  && (sstat2 & DUAL_EDGE_ERR) != 0) {
1689                         /*
1690                          * This error applies regardless of
1691                          * data direction, so ignore the value
1692                          * in the phase table.
1693                          */
1694                         mesg_out = MSG_INITIATOR_DET_ERR;
1695                 }
1696 
1697                 /*
1698                  * We've set the hardware to assert ATN if we   
1699                  * get a parity error on "in" phases, so all we  
1700                  * need to do is stuff the message buffer with
1701                  * the appropriate message.  "In" phases have set
1702                  * mesg_out to something other than MSG_NOP.
1703                  */
1704                 if (mesg_out != MSG_NOOP) {
1705                         if (ahc->msg_type != MSG_TYPE_NONE)
1706                                 ahc->send_msg_perror = TRUE;
1707                         else
1708                                 ahc_outb(ahc, MSG_OUT, mesg_out);
1709                 }
1710                 /*
1711                  * Force a renegotiation with this target just in
1712                  * case we are out of sync for some external reason
1713                  * unknown (or unreported) by the target.
1714                  */
1715                 ahc_fetch_devinfo(ahc, &devinfo);
1716                 ahc_force_renegotiation(ahc, &devinfo);
1717 
1718                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1719                 ahc_unpause(ahc);
1720         } else if ((status & SELTO) != 0) {
1721                 u_int   scbptr;
1722 
1723                 /* Stop the selection */
1724                 ahc_outb(ahc, SCSISEQ, 0);
1725 
1726                 /* No more pending messages */
1727                 ahc_clear_msg_state(ahc);
1728 
1729                 /* Clear interrupt state */
1730                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1731                 ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRBUSFREE|CLRSCSIPERR);
1732 
1733                 /*
1734                  * Although the driver does not care about the
1735                  * 'Selection in Progress' status bit, the busy
1736                  * LED does.  SELINGO is only cleared by a sucessfull
1737                  * selection, so we must manually clear it to insure
1738                  * the LED turns off just incase no future successful
1739                  * selections occur (e.g. no devices on the bus).
1740                  */
1741                 ahc_outb(ahc, CLRSINT0, CLRSELINGO);
1742 
1743                 scbptr = ahc_inb(ahc, WAITING_SCBH);
1744                 ahc_outb(ahc, SCBPTR, scbptr);
1745                 scb_index = ahc_inb(ahc, SCB_TAG);
1746 
1747                 scb = ahc_lookup_scb(ahc, scb_index);
1748                 if (scb == NULL) {
1749                         printf("%s: ahc_intr - referenced scb not "
1750                                "valid during SELTO scb(%d, %d)\n",
1751                                ahc_name(ahc), scbptr, scb_index);
1752                         ahc_dump_card_state(ahc);
1753                 } else {
1754                         struct ahc_devinfo devinfo;
1755 #ifdef AHC_DEBUG
1756                         if ((ahc_debug & AHC_SHOW_SELTO) != 0) {
1757                                 ahc_print_path(ahc, scb);
1758                                 printf("Saw Selection Timeout for SCB 0x%x\n",
1759                                        scb_index);
1760                         }
1761 #endif
1762                         ahc_scb_devinfo(ahc, &devinfo, scb);
1763                         ahc_set_transaction_status(scb, CAM_SEL_TIMEOUT);
1764                         ahc_freeze_devq(ahc, scb);
1765 
1766                         /*
1767                          * Cancel any pending transactions on the device
1768                          * now that it seems to be missing.  This will
1769                          * also revert us to async/narrow transfers until
1770                          * we can renegotiate with the device.
1771                          */
1772                         ahc_handle_devreset(ahc, &devinfo,
1773                                             CAM_SEL_TIMEOUT,
1774                                             "Selection Timeout",
1775                                             /*verbose_level*/1);
1776                 }
1777                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1778                 ahc_restart(ahc);
1779         } else if ((status & BUSFREE) != 0
1780                 && (ahc_inb(ahc, SIMODE1) & ENBUSFREE) != 0) {
1781                 struct  ahc_devinfo devinfo;
1782                 u_int   lastphase;
1783                 u_int   saved_scsiid;
1784                 u_int   saved_lun;
1785                 u_int   target;
1786                 u_int   initiator_role_id;
1787                 char    channel;
1788                 int     printerror;
1789 
1790                 /*
1791                  * Clear our selection hardware as soon as possible.
1792                  * We may have an entry in the waiting Q for this target,
1793                  * that is affected by this busfree and we don't want to
1794                  * go about selecting the target while we handle the event.
1795                  */
1796                 ahc_outb(ahc, SCSISEQ,
1797                          ahc_inb(ahc, SCSISEQ) & (ENSELI|ENRSELI|ENAUTOATNP));
1798 
1799                 /*
1800                  * Disable busfree interrupts and clear the busfree
1801                  * interrupt status.  We do this here so that several
1802                  * bus transactions occur prior to clearing the SCSIINT
1803                  * latch.  It can take a bit for the clearing to take effect.
1804                  */
1805                 ahc_outb(ahc, SIMODE1, ahc_inb(ahc, SIMODE1) & ~ENBUSFREE);
1806                 ahc_outb(ahc, CLRSINT1, CLRBUSFREE|CLRSCSIPERR);
1807 
1808                 /*
1809                  * Look at what phase we were last in.
1810                  * If its message out, chances are pretty good
1811                  * that the busfree was in response to one of
1812                  * our abort requests.
1813                  */
1814                 lastphase = ahc_inb(ahc, LASTPHASE);
1815                 saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
1816                 saved_lun = ahc_inb(ahc, SAVED_LUN);
1817                 target = SCSIID_TARGET(ahc, saved_scsiid);
1818                 initiator_role_id = SCSIID_OUR_ID(saved_scsiid);
1819                 channel = SCSIID_CHANNEL(ahc, saved_scsiid);
1820                 ahc_compile_devinfo(&devinfo, initiator_role_id,
1821                                     target, saved_lun, channel, ROLE_INITIATOR);
1822                 printerror = 1;
1823 
1824                 if (lastphase == P_MESGOUT) {
1825                         u_int tag;
1826 
1827                         tag = SCB_LIST_NULL;
1828                         if (ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT_TAG, TRUE)
1829                          || ahc_sent_msg(ahc, AHCMSG_1B, MSG_ABORT, TRUE)) {
1830                                 if (ahc->msgout_buf[ahc->msgout_index - 1]
1831                                  == MSG_ABORT_TAG)
1832                                         tag = scb->hscb->tag;
1833                                 ahc_print_path(ahc, scb);
1834                                 printf("SCB %d - Abort%s Completed.\n",
1835                                        scb->hscb->tag, tag == SCB_LIST_NULL ?
1836                                        "" : " Tag");
1837                                 ahc_abort_scbs(ahc, target, channel,
1838                                                saved_lun, tag,
1839                                                ROLE_INITIATOR,
1840                                                CAM_REQ_ABORTED);
1841                                 printerror = 0;
1842                         } else if (ahc_sent_msg(ahc, AHCMSG_1B,
1843                                                 MSG_BUS_DEV_RESET, TRUE)) {
1844 #ifdef __FreeBSD__
1845                                 /*
1846                                  * Don't mark the user's request for this BDR
1847                                  * as completing with CAM_BDR_SENT.  CAM3
1848                                  * specifies CAM_REQ_CMP.
1849                                  */
1850                                 if (scb != NULL
1851                                  && scb->io_ctx->ccb_h.func_code== XPT_RESET_DEV
1852                                  && ahc_match_scb(ahc, scb, target, channel,
1853                                                   CAM_LUN_WILDCARD,
1854                                                   SCB_LIST_NULL,
1855                                                   ROLE_INITIATOR)) {
1856                                         ahc_set_transaction_status(scb, CAM_REQ_CMP);
1857                                 }
1858 #endif
1859                                 ahc_compile_devinfo(&devinfo,
1860                                                     initiator_role_id,
1861                                                     target,
1862                                                     CAM_LUN_WILDCARD,
1863                                                     channel,
1864                                                     ROLE_INITIATOR);
1865                                 ahc_handle_devreset(ahc, &devinfo,
1866                                                     CAM_BDR_SENT,
1867                                                     "Bus Device Reset",
1868                                                     /*verbose_level*/0);
1869                                 printerror = 0;
1870                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1871                                                 MSG_EXT_PPR, FALSE)) {
1872                                 struct ahc_initiator_tinfo *tinfo;
1873                                 struct ahc_tmode_tstate *tstate;
1874 
1875                                 /*
1876                                  * PPR Rejected.  Try non-ppr negotiation
1877                                  * and retry command.
1878                                  */
1879                                 tinfo = ahc_fetch_transinfo(ahc,
1880                                                             devinfo.channel,
1881                                                             devinfo.our_scsiid,
1882                                                             devinfo.target,
1883                                                             &tstate);
1884                                 tinfo->curr.transport_version = 2;
1885                                 tinfo->goal.transport_version = 2;
1886                                 tinfo->goal.ppr_options = 0;
1887                                 ahc_qinfifo_requeue_tail(ahc, scb);
1888                                 printerror = 0;
1889                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1890                                                 MSG_EXT_WDTR, FALSE)) {
1891                                 /*
1892                                  * Negotiation Rejected.  Go-narrow and
1893                                  * retry command.
1894                                  */
1895                                 ahc_set_width(ahc, &devinfo,
1896                                               MSG_EXT_WDTR_BUS_8_BIT,
1897                                               AHC_TRANS_CUR|AHC_TRANS_GOAL,
1898                                               /*paused*/TRUE);
1899                                 ahc_qinfifo_requeue_tail(ahc, scb);
1900                                 printerror = 0;
1901                         } else if (ahc_sent_msg(ahc, AHCMSG_EXT,
1902                                                 MSG_EXT_SDTR, FALSE)) {
1903                                 /*
1904                                  * Negotiation Rejected.  Go-async and
1905                                  * retry command.
1906                                  */
1907                                 ahc_set_syncrate(ahc, &devinfo,
1908                                                 /*syncrate*/NULL,
1909                                                 /*period*/0, /*offset*/0,
1910                                                 /*ppr_options*/0,
1911                                                 AHC_TRANS_CUR|AHC_TRANS_GOAL,
1912                                                 /*paused*/TRUE);
1913                                 ahc_qinfifo_requeue_tail(ahc, scb);
1914                                 printerror = 0;
1915                         }
1916                 }
1917                 if (printerror != 0) {
1918                         u_int i;
1919 
1920                         if (scb != NULL) {
1921                                 u_int tag;
1922 
1923                                 if ((scb->hscb->control & TAG_ENB) != 0)
1924                                         tag = scb->hscb->tag;
1925                                 else
1926                                         tag = SCB_LIST_NULL;
1927                                 ahc_print_path(ahc, scb);
1928                                 ahc_abort_scbs(ahc, target, channel,
1929                                                SCB_GET_LUN(scb), tag,
1930                                                ROLE_INITIATOR,
1931                                                CAM_UNEXP_BUSFREE);
1932                         } else {
1933                                 /*
1934                                  * We had not fully identified this connection,
1935                                  * so we cannot abort anything.
1936                                  */
1937                                 printf("%s: ", ahc_name(ahc));
1938                         }
1939                         for (i = 0; i < num_phases; i++) {
1940                                 if (lastphase == ahc_phase_table[i].phase)
1941                                         break;
1942                         }
1943                         if (lastphase != P_BUSFREE) {
1944                                 /*
1945                                  * Renegotiate with this device at the
1946                                  * next oportunity just in case this busfree
1947                                  * is due to a negotiation mismatch with the
1948                                  * device.
1949                                  */
1950                                 ahc_force_renegotiation(ahc, &devinfo);
1951                         }
1952                         printf("Unexpected busfree %s\n"
1953                                "SEQADDR == 0x%x\n",
1954                                ahc_phase_table[i].phasemsg,
1955                                ahc_inb(ahc, SEQADDR0)
1956                                 | (ahc_inb(ahc, SEQADDR1) << 8));
1957                 }
1958                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1959                 ahc_restart(ahc);
1960         } else {
1961                 printf("%s: Missing case in ahc_handle_scsiint. status = %x\n",
1962                        ahc_name(ahc), status);
1963                 ahc_outb(ahc, CLRINT, CLRSCSIINT);
1964         }
1965 }
1966 
1967 /*
1968  * Force renegotiation to occur the next time we initiate
1969  * a command to the current device.
1970  */
1971 static void
1972 ahc_force_renegotiation(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
1973 {
1974         struct  ahc_initiator_tinfo *targ_info;
1975         struct  ahc_tmode_tstate *tstate;
1976 
1977         targ_info = ahc_fetch_transinfo(ahc,
1978                                         devinfo->channel,
1979                                         devinfo->our_scsiid,
1980                                         devinfo->target,
1981                                         &tstate);
1982         ahc_update_neg_request(ahc, devinfo, tstate,
1983                                targ_info, AHC_NEG_IF_NON_ASYNC);
1984 }
1985 
1986 #define AHC_MAX_STEPS 2000
1987 static void
1988 ahc_clear_critical_section(struct ahc_softc *ahc)
1989 {
1990         int     stepping;
1991         int     steps;
1992         u_int   simode0;
1993         u_int   simode1;
1994 
1995         if (ahc->num_critical_sections == 0)
1996                 return;
1997 
1998         stepping = FALSE;
1999         steps = 0;
2000         simode0 = 0;
2001         simode1 = 0;
2002         for (;;) {
2003                 struct  cs *cs;
2004                 u_int   seqaddr;
2005                 u_int   i;
2006 
2007                 seqaddr = ahc_inb(ahc, SEQADDR0)
2008                         | (ahc_inb(ahc, SEQADDR1) << 8);
2009 
2010                 /*
2011                  * Seqaddr represents the next instruction to execute, 
2012                  * so we are really executing the instruction just
2013                  * before it.
2014                  */
2015                 if (seqaddr != 0)
2016                         seqaddr -= 1;
2017                 cs = ahc->critical_sections;
2018                 for (i = 0; i < ahc->num_critical_sections; i++, cs++) {
2019                         
2020                         if (cs->begin < seqaddr && cs->end >= seqaddr)
2021                                 break;
2022                 }
2023 
2024                 if (i == ahc->num_critical_sections)
2025                         break;
2026 
2027                 if (steps > AHC_MAX_STEPS) {
2028                         printf("%s: Infinite loop in critical section\n",
2029                                ahc_name(ahc));
2030                         ahc_dump_card_state(ahc);
2031                         panic("critical section loop");
2032                 }
2033 
2034                 steps++;
2035                 if (stepping == FALSE) {
2036 
2037                         /*
2038                          * Disable all interrupt sources so that the
2039                          * sequencer will not be stuck by a pausing
2040                          * interrupt condition while we attempt to
2041                          * leave a critical section.
2042                          */
2043                         simode0 = ahc_inb(ahc, SIMODE0);
2044                         ahc_outb(ahc, SIMODE0, 0);
2045                         simode1 = ahc_inb(ahc, SIMODE1);
2046                         if ((ahc->features & AHC_DT) != 0)
2047                                 /*
2048                                  * On DT class controllers, we
2049                                  * use the enhanced busfree logic.
2050                                  * Unfortunately we cannot re-enable
2051                                  * busfree detection within the
2052                                  * current connection, so we must
2053                                  * leave it on while single stepping.
2054                                  */
2055                                 ahc_outb(ahc, SIMODE1, simode1 & ENBUSFREE);
2056                         else
2057                                 ahc_outb(ahc, SIMODE1, 0);
2058                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
2059                         ahc_outb(ahc, SEQCTL, ahc->seqctl | STEP);
2060                         stepping = TRUE;
2061                 }
2062                 if ((ahc->features & AHC_DT) != 0) {
2063                         ahc_outb(ahc, CLRSINT1, CLRBUSFREE);
2064                         ahc_outb(ahc, CLRINT, CLRSCSIINT);
2065                 }
2066                 ahc_outb(ahc, HCNTRL, ahc->unpause);
2067                 while (!ahc_is_paused(ahc))
2068                         ahc_delay(200);
2069         }
2070         if (stepping) {
2071                 ahc_outb(ahc, SIMODE0, simode0);
2072                 ahc_outb(ahc, SIMODE1, simode1);
2073                 ahc_outb(ahc, SEQCTL, ahc->seqctl);
2074         }
2075 }
2076 
2077 /*
2078  * Clear any pending interrupt status.
2079  */
2080 static void
2081 ahc_clear_intstat(struct ahc_softc *ahc)
2082 {
2083         /* Clear any interrupt conditions this may have caused */
2084         ahc_outb(ahc, CLRSINT1, CLRSELTIMEO|CLRATNO|CLRSCSIRSTI
2085                                 |CLRBUSFREE|CLRSCSIPERR|CLRPHASECHG|
2086                                 CLRREQINIT);
2087         ahc_flush_device_writes(ahc);
2088         ahc_outb(ahc, CLRSINT0, CLRSELDO|CLRSELDI|CLRSELINGO);
2089         ahc_flush_device_writes(ahc);
2090         ahc_outb(ahc, CLRINT, CLRSCSIINT);
2091         ahc_flush_device_writes(ahc);
2092 }
2093 
2094 /**************************** Debugging Routines ******************************/
2095 #ifdef AHC_DEBUG
2096 uint32_t ahc_debug = AHC_DEBUG_OPTS;
2097 #endif
2098 
2099 #if 0 /* unused */
2100 static void
2101 ahc_print_scb(struct scb *scb)
2102 {
2103         int i;
2104 
2105         struct hardware_scb *hscb = scb->hscb;
2106 
2107         printf("scb:%p control:0x%x scsiid:0x%x lun:%d cdb_len:%d\n",
2108                (void *)scb,
2109                hscb->control,
2110                hscb->scsiid,
2111                hscb->lun,
2112                hscb->cdb_len);
2113         printf("Shared Data: ");
2114         for (i = 0; i < sizeof(hscb->shared_data.cdb); i++)
2115                 printf("%#02x", hscb->shared_data.cdb[i]);
2116         printf("        dataptr:%#x datacnt:%#x sgptr:%#x tag:%#x\n",
2117                 ahc_le32toh(hscb->dataptr),
2118                 ahc_le32toh(hscb->datacnt),
2119                 ahc_le32toh(hscb->sgptr),
2120                 hscb->tag);
2121         if (scb->sg_count > 0) {
2122                 for (i = 0; i < scb->sg_count; i++) {
2123                         printf("sg[%d] - Addr 0x%x%x : Length %d\n",
2124                                i,
2125                                (ahc_le32toh(scb->sg_list[i].len) >> 24
2126                                 & SG_HIGH_ADDR_BITS),
2127                                ahc_le32toh(scb->sg_list[i].addr),
2128                                ahc_le32toh(scb->sg_list[i].len));
2129                 }
2130         }
2131 }
2132 #endif
2133 
2134 /************************* Transfer Negotiation *******************************/
2135 /*
2136  * Allocate per target mode instance (ID we respond to as a target)
2137  * transfer negotiation data structures.
2138  */
2139 static struct ahc_tmode_tstate *
2140 ahc_alloc_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel)
2141 {
2142         struct ahc_tmode_tstate *master_tstate;
2143         struct ahc_tmode_tstate *tstate;
2144         int i;
2145 
2146         master_tstate = ahc->enabled_targets[ahc->our_id];
2147         if (channel == 'B') {
2148                 scsi_id += 8;
2149                 master_tstate = ahc->enabled_targets[ahc->our_id_b + 8];
2150         }
2151         if (ahc->enabled_targets[scsi_id] != NULL
2152          && ahc->enabled_targets[scsi_id] != master_tstate)
2153                 panic("%s: ahc_alloc_tstate - Target already allocated",
2154                       ahc_name(ahc));
2155         tstate = (struct ahc_tmode_tstate*)malloc(sizeof(*tstate),
2156                                                    M_DEVBUF, M_NOWAIT);
2157         if (tstate == NULL)
2158                 return (NULL);
2159 
2160         /*
2161          * If we have allocated a master tstate, copy user settings from
2162          * the master tstate (taken from SRAM or the EEPROM) for this
2163          * channel, but reset our current and goal settings to async/narrow
2164          * until an initiator talks to us.
2165          */
2166         if (master_tstate != NULL) {
2167                 memcpy(tstate, master_tstate, sizeof(*tstate));
2168                 memset(tstate->enabled_luns, 0, sizeof(tstate->enabled_luns));
2169                 tstate->ultraenb = 0;
2170                 for (i = 0; i < AHC_NUM_TARGETS; i++) {
2171                         memset(&tstate->transinfo[i].curr, 0,
2172                               sizeof(tstate->transinfo[i].curr));
2173                         memset(&tstate->transinfo[i].goal, 0,
2174                               sizeof(tstate->transinfo[i].goal));
2175                 }
2176         } else
2177                 memset(tstate, 0, sizeof(*tstate));
2178         ahc->enabled_targets[scsi_id] = tstate;
2179         return (tstate);
2180 }
2181 
2182 #ifdef AHC_TARGET_MODE
2183 /*
2184  * Free per target mode instance (ID we respond to as a target)
2185  * transfer negotiation data structures.
2186  */
2187 static void
2188 ahc_free_tstate(struct ahc_softc *ahc, u_int scsi_id, char channel, int force)
2189 {
2190         struct ahc_tmode_tstate *tstate;
2191 
2192         /*
2193          * Don't clean up our "master" tstate.
2194          * It has our default user settings.
2195          */
2196         if (((channel == 'B' && scsi_id == ahc->our_id_b)
2197           || (channel == 'A' && scsi_id == ahc->our_id))
2198          && force == FALSE)
2199                 return;
2200 
2201         if (channel == 'B')
2202                 scsi_id += 8;
2203         tstate = ahc->enabled_targets[scsi_id];
2204         if (tstate != NULL)
2205                 free(tstate, M_DEVBUF);
2206         ahc->enabled_targets[scsi_id] = NULL;
2207 }
2208 #endif
2209 
2210 /*
2211  * Called when we have an active connection to a target on the bus,
2212  * this function finds the nearest syncrate to the input period limited
2213  * by the capabilities of the bus connectivity of and sync settings for
2214  * the target.
2215  */
2216 const struct ahc_syncrate *
2217 ahc_devlimited_syncrate(struct ahc_softc *ahc,
2218                         struct ahc_initiator_tinfo *tinfo,
2219                         u_int *period, u_int *ppr_options, role_t role)
2220 {
2221         struct  ahc_transinfo *transinfo;
2222         u_int   maxsync;
2223 
2224         if ((ahc->features & AHC_ULTRA2) != 0) {
2225                 if ((ahc_inb(ahc, SBLKCTL) & ENAB40) != 0
2226                  && (ahc_inb(ahc, SSTAT2) & EXP_ACTIVE) == 0) {
2227                         maxsync = AHC_SYNCRATE_DT;
2228                 } else {
2229                         maxsync = AHC_SYNCRATE_ULTRA;
2230                         /* Can't do DT on an SE bus */
2231                         *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2232                 }
2233         } else if ((ahc->features & AHC_ULTRA) != 0) {
2234                 maxsync = AHC_SYNCRATE_ULTRA;
2235         } else {
2236                 maxsync = AHC_SYNCRATE_FAST;
2237         }
2238         /*
2239          * Never allow a value higher than our current goal
2240          * period otherwise we may allow a target initiated
2241          * negotiation to go above the limit as set by the
2242          * user.  In the case of an initiator initiated
2243          * sync negotiation, we limit based on the user
2244          * setting.  This allows the system to still accept
2245          * incoming negotiations even if target initiated
2246          * negotiation is not performed.
2247          */
2248         if (role == ROLE_TARGET)
2249                 transinfo = &tinfo->user;
2250         else 
2251                 transinfo = &tinfo->goal;
2252         *ppr_options &= transinfo->ppr_options;
2253         if (transinfo->width == MSG_EXT_WDTR_BUS_8_BIT) {
2254                 maxsync = max(maxsync, (u_int)AHC_SYNCRATE_ULTRA2);
2255                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2256         }
2257         if (transinfo->period == 0) {
2258                 *period = 0;
2259                 *ppr_options = 0;
2260                 return (NULL);
2261         }
2262         *period = max(*period, (u_int)transinfo->period);
2263         return (ahc_find_syncrate(ahc, period, ppr_options, maxsync));
2264 }
2265 
2266 /*
2267  * Look up the valid period to SCSIRATE conversion in our table.
2268  * Return the period and offset that should be sent to the target
2269  * if this was the beginning of an SDTR.
2270  */
2271 const struct ahc_syncrate *
2272 ahc_find_syncrate(struct ahc_softc *ahc, u_int *period,
2273                   u_int *ppr_options, u_int maxsync)
2274 {
2275         const struct ahc_syncrate *syncrate;
2276 
2277         if ((ahc->features & AHC_DT) == 0)
2278                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2279 
2280         /* Skip all DT only entries if DT is not available */
2281         if ((*ppr_options & MSG_EXT_PPR_DT_REQ) == 0
2282          && maxsync < AHC_SYNCRATE_ULTRA2)
2283                 maxsync = AHC_SYNCRATE_ULTRA2;
2284 
2285         /* Now set the maxsync based on the card capabilities
2286          * DT is already done above */
2287         if ((ahc->features & (AHC_DT | AHC_ULTRA2)) == 0
2288             && maxsync < AHC_SYNCRATE_ULTRA)
2289                 maxsync = AHC_SYNCRATE_ULTRA;
2290         if ((ahc->features & (AHC_DT | AHC_ULTRA2 | AHC_ULTRA)) == 0
2291             && maxsync < AHC_SYNCRATE_FAST)
2292                 maxsync = AHC_SYNCRATE_FAST;
2293 
2294         for (syncrate = &ahc_syncrates[maxsync];
2295              syncrate->rate != NULL;
2296              syncrate++) {
2297 
2298                 /*
2299                  * The Ultra2 table doesn't go as low
2300                  * as for the Fast/Ultra cards.
2301                  */
2302                 if ((ahc->features & AHC_ULTRA2) != 0
2303                  && (syncrate->sxfr_u2 == 0))
2304                         break;
2305 
2306                 if (*period <= syncrate->period) {
2307                         /*
2308                          * When responding to a target that requests
2309                          * sync, the requested rate may fall between
2310                          * two rates that we can output, but still be
2311                          * a rate that we can receive.  Because of this,
2312                          * we want to respond to the target with
2313                          * the same rate that it sent to us even
2314                          * if the period we use to send data to it
2315                          * is lower.  Only lower the response period
2316                          * if we must.
2317                          */
2318                         if (syncrate == &ahc_syncrates[maxsync])
2319                                 *period = syncrate->period;
2320 
2321                         /*
2322                          * At some speeds, we only support
2323                          * ST transfers.
2324                          */
2325                         if ((syncrate->sxfr_u2 & ST_SXFR) != 0)
2326                                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2327                         break;
2328                 }
2329         }
2330 
2331         if ((*period == 0)
2332          || (syncrate->rate == NULL)
2333          || ((ahc->features & AHC_ULTRA2) != 0
2334           && (syncrate->sxfr_u2 == 0))) {
2335                 /* Use asynchronous transfers. */
2336                 *period = 0;
2337                 syncrate = NULL;
2338                 *ppr_options &= ~MSG_EXT_PPR_DT_REQ;
2339         }
2340         return (syncrate);
2341 }
2342 
2343 /*
2344  * Convert from an entry in our syncrate table to the SCSI equivalent
2345  * sync "period" factor.
2346  */
2347 u_int
2348 ahc_find_period(struct ahc_softc *ahc, u_int scsirate, u_int maxsync)
2349 {
2350         const struct ahc_syncrate *syncrate;
2351 
2352         if ((ahc->features & AHC_ULTRA2) != 0)
2353                 scsirate &= SXFR_ULTRA2;
2354         else
2355                 scsirate &= SXFR;
2356 
2357         /* now set maxsync based on card capabilities */
2358         if ((ahc->features & AHC_DT) == 0 && maxsync < AHC_SYNCRATE_ULTRA2)
2359                 maxsync = AHC_SYNCRATE_ULTRA2;
2360         if ((ahc->features & (AHC_DT | AHC_ULTRA2)) == 0
2361             && maxsync < AHC_SYNCRATE_ULTRA)
2362                 maxsync = AHC_SYNCRATE_ULTRA;
2363         if ((ahc->features & (AHC_DT | AHC_ULTRA2 | AHC_ULTRA)) == 0
2364             && maxsync < AHC_SYNCRATE_FAST)
2365                 maxsync = AHC_SYNCRATE_FAST;
2366 
2367 
2368         syncrate = &ahc_syncrates[maxsync];
2369         while (syncrate->rate != NULL) {
2370 
2371                 if ((ahc->features & AHC_ULTRA2) != 0) {
2372                         if (syncrate->sxfr_u2 == 0)
2373                                 break;
2374                         else if (scsirate == (syncrate->sxfr_u2 & SXFR_ULTRA2))
2375                                 return (syncrate->period);
2376                 } else if (scsirate == (syncrate->sxfr & SXFR)) {
2377                                 return (syncrate->period);
2378                 }
2379                 syncrate++;
2380         }
2381         return (0); /* async */
2382 }
2383 
2384 /*
2385  * Truncate the given synchronous offset to a value the
2386  * current adapter type and syncrate are capable of.
2387  */
2388 static void
2389 ahc_validate_offset(struct ahc_softc *ahc,
2390                     struct ahc_initiator_tinfo *tinfo,
2391                     const struct ahc_syncrate *syncrate,
2392                     u_int *offset, int wide, role_t role)
2393 {
2394         u_int maxoffset;
2395 
2396         /* Limit offset to what we can do */
2397         if (syncrate == NULL) {
2398                 maxoffset = 0;
2399         } else if ((ahc->features & AHC_ULTRA2) != 0) {
2400                 maxoffset = MAX_OFFSET_ULTRA2;
2401         } else {
2402                 if (wide)
2403                         maxoffset = MAX_OFFSET_16BIT;
2404                 else
2405                         maxoffset = MAX_OFFSET_8BIT;
2406         }
2407         *offset = min(*offset, maxoffset);
2408         if (tinfo != NULL) {
2409                 if (role == ROLE_TARGET)
2410                         *offset = min(*offset, (u_int)tinfo->user.offset);
2411                 else
2412                         *offset = min(*offset, (u_int)tinfo->goal.offset);
2413         }
2414 }
2415 
2416 /*
2417  * Truncate the given transfer width parameter to a value the
2418  * current adapter type is capable of.
2419  */
2420 static void
2421 ahc_validate_width(struct ahc_softc *ahc, struct ahc_initiator_tinfo *tinfo,
2422                    u_int *bus_width, role_t role)
2423 {
2424         switch (*bus_width) {
2425         default:
2426                 if (ahc->features & AHC_WIDE) {
2427                         /* Respond Wide */
2428                         *bus_width = MSG_EXT_WDTR_BUS_16_BIT;
2429                         break;
2430                 }
2431                 /* FALLTHROUGH */
2432         case MSG_EXT_WDTR_BUS_8_BIT:
2433                 *bus_width = MSG_EXT_WDTR_BUS_8_BIT;
2434                 break;
2435         }
2436         if (tinfo != NULL) {
2437                 if (role == ROLE_TARGET)
2438                         *bus_width = min((u_int)tinfo->user.width, *bus_width);
2439                 else
2440                         *bus_width = min((u_int)tinfo->goal.width, *bus_width);
2441         }
2442 }
2443 
2444 /*
2445  * Update the bitmask of targets for which the controller should
2446  * negotiate with at the next convenient oportunity.  This currently
2447  * means the next time we send the initial identify messages for
2448  * a new transaction.
2449  */
2450 int
2451 ahc_update_neg_request(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2452                        struct ahc_tmode_tstate *tstate,
2453                        struct ahc_initiator_tinfo *tinfo, ahc_neg_type neg_type)
2454 {
2455         u_int auto_negotiate_orig;
2456 
2457         auto_negotiate_orig = tstate->auto_negotiate;
2458         if (neg_type == AHC_NEG_ALWAYS) {
2459                 /*
2460                  * Force our "current" settings to be
2461                  * unknown so that unless a bus reset
2462                  * occurs the need to renegotiate is
2463                  * recorded persistently.
2464                  */
2465                 if ((ahc->features & AHC_WIDE) != 0)
2466                         tinfo->curr.width = AHC_WIDTH_UNKNOWN;
2467                 tinfo->curr.period = AHC_PERIOD_UNKNOWN;
2468                 tinfo->curr.offset = AHC_OFFSET_UNKNOWN;
2469         }
2470         if (tinfo->curr.period != tinfo->goal.period
2471          || tinfo->curr.width != tinfo->goal.width
2472          || tinfo->curr.offset != tinfo->goal.offset
2473          || tinfo->curr.ppr_options != tinfo->goal.ppr_options
2474          || (neg_type == AHC_NEG_IF_NON_ASYNC
2475           && (tinfo->goal.offset != 0
2476            || tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT
2477            || tinfo->goal.ppr_options != 0)))
2478                 tstate->auto_negotiate |= devinfo->target_mask;
2479         else
2480                 tstate->auto_negotiate &= ~devinfo->target_mask;
2481 
2482         return (auto_negotiate_orig != tstate->auto_negotiate);
2483 }
2484 
2485 /*
2486  * Update the user/goal/curr tables of synchronous negotiation
2487  * parameters as well as, in the case of a current or active update,
2488  * any data structures on the host controller.  In the case of an
2489  * active update, the specified target is currently talking to us on
2490  * the bus, so the transfer parameter update must take effect
2491  * immediately.
2492  */
2493 void
2494 ahc_set_syncrate(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2495                  const struct ahc_syncrate *syncrate, u_int period,
2496                  u_int offset, u_int ppr_options, u_int type, int paused)
2497 {
2498         struct  ahc_initiator_tinfo *tinfo;
2499         struct  ahc_tmode_tstate *tstate;
2500         u_int   old_period;
2501         u_int   old_offset;
2502         u_int   old_ppr;
2503         int     active;
2504         int     update_needed;
2505 
2506         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
2507         update_needed = 0;
2508 
2509         if (syncrate == NULL) {
2510                 period = 0;
2511                 offset = 0;
2512         }
2513 
2514         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2515                                     devinfo->target, &tstate);
2516 
2517         if ((type & AHC_TRANS_USER) != 0) {
2518                 tinfo->user.period = period;
2519                 tinfo->user.offset = offset;
2520                 tinfo->user.ppr_options = ppr_options;
2521         }
2522 
2523         if ((type & AHC_TRANS_GOAL) != 0) {
2524                 tinfo->goal.period = period;
2525                 tinfo->goal.offset = offset;
2526                 tinfo->goal.ppr_options = ppr_options;
2527         }
2528 
2529         old_period = tinfo->curr.period;
2530         old_offset = tinfo->curr.offset;
2531         old_ppr    = tinfo->curr.ppr_options;
2532 
2533         if ((type & AHC_TRANS_CUR) != 0
2534          && (old_period != period
2535           || old_offset != offset
2536           || old_ppr != ppr_options)) {
2537                 u_int   scsirate;
2538 
2539                 update_needed++;
2540                 scsirate = tinfo->scsirate;
2541                 if ((ahc->features & AHC_ULTRA2) != 0) {
2542 
2543                         scsirate &= ~(SXFR_ULTRA2|SINGLE_EDGE|ENABLE_CRC);
2544                         if (syncrate != NULL) {
2545                                 scsirate |= syncrate->sxfr_u2;
2546                                 if ((ppr_options & MSG_EXT_PPR_DT_REQ) != 0)
2547                                         scsirate |= ENABLE_CRC;
2548                                 else
2549                                         scsirate |= SINGLE_EDGE;
2550                         }
2551                 } else {
2552 
2553                         scsirate &= ~(SXFR|SOFS);
2554                         /*
2555                          * Ensure Ultra mode is set properly for
2556                          * this target.
2557                          */
2558                         tstate->ultraenb &= ~devinfo->target_mask;
2559                         if (syncrate != NULL) {
2560                                 if (syncrate->sxfr & ULTRA_SXFR) {
2561                                         tstate->ultraenb |=
2562                                                 devinfo->target_mask;
2563                                 }
2564                                 scsirate |= syncrate->sxfr & SXFR;
2565                                 scsirate |= offset & SOFS;
2566                         }
2567                         if (active) {
2568                                 u_int sxfrctl0;
2569 
2570                                 sxfrctl0 = ahc_inb(ahc, SXFRCTL0);
2571                                 sxfrctl0 &= ~FAST20;
2572                                 if (tstate->ultraenb & devinfo->target_mask)
2573                                         sxfrctl0 |= FAST20;
2574                                 ahc_outb(ahc, SXFRCTL0, sxfrctl0);
2575                         }
2576                 }
2577                 if (active) {
2578                         ahc_outb(ahc, SCSIRATE, scsirate);
2579                         if ((ahc->features & AHC_ULTRA2) != 0)
2580                                 ahc_outb(ahc, SCSIOFFSET, offset);
2581                 }
2582 
2583                 tinfo->scsirate = scsirate;
2584                 tinfo->curr.period = period;
2585                 tinfo->curr.offset = offset;
2586                 tinfo->curr.ppr_options = ppr_options;
2587 
2588                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
2589                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
2590                 if (bootverbose) {
2591                         if (offset != 0) {
2592                                 printf("%s: target %d synchronous at %sMHz%s, "
2593                                        "offset = 0x%x\n", ahc_name(ahc),
2594                                        devinfo->target, syncrate->rate,
2595                                        (ppr_options & MSG_EXT_PPR_DT_REQ)
2596                                        ? " DT" : "", offset);
2597                         } else {
2598                                 printf("%s: target %d using "
2599                                        "asynchronous transfers\n",
2600                                        ahc_name(ahc), devinfo->target);
2601                         }
2602                 }
2603         }
2604 
2605         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2606                                                 tinfo, AHC_NEG_TO_GOAL);
2607 
2608         if (update_needed)
2609                 ahc_update_pending_scbs(ahc);
2610 }
2611 
2612 /*
2613  * Update the user/goal/curr tables of wide negotiation
2614  * parameters as well as, in the case of a current or active update,
2615  * any data structures on the host controller.  In the case of an
2616  * active update, the specified target is currently talking to us on
2617  * the bus, so the transfer parameter update must take effect
2618  * immediately.
2619  */
2620 void
2621 ahc_set_width(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2622               u_int width, u_int type, int paused)
2623 {
2624         struct  ahc_initiator_tinfo *tinfo;
2625         struct  ahc_tmode_tstate *tstate;
2626         u_int   oldwidth;
2627         int     active;
2628         int     update_needed;
2629 
2630         active = (type & AHC_TRANS_ACTIVE) == AHC_TRANS_ACTIVE;
2631         update_needed = 0;
2632         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2633                                     devinfo->target, &tstate);
2634 
2635         if ((type & AHC_TRANS_USER) != 0)
2636                 tinfo->user.width = width;
2637 
2638         if ((type & AHC_TRANS_GOAL) != 0)
2639                 tinfo->goal.width = width;
2640 
2641         oldwidth = tinfo->curr.width;
2642         if ((type & AHC_TRANS_CUR) != 0 && oldwidth != width) {
2643                 u_int   scsirate;
2644 
2645                 update_needed++;
2646                 scsirate =  tinfo->scsirate;
2647                 scsirate &= ~WIDEXFER;
2648                 if (width == MSG_EXT_WDTR_BUS_16_BIT)
2649                         scsirate |= WIDEXFER;
2650 
2651                 tinfo->scsirate = scsirate;
2652 
2653                 if (active)
2654                         ahc_outb(ahc, SCSIRATE, scsirate);
2655 
2656                 tinfo->curr.width = width;
2657 
2658                 ahc_send_async(ahc, devinfo->channel, devinfo->target,
2659                                CAM_LUN_WILDCARD, AC_TRANSFER_NEG);
2660                 if (bootverbose) {
2661                         printf("%s: target %d using %dbit transfers\n",
2662                                ahc_name(ahc), devinfo->target,
2663                                8 * (0x01 << width));
2664                 }
2665         }
2666 
2667         update_needed += ahc_update_neg_request(ahc, devinfo, tstate,
2668                                                 tinfo, AHC_NEG_TO_GOAL);
2669         if (update_needed)
2670                 ahc_update_pending_scbs(ahc);
2671 }
2672 
2673 /*
2674  * Update the current state of tagged queuing for a given target.
2675  */
2676 static void
2677 ahc_set_tags(struct ahc_softc *ahc, struct scsi_cmnd *cmd,
2678              struct ahc_devinfo *devinfo, ahc_queue_alg alg)
2679 {
2680         struct scsi_device *sdev = cmd->device;
2681 
2682         ahc_platform_set_tags(ahc, sdev, devinfo, alg);
2683         ahc_send_async(ahc, devinfo->channel, devinfo->target,
2684                        devinfo->lun, AC_TRANSFER_NEG);
2685 }
2686 
2687 /*
2688  * When the transfer settings for a connection change, update any
2689  * in-transit SCBs to contain the new data so the hardware will
2690  * be set correctly during future (re)selections.
2691  */
2692 static void
2693 ahc_update_pending_scbs(struct ahc_softc *ahc)
2694 {
2695         struct  scb *pending_scb;
2696         int     pending_scb_count;
2697         int     i;
2698         int     paused;
2699         u_int   saved_scbptr;
2700 
2701         /*
2702          * Traverse the pending SCB list and ensure that all of the
2703          * SCBs there have the proper settings.
2704          */
2705         pending_scb_count = 0;
2706         LIST_FOREACH(pending_scb, &ahc->pending_scbs, pending_links) {
2707                 struct ahc_devinfo devinfo;
2708                 struct hardware_scb *pending_hscb;
2709                 struct ahc_initiator_tinfo *tinfo;
2710                 struct ahc_tmode_tstate *tstate;
2711 
2712                 ahc_scb_devinfo(ahc, &devinfo, pending_scb);
2713                 tinfo = ahc_fetch_transinfo(ahc, devinfo.channel,
2714                                             devinfo.our_scsiid,
2715                                             devinfo.target, &tstate);
2716                 pending_hscb = pending_scb->hscb;
2717                 pending_hscb->control &= ~ULTRAENB;
2718                 if ((tstate->ultraenb & devinfo.target_mask) != 0)
2719                         pending_hscb->control |= ULTRAENB;
2720                 pending_hscb->scsirate = tinfo->scsirate;
2721                 pending_hscb->scsioffset = tinfo->curr.offset;
2722                 if ((tstate->auto_negotiate & devinfo.target_mask) == 0
2723                  && (pending_scb->flags & SCB_AUTO_NEGOTIATE) != 0) {
2724                         pending_scb->flags &= ~SCB_AUTO_NEGOTIATE;
2725                         pending_hscb->control &= ~MK_MESSAGE;
2726                 }
2727                 ahc_sync_scb(ahc, pending_scb,
2728                              BUS_DMASYNC_PREREAD|BUS_DMASYNC_PREWRITE);
2729                 pending_scb_count++;
2730         }
2731 
2732         if (pending_scb_count == 0)
2733                 return;
2734 
2735         if (ahc_is_paused(ahc)) {
2736                 paused = 1;
2737         } else {
2738                 paused = 0;
2739                 ahc_pause(ahc);
2740         }
2741 
2742         saved_scbptr = ahc_inb(ahc, SCBPTR);
2743         /* Ensure that the hscbs down on the card match the new information */
2744         for (i = 0; i < ahc->scb_data->maxhscbs; i++) {
2745                 struct  hardware_scb *pending_hscb;
2746                 u_int   control;
2747                 u_int   scb_tag;
2748 
2749                 ahc_outb(ahc, SCBPTR, i);
2750                 scb_tag = ahc_inb(ahc, SCB_TAG);
2751                 pending_scb = ahc_lookup_scb(ahc, scb_tag);
2752                 if (pending_scb == NULL)
2753                         continue;
2754 
2755                 pending_hscb = pending_scb->hscb;
2756                 control = ahc_inb(ahc, SCB_CONTROL);
2757                 control &= ~(ULTRAENB|MK_MESSAGE);
2758                 control |= pending_hscb->control & (ULTRAENB|MK_MESSAGE);
2759                 ahc_outb(ahc, SCB_CONTROL, control);
2760                 ahc_outb(ahc, SCB_SCSIRATE, pending_hscb->scsirate);
2761                 ahc_outb(ahc, SCB_SCSIOFFSET, pending_hscb->scsioffset);
2762         }
2763         ahc_outb(ahc, SCBPTR, saved_scbptr);
2764 
2765         if (paused == 0)
2766                 ahc_unpause(ahc);
2767 }
2768 
2769 /**************************** Pathing Information *****************************/
2770 static void
2771 ahc_fetch_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2772 {
2773         u_int   saved_scsiid;
2774         role_t  role;
2775         int     our_id;
2776 
2777         if (ahc_inb(ahc, SSTAT0) & TARGET)
2778                 role = ROLE_TARGET;
2779         else
2780                 role = ROLE_INITIATOR;
2781 
2782         if (role == ROLE_TARGET
2783          && (ahc->features & AHC_MULTI_TID) != 0
2784          && (ahc_inb(ahc, SEQ_FLAGS)
2785            & (CMDPHASE_PENDING|TARG_CMD_PENDING|NO_DISCONNECT)) != 0) {
2786                 /* We were selected, so pull our id from TARGIDIN */
2787                 our_id = ahc_inb(ahc, TARGIDIN) & OID;
2788         } else if ((ahc->features & AHC_ULTRA2) != 0)
2789                 our_id = ahc_inb(ahc, SCSIID_ULTRA2) & OID;
2790         else
2791                 our_id = ahc_inb(ahc, SCSIID) & OID;
2792 
2793         saved_scsiid = ahc_inb(ahc, SAVED_SCSIID);
2794         ahc_compile_devinfo(devinfo,
2795                             our_id,
2796                             SCSIID_TARGET(ahc, saved_scsiid),
2797                             ahc_inb(ahc, SAVED_LUN),
2798                             SCSIID_CHANNEL(ahc, saved_scsiid),
2799                             role);
2800 }
2801 
2802 static const struct ahc_phase_table_entry*
2803 ahc_lookup_phase_entry(int phase)
2804 {
2805         const struct ahc_phase_table_entry *entry;
2806         const struct ahc_phase_table_entry *last_entry;
2807 
2808         /*
2809          * num_phases doesn't include the default entry which
2810          * will be returned if the phase doesn't match.
2811          */
2812         last_entry = &ahc_phase_table[num_phases];
2813         for (entry = ahc_phase_table; entry < last_entry; entry++) {
2814                 if (phase == entry->phase)
2815                         break;
2816         }
2817         return (entry);
2818 }
2819 
2820 void
2821 ahc_compile_devinfo(struct ahc_devinfo *devinfo, u_int our_id, u_int target,
2822                     u_int lun, char channel, role_t role)
2823 {
2824         devinfo->our_scsiid = our_id;
2825         devinfo->target = target;
2826         devinfo->lun = lun;
2827         devinfo->target_offset = target;
2828         devinfo->channel = channel;
2829         devinfo->role = role;
2830         if (channel == 'B')
2831                 devinfo->target_offset += 8;
2832         devinfo->target_mask = (0x01 << devinfo->target_offset);
2833 }
2834 
2835 void
2836 ahc_print_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2837 {
2838         printf("%s:%c:%d:%d: ", ahc_name(ahc), devinfo->channel,
2839                devinfo->target, devinfo->lun);
2840 }
2841 
2842 static void
2843 ahc_scb_devinfo(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2844                 struct scb *scb)
2845 {
2846         role_t  role;
2847         int     our_id;
2848 
2849         our_id = SCSIID_OUR_ID(scb->hscb->scsiid);
2850         role = ROLE_INITIATOR;
2851         if ((scb->flags & SCB_TARGET_SCB) != 0)
2852                 role = ROLE_TARGET;
2853         ahc_compile_devinfo(devinfo, our_id, SCB_GET_TARGET(ahc, scb),
2854                             SCB_GET_LUN(scb), SCB_GET_CHANNEL(ahc, scb), role);
2855 }
2856 
2857 
2858 /************************ Message Phase Processing ****************************/
2859 static void
2860 ahc_assert_atn(struct ahc_softc *ahc)
2861 {
2862         u_int scsisigo;
2863 
2864         scsisigo = ATNO;
2865         if ((ahc->features & AHC_DT) == 0)
2866                 scsisigo |= ahc_inb(ahc, SCSISIGI);
2867         ahc_outb(ahc, SCSISIGO, scsisigo);
2868 }
2869 
2870 /*
2871  * When an initiator transaction with the MK_MESSAGE flag either reconnects
2872  * or enters the initial message out phase, we are interrupted.  Fill our
2873  * outgoing message buffer with the appropriate message and beging handing
2874  * the message phase(s) manually.
2875  */
2876 static void
2877 ahc_setup_initiator_msgout(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
2878                            struct scb *scb)
2879 {
2880         /*
2881          * To facilitate adding multiple messages together,
2882          * each routine should increment the index and len
2883          * variables instead of setting them explicitly.
2884          */
2885         ahc->msgout_index = 0;
2886         ahc->msgout_len = 0;
2887 
2888         if ((scb->flags & SCB_DEVICE_RESET) == 0
2889          && ahc_inb(ahc, MSG_OUT) == MSG_IDENTIFYFLAG) {
2890                 u_int identify_msg;
2891 
2892                 identify_msg = MSG_IDENTIFYFLAG | SCB_GET_LUN(scb);
2893                 if ((scb->hscb->control & DISCENB) != 0)
2894                         identify_msg |= MSG_IDENTIFY_DISCFLAG;
2895                 ahc->msgout_buf[ahc->msgout_index++] = identify_msg;
2896                 ahc->msgout_len++;
2897 
2898                 if ((scb->hscb->control & TAG_ENB) != 0) {
2899                         ahc->msgout_buf[ahc->msgout_index++] =
2900                             scb->hscb->control & (TAG_ENB|SCB_TAG_TYPE);
2901                         ahc->msgout_buf[ahc->msgout_index++] = scb->hscb->tag;
2902                         ahc->msgout_len += 2;
2903                 }
2904         }
2905 
2906         if (scb->flags & SCB_DEVICE_RESET) {
2907                 ahc->msgout_buf[ahc->msgout_index++] = MSG_BUS_DEV_RESET;
2908                 ahc->msgout_len++;
2909                 ahc_print_path(ahc, scb);
2910                 printf("Bus Device Reset Message Sent\n");
2911                 /*
2912                  * Clear our selection hardware in advance of
2913                  * the busfree.  We may have an entry in the waiting
2914                  * Q for this target, and we don't want to go about
2915                  * selecting while we handle the busfree and blow it
2916                  * away.
2917                  */
2918                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2919         } else if ((scb->flags & SCB_ABORT) != 0) {
2920                 if ((scb->hscb->control & TAG_ENB) != 0)
2921                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT_TAG;
2922                 else
2923                         ahc->msgout_buf[ahc->msgout_index++] = MSG_ABORT;
2924                 ahc->msgout_len++;
2925                 ahc_print_path(ahc, scb);
2926                 printf("Abort%s Message Sent\n",
2927                        (scb->hscb->control & TAG_ENB) != 0 ? " Tag" : "");
2928                 /*
2929                  * Clear our selection hardware in advance of
2930                  * the busfree.  We may have an entry in the waiting
2931                  * Q for this target, and we don't want to go about
2932                  * selecting while we handle the busfree and blow it
2933                  * away.
2934                  */
2935                 ahc_outb(ahc, SCSISEQ, (ahc_inb(ahc, SCSISEQ) & ~ENSELO));
2936         } else if ((scb->flags & (SCB_AUTO_NEGOTIATE|SCB_NEGOTIATE)) != 0) {
2937                 ahc_build_transfer_msg(ahc, devinfo);
2938         } else {
2939                 printf("ahc_intr: AWAITING_MSG for an SCB that "
2940                        "does not have a waiting message\n");
2941                 printf("SCSIID = %x, target_mask = %x\n", scb->hscb->scsiid,
2942                        devinfo->target_mask);
2943                 panic("SCB = %d, SCB Control = %x, MSG_OUT = %x "
2944                       "SCB flags = %x", scb->hscb->tag, scb->hscb->control,
2945                       ahc_inb(ahc, MSG_OUT), scb->flags);
2946         }
2947 
2948         /*
2949          * Clear the MK_MESSAGE flag from the SCB so we aren't
2950          * asked to send this message again.
2951          */
2952         ahc_outb(ahc, SCB_CONTROL, ahc_inb(ahc, SCB_CONTROL) & ~MK_MESSAGE);
2953         scb->hscb->control &= ~MK_MESSAGE;
2954         ahc->msgout_index = 0;
2955         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
2956 }
2957 
2958 /*
2959  * Build an appropriate transfer negotiation message for the
2960  * currently active target.
2961  */
2962 static void
2963 ahc_build_transfer_msg(struct ahc_softc *ahc, struct ahc_devinfo *devinfo)
2964 {
2965         /*
2966          * We need to initiate transfer negotiations.
2967          * If our current and goal settings are identical,
2968          * we want to renegotiate due to a check condition.
2969          */
2970         struct  ahc_initiator_tinfo *tinfo;
2971         struct  ahc_tmode_tstate *tstate;
2972         const struct ahc_syncrate *rate;
2973         int     dowide;
2974         int     dosync;
2975         int     doppr;
2976         u_int   period;
2977         u_int   ppr_options;
2978         u_int   offset;
2979 
2980         tinfo = ahc_fetch_transinfo(ahc, devinfo->channel, devinfo->our_scsiid,
2981                                     devinfo->target, &tstate);
2982         /*
2983          * Filter our period based on the current connection.
2984          * If we can't perform DT transfers on this segment (not in LVD
2985          * mode for instance), then our decision to issue a PPR message
2986          * may change.
2987          */
2988         period = tinfo->goal.period;
2989         offset = tinfo->goal.offset;
2990         ppr_options = tinfo->goal.ppr_options;
2991         /* Target initiated PPR is not allowed in the SCSI spec */
2992         if (devinfo->role == ROLE_TARGET)
2993                 ppr_options = 0;
2994         rate = ahc_devlimited_syncrate(ahc, tinfo, &period,
2995                                        &ppr_options, devinfo->role);
2996         dowide = tinfo->curr.width != tinfo->goal.width;
2997         dosync = tinfo->curr.offset != offset || tinfo->curr.period != period;
2998         /*
2999          * Only use PPR if we have options that need it, even if the device
3000          * claims to support it.  There might be an expander in the way
3001          * that doesn't.
3002          */
3003         doppr = ppr_options != 0;
3004 
3005         if (!dowide && !dosync && !doppr) {
3006                 dowide = tinfo->goal.width != MSG_EXT_WDTR_BUS_8_BIT;
3007                 dosync = tinfo->goal.offset != 0;
3008         }
3009 
3010         if (!dowide && !dosync && !doppr) {
3011                 /*
3012                  * Force async with a WDTR message if we have a wide bus,
3013                  * or just issue an SDTR with a 0 offset.
3014                  */
3015                 if ((ahc->features & AHC_WIDE) != 0)
3016                         dowide = 1;
3017                 else
3018                         dosync = 1;
3019 
3020                 if (bootverbose) {
3021                         ahc_print_devinfo(ahc, devinfo);
3022                         printf("Ensuring async\n");
3023                 }
3024         }
3025 
3026         /* Target initiated PPR is not allowed in the SCSI spec */
3027         if (devinfo->role == ROLE_TARGET)
3028                 doppr = 0;
3029 
3030         /*
3031          * Both the PPR message and SDTR message require the
3032          * goal syncrate to be limited to what the target device
3033          * is capable of handling (based on whether an LVD->SE
3034          * expander is on the bus), so combine these two cases.
3035          * Regardless, guarantee that if we are using WDTR and SDTR
3036          * messages that WDTR comes first.
3037          */
3038         if (doppr || (dosync && !dowide)) {
3039 
3040                 offset = tinfo->goal.offset;
3041                 ahc_validate_offset(ahc, tinfo, rate, &offset,
3042                                     doppr ? tinfo->goal.width
3043                                           : tinfo->curr.width,
3044                                     devinfo->role);
3045                 if (doppr) {
3046                         ahc_construct_ppr(ahc, devinfo, period, offset,
3047                                           tinfo->goal.width, ppr_options);
3048                 } else {
3049                         ahc_construct_sdtr(ahc, devinfo, period, offset);
3050                 }
3051         } else {
3052                 ahc_construct_wdtr(ahc, devinfo, tinfo->goal.width);
3053         }
3054 }
3055 
3056 /*
3057  * Build a synchronous negotiation message in our message
3058  * buffer based on the input parameters.
3059  */
3060 static void
3061 ahc_construct_sdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3062                    u_int period, u_int offset)
3063 {
3064         if (offset == 0)
3065                 period = AHC_ASYNC_XFER_PERIOD;
3066         ahc->msgout_index += spi_populate_sync_msg(
3067                         ahc->msgout_buf + ahc->msgout_index, period, offset);
3068         ahc->msgout_len += 5;
3069         if (bootverbose) {
3070                 printf("(%s:%c:%d:%d): Sending SDTR period %x, offset %x\n",
3071                        ahc_name(ahc), devinfo->channel, devinfo->target,
3072                        devinfo->lun, period, offset);
3073         }
3074 }
3075 
3076 /*
3077  * Build a wide negotiation message in our message
3078  * buffer based on the input parameters.
3079  */
3080 static void
3081 ahc_construct_wdtr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3082                    u_int bus_width)
3083 {
3084         ahc->msgout_index += spi_populate_width_msg(
3085                         ahc->msgout_buf + ahc->msgout_index, bus_width);
3086         ahc->msgout_len += 4;
3087         if (bootverbose) {
3088                 printf("(%s:%c:%d:%d): Sending WDTR %x\n",
3089                        ahc_name(ahc), devinfo->channel, devinfo->target,
3090                        devinfo->lun, bus_width);
3091         }
3092 }
3093 
3094 /*
3095  * Build a parallel protocol request message in our message
3096  * buffer based on the input parameters.
3097  */
3098 static void
3099 ahc_construct_ppr(struct ahc_softc *ahc, struct ahc_devinfo *devinfo,
3100                   u_int period, u_int offset, u_int bus_width,
3101                   u_int ppr_options)
3102 {
3103         if (offset == 0)
3104                 period = AHC_ASYNC_XFER_PERIOD;
3105         ahc->msgout_index += spi_populate_ppr_msg(
3106                         ahc->msgout_buf + ahc->msgout_index, period, offset,
3107                         bus_width, ppr_options);
3108         ahc->msgout_len += 8;
3109         if (bootverbose) {
3110                 printf("(%s:%c:%d:%d): Sending PPR bus_width %x, period %x, "
3111                        "offset %x, ppr_options %x\n", ahc_name(ahc),
3112                        devinfo->channel, devinfo->target, devinfo->lun,
3113                        bus_width, period, offset, ppr_options);
3114         }
3115 }
3116 
3117 /*
3118  * Clear any active message state.
3119  */
3120 static void
3121 ahc_clear_msg_state(struct ahc_softc *ahc)
3122 {
3123         ahc->msgout_len = 0;
3124         ahc->msgin_index = 0;
3125         ahc->msg_type = MSG_TYPE_NONE;
3126         if ((ahc_inb(ahc, SCSISIGI) & ATNI) != 0) {
3127                 /*
3128                  * The target didn't care to respond to our
3129                  * message request, so clear ATN.
3130                  */
3131                 ahc_outb(ahc, CLRSINT1, CLRATNO);
3132         }
3133         ahc_outb(ahc, MSG_OUT, MSG_NOOP);
3134         ahc_outb(ahc, SEQ_FLAGS2,
3135                  ahc_inb(ahc, SEQ_FLAGS2) & ~TARGET_MSG_PENDING);
3136 }
3137 
3138 static void
3139 ahc_handle_proto_violation(struct ahc_softc *ahc)
3140 {
3141         struct  ahc_devinfo devinfo;
3142         struct  scb *scb;
3143         u_int   scbid;
3144         u_int   seq_flags;
3145         u_int   curphase;
3146         u_int   lastphase;
3147         int     found;
3148 
3149         ahc_fetch_devinfo(ahc, &devinfo);
3150         scbid = ahc_inb(ahc, SCB_TAG);
3151         scb = ahc_lookup_scb(ahc, scbid);
3152         seq_flags = ahc_inb(ahc, SEQ_FLAGS);
3153         curphase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
3154         lastphase = ahc_inb(ahc, LASTPHASE);
3155         if ((seq_flags & NOT_IDENTIFIED) != 0) {
3156 
3157                 /*
3158                  * The reconnecting target either did not send an
3159                  * identify message, or did, but we didn't find an SCB
3160                  * to match.
3161                  */
3162                 ahc_print_devinfo(ahc, &devinfo);
3163                 printf("Target did not send an IDENTIFY message. "
3164                        "LASTPHASE = 0x%x.\n", lastphase);
3165                 scb = NULL;
3166         } else if (scb == NULL) {
3167                 /*
3168                  * We don't seem to have an SCB active for this
3169                  * transaction.  Print an error and reset the bus.
3170                  */
3171                 ahc_print_devinfo(ahc, &devinfo);
3172                 printf("No SCB found during protocol violation\n");
3173                 goto proto_violation_reset;
3174         } else {
3175                 ahc_set_transaction_status(scb, CAM_SEQUENCE_FAIL);
3176                 if ((seq_flags & NO_CDB_SENT) != 0) {
3177                         ahc_print_path(ahc, scb);
3178                         printf("No or incomplete CDB sent to device.\n");
3179                 } else if ((ahc_inb(ahc, SCB_CONTROL) & STATUS_RCVD) == 0) {
3180                         /*
3181                          * The target never bothered to provide status to
3182                          * us prior to completing the command.  Since we don't
3183                          * know the disposition of this command, we must attempt
3184                          * to abort it.  Assert ATN and prepare to send an abort
3185                          * message.
3186                          */
3187                         ahc_print_path(ahc, scb);
3188                         printf("Completed command without status.\n");
3189                 } else {
3190                         ahc_print_path(ahc, scb);
3191                         printf("Unknown protocol violation.\n");
3192                         ahc_dump_card_state(ahc);
3193                 }
3194         }
3195         if ((lastphase & ~P_DATAIN_DT) == 0
3196          || lastphase == P_COMMAND) {
3197 proto_violation_reset:
3198                 /*
3199                  * Target either went directly to data/command
3200                  * phase or didn't respond to our ATN.
3201                  * The only safe thing to do is to blow
3202                  * it away with a bus reset.
3203                  */
3204                 found = ahc_reset_channel(ahc, 'A', TRUE);
3205                 printf("%s: Issued Channel %c Bus Reset. "
3206                        "%d SCBs aborted\n", ahc_name(ahc), 'A', found);
3207         } else {
3208                 /*
3209                  * Leave the selection hardware off in case
3210                  * this abort attempt will affect yet to
3211                  * be sent commands.
3212                  */
3213                 ahc_outb(ahc, SCSISEQ,
3214                          ahc_inb(ahc, SCSISEQ) & ~ENSELO);
3215                 ahc_assert_atn(ahc);
3216                 ahc_outb(ahc, MSG_OUT, HOST_MSG);
3217                 if (scb == NULL) {
3218                         ahc_print_devinfo(ahc, &devinfo);
3219                         ahc->msgout_buf[0] = MSG_ABORT_TASK;
3220                         ahc->msgout_len = 1;
3221                         ahc->msgout_index = 0;
3222                         ahc->msg_type = MSG_TYPE_INITIATOR_MSGOUT;
3223                 } else {
3224                         ahc_print_path(ahc, scb);
3225                         scb->flags |= SCB_ABORT;
3226                 }
3227                 printf("Protocol violation %s.  Attempting to abort.\n",
3228                        ahc_lookup_phase_entry(curphase)->phasemsg);
3229         }
3230 }
3231 
3232 /*
3233  * Manual message loop handler.
3234  */
3235 static void
3236 ahc_handle_message_phase(struct ahc_softc *ahc)
3237 {
3238         struct  ahc_devinfo devinfo;
3239         u_int   bus_phase;
3240         int     end_session;
3241 
3242         ahc_fetch_devinfo(ahc, &devinfo);
3243         end_session = FALSE;
3244         bus_phase = ahc_inb(ahc, SCSISIGI) & PHASE_MASK;
3245 
3246 reswitch:
3247         switch (ahc->msg_type) {
3248         case MSG_TYPE_INITIATOR_MSGOUT:
3249         {
3250                 int lastbyte;
3251                 int phasemis;
3252                 int msgdone;
3253 
3254                 if (ahc->msgout_len == 0)
3255                         panic("HOST_MSG_LOOP interrupt with no active message");
3256 
3257 #ifdef AHC_DEBUG
3258                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
3259                         ahc_print_devinfo(ahc, &devinfo);
3260                         printf("INITIATOR_MSG_OUT");
3261                 }
3262 #endif
3263                 phasemis = bus_phase != P_MESGOUT;
3264                 if (phasemis) {
3265 #ifdef AHC_DEBUG
3266                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
3267                                 printf(" PHASEMIS %s\n",
3268                                        ahc_lookup_phase_entry(bus_phase)
3269                                                              ->phasemsg);
3270                         }
3271 #endif
3272                         if (bus_phase == P_MESGIN) {
3273                                 /*
3274                                  * Change gears and see if
3275                                  * this messages is of interest to
3276                                  * us or should be passed back to
3277                                  * the sequencer.
3278                                  */
3279                                 ahc_outb(ahc, CLRSINT1, CLRATNO);
3280                                 ahc->send_msg_perror = FALSE;
3281                                 ahc->msg_type = MSG_TYPE_INITIATOR_MSGIN;
3282                                 ahc->msgin_index = 0;
3283                                 goto reswitch;
3284                         }
3285                         end_session = TRUE;
3286                         break;
3287                 }
3288 
3289                 if (ahc->send_msg_perror) {
3290                         ahc_outb(ahc, CLRSINT1, CLRATNO);
3291                         ahc_outb(ahc, CLRSINT1, CLRREQINIT);
3292 #ifdef AHC_DEBUG
3293                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
3294                                 printf(" byte 0x%x\n", ahc->send_msg_perror);
3295 #endif
3296                         ahc_outb(ahc, SCSIDATL, MSG_PARITY_ERROR);
3297                         break;
3298                 }
3299 
3300                 msgdone = ahc->msgout_index == ahc->msgout_len;
3301                 if (msgdone) {
3302                         /*
3303                          * The target has requested a retry.
3304                          * Re-assert ATN, reset our message index to
3305                          * 0, and try again.
3306                          */
3307                         ahc->msgout_index = 0;
3308                         ahc_assert_atn(ahc);
3309                 }
3310 
3311                 lastbyte = ahc->msgout_index == (ahc->msgout_len - 1);
3312                 if (lastbyte) {
3313                         /* Last byte is signified by dropping ATN */
3314                         ahc_outb(ahc, CLRSINT1, CLRATNO);
3315                 }
3316 
3317                 /*
3318                  * Clear our interrupt status and present
3319                  * the next byte on the bus.
3320                  */
3321                 ahc_outb(ahc, CLRSINT1, CLRREQINIT);
3322 #ifdef AHC_DEBUG
3323                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0)
3324                         printf(" byte 0x%x\n",
3325                                ahc->msgout_buf[ahc->msgout_index]);
3326 #endif
3327                 ahc_outb(ahc, SCSIDATL, ahc->msgout_buf[ahc->msgout_index++]);
3328                 break;
3329         }
3330         case MSG_TYPE_INITIATOR_MSGIN:
3331         {
3332                 int phasemis;
3333                 int message_done;
3334 
3335 #ifdef AHC_DEBUG
3336                 if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
3337                         ahc_print_devinfo(ahc, &devinfo);
3338                         printf("INITIATOR_MSG_IN");
3339                 }
3340 #endif
3341                 phasemis = bus_phase != P_MESGIN;
3342                 if (phasemis) {
3343 #ifdef AHC_DEBUG
3344                         if ((ahc_debug & AHC_SHOW_MESSAGES) != 0) {
3345                                 printf(" PHASEMIS %s\n",
3346                                        ahc_lookup_phase_entry(bus_phase)
3347                                                              ->phasemsg);
3348                         }